diff --git a/.claude/skills/afx/SKILL.md b/.claude/skills/afx/SKILL.md index fddf629ea..6355b548d 100644 --- a/.claude/skills/afx/SKILL.md +++ b/.claude/skills/afx/SKILL.md @@ -116,7 +116,8 @@ workspace on this Tower with its agents, each as an address ready to paste (see below). `` is the workspace's directory name, or the name it was given with `afx workspace name`. A named architect that is not registered fails, listing the workspace's architects and its front door; nothing is rerouted. Mail to a registered architect with no live -terminal is held (`no-live-pty`), like any other. +terminal is held (`no-live-pty`), like any other, while its workspace is running; an address that +names a stopped workspace (one with no open terminal) is refused as not running. **Replying to another workspace.** A message from another workspace names its sender by full address, and its last line is the command that answers it. Run it as printed: diff --git a/.codex/skills/afx/SKILL.md b/.codex/skills/afx/SKILL.md index fddf629ea..6355b548d 100644 --- a/.codex/skills/afx/SKILL.md +++ b/.codex/skills/afx/SKILL.md @@ -116,7 +116,8 @@ workspace on this Tower with its agents, each as an address ready to paste (see below). `` is the workspace's directory name, or the name it was given with `afx workspace name`. A named architect that is not registered fails, listing the workspace's architects and its front door; nothing is rerouted. Mail to a registered architect with no live -terminal is held (`no-live-pty`), like any other. +terminal is held (`no-live-pty`), like any other, while its workspace is running; an address that +names a stopped workspace (one with no open terminal) is refused as not running. **Replying to another workspace.** A message from another workspace names its sender by full address, and its last line is the command that answers it. Run it as printed: diff --git a/codev-skeleton/.claude/skills/afx/SKILL.md b/codev-skeleton/.claude/skills/afx/SKILL.md index fddf629ea..6355b548d 100644 --- a/codev-skeleton/.claude/skills/afx/SKILL.md +++ b/codev-skeleton/.claude/skills/afx/SKILL.md @@ -116,7 +116,8 @@ workspace on this Tower with its agents, each as an address ready to paste (see below). `` is the workspace's directory name, or the name it was given with `afx workspace name`. A named architect that is not registered fails, listing the workspace's architects and its front door; nothing is rerouted. Mail to a registered architect with no live -terminal is held (`no-live-pty`), like any other. +terminal is held (`no-live-pty`), like any other, while its workspace is running; an address that +names a stopped workspace (one with no open terminal) is refused as not running. **Replying to another workspace.** A message from another workspace names its sender by full address, and its last line is the command that answers it. Run it as printed: diff --git a/codev-skeleton/.codex/skills/afx/SKILL.md b/codev-skeleton/.codex/skills/afx/SKILL.md index fddf629ea..6355b548d 100644 --- a/codev-skeleton/.codex/skills/afx/SKILL.md +++ b/codev-skeleton/.codex/skills/afx/SKILL.md @@ -116,7 +116,8 @@ workspace on this Tower with its agents, each as an address ready to paste (see below). `` is the workspace's directory name, or the name it was given with `afx workspace name`. A named architect that is not registered fails, listing the workspace's architects and its front door; nothing is rerouted. Mail to a registered architect with no live -terminal is held (`no-live-pty`), like any other. +terminal is held (`no-live-pty`), like any other, while its workspace is running; an address that +names a stopped workspace (one with no open terminal) is refused as not running. **Replying to another workspace.** A message from another workspace names its sender by full address, and its last line is the command that answers it. Run it as printed: diff --git a/codev-skeleton/resources/commands/agent-farm.md b/codev-skeleton/resources/commands/agent-farm.md index 337ef86e7..0f91f6548 100644 --- a/codev-skeleton/resources/commands/agent-farm.md +++ b/codev-skeleton/resources/commands/agent-farm.md @@ -128,7 +128,8 @@ codev-cloud /Users/ana/dev/codev-cloud ``` - One block per workspace: its address name and path, then its architects, builders and shells. - Workspaces that are not running come last, marked `not running`, with no agents listed. + Workspaces that are not running (no open terminal) come last, marked `not running`, with no + agents listed; an address that names one is refused as not running. - A line that is only an address and `live` or `no live terminal` is ready to paste into `afx send`. Mail to an agent with no live terminal is held (`no-live-pty`) until it has one. - An agent the caller may not address is still listed, with `reach through
` beside diff --git a/codev/projects/bugfix-1978-afx-workspace-list-shows-stopp/status.yaml b/codev/projects/bugfix-1978-afx-workspace-list-shows-stopp/status.yaml new file mode 100644 index 000000000..1e8d397cf --- /dev/null +++ b/codev/projects/bugfix-1978-afx-workspace-list-shows-stopp/status.yaml @@ -0,0 +1,17 @@ +id: bugfix-1978 +title: afx-workspace-list-shows-stopp +protocol: bugfix +phase: verified +plan_phases: [] +current_plan_phase: null +gates: + pr: + status: approved + requested_at: '2026-11-24T22:31:55.063Z' + approved_at: '2026-11-25T00:39:59.209Z' +iteration: 1 +build_complete: false +history: [] +started_at: '2026-11-24T21:54:58.375Z' +updated_at: '2026-11-25T00:40:04.043Z' +pr_ready_for_human: false diff --git a/codev/resources/commands/agent-farm.md b/codev/resources/commands/agent-farm.md index 0ea79d9c8..d1c25faf1 100644 --- a/codev/resources/commands/agent-farm.md +++ b/codev/resources/commands/agent-farm.md @@ -250,7 +250,8 @@ codev-cloud /Users/ana/dev/codev-cloud ``` - One block per workspace: its address name and path, then its architects, builders and shells. - Workspaces that are not running come last, marked `not running`, with no agents listed. + Workspaces that are not running (no open terminal) come last, marked `not running`, with no + agents listed; an address that names one is refused as not running. - A line that is only an address and `live` or `no live terminal` is ready to paste into `afx send`. Mail to an agent with no live terminal is held (`no-live-pty`) until it has one. - An agent the caller may not address is still listed, with `reach through
` beside diff --git a/codev/state/bugfix-1978_thread.md b/codev/state/bugfix-1978_thread.md new file mode 100644 index 000000000..bb4ec6f04 --- /dev/null +++ b/codev/state/bugfix-1978_thread.md @@ -0,0 +1,82 @@ +# bugfix-1978 thread + +Issue #1978: `afx workspace list` shows stopped workspaces as running, because an empty +terminal-map entry counts as running. + +## Investigate (2026-11-24) + +Reproduced read-only on the installed Tower (3.3.8): `afx workspace list --json` gives 53 +workspaces, 46 marked running, 7 not running, and only 12 with a live agent. + +The root cause is proved, not inferred. `getInstances()` (`tower-instances.ts`) sits behind +`/health`, `/api/workspaces`, `/api/status` and `/api/workspaces/:path/status`. It calls +`getTerminalsForWorkspace()` for every known workspace that exists on disk and is not a temp dir +or a builder worktree. That function ends with `workspaceTerminals.set(path, freshEntry)` whether +or not the entry holds a terminal. The 7 marked not running are exactly the ones `getInstances` +skips: 6 missing directories and `/private/tmp/todo`. The per-workspace reads (`GET +/workspace/

