Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(agent-status): a deleted node now stops haunting the notch, the phone and the inbox
enes26e764068a6d
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.tsindex 3d968287b..86aa63772 100644--- a/src/core/agent-status-mirror.test.ts+++ b/src/core/agent-status-mirror.test.ts@@ -1969,3 +1969,136 @@ describe('a restored entry is never proof', () => {expect('restored' in doc.nodes.n1).toBe(false)})})++// `clearNode` had NO production caller, so deleting a node told the live surfaces nothing: the+// notch HUD kept its needs-you/done row until the 6 h prune and the phone's Live Activity for it+// was never ended. It now fires the one end edge those surfaces listen for.+describe('clearNode (permanent node destroy) fires the end edge', () => {+ beforeEach(() => _resetForTest())+ afterEach(() => _resetForTest())++ it('fires ONE end edge for a node deleted mid-turn, carrying its identity', () => {+ const edges: NodeStateChange[] = []+ const off = onNodeStateChange((c) => edges.push(c))+ recordAgentEvent(ev({ nodeId: 'n1', sessionId: 's1', state: 'working', newTurn: true }))+ edges.length = 0++ clearNode('n1')++ expect(edges).toHaveLength(1)+ expect(edges[0]).toMatchObject({+ nodeId: 'n1',+ agentId: 'claude',+ sessionId: 's1',+ event: 'end',+ state: 'done'+ })+ off()+ })++ it('fires the end edge for a node deleted while BLOCKED, and pushes no inbox event', () => {+ const edges: NodeStateChange[] = []+ const off = onNodeStateChange((c) => edges.push(c))+ recordAgentEvent(ev({ nodeId: 'n1', state: 'working', newTurn: true }))+ recordAgentEvent(ev({ nodeId: 'n1', state: 'blocked', lastMessage: 'Approve?' }))+ const feedBefore = _inboxSnapshot().events.length+ edges.length = 0++ clearNode('n1')++ expect(edges).toHaveLength(1)+ expect(edges[0]).toMatchObject({ nodeId: 'n1', event: 'end', state: 'done' })+ // The node is GONE — there is nothing left to read or act on, so no feed card is produced.+ expect(_inboxSnapshot().events).toHaveLength(feedBefore)+ // Its unanswered card is archived rather than dropped (unchanged behavior).+ expect(_inboxSnapshot().events[0].resolved).toBe(true)+ off()+ })++ it('fires NOTHING for an already-done node — the done edge already ended that card', () => {+ recordAgentEvent(ev({ nodeId: 'n1', state: 'working', newTurn: true }))+ recordAgentEvent(ev({ nodeId: 'n1', state: 'done' }))+ const edges: NodeStateChange[] = []+ const off = onNodeStateChange((c) => edges.push(c))++ clearNode('n1')++ expect(edges).toEqual([])+ off()+ })++ it('fires NOTHING for an idle node, or one the mirror never saw', () => {+ const edges: NodeStateChange[] = []+ const off = onNodeStateChange((c) => edges.push(c))+ // A session end resets the node to idle (state undefined) — and fires its own end edge.+ recordAgentEvent(ev({ nodeId: 'n1', state: 'working', newTurn: true }))+ recordAgentEvent(ev({ nodeId: 'n1', kind: 'session', sessionPhase: 'end' }))+ edges.length = 0++ clearNode('n1')+ clearNode('never-seen')++ expect(edges).toEqual([])+ off()+ })+})++// The feed's only bound was INBOX_EVENTS_CAP, so an unresolved approval on a node nobody came back+// to stayed a red "Needs you" card with the tray badge lit forever.+describe('inbox event age prune (flush)', () => {+ let dir: string+ let file: string+ let nowSpy: ReturnType<typeof vi.spyOn>++ beforeEach(() => {+ _resetForTest()+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-status-'))+ file = path.join(dir, 'agent-status.json')+ initAgentStatusMirror(file)+ nowSpy = vi.spyOn(Date, 'now')+ })++ afterEach(() => {+ nowSpy.mockRestore()+ _resetForTest()+ fs.rmSync(dir, { recursive: true, force: true })+ })++ it('drops events older than EXPIRE_MS — unresolved AND resolved alike — on the flush that finds them', async () => {+ nowSpy.mockReturnValue(1_000_000)+ // An UNRESOLVED ask nobody ever answered: the red card + the lit tray badge.+ recordAgentEvent(ev({ nodeId: 'old', state: 'blocked', lastMessage: 'Approve?' }))+ // A RESOLVED done: the phone's archive/history.+ recordAgentEvent(ev({ nodeId: 'arch', state: 'working', newTurn: true }))+ recordAgentEvent(ev({ nodeId: 'arch', state: 'done', lastMessage: 'All done.' }))+ ackDone('arch')+ expect(_inboxSnapshot().events).toHaveLength(2)+ expect(_inboxSnapshot().events[0].resolved).toBeUndefined()+ expect(_inboxSnapshot().events[1].resolved).toBe(true)++ // A fresh ask arrives just past the window on the two above.+ nowSpy.mockReturnValue(1_000_000 + EXPIRE_MS + 1)+ recordAgentEvent(ev({ nodeId: 'new', state: 'blocked', lastMessage: 'Approve me?' }))++ await flush()++ // Both aged kinds are gone from memory; only the fresh card survives.+ expect(_inboxSnapshot().events.map((e) => e.nodeId)).toEqual(['new'])+ // ...and the FILE the phone reads agrees on the SAME flush: `buildFile` passes `inbox` through+ // verbatim, so a prune placed after it would leave the aged card on disk for one more write —+ // and an abandoned node schedules none.+ const doc = JSON.parse(fs.readFileSync(file, 'utf-8'))+ expect(doc.inbox.events.map((e: { nodeId: string }) => e.nodeId)).toEqual(['new'])+ })++ it('keeps an unresolved ask INSIDE the window — a human may still be coming back to answer it', async () => {+ nowSpy.mockReturnValue(1_000_000)+ recordAgentEvent(ev({ nodeId: 'n1', state: 'blocked', lastMessage: 'Approve?' }))++ nowSpy.mockReturnValue(1_000_000 + EXPIRE_MS - 1)+ await flush()++ expect(_inboxSnapshot().events).toHaveLength(1)+ expect(_inboxSnapshot().events[0].resolved).toBeUndefined()+ })+})diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.tsindex d7ece2f6b..30fc19ff2 100644--- a/src/core/agent-status-mirror.ts+++ b/src/core/agent-status-mirror.ts@@ -1493,11 +1493,15 @@ export function recordContextUsage(nodeId: string, percent: number): void {}/**- * Remove a node (call on permanent destroy). Its `nodes` entries (main + inbox activity) drop,- * but its inbox EVENTS stay as feed history — marked resolved so the phone archives them.- * Schedules a write so the file reflects the removal.+ * Remove a node (call on permanent destroy — the `×`/delete path, NOT an unmount, park, offscreen+ * release or detach: those all leave the tmux session running and the node's status live). Its+ * `nodes` entries (main + inbox activity) drop, but its inbox EVENTS stay as feed history — marked+ * resolved so the phone archives them. Schedules a write so the file reflects the removal, and+ * fires ONE end edge when the node was mid-turn (see below).*/export function clearNode(nodeId: string): void {+ // Read BEFORE the delete — the end edge below is decided on the state the node died holding.+ const prev = state.get(nodeId)let changed = state.delete(nodeId)if (inboxNodes.delete(nodeId)) changed = truependingQuestions.delete(nodeId)@@ -1508,6 +1512,30 @@ export function clearNode(nodeId: string): void {changed = true}}+ // A node deleted MID-TURN owes exactly one end edge, for the same reason the session-ended-+ // mid-turn branch in `produceInboxFromState` does: dropping the map entry only makes the mirror+ // FILE forget the node, while every LIVE surface is driven by this seam, not by the file. With+ // no edge, deleting a working/blocked node left the notch HUD holding its needs-you/done row+ // until the 6 h prune — its title collapsing to the literal 'Session' once the entry behind it+ // was gone — and left the phone a Live Activity nothing would ever end.+ //+ // Only when it was actually mid-turn. An already-`done` node fired its own 'end' on the done+ // edge, and an idle one (state undefined — never started, or reset by a session boundary) never+ // opened a card at all; firing here would be a second 'end' for one card.+ //+ // No inbox event, by the same rule the mid-turn branch states: the node is GONE, so a feed card+ // pointing at it is one the user can neither read nor act on. This is a dismissal, not news.+ if (prev?.state && prev.state !== 'done') {+ fireNodeStateChange({+ nodeId,+ ...(prev.agentId ? { agentId: prev.agentId } : {}),+ ...(prev.sessionId ? { sessionId: prev.sessionId } : {}),+ event: 'end',+ state: 'done',+ message: 'Ended',+ ts: Date.now()+ })+ }if (changed) scheduleWrite()}@@ -1662,6 +1690,31 @@ export async function flush(): Promise<void> {const file = resolveFile()if (!file) returnconst now = Date.now()+ // Age out inbox events on the SAME 6 h horizon as the two prunes below, applied to RESOLVED and+ // UNRESOLVED alike. Until this existed the feed's only bound was INBOX_EVENTS_CAP, so an+ // unresolved approval on a node nobody ever came back to stayed a red "Needs you" card with the+ // tray badge lit forever — a node abandoned mid-approval emits nothing further, so neither the+ // state-leave `resolveUnresolvedFor` nor the 50-event cap would ever reach it.+ //+ // One window for both kinds, deliberately:+ // - UNRESOLVED must not get a SHORTER one. An agent can legitimately sit blocked on a human for+ // hours, and this card (with its `pendingId` ticket) is how the phone answers the hook that is+ // still holding open. Cutting it early would trade a stale badge for lost functionality, which+ // is the worse bug.+ // - RESOLVED must not get a LONGER one. It is the phone's archive, but the phone keeps its own+ // copy of what it has read; this file is a live side-channel, not the archive of record, and+ // the cap already bounds history.+ // 6 h is the horizon at which the module stops believing anything about a node at all, so an+ // event outliving `state`/`inboxNodes` would be a card about a node the mirror has forgotten.+ // Well clear of QUESTION_DEDUP_WINDOW_MS (10 min), so the title-dedup is untouched.+ //+ // Pruned BEFORE the doc is built, unlike the two below: `buildFile` applies the expiry to `nodes`+ // itself but passes `inbox` through verbatim, so pruning after it would leave the aged card in+ // the FILE for one more flush — and an abandoned node schedules no further writes, so "one more+ // flush" can be never.+ if (inboxEvents.some((e) => now - e.ts > EXPIRE_MS)) {+ inboxEvents = inboxEvents.filter((e) => now - e.ts <= EXPIRE_MS)+ }const inbox: MirrorInbox = { events: inboxEvents, nodes: Object.fromEntries(inboxNodes) }const doc = buildFile(Object.fromEntries(state), now, undefined, safeSettings(), safeUsage(), inbox, safeServer())// Also drop expired entries from memory so the map itself can't grow without bound.diff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.tsindex 23f08478d..63b18150f 100644--- a/src/core/pty-coattach.test.ts+++ b/src/core/pty-coattach.test.ts@@ -197,6 +197,37 @@ describe('terminal co-attach: one PTY, N subscribers', () => {expect(spawned).toHaveLength(1)})+ // The agent-status mirror feeds the notch HUD, the phone's Live Activity and its Inbox. Deleting+ // a node used to tell it NOTHING — `clearNode` had no production caller — so those surfaces kept+ // rendering a node that no longer exists. It is wired at the one core chokepoint both shells+ // share (`endSession`), and gated on the DELETE intent: a RECYCLE keeps the node, so clearing+ // there would blank a live badge for a node still sitting on the canvas.+ it('a DELETE clears the node from the agent-status mirror; a RECYCLE keeps it', async () => {+ const mirror = await import('./agent-status-mirror')+ mirror._resetForTest()+ try {+ const m = await manager()+ await create(ALICE)+ mirror.recordAgentEvent({+ nodeId: 'node-1',+ agentId: 'claude',+ kind: 'state',+ state: 'working'+ } as never)+ expect(mirror._snapshot()['node-1']).toBeDefined()++ // A worktree move recycles the session; the node lives on, so its status must survive.+ await m.recycleSession(ALICE, 'node-1')+ expect(mirror._snapshot()['node-1']).toBeDefined()++ // The × is permanent — the entry goes with the node.+ await m.destroySession(ALICE, 'node-1')+ expect(mirror._snapshot()['node-1']).toBeUndefined()+ } finally {+ mirror._resetForTest()+ }+ })+it('a relay-served (detached) pty is NOT indexed: it keeps its own session', async () => {const m = await manager()const chunks: string[] = []diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 3da510954..a6eabfdac 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -69,6 +69,7 @@ import {installCodexLauncher} from './codex-identity-proxy'import { ensureNodeToken, ensureRemoteNodeToken, sweepNodeToken } from './agents/node-token-service'+import { clearNode as clearNodeAgentStatus } from './agent-status-mirror'import { hasSharedIdentity, type AgentId } from '../shared/agents/config'// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which@@ -3160,6 +3161,23 @@ export class PtyManager {// after the sweep would close most of it, but it depends on respawn ordering and still leaves a// gap; not sweeping leaves none, and there is nothing stale to clean up.if (intent === 'delete') sweepNodeToken(persistKey)+ // The node's agent-status goes with it — and, like the token, ONLY on a delete: a RECYCLE keeps+ // the node (the worktree move replaces this session, and the respawned agent re-asserts state+ // onto the SAME entry), so clearing there would blank a live badge and end a Live Activity for+ // a node that is still on the canvas.+ //+ // Deleting a node used to tell the mirror nothing at all — `clearNode` had no production caller+ // — so the surfaces the mirror feeds kept rendering a node that no longer exists: the notch HUD+ // held its needs-you/done row until the 6 h prune (its title collapsing to the literal+ // 'Session' once the entry behind it aged out), the phone's Inbox cards for it were never+ // resolved, and its Live Activity was never ended.+ //+ // Wired HERE rather than in each shell's `pty:destroy` listener because this is the one core+ // chokepoint every permanent delete funnels through (wire handler → endFromClient → endSession,+ // plus the internal `destroySession`), and both shells register it via `registerIpc()`. The+ // shells' own listeners are the wrong seam twice over: they are registered for `pty:recycle`+ // too, and there are two of them to keep in step.+ if (intent === 'delete') clearNodeAgentStatus(persistKey)if (sshRemote) {// Remote (ssh-project) node: end the REMOTE session.const ssh = findSsh()