/api/state`, `/api/overview`) leave empty entries the same way, which is how +`shannon/.builders/research-8593`, a worktree, got one. + +Every "running" in the address book, the naming rules (`findWorkspaceByAddressName`, +`workspaceAddressName`), the resolvers (`locateWorkspace`), the reply footer +(`crossWorkspaceOrigin`) and the name route is "has a key in the terminal map". `afx whoami` uses +"has a `terminal_sessions` row" instead. + +Decisions sent to the architect: +1. A workspace is running when the map holds at least one terminal for it whose session is open + (it exists in the terminal manager and has not exited). A workspace that is activated but has + no terminal yet is not running. "Open" rather than "writable", so the naming and ambiguity + rules do not flip while a shellper reconnects. The rule is one function, + `runningWorkspaces()`, in the shared naming module: Tower feeds it its open terminals and + whoami feeds it the `terminal_sessions` rows. +2. A send to a registered agent in a stopped workspace, by an address that names the workspace, + is refused as not running, whether or not an entry exists. Own-workspace sends, with no + workspace written, still hold as before. +3. Read routes that create entries are left alone: that is a separate change of about 15 call + sites, and (1) does not depend on it. + +The architect agreed to all three (2026-11-24 22:00Z) and added two things to pin down: +(a) mail already held for an agent of a stopped workspace stays held, shows in `afx inbox`, and +delivers when the workspace starts; (b) what a send gets in the window after a Tower restart, +before the shellpers are re-adopted. + +## Fix (2026-11-24) + +- `runningWorkspaces()` (`utils/workspace-address.ts`) is the one definition. Tower feeds it + through `runningWorkspacePaths()` (`tower-messages.ts`): a terminal counts when its id is on the + map and its session exists and has not exited. That function is used by the address book, + `locateWorkspace`, `crossWorkspaceOrigin` and the name route. `afx whoami` feeds + `runningWorkspaces()` from the `terminal_sessions` rows and no longer adds its own workspace + (that never changed its own name). +- (b) The window is real: Tower listens before the startup reconcile finishes. On today's + restart that took 0.6 s for 64 sessions (21:28:47.463 listen, 21:28:48.081 reconcile complete). + `/api/send` and `/api/address-book` now await `whenStartupReconcileSettled()` (bounded at 10 s), + as the dashboard's reads already did. +- (a) The fix doesn't touch the mailbox: delivery keys on the agent's live session, not on + "running". The e2e pins it: mail held while the workspace is stopped stays held, is listed by + `afx inbox`, is untouched by the refusal, and is offered to the new terminal when the workspace + starts (its reason goes from `no-live-pty` to `no-profile` under the inert terminal). +- Fixtures that encoded the bug: `spec-1313-registry-resolve` treated an empty slot as a live + workspace, and one route test removed every session on the Tower to simulate one dead + recipient. +- Checked the tests against the pre-fix source and build: 9 unit tests and 4 e2e cases fail, and + the e2e reproduces every consequence in the issue. With the fix, all pass. +- Step 5 (verify on a real Tower with many workspaces) needs the fix on the live Tower, which + means an install plus a Tower restart: the owner's call. A test Tower on a copy of `global.db` + would reconcile the live shellpers and take over their connections, so I didn't do that. + +## PR #1980 and CMAP (2026-11-24) + +- codex: REQUEST_CHANGES. + - (1) whoami can still disagree with Tower when Tower keeps a `terminal_sessions` row for a + shellper it has not re-adopted. This is the residual gap the architect accepted; it is now + stated in the PR body. + - (2) Commit prefixes: the three it named are porch's own `chore(porch)` commits. + - (3) PR headings: kept in PRFT form, as the architect asked. +- claude: APPROVE, with nits. Fixed in place: + - the address book carries `running` structurally, and throws if a running workspace has no + slot; + - `runningWorkspacePaths()` stops at the first open terminal per workspace; + - the name route waits for the startup reconcile; + - the afx skill (4 copies) and `agent-farm.md` (2 copies) say that naming a stopped workspace is + refused, and the shipped-skill hashes were regenerated. diff --git a/packages/codev/src/agent-farm/__tests__/bugfix-1094-tower-guard.test.ts b/packages/codev/src/agent-farm/__tests__/bugfix-1094-tower-guard.test.ts index ccfb2cabf..5860be3b1 100644 --- a/packages/codev/src/agent-farm/__tests__/bugfix-1094-tower-guard.test.ts +++ b/packages/codev/src/agent-farm/__tests__/bugfix-1094-tower-guard.test.ts @@ -21,6 +21,8 @@ const { mockGetWorkspaceTerminals, mockLookupBuilderSpawningArchitect } = vi.hoi vi.mock('../servers/tower-terminals.js', () => ({ getWorkspaceTerminals: () => mockGetWorkspaceTerminals(), + // Every terminal on the fake map is open, so a workspace with one is running (Issue #1978). + getTerminalManager: () => ({ getSession: () => ({ status: 'running' }) }), })); vi.mock('../state.js', () => ({ diff --git a/packages/codev/src/agent-farm/__tests__/cross-workspace-addressing.e2e.test.ts b/packages/codev/src/agent-farm/__tests__/cross-workspace-addressing.e2e.test.ts index 76e7d1c2c..bfd604540 100644 --- a/packages/codev/src/agent-farm/__tests__/cross-workspace-addressing.e2e.test.ts +++ b/packages/codev/src/agent-farm/__tests__/cross-workspace-addressing.e2e.test.ts @@ -56,6 +56,8 @@ vi.mock('../db/index.js', async (importOriginal) => { const { send } = await import('../commands/send.js'); const { workspaceName } = await import('../commands/workspace-name.js'); const { workspaceList } = await import('../commands/workspace-list.js'); +const { resolveIdentity } = await import('../commands/whoami.js'); +const { inboxList } = await import('../commands/inbox.js'); /** An inert terminal: it stays alive, reads nothing, and shows no agent composer. */ const INERT_SCRIPT = 'trap "" INT; while true; do sleep 3600; done'; @@ -222,6 +224,11 @@ async function activate(workspacePath: string): Promise { throw new Error(`workspace ${workspacePath} did not activate: ${res?.status} ${await res?.text()}`); } +async function deactivate(workspacePath: string): Promise { + const res = await tower('POST', `/api/workspaces/${encodeWorkspacePath(workspacePath)}/deactivate`); + if (!res.ok) throw new Error(`workspace ${workspacePath} did not deactivate: ${res.status} ${await res.text()}`); +} + async function addArchitect(workspacePath: string, name: string): Promise { const res = await tower('POST', `/api/workspaces/${encodeWorkspacePath(workspacePath)}/architects`, { name }); if (!res.ok) throw new Error(`add-architect ${name} failed: ${res.status} ${await res.text()}`); @@ -283,6 +290,8 @@ describe('Spec 1940: cross-workspace addressing on a real Tower that has never c /** `/b/codev`: a second directory called `codev`, started only for the last cases. */ let otherCodev: string; let builderWorktree: string; + /** The inert program every workspace here runs as its architect. */ + let inertAgent: string; const active: string[] = []; const review = (): Agent => ({ cwd: codev, architect: 'review' }); @@ -302,7 +311,7 @@ describe('Spec 1940: cross-workspace addressing on a real Tower that has never c // The temp dir is behind a symlink on macOS (/var → /private/var); Tower keys a // workspace by its real path, and the CLI must name the same one. root = realpathSync(mkdtempSync(join(tmpdir(), 'codev-1940-'))); - const inertAgent = writeInertAgent(root); + inertAgent = writeInertAgent(root); codev = makeWorkspace(join(root, 'a', 'codev'), inertAgent); cloud = makeWorkspace(join(root, 'codev-cloud'), inertAgent); otherCodev = makeWorkspace(join(root, 'b', 'codev'), inertAgent); @@ -528,6 +537,114 @@ describe('Spec 1940: cross-workspace addressing on a real Tower that has never c ]); }); + describe('a stopped workspace that Tower holds an empty slot for (Issue #1978)', () => { + /** + * `/parked/codev-cloud`: started once, so Tower registered it and its architect + * `main`, then stopped, which keeps that registration. It shares its directory name with + * the running codev-cloud. + */ + let parked: string; + const HELD_WHILE_STOPPED = 'For main in the parked workspace, when it is back'; + + /** A person at a plain shell in the parked workspace: no terminal of Tower's. */ + const atParked = (): Agent => ({ cwd: parked }); + + beforeAll(async () => { + parked = makeWorkspace(join(root, 'parked', 'codev-cloud'), inertAgent); + await activate(parked); + await deactivate(parked); + // What a dashboard or extension poll of a stopped workspace does: it asks for the + // workspace's state, and the route leaves an empty slot on the terminal map. + const res = await tower('GET', `/workspace/${encodeWorkspacePath(parked)}/api/state`); + expect(res.ok).toBe(true); + }, 60_000); + + it('afx workspace list lists it as not running, with no agents, and the running codev-cloud keeps the name', async () => { + const listed = await runAs(builder(), () => workspaceList()); + + expect(listed.exitCode).toBeNull(); + const lines = listed.stdout.map((line) => line.replace(/ +/g, ' ').trim()); + // The running workspaces, exactly as before, then the stopped one, with no agents. + expect(lines).toEqual([ + `codev ${codev}`, + 'codev:architect:main live reach through codev:architect', + 'codev:architect:review live reach through codev:architect', + `codev-cloud ${cloud}`, + 'codev-cloud:architect:main live', + 'codev-cloud:architect:data no live terminal reach through architect', + 'codev-cloud:architect:tunnel live reach through architect', + `codev-cloud:${BUILDER} live`, + // The running codev-cloud keeps the directory name; the stopped one has none of its own. + `(no address name) ${parked} not running`, + `no address name: it shares the directory name 'codev-cloud' with ${cloud}; give it a name of its own: afx workspace name `, + ]); + }); + + it('the shared directory name still reaches the running workspace: the stopped one is not a second match', async () => { + const sent = await afxSend(review(), 'codev-cloud:architect:tunnel', 'Tunnel, past the parked namesake'); + + expect(sent.exitCode).toBeNull(); + expect(mailWithBody('Tunnel, past the parked namesake')).toMatchObject({ workspace_path: cloud, to_agent: 'tunnel' }); + }); + + it('afx whoami gives the address the listing prints for the same agent', async () => { + const who = await runAs(builder(), async () => resolveIdentity()); + const book = await tower('GET', `/api/address-book?workspace=${encodeURIComponent(cloud)}&from=${BUILDER}`); + const listed = ((await book.json()) as { workspaces: Array<{ path: string; agents: Array<{ name: string; address: string | null }> }> }) + .workspaces.find((w) => w.path === cloud)! + .agents.find((a) => a.name === BUILDER)!; + + expect(who.result).toMatchObject({ type: 'builder', name: BUILDER, address: `codev-cloud:${BUILDER}` }); + expect(listed.address).toBe(`codev-cloud:${BUILDER}`); + }); + + it('mail held for its architect while it is stopped stays held, and is listed by afx inbox', async () => { + // A sender in the workspace itself addresses no workspace, and that path holds mail + // for a registered agent with no terminal, as it always has. + const sent = await afxSend(atParked(), 'architect', HELD_WHILE_STOPPED); + expect(sent.exitCode).toBeNull(); + expect(sent.result).toBe('held'); + const held = mailWithBody(HELD_WHILE_STOPPED); + expect(held).toMatchObject({ workspace_path: parked, to_agent: 'main', status: 'held', reason: 'no-live-pty' }); + + const inbox = await runAs(atParked(), () => inboxList()); + expect(inbox.exitCode).toBeNull(); + expect(inbox.stdout.some((line) => line.includes(held.id) && line.includes('no-live-pty'))).toBe(true); + }); + + it('once it has a name, a send to its registered architect is refused as not running, and nothing is stored', async () => { + const named = await runAs(atParked(), () => workspaceName({ name: 'parked' })); + expect(named.exitCode).toBeNull(); + const before = mailCount(); + + const sent = await afxSend(review(), 'parked:architect', 'For the parked workspace, by its name'); + + expect(sent.exitCode).toBe(1); + expect(outcomeLines(sent)).toEqual([]); + expect(sent.stderr).toEqual([`[error] Workspace 'parked' (${parked}) is not running. (NOT_FOUND)`]); + expect(mailCount()).toBe(before); + // The mail it already held is untouched by the refusal. + expect(mailWithBody(HELD_WHILE_STOPPED)).toMatchObject({ status: 'held', reason: 'no-live-pty' }); + }); + + it('when the workspace starts, the mail held for its architect is offered to the new terminal', async () => { + await start(parked); + + // The inert terminal shows no agent composer, so the gate holds the message for that + // reason now: it was offered to a live terminal, and it is still on record, not dropped. + let mail = mailWithBody(HELD_WHILE_STOPPED); + for (let attempt = 0; attempt < 60 && mail.reason === 'no-live-pty'; attempt++) { + await new Promise((r) => setTimeout(r, 500)); + mail = mailWithBody(HELD_WHILE_STOPPED); + } + expect(mail).toMatchObject({ workspace_path: parked, to_agent: 'main', status: 'held', reason: 'no-profile' }); + // And the address that was refused while it was stopped now reaches it. + const sent = await afxSend(review(), 'parked:architect', 'For the parked workspace, now running'); + expect(sent.exitCode).toBeNull(); + expect(mailWithBody('For the parked workspace, now running')).toMatchObject({ workspace_path: parked, to_agent: 'main' }); + }, 60_000); + }); + describe('two running workspaces whose directories are both called codev', () => { beforeAll(async () => { await start(otherCodev); diff --git a/packages/codev/src/agent-farm/__tests__/spec-1313-registry-resolve.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1313-registry-resolve.test.ts index 0aa4989a9..529208748 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1313-registry-resolve.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1313-registry-resolve.test.ts @@ -29,6 +29,8 @@ const { vi.mock('../servers/tower-terminals.js', () => ({ getWorkspaceTerminals: () => mockGetWorkspaceTerminals(), + // Every terminal on the fake map is open, so a workspace with one is running (Issue #1978). + getTerminalManager: () => ({ getSession: () => ({ status: 'running' }) }), })); vi.mock('../state.js', () => ({ @@ -56,7 +58,16 @@ function resolveInRegistry(target: string, workspace?: string, sender?: string) return resolveAgentInRegistry(address, { id: sender, workspace }); } -/** A minimal WorkspaceTerminals; the resolver only cares that the key (path) exists. */ +/** + * A running workspace: its architect `main` has a terminal, and no builder does, so every + * registered builder is offline. Issue #1978: a workspace runs while it has a terminal, not + * while its key is on the map. + */ +function runningEntry(): WorkspaceTerminals { + return { architects: new Map([['main', 'term-main']]), builders: new Map(), shells: new Map(), fileTabs: new Map() }; +} + +/** The slot many routes leave on the map for a workspace they were asked about: no terminal. */ function emptyEntry(): WorkspaceTerminals { return { architects: new Map(), builders: new Map(), shells: new Map(), fileTabs: new Map() }; } @@ -69,10 +80,10 @@ function builder(id: string): Builder { describe('Spec 1313 — resolveAgentInRegistry (offline-hold fallback)', () => { beforeEach(() => { vi.clearAllMocks(); - // Default: both workspaces are live-registered (so the workspace lookup can - // map a project basename → path); registries are empty unless a test sets them. + // Default: both workspaces are running (so the workspace lookup can map a project + // basename → path); registries are empty unless a test sets them. mockGetWorkspaceTerminals.mockReturnValue( - new Map([[WS_A, emptyEntry()], [WS_B, emptyEntry()]]), + new Map([[WS_A, runningEntry()], [WS_B, runningEntry()]]), ); mockGetBuilders.mockReturnValue([]); mockGetArchitects.mockReturnValue([]); @@ -115,13 +126,23 @@ describe('Spec 1313 — resolveAgentInRegistry (offline-hold fallback)', () => { }); it('NOT_FOUND when the project workspace is not active (the boundary of the workspace lookup)', () => { - // Only WS_A is live-registered; proj-b maps to no workspace. - mockGetWorkspaceTerminals.mockReturnValue(new Map([[WS_A, emptyEntry()]])); + // Only WS_A is running; proj-b maps to no workspace. + mockGetWorkspaceTerminals.mockReturnValue(new Map([[WS_A, runningEntry()]])); const result = resolveInRegistry('proj-b:spir-200', WS_A); expect(isResolveError(result) && result.code).toBe('NOT_FOUND'); }); + it('NOT_FOUND when the project workspace has only an empty slot on the map (Issue #1978)', () => { + // A stopped workspace that a route was asked about: its builder is registered, and its + // mail is refused as for a workspace with no slot, not held for nobody to deliver. + mockGetWorkspaceTerminals.mockReturnValue(new Map([[WS_A, runningEntry()], [WS_B, emptyEntry()]])); + mockGetBuilders.mockImplementation((ws) => (ws === WS_B ? [builder('spir-200')] : [])); + + const result = resolveInRegistry('proj-b:spir-200', WS_A); + expect(result).toEqual({ code: 'NOT_FOUND', message: "Workspace 'proj-b' not found. No workspace with that name or directory name is registered." }); + }); + it('NOT_FOUND for project:builder when the agent is absent from the target registry', () => { mockGetBuilders.mockReturnValue([]); // proj-b is live but has no such builder const result = resolveInRegistry('proj-b:spir-200', WS_A); diff --git a/packages/codev/src/agent-farm/__tests__/spec-1940-address-book.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1940-address-book.test.ts index 9cbac037c..d595368af 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1940-address-book.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1940-address-book.test.ts @@ -11,10 +11,14 @@ * codev-cloud main, review, tunnel builder-spir-7 (spawned by review), shell-7 * tunnel is registered and has no terminal * scratch registered, not running + * + * Issue #1978: a workspace is running while it holds an open terminal, not while it merely + * has a slot on the terminal map, which many routes create for any workspace they are asked + * about. */ import { describe, it, expect, beforeEach, vi } from 'vitest'; -import type { AddressBookAgent, AddressBookWorkspace } from '@cluesmith/codev-types'; +import type { AddressBookAgent, AddressBookWorkspace, AgentAddress } from '@cluesmith/codev-types'; import type { WorkspaceTerminals } from '../servers/tower-types.js'; import type { Builder } from '../types.js'; @@ -28,7 +32,7 @@ const { mockGetRegisteredWorkspaces, } = vi.hoisted(() => ({ mockGetWorkspaceTerminals: vi.fn<() => Map>(), - mockGetSession: vi.fn<(id: string) => { writable: boolean } | undefined>(), + mockGetSession: vi.fn<(id: string) => { writable: boolean; status: 'running' | 'exited' } | undefined>(), mockGetBuilders: vi.fn<(ws?: string) => Builder[]>(), mockGetArchitects: vi.fn<(ws: string) => Array<{ name: string }>>(), mockGetArchitectByName: vi.fn<(ws: string, name: string) => { name: string } | null>(), @@ -122,7 +126,9 @@ beforeEach(() => { [CLOUD, entry(['main', 'review'], ['builder-spir-7'], ['shell-7'])], ]); mockGetWorkspaceTerminals.mockImplementation(() => terminals); - mockGetSession.mockImplementation((id) => (exited.has(id) ? undefined : { writable: !disconnected.has(id) })); + mockGetSession.mockImplementation((id) => + exited.has(id) ? undefined : { writable: !disconnected.has(id), status: 'running' }, + ); mockGetArchitects.mockImplementation((ws) => (architects[ws] ?? []).map((name) => ({ name }))); mockGetArchitectByName.mockImplementation((ws, name) => ((architects[ws] ?? []).includes(name) ? { name } : null)); mockGetBuilders.mockImplementation((ws) => Object.keys(spawnedBy[ws ?? ''] ?? {}).map((id) => ({ id }) as unknown as Builder)); @@ -237,6 +243,65 @@ describe('Spec 1940 phase 5 — the address book', () => { } }); + describe('a stopped workspace with an empty slot on the terminal map (Issue #1978)', () => { + // What a dashboard poll or `/health` leaves behind for a workspace that is not running: + // a slot with no terminal in it. Its architect is still registered, as a stop leaves it. + beforeEach(() => { + architects[SCRATCH] = ['main']; + terminals.set(SCRATCH, entry([])); + }); + + it('is listed as not running, after the running ones, with no agents', () => { + expect(addressBook(ARCHITECT).workspaces.map((w) => [w.path, w.running])).toEqual([ + [CODEV, true], + [CLOUD, true], + [SCRATCH, false], + ]); + expect(workspaceAt(SCRATCH).agents).toEqual([]); + }); + + it('a send to its registered architect is refused as not running, the same answer as with no slot', () => { + const address = (text: string) => parseTarget(text) as AgentAddress; + const withSlot = resolveTarget(address('scratch:architect:main'), ARCHITECT); + expect(withSlot).toEqual({ code: 'NOT_FOUND', message: `Workspace 'scratch' (${SCRATCH}) is not running.` }); + // The registry answers the same: mail is refused, not held for an architect nobody is running. + expect(resolveAgentInRegistry(address('scratch:architect:main'), ARCHITECT)).toEqual(withSlot); + expect(sendAs(ARCHITECT, 'scratch:architect')).toEqual({ refused: 'NOT_FOUND' }); + + terminals.delete(SCRATCH); + expect(resolveTarget(address('scratch:architect:main'), ARCHITECT)).toEqual(withSlot); + expect(resolveAgentInRegistry(address('scratch:architect:main'), ARCHITECT)).toEqual(withSlot); + }); + + it('takes no part in ambiguity: a running workspace with its directory name keeps the name', () => { + const OLD = '/home/user/old/codev-cloud'; + architects[OLD] = ['main']; + stopped.push(OLD); + terminals.set(OLD, entry([])); + expect(workspaceAt(CLOUD).addressName).toBe('codev-cloud'); + expect(workspaceAt(OLD)).toMatchObject({ running: false, agents: [] }); + expect(sendAs(ARCHITECT, 'codev-cloud:architect:main')).toEqual({ workspacePath: CLOUD, reached: 'main' }); + }); + + it('a workspace whose every terminal has exited is not running either', () => { + architects[SCRATCH] = ['solo']; + terminals.set(SCRATCH, entry(['solo'], [], ['shell-9'])); + exited.add('term-shell-9'); + mockGetSession.mockImplementation((id) => + id === 'term-solo' ? { writable: false, status: 'exited' } : exited.has(id) ? undefined : { writable: true, status: 'running' }, + ); + expect(workspaceAt(SCRATCH)).toMatchObject({ running: false, agents: [] }); + }); + + it('a workspace whose only terminal is reconnecting is still running, and its mail is held', () => { + architects[SCRATCH] = ['solo']; + terminals.set(SCRATCH, entry(['solo'])); + disconnected.add('term-solo'); + expect(workspaceAt(SCRATCH).running).toBe(true); + expect(linesOf(SCRATCH)).toEqual(['scratch:architect:solo | no terminal | sendable']); + }); + }); + describe('a live terminal', () => { it('is one that is on the terminal map and still has a session', () => { exited.add('term-review'); diff --git a/packages/codev/src/agent-farm/__tests__/spec-1940-cross-workspace-resolve.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1940-cross-workspace-resolve.test.ts index 40d990458..ecc6a4924 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1940-cross-workspace-resolve.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1940-cross-workspace-resolve.test.ts @@ -37,6 +37,8 @@ const { vi.mock('../servers/tower-terminals.js', () => ({ getWorkspaceTerminals: () => mockGetWorkspaceTerminals(), + // Every terminal on the fake map is open, so a workspace with one is running (Issue #1978). + getTerminalManager: () => ({ getSession: () => ({ status: 'running' }) }), })); vi.mock('../state.js', () => ({ diff --git a/packages/codev/src/agent-farm/__tests__/spec-1940-reply-footer.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1940-reply-footer.test.ts index 8fe2f44c5..87872cbca 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1940-reply-footer.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1940-reply-footer.test.ts @@ -38,6 +38,8 @@ const { vi.mock('../servers/tower-terminals.js', () => ({ getWorkspaceTerminals: () => mockGetWorkspaceTerminals(), + // Every terminal on the fake map is open, so a workspace with one is running (Issue #1978). + getTerminalManager: () => ({ getSession: () => ({ status: 'running' }) }), })); vi.mock('../state.js', () => ({ diff --git a/packages/codev/src/agent-farm/__tests__/spec-755-phase3-routing.test.ts b/packages/codev/src/agent-farm/__tests__/spec-755-phase3-routing.test.ts index b7cc45602..f71bdadaa 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-755-phase3-routing.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-755-phase3-routing.test.ts @@ -28,6 +28,8 @@ const { mockGetWorkspaceTerminals, mockLookupBuilderSpawningArchitect } = vi.hoi vi.mock('../servers/tower-terminals.js', () => ({ getWorkspaceTerminals: () => mockGetWorkspaceTerminals(), + // Every terminal on the fake map is open, so a workspace with one is running (Issue #1978). + getTerminalManager: () => ({ getSession: () => ({ status: 'running' }) }), })); vi.mock('../state.js', () => ({ diff --git a/packages/codev/src/agent-farm/__tests__/tower-messages.test.ts b/packages/codev/src/agent-farm/__tests__/tower-messages.test.ts index 62e9ac36b..7f22e7b4c 100644 --- a/packages/codev/src/agent-farm/__tests__/tower-messages.test.ts +++ b/packages/codev/src/agent-farm/__tests__/tower-messages.test.ts @@ -16,6 +16,8 @@ const { mockGetWorkspaceTerminals } = vi.hoisted(() => ({ vi.mock('../servers/tower-terminals.js', () => ({ getWorkspaceTerminals: () => mockGetWorkspaceTerminals(), + // Every terminal on the fake map is open, so a workspace with one is running (Issue #1978). + getTerminalManager: () => ({ getSession: () => ({ status: 'running' }) }), })); import { diff --git a/packages/codev/src/agent-farm/__tests__/tower-routes.test.ts b/packages/codev/src/agent-farm/__tests__/tower-routes.test.ts index 942172388..6e248eca6 100644 --- a/packages/codev/src/agent-farm/__tests__/tower-routes.test.ts +++ b/packages/codev/src/agent-farm/__tests__/tower-routes.test.ts @@ -58,6 +58,7 @@ const { mockGetInstances, mockGetTerminalManager, mockGetSession, mockGetKnownWorkspacePaths, mockGetAllKnownWorkspacePaths, mockIsStartupReconcileSettled, + mockWhenStartupReconcileSettled, sendDbHolder } = vi.hoisted(() => ({ mockGetInstances: vi.fn(), mockGetTerminalManager: vi.fn(), @@ -85,6 +86,7 @@ const { mockGetInstances, mockGetTerminalManager, mockGetSession, mockGetKnownWorkspacePaths: vi.fn(() => []), mockGetAllKnownWorkspacePaths: vi.fn((): string[] => []), mockIsStartupReconcileSettled: vi.fn(() => true), + mockWhenStartupReconcileSettled: vi.fn(async () => {}), // Holder for the in-memory global.db used by the Spec 1313 send path (mailbox // persist + gate delivery). Re-created per test in beforeEach. sendDbHolder: { db: null as unknown as import('better-sqlite3').Database }, @@ -124,6 +126,7 @@ vi.mock('../servers/tower-terminals.js', () => ({ getTerminalsForWorkspace: mockGetTerminalsForWorkspace, getRehydratedTerminalsEntry: mockGetRehydratedTerminalsEntry, isStartupReconcileSettled: mockIsStartupReconcileSettled, + whenStartupReconcileSettled: mockWhenStartupReconcileSettled, })); vi.mock('../servers/tower-tunnel.js', () => ({ @@ -143,6 +146,8 @@ vi.mock('../servers/tower-messages.js', async (importOriginal) => ({ // The address book asks the permission rule on its own; it is the real one, as the // resolvers behind the route are wherever the address book is tested. refusalToAddress: (await importOriginal()).refusalToAddress, + // The real definition of a running workspace (Issue #1978), read off the faked terminal map. + runningWorkspacePaths: (await importOriginal()).runningWorkspacePaths, resolveTarget: (...args: unknown[]) => mockResolveTarget(...args), resolveAgentInRegistry: (...args: unknown[]) => mockResolveAgentInRegistry(...args), broadcastMessage: (...args: unknown[]) => mockBroadcastMessage(...args), @@ -291,6 +296,8 @@ function gateSession(mockWrite: (data: string) => void, ring: string, writable = // input can hand in a `write` that skips the feed. write: (data: string): boolean => { mockWrite(data); gateScreen.feed(data.replace(/\n/g, '\r\n')); return true; }, pid: 1234, + // A live PTY's session has not exited; whether it takes input is `writable`'s business. + status: 'running' as const, writable, isUserIdle: () => true, composing: false, @@ -2587,6 +2594,32 @@ describe('tower-routes', () => { expect(mailbox.findHeldForAgent(sendDbHolder.db, CLOUD, 'main')).toHaveLength(0); }); + // Issue #1978: right after a restart the terminal map is empty until the startup + // reconcile adopts each workspace's sessions, so a workspace that is coming back has no + // terminal yet and would be refused as not running. The send waits for the reconcile. + it('waits for the startup reconcile, so a workspace whose terminals are being adopted is not refused', async () => { + vi.mocked(getWorkspaceTerminals).mockImplementation(() => new Map() as any); + let settle!: () => void; + mockWhenStartupReconcileSettled.mockReturnValueOnce(new Promise((resolve) => { settle = resolve; })); + + const sending = send('codev-cloud:architect:tunnel', 'architect:review'); + await new Promise((r) => setTimeout(r, 20)); + expect(mockResolveTarget).not.toHaveBeenCalled(); + expect(allRows()).toHaveLength(0); + + // The reconcile adopts both workspaces' sessions, then settles. + const writes = liveAgents({ + [CODEV]: { architects: ['main', 'review'] }, + [CLOUD]: { architects: ['main', 'review', 'tunnel'] }, + }); + settle(); + const { status, body } = await sending; + + expect(status).toBe(200); + expect(body).toMatchObject({ ok: true, delivered: true, resolvedTo: 'tunnel' }); + await vi.waitFor(() => expect(writes['codev-cloud/tunnel'].mock.calls.at(-1)?.[0]).toBe('\r')); + }); + it('schedules it on the --delay path too, with no live terminal', async () => { liveAgents({ [CODEV]: { architects: ['main', 'review'] }, [CLOUD]: { architects: ['main', 'review'] } }); const { status, body } = await send('codev-cloud:architect:tunnel', 'architect:review', { options: { deliverAfter: 30 } }); @@ -2910,7 +2943,12 @@ describe('tower-routes', () => { }); it('held for a recipient whose terminal session is gone (the dead-session hold)', async () => { - mockGetTerminalManager.mockReturnValue({ listSessions: () => [], getSession: () => null }); + // Only the recipient's session is gone: its workspace still has open terminals, so + // it is running (Issue #1978), and the map still names the dead terminal. + mockGetTerminalManager.mockReturnValue({ + listSessions: () => [], + getSession: (id: string) => (id === 'term-codev-cloud/tunnel' ? null : gateSession(vi.fn(), '❯ ', true, id)), + }); const { body } = await send('codev-cloud:architect:tunnel', 'architect:review'); expect(body).toMatchObject({ ok: true, held: true, reason: 'no-live-pty', terminalId: 'term-codev-cloud/tunnel' }); expect(lastFrame()).toBe(`${HEADER}\nhello\n${REPLY}`); diff --git a/packages/codev/src/agent-farm/__tests__/workspace-address.test.ts b/packages/codev/src/agent-farm/__tests__/workspace-address.test.ts index 94efb31f1..525641296 100644 --- a/packages/codev/src/agent-farm/__tests__/workspace-address.test.ts +++ b/packages/codev/src/agent-farm/__tests__/workspace-address.test.ts @@ -11,6 +11,7 @@ import { findWorkspaceByAddressName, isSameWorkspace, printableAddressName, + runningWorkspaces, validateProposedName, workspaceAddressName, WORKSPACE_NAME_COMMAND, @@ -470,6 +471,21 @@ describe('printableAddressName', () => { }); }); +describe('runningWorkspaces (Issue #1978)', () => { + it('is every workspace that has a terminal, once each, in the first spelling given', () => { + expect(runningWorkspaces([A, CLOUD, A, A])).toEqual([A, CLOUD]); + }); + + it('is nothing when there are no terminals: being known or having a slot does not count', () => { + expect(runningWorkspaces([])).toEqual([]); + }); + + it('counts two spellings of one directory as one workspace (Windows keys)', () => { + forceHostPlatform('win32'); + expect(runningWorkspaces(['C:/nx-1978/codev', 'c:/nx-1978/codev'])).toEqual(['C:/nx-1978/codev']); + }); +}); + describe('isSameWorkspace', () => { it('compares workspace keys', () => { expect(isSameWorkspace(A, A)).toBe(true); diff --git a/packages/codev/src/agent-farm/commands/whoami.ts b/packages/codev/src/agent-farm/commands/whoami.ts index d4ae75c5f..67c1c3c0c 100644 --- a/packages/codev/src/agent-farm/commands/whoami.ts +++ b/packages/codev/src/agent-farm/commands/whoami.ts @@ -35,7 +35,7 @@ import type { AgentAddress } from '@cluesmith/codev-types'; import { getRegisteredWorkspaces, lookupBuilderSpawningArchitect } from '../state.js'; import { getGlobalDbPath } from '../db/index.js'; import { normalizeWorkspacePath } from '../utils/workspace-path.js'; -import { printableAddressName } from '../utils/workspace-address.js'; +import { printableAddressName, runningWorkspaces } from '../utils/workspace-address.js'; import { TOWER_RESTART_COMMAND } from '../utils/older-tower.js'; export interface WhoamiOptions { @@ -109,17 +109,15 @@ function workspaceDisplayName(workspaceRoot: string | null, db: Database.Databas } /** - * The workspaces that have a terminal, as global.db records them: Tower writes a - * `terminal_sessions` row when it starts a terminal and deletes a workspace's rows when - * the workspace stops. This is whoami's stand-in for Tower's own list of running - * workspaces, which only Tower holds; the caller's own workspace is counted as running, - * since the caller is in it. + * The running workspaces, by the one definition Tower uses ({@link runningWorkspaces}), fed + * from global.db because whoami does not need Tower: Tower writes a `terminal_sessions` row + * when it starts a terminal and deletes it when the terminal ends or its workspace stops. + * Whether the caller's own workspace is running does not change its own name, so it is not + * added. */ -function workspacesWithTerminals(db: Database.Database, ownWorkspace: string): string[] { - const rows = db.prepare('SELECT DISTINCT workspace_path FROM terminal_sessions').all() as Array<{ - workspace_path: string; - }>; - return [...rows.map((row) => row.workspace_path), ownWorkspace]; +function runningWorkspacesInDb(db: Database.Database): string[] { + const rows = db.prepare('SELECT workspace_path FROM terminal_sessions').all() as Array<{ workspace_path: string }>; + return runningWorkspaces(rows.map((row) => row.workspace_path)); } /** @@ -156,7 +154,7 @@ function ownAddress(agent: AgentAddress, workspaceRoot: string | null, db: Datab `restarting Tower migrates it: ${TOWER_RESTART_COMMAND}`, }; } - named = printableAddressName(root, getRegisteredWorkspaces(db), workspacesWithTerminals(db, root)); + named = printableAddressName(root, getRegisteredWorkspaces(db), runningWorkspacesInDb(db)); } catch (err) { // Any other failure is reported as itself: advice for a cause it is not would mislead. const cause = err instanceof Error ? err.message : String(err); diff --git a/packages/codev/src/agent-farm/servers/tower-address-book.ts b/packages/codev/src/agent-farm/servers/tower-address-book.ts index 3808d0bae..97735354c 100644 --- a/packages/codev/src/agent-farm/servers/tower-address-book.ts +++ b/packages/codev/src/agent-farm/servers/tower-address-book.ts @@ -25,6 +25,7 @@ import { refusalToAddress, resolveAgentInRegistry, resolveTarget, + runningWorkspacePaths, type SenderContext, } from './tower-messages.js'; @@ -140,30 +141,37 @@ function agentEntry( return entry; } -/** A workspace Tower knows, in the spelling it runs under when it is running. */ -interface ListedWorkspace { - path: string; - entry: WorkspaceTerminals | undefined; -} +/** + * A workspace Tower knows, in the spelling it runs under when it is running. `entry` is its + * slot on the terminal map, read only when it is running: a stopped workspace can have a + * slot too (Issue #1978). + */ +type ListedWorkspace = { path: string; running: true; entry: WorkspaceTerminals } | { path: string; running: false }; /** * Every workspace Tower knows, once each, told apart by key as the naming module tells * them: the running ones first, then the registered ones that are not running, each group * in path order. */ -function listedWorkspaces(registeredPaths: string[], terminals: Map): ListedWorkspace[] { +function listedWorkspaces( + registeredPaths: string[], + running: string[], + terminals: Map, +): ListedWorkspace[] { const byKey = new Map(); - for (const [path, entry] of terminals) byKey.set(workspaceKey(path), { path, entry }); + for (const path of running) { + const entry = terminals.get(path); + // `running` is read off these slots, so a running workspace without one is a bug here. + if (entry === undefined) throw new Error(`running workspace ${path} has no slot on the terminal map`); + byKey.set(workspaceKey(path), { path, running: true, entry }); + } for (const path of registeredPaths) { const key = workspaceKey(path); - if (!byKey.has(key)) byKey.set(key, { path, entry: undefined }); + if (!byKey.has(key)) byKey.set(key, { path, running: false }); } const inPathOrder = (a: ListedWorkspace, b: ListedWorkspace) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0); const all = [...byKey.values()]; - return [ - ...all.filter((w) => w.entry !== undefined).sort(inPathOrder), - ...all.filter((w) => w.entry === undefined).sort(inPathOrder), - ]; + return [...all.filter((w) => w.running).sort(inPathOrder), ...all.filter((w) => !w.running).sort(inPathOrder)]; } /** @@ -174,19 +182,17 @@ function listedWorkspaces(registeredPaths: string[], terminals: Map w.workspacePath), terminals).map((listed): AddressBookWorkspace => { - const named = printableAddressName(listed.path, registered, active); + const workspaces = listedWorkspaces(registered.map((w) => w.workspacePath), running, getWorkspaceTerminals()).map((listed): AddressBookWorkspace => { + const named = printableAddressName(listed.path, registered, running); const isCallersOwn = caller.workspace !== undefined && isSameWorkspace(listed.path, caller.workspace); - const agents = - listed.entry === undefined - ? [] - : seatsOf(listed.path, listed.entry).map((seat) => agentEntry(seat, listed.path, named.name, isCallersOwn, caller)); + const agents = listed.running + ? seatsOf(listed.path, listed.entry).map((seat) => agentEntry(seat, listed.path, named.name, isCallersOwn, caller)) + : []; const workspace: AddressBookWorkspace = { path: listed.path, - running: listed.entry !== undefined, + running: listed.running, addressName: named.name, agents, }; diff --git a/packages/codev/src/agent-farm/servers/tower-messages.ts b/packages/codev/src/agent-farm/servers/tower-messages.ts index 8c8c7b195..a7bd245d6 100644 --- a/packages/codev/src/agent-farm/servers/tower-messages.ts +++ b/packages/codev/src/agent-farm/servers/tower-messages.ts @@ -17,7 +17,7 @@ import { stripLeadingZeros, CROSS_TOWER_UNAVAILABLE_MESSAGE, } from '../utils/agent-names.js'; -import { getWorkspaceTerminals } from './tower-terminals.js'; +import { getTerminalManager, getWorkspaceTerminals } from './tower-terminals.js'; import type { WorkspaceTerminals } from './tower-types.js'; import { lookupBuilderSpawningArchitect, @@ -28,7 +28,12 @@ import { } from '../state.js'; import { DEFAULT_ARCHITECT_NAME } from '../utils/architect-name.js'; import { workspaceKey } from '../utils/workspace-path.js'; -import { findWorkspaceByAddressName, isSameWorkspace, printableAddressName } from '../utils/workspace-address.js'; +import { + findWorkspaceByAddressName, + isSameWorkspace, + printableAddressName, + runningWorkspaces, +} from '../utils/workspace-address.js'; import { isAddressComponent, tryFormatAddress } from '@cluesmith/codev-sdk/address'; import type { CrossWorkspaceOrigin, ReplyRoute } from '../utils/message-format.js'; @@ -180,6 +185,26 @@ function canonicalSender(sender: SenderContext): SenderContext { return sender.workspace ? { ...sender, workspace: workspaceKey(sender.workspace) } : sender; } +/** + * The workspaces running on this Tower now ({@link runningWorkspaces}), in the spelling the + * terminal map keys them by. Tower's terminals are those on the map whose session is open: + * it exists and has not exited. The map keeps an exited builder's or shell's id until the + * workspace's next rebuild, so being on the map is not enough. A session whose process + * connection is down still counts while it reconnects: whether it takes input now is a fact + * about the agent, and the send route holds its mail `no-live-pty`. + */ +export function runningWorkspacePaths(): string[] { + const manager = getTerminalManager(); + const isOpen = (terminalId: string) => manager.getSession(terminalId)?.status === 'running'; + const withAnOpenTerminal: string[] = []; + for (const [workspacePath, entry] of getWorkspaceTerminals()) { + if ([entry.architects, entry.builders, entry.shells].some((terminals) => [...terminals.values()].some(isOpen))) { + withAnOpenTerminal.push(workspacePath); + } + } + return runningWorkspaces(withAnOpenTerminal); +} + /** The workspace an address points into, and whether it is the sender's own. */ interface TargetWorkspace { workspacePath: string; @@ -203,11 +228,7 @@ function locateWorkspace(address: AgentAddress, sender: SenderContext): TargetWo if (address.workspace !== undefined) { // The only place the name table is read: an address that names no workspace costs // no query here. - const found = findWorkspaceByAddressName( - address.workspace, - getRegisteredWorkspaces(), - getWorkspaceTerminals().keys(), - ); + const found = findWorkspaceByAddressName(address.workspace, getRegisteredWorkspaces(), runningWorkspacePaths()); if (!found.ok) return { code: found.code, message: found.message }; return { workspacePath: found.workspacePath, @@ -515,9 +536,11 @@ export interface RegistryResolveResult { * between sessions would be refused when it should be held (Spec 1940). * - Any form with a workspace in front — the workspace comes from the same lookup * the live resolver uses ({@link locateWorkspace}), and the agent is held against - * ITS registry. Boundary: that lookup reads the live workspace map, so the target - * workspace must be active (its agent's PTY may be dead); a fully-inactive - * workspace still NOT_FOUNDs, exactly as the live resolver does. + * ITS registry. Boundary: that lookup finds only a running workspace + * ({@link runningWorkspacePaths}), so the target workspace must be running (its + * agent's PTY may be dead); a stopped workspace is refused as not running, exactly + * as the live resolver refuses it, whatever entry the terminal map holds for it + * (Issue #1978). * * A cleaned-up builder (`afx cleanup`) is deleted from global.db too, so it * correctly resolves to NOT_FOUND here — mail is only held for agents that still @@ -690,7 +713,7 @@ export function crossWorkspaceOrigin(sender: MessageSender, recipient: MessageRe const agent = senderAgent(sender.id); if (agent === null) return null; - const named = printableAddressName(sender.workspace, getRegisteredWorkspaces(), getWorkspaceTerminals().keys()); + const named = printableAddressName(sender.workspace, getRegisteredWorkspaces(), runningWorkspacePaths()); if (named.name === null) return { sender: agent, reply: { how: 'no-address' } }; const senderAddress: AgentAddress = { ...agent, workspace: named.name }; // A name that fits the component rule can still have no text form: `architect:` diff --git a/packages/codev/src/agent-farm/servers/tower-routes.ts b/packages/codev/src/agent-farm/servers/tower-routes.ts index 4d807fdf9..04a8c2b39 100644 --- a/packages/codev/src/agent-farm/servers/tower-routes.ts +++ b/packages/codev/src/agent-farm/servers/tower-routes.ts @@ -76,6 +76,7 @@ import { broadcastMessage, isResolveError, crossWorkspaceOrigin, + runningWorkspacePaths, type MessageRecipient, type ResolveError, type ResolveResult, @@ -180,6 +181,7 @@ import { deleteFileTab, getRehydratedTerminalsEntry, isStartupReconcileSettled, + whenStartupReconcileSettled, getTerminalSessionById, getActiveShellLabels, updateTerminalLabel, @@ -981,7 +983,10 @@ async function handleSetWorkspaceAddressName( }); } - const active = [...getWorkspaceTerminals().keys()]; + // Issue #1978: the answer depends on which workspaces are running, which is incomplete + // until the startup reconcile settles (see handleSend). + await whenStartupReconcileSettled(); + const active = runningWorkspacePaths(); const registered = getRegisteredWorkspaces(); if (!registered.some((w) => isSameWorkspace(w.workspacePath, workspacePath))) { return sendJson(res, 404, { @@ -1035,7 +1040,7 @@ async function handleSetWorkspaceAddressName( * are optional. The answer is `tower-address-book.ts`'s; this only reads the query. `from` * is held to the rule `/api/send` holds it to, since it is the same identity. */ -function handleAddressBook(res: http.ServerResponse, url: URL): void { +async function handleAddressBook(res: http.ServerResponse, url: URL): Promise { const from = url.searchParams.get('from') ?? undefined; if (from !== undefined && !isSafeSenderId(from)) { return sendJson(res, 400, { @@ -1046,6 +1051,10 @@ function handleAddressBook(res: http.ServerResponse, url: URL): void { }); } const workspace = url.searchParams.get('workspace') || undefined; + // Issue #1978: right after a restart the terminal map fills as the startup reconcile + // adopts each session, and a workspace whose terminals are still being adopted would be + // listed as not running. The wait is bounded, as it is for the dashboard. + await whenStartupReconcileSettled(); const book: AddressBookResponse = addressBook({ id: from, workspace }); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(book)); @@ -2565,6 +2574,12 @@ async function handleSend( // coming from somewhere the others do not. const frameSender: FrameSender = { id: from, workspace: senderWorkspace }; + // Issue #1978: a workspace counts as running only once Tower holds a terminal for it, and + // right after a restart the startup reconcile is still adopting them (usually well under a + // second). Resolving before it settles would refuse a workspace that is coming back as not + // running, so the send waits for it, bounded as the dashboard's reads are. + await whenStartupReconcileSettled(); + // Spec 1940: the address is read once, here, by the one shared parser, and every path // below resolves the structured form. Text that is not an address is refused before // anything is resolved or stored, with the shape that was expected. diff --git a/packages/codev/src/agent-farm/utils/workspace-address.ts b/packages/codev/src/agent-farm/utils/workspace-address.ts index a83f0e9bc..ae093658f 100644 --- a/packages/codev/src/agent-farm/utils/workspace-address.ts +++ b/packages/codev/src/agent-farm/utils/workspace-address.ts @@ -10,7 +10,8 @@ * * - `registered`: every workspace Tower has a row for, running or not, with its explicit * name (`known_workspaces`). - * - `active`: the paths of the workspaces that are running now (the live terminal map). + * - `active`: the paths of the workspaces that are running now, as {@link runningWorkspaces} + * decides it. * * A running workspace with no row counts as registered and unnamed. */ @@ -37,6 +38,29 @@ function basenameOf(workspacePath: string): string { return path.basename(workspacePath).toLowerCase(); } +/** + * The workspaces that are running (Issue #1978). This is the one definition of "running", + * used by every rule in this module, by Tower's address book and resolvers, and by + * `afx whoami`: a workspace is running while it has at least one terminal. Being registered, + * having been activated, or holding a slot in Tower's terminal map does not make it running. + * Many Tower routes create that slot for any workspace they are asked about, so a slot shows + * only that someone asked. + * + * `terminalWorkspaces` gives, for each terminal, the workspace it belongs to. Tower passes + * its open terminals. `afx whoami`, which runs without Tower, passes the `terminal_sessions` + * rows: Tower writes one when it starts a terminal and deletes it when the terminal ends. + * Each workspace is returned once, in the first spelling given for it, and two spellings of + * one directory are one workspace. + */ +export function runningWorkspaces(terminalWorkspaces: Iterable): string[] { + const byKey = new Map(); + for (const workspacePath of terminalWorkspaces) { + const key = workspaceKey(workspacePath); + if (!byKey.has(key)) byKey.set(key, workspacePath); + } + return [...byKey.values()]; +} + /** A workspace Tower knows: registered, running, or both. */ interface KnownWorkspace { /** The spelling it runs under when it is running (the key of the live terminal map), else its row's. */ diff --git a/packages/codev/src/lib/shipped-skill-hashes.ts b/packages/codev/src/lib/shipped-skill-hashes.ts index 9d25cc1a8..4112c48e6 100644 --- a/packages/codev/src/lib/shipped-skill-hashes.ts +++ b/packages/codev/src/lib/shipped-skill-hashes.ts @@ -30,6 +30,7 @@ export const SHIPPED_SKILL_HASHES: Record = { '5a146541ee4cf6f3f1804b6f0d7ec0c2bdcdb2dcc9443c4243a217e75fce8314', '6667cf41ea594e02fb0a5a5475431af9df521f8bfb4ae99c9fde111f69bf9583', '69af469e4fd5a31a9ce2c4944e4231486072cf33e4e8aaf79451951589f658ea', + '6e071d16d833dc0f7fa8bbe54ab8123ff1913897aa2c17b7848caf0de765264d', '73cec3d46515f181a41d83051c2efc0d38290f709b0b91f52770808f08563c32', '7db196a617386f5eae0e0c4f34338583e1860b04ad846727b59be8ff49a56465', '961c1c892f8cc559df64a7596e39b09053298bc6d10a0e9bf7cd7d017e1d5734', @@ -149,6 +150,7 @@ export const SHIPPED_SKILL_HASHES: Record = { '5a146541ee4cf6f3f1804b6f0d7ec0c2bdcdb2dcc9443c4243a217e75fce8314', '6667cf41ea594e02fb0a5a5475431af9df521f8bfb4ae99c9fde111f69bf9583', '69af469e4fd5a31a9ce2c4944e4231486072cf33e4e8aaf79451951589f658ea', + '6e071d16d833dc0f7fa8bbe54ab8123ff1913897aa2c17b7848caf0de765264d', '73cec3d46515f181a41d83051c2efc0d38290f709b0b91f52770808f08563c32', '7db196a617386f5eae0e0c4f34338583e1860b04ad846727b59be8ff49a56465', '961c1c892f8cc559df64a7596e39b09053298bc6d10a0e9bf7cd7d017e1d5734', diff --git a/packages/types/src/api.ts b/packages/types/src/api.ts index db5f5943e..cb34816b8 100644 --- a/packages/types/src/api.ts +++ b/packages/types/src/api.ts @@ -813,7 +813,10 @@ export interface AddressBookAgent { /** One workspace in the address book: every workspace Tower has registered is listed. */ export interface AddressBookWorkspace { path: string; - /** Whether it is running. A workspace that is not has no agents listed and takes no mail. */ + /** + * Whether it is running: Tower holds at least one open terminal for it (Issue #1978). A + * workspace that is not has no agents listed, and an address that names it is refused. + */ running: boolean; /** The name other workspaces write before the colon; `null` when it has none it can be written by. */ addressName: string | null;