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(subagents): replay running lifecycle cards after renderer reload
reviewd1c1f56de492
diff --git a/CLAUDE.md b/CLAUDE.mdindex d2fb92d7f..b3d6908df 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4697,3 +4697,14 @@ Remote cache entries requested in this run are retained until exit, including cawaits are coordinated with a concurrent cache reader. The 20-entry cap is soft for retained files,so disk use may grow in a long run; prior-run entries are eligible again after restart. `mediaRange`handles suffix ranges and rejects unsatisfiable ones without weakening the serve-time path jail.++## Subagent reload replay (#680)++`core/subagent-replay.ts` retains at most 512 running starts for the existing WORKING_STALE_MS,+with original host timestamps. The shared mirror event path feeds it (including synthetic async+ends); session boundaries and clearNode discard it. Both shells expose the same read, and desktop+preload / browser / relay subscribe before requesting it. Only lifecycle events wait behind the+snapshot (bounded to 512 events / 3 seconds); live permission alerts are not delayed or replayed.+No disk restore, transcript backlog, completed-card replay, or authorization evidence is provided.+A host restart or a missed original start is still outside this recovery.+diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex aee2f2fea..8554e809f 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -693,3 +693,5 @@ who never saw it.- Media URLs live for the app run. Remote cache pruning must keep files already handed toplayers; the cache cap is soft until restart. Use the existing `video` node for audio too.+- Subagent reload replay is display-only and current-host-only. Never replay status/permission+ events or treat a replayed card as verified process ownership; subscribe before taking its snapshot.diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.tsindex c052e9c38..2c0b6c922 100644--- a/src/core/agent-status-mirror.ts+++ b/src/core/agent-status-mirror.ts@@ -1,3 +1,4 @@+import { subagentReplay } from './subagent-replay'import fs from 'fs'import path from 'path'import { writeFileAtomic } from './fs-atomic'@@ -1396,6 +1397,7 @@ interface NeedsYouClassification {*/export function recordAgentEvent(rawEvent: NormalizedAgentEvent): NormalizedAgentEvent {if (!rawEvent?.nodeId) return rawEvent+ subagentReplay.record(rawEvent)const ev = resolveGrokStopCancelled(rawEvent)const nodeId = ev.nodeIdconst now = Date.now()@@ -1719,6 +1721,7 @@ export function recordContextUsage(nodeId: string, percent: number): void {* fires ONE end edge when the node was mid-turn (see below).*/export function clearNode(nodeId: string): void {+ subagentReplay.clearParent(nodeId)// 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)@@ -1990,6 +1993,7 @@ export async function flush(): Promise<void> {/** Reset all module state (in-memory map + config + listeners + inbox). Test-only. */export function _resetForTest(): void {+ subagentReplay.clear()state.clear()if (sweepTimer) clearInterval(sweepTimer)sweepTimer = nulldiff --git a/src/core/subagent-replay.test.ts b/src/core/subagent-replay.test.tsnew file mode 100644index 000000000..a93a0a0f3--- /dev/null+++ b/src/core/subagent-replay.test.ts@@ -0,0 +1,47 @@+import { afterEach, describe, expect, it } from 'vitest'+import { SubagentReplay, subagentReplay } from './subagent-replay'+import { recordAgentEvent, clearNode, _resetForTest } from './agent-status-mirror'+import { WORKING_STALE_MS } from '../shared/agents/stale'+import type { NormalizedAgentEvent } from '../shared/agents/normalize'+const start: NormalizedAgentEvent = { kind: 'subagent-start', agentId: 'claude', nodeId: 'p', toolUseId: 'child', taskLabel: 'task' }+afterEach(_resetForTest)+describe('subagent reload memory', () => {+ it('restores a running card across turns, with its original time and no authority fields', () => {+ const replay = new SubagentReplay()+ replay.record({ ...start, verified: true, pendingId: 'secret', sessionId: 's' }, 100)+ replay.record({ ...start, kind: 'state', state: 'working', newTurn: true }, 200)+ replay.record(start, 300)+ expect(replay.snapshot(400)).toEqual([{ ...start, subagentType: undefined, subagentStartedAt: 100 }])+ replay.record({ ...start, kind: 'session', sessionTitle: 'renamed' }, 500)+ expect(replay.snapshot(500)).toHaveLength(1)+ })+ it('ends, session boundaries and deletes clear only the intended parent', () => {+ const replay = new SubagentReplay()+ replay.record(start, 100)+ replay.record({ ...start, nodeId: 'other' }, 100)+ replay.record({ ...start, kind: 'subagent-end' }, 200)+ expect(replay.snapshot(200).map((e) => e.nodeId)).toEqual(['other'])+ replay.record({ ...start, nodeId: 'other', kind: 'session', sessionPhase: 'end' }, 300)+ expect(replay.snapshot(300)).toEqual([])+ replay.record(start, 400)+ replay.clearParent('p')+ expect(replay.snapshot(400)).toEqual([])+ })+ it('bounds memory, expires stale work and refuses future-dated starts after clock rollback', () => {+ const replay = new SubagentReplay(2)+ for (const toolUseId of ['a', 'b', 'c']) replay.record({ ...start, toolUseId }, 100)+ expect(replay.snapshot(100).map((e) => e.toolUseId)).toEqual(['b', 'c'])+ expect(replay.snapshot(100 + WORKING_STALE_MS)).toEqual([])+ replay.record(start, 500)+ expect(replay.snapshot(499)).toEqual([])+ })+ it('the shared mirror path records starts and synthetic ends; node deletion clears replay', () => {+ recordAgentEvent(start)+ expect(subagentReplay.snapshot()).toHaveLength(1)+ recordAgentEvent({ ...start, kind: 'subagent-end' })+ expect(subagentReplay.snapshot()).toEqual([])+ recordAgentEvent(start)+ clearNode('p')+ expect(subagentReplay.snapshot()).toEqual([])+ })+})diff --git a/src/core/subagent-replay.ts b/src/core/subagent-replay.tsnew file mode 100644index 000000000..3c82fc400--- /dev/null+++ b/src/core/subagent-replay.ts@@ -0,0 +1,45 @@+import type { NormalizedAgentEvent } from '../shared/agents/normalize'+import { WORKING_STALE_MS } from '../shared/agents/stale'++/** Current-host, display-only lifecycle memory. Never persisted or used as permission evidence.+ * Replays only running starts: old approvals, turn completions and alerts must not fire again. */+export class SubagentReplay {+ private readonly starts = new Map<string, NormalizedAgentEvent>()+ constructor(private readonly limit = 512) {}++ record(event: NormalizedAgentEvent, now = Date.now()): void {+ this.prune(now)+ if (event.kind === 'session' && event.sessionPhase) {+ this.clearParent(event.nodeId)+ } else if (event.kind === 'subagent-end' && event.toolUseId) {+ this.starts.delete(this.key(event))+ } else if (event.kind === 'subagent-start' && event.toolUseId) {+ const key = this.key(event)+ if (!this.starts.has(key)) {+ // Copy just the display fields. In particular, a replay never carries verified identity.+ this.starts.set(key, {+ kind: 'subagent-start', nodeId: event.nodeId, agentId: event.agentId,+ toolUseId: event.toolUseId, subagentType: event.subagentType,+ taskLabel: event.taskLabel?.slice(0, 4000), subagentStartedAt: now+ })+ }+ while (this.starts.size > this.limit) this.starts.delete(this.starts.keys().next().value!)+ }+ }++ snapshot(now = Date.now()): NormalizedAgentEvent[] {+ this.prune(now)+ return [...this.starts.values()].map((e) => ({ ...e }))+ }+ clearParent(nodeId: string): void {+ for (const [key, e] of this.starts) if (e.nodeId === nodeId) this.starts.delete(key)+ }+ clear(): void { this.starts.clear() }+ private key(e: NormalizedAgentEvent): string { return JSON.stringify([e.nodeId, e.toolUseId]) }+ private prune(now: number): void {+ for (const [key, e] of this.starts) {+ if (now - e.subagentStartedAt! >= WORKING_STALE_MS || now < e.subagentStartedAt!) this.starts.delete(key)+ }+ }+}+export const subagentReplay = new SubagentReplay()diff --git a/src/main/index.ts b/src/main/index.tsindex 6e451993a..626c9f83f 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,3 +1,4 @@+import { subagentReplay } from '../core/subagent-replay'import { grokHomeDir, grokSessionDir, grokSessionsDir } from '../core/agents/grok-paths'import { join, resolve, posix } from 'path'import { startSessionNameSweep, displayNodeTitle } from '../core/session-name-sweep'@@ -2770,6 +2771,7 @@ app.whenReady().then(async () => {// just-read node's latest state is `done`. The mirror resolves the node's done inbox event(s)// (phone Inbox archives the card) and re-sends an 'end' live-update so the paired phone dismisses// its lingering DONE Live Activity. Fire-and-forget; the mirror no-ops with no unresolved done.+ corePlatform.handle(IPC.agentSubagentSnapshot, () => subagentReplay.snapshot())corePlatform.handle(IPC.agentAckDone, (nodeId: string) => {ackDone(nodeId)})diff --git a/src/preload/index.ts b/src/preload/index.tsindex ce50c6fd6..9dcfb5c5a 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -1,3 +1,4 @@+import { subscribeAgentReplay } from '../shared/agent-replay-subscription'import { contextBridge, ipcRenderer, webFrame, webUtils } from 'electron'import { IPC } from '../shared/ipc'import { resolveUiScale } from '../shared/ui-scale'@@ -776,11 +777,11 @@ const api: NodeTerminalApi = {ipcRenderer.on(IPC.agentUnreadClear, handler)return () => ipcRenderer.removeListener(IPC.agentUnreadClear, handler)},- onAgentStatus: (listener) => {- const handler = (_e: unknown, payload: Parameters<typeof listener>[0]) => listener(payload)+ onAgentStatus: (listener) => subscribeAgentReplay((cb) => {+ const handler = (_e: unknown, payload: Parameters<typeof listener>[0]) => cb(payload)ipcRenderer.on(IPC.agentStatus, handler)return () => ipcRenderer.removeListener(IPC.agentStatus, handler)- },+ }, () => ipcRenderer.invoke(IPC.agentSubagentSnapshot), listener),reportHibernated: (nodeId, on) => ipcRenderer.send(IPC.agentHibernated, { nodeId, on }),onAgentWake: (listener) => {const handler = (_e: unknown, nodeId: string) => listener(nodeId)diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex bc8a799ea..c381ebeef 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -1,3 +1,5 @@+import type { NormalizedAgentEvent } from '../../shared/agents/normalize'+import { subscribeAgentReplay } from '../../shared/agent-replay-subscription'// WebSocket bridge that reconstructs `window.nodeTerminal` in the browser (Server Edition).//// Under Electron the preload already defines `window.nodeTerminal`; this module only runs when@@ -666,7 +668,10 @@ export function buildAgentApi(| 'onAgentRenameNode'> {return {- onAgentStatus: (listener) => client.subscribe(IPC.agentStatus, listener as Listener),+ onAgentStatus: (listener) => subscribeAgentReplay(+ (cb) => client.subscribe(IPC.agentStatus, cb as Listener),+ () => client.request(IPC.agentSubagentSnapshot) as Promise<NormalizedAgentEvent[]>, listener+ ),// REAL forward: the Server Edition writes its own agent-status mirror, and the phone reads it// over its SSH browse path — a browser canvas hibernating a node must reach that file too.reportHibernated: (nodeId, on) => {diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex e42c67407..d31364c8f 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -12989,7 +12989,8 @@ export function Canvas() {an.start(e.toolUseId, {parentNodeId: e.nodeId,type: e.subagentType,- label: e.taskLabel+ label: e.taskLabel,+ startedAt: e.subagentStartedAt})}breakdiff --git a/src/renderer/state/agentNodes.ts b/src/renderer/state/agentNodes.tsindex c441401ba..0cb3997f3 100644--- a/src/renderer/state/agentNodes.ts+++ b/src/renderer/state/agentNodes.ts@@ -85,7 +85,7 @@ interface AgentNodesState {toggleExpanded(id: string): void/** Drop a card's dragged position + resized size, returning it to its laid-out spot. */resetPlacement(id: string): void- start(toolUseId: string, viz: Omit<SubagentViz, 'state' | 'startedAt'>): void+ start(toolUseId: string, viz: Omit<SubagentViz, 'state' | 'startedAt'> & { startedAt?: number }): voidfinish(toolUseId: string, result: SubagentResult): void/** Append a chunk of the subagent's live transcript. */appendActivity(toolUseId: string, chunk: string): void@@ -258,7 +258,7 @@ export const useAgentNodes = create<AgentNodesState>((set) => ({start: (toolUseId, viz) =>set((s) => ({- byId: { ...s.byId, [toolUseId]: { ...viz, state: 'working', startedAt: Date.now() } }+ byId: { ...s.byId, [toolUseId]: { ...viz, state: 'working', startedAt: viz.startedAt ?? s.byId[toolUseId]?.startedAt ?? Date.now() } }})),finish: (toolUseId, result) =>diff --git a/src/renderer/state/agentNodes.turn-boundary.test.ts b/src/renderer/state/agentNodes.turn-boundary.test.tsindex 1d3df2365..4763dba14 100644--- a/src/renderer/state/agentNodes.turn-boundary.test.ts+++ b/src/renderer/state/agentNodes.turn-boundary.test.ts@@ -281,3 +281,11 @@ describe('Eco still sees the live subagent after a new turn (issue #547)', () =>expect(candidates()[0].liveSubagents).toBe(false)})})++it('replayed starts retain host timing when a buffered live duplicate follows', () => {+ const store = useAgentNodes.getState()+ store.start('reload-child', { parentNodeId: 'reload-parent', startedAt: 123 })+ store.start('reload-child', { parentNodeId: 'reload-parent' })+ expect(useAgentNodes.getState().byId['reload-child'].startedAt).toBe(123)+ store.clearForParent('reload-parent')+})diff --git a/src/server/index.ts b/src/server/index.tsindex 15ead1c4b..ca53cc0b6 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -1,3 +1,4 @@+import { subagentReplay } from '../core/subagent-replay'import fs from 'fs'import { readAgentSessionName } from '../core/agent-session-name'import { startSessionNameSweep, displayNodeTitle } from '../core/session-name-sweep'@@ -530,6 +531,7 @@ export async function startServer(// calls it when the just-read node's latest state is `done`. The mirror resolves the node's done// inbox event(s) + re-sends an 'end' live-update so the paired phone dismisses its lingering DONE// Live Activity. Fire-and-forget; no-op with no unresolved done.+ platform.handle(IPC.agentSubagentSnapshot, () => subagentReplay.snapshot())platform.handle(IPC.agentAckDone, (nodeId: string) => {ackDone(nodeId)})diff --git a/src/shared/agent-replay-subscription.test.ts b/src/shared/agent-replay-subscription.test.tsnew file mode 100644index 000000000..137328bde--- /dev/null+++ b/src/shared/agent-replay-subscription.test.ts@@ -0,0 +1,46 @@+import { afterEach, expect, it, vi } from 'vitest'+import { subscribeAgentReplay } from './agent-replay-subscription'+import type { NormalizedAgentEvent } from './agents/normalize'+const start: NormalizedAgentEvent = { kind: 'subagent-start', agentId: 'claude', nodeId: 'p', toolUseId: 'child', subagentStartedAt: 10 }+function harness() {+ let push!: (e: NormalizedAgentEvent) => void+ let resolve!: (es: NormalizedAgentEvent[]) => void+ let reject!: (e: Error) => void+ const unsub = vi.fn()+ const seen: NormalizedAgentEvent[] = []+ const snapshot = new Promise<NormalizedAgentEvent[]>((a, b) => { resolve = a; reject = b })+ const dispose = subscribeAgentReplay((cb) => { push = cb; return unsub }, () => snapshot, (e) => seen.push(e))+ return { push, resolve, reject, seen, dispose, unsub }+}+afterEach(() => vi.useRealTimers())+it('subscribes before snapshot and drains an end after replay; does not replay alerts', async () => {+ const h = harness()+ const end = { ...start, kind: 'subagent-end' as const }+ const alert = { ...start, kind: 'state' as const, state: 'blocked' as const }+ h.push(end); h.push(alert)+ expect(h.seen).toEqual([alert])+ h.resolve([start, alert])+ await new Promise((r) => setTimeout(r, 0))+ expect(h.seen).toEqual([alert, start, end])+ h.dispose()+})+it('failure still delivers queued and later live events', async () => {+ const h = harness(); h.push(start); h.reject(new Error('old host'))+ await new Promise((r) => setTimeout(r, 0))+ h.push({ ...start, kind: 'subagent-end' })+ expect(h.seen.map((e) => e.kind)).toEqual(['subagent-start', 'subagent-end'])+ h.dispose()+})+it('disposal cancels replay and unsubscribes', async () => {+ const h = harness(); h.push(start); h.dispose(); h.resolve([start])+ await new Promise((r) => setTimeout(r, 0))+ expect(h.seen).toEqual([]); expect(h.unsub).toHaveBeenCalledOnce()+})+it('timeout abandons a late snapshot instead of resurrecting ended work', async () => {+ vi.useFakeTimers()+ const h = harness(); h.push({ ...start, kind: 'subagent-end' })+ await vi.advanceTimersByTimeAsync(3000)+ h.resolve([start]); await vi.runAllTimersAsync()+ expect(h.seen.map((e) => e.kind)).toEqual(['subagent-end'])+ h.dispose()+})diff --git a/src/shared/agent-replay-subscription.ts b/src/shared/agent-replay-subscription.tsnew file mode 100644index 000000000..162eed52a--- /dev/null+++ b/src/shared/agent-replay-subscription.ts@@ -0,0 +1,33 @@+import type { NormalizedAgentEvent } from './agents/normalize'++/** Subscribe first, then replay the snapshot before live events received during the request.+ * Buffer ONLY lifecycle events: alerts/input requests still arrive immediately. A failed or+ * old host must not disable live delivery. Disposal cancels the outstanding replay. */+export function subscribeAgentReplay(+ subscribe: (cb: (e: NormalizedAgentEvent) => void) => () => void,+ snapshot: () => Promise<NormalizedAgentEvent[]>,+ listener: (e: NormalizedAgentEvent) => void+): () => void {+ let waiting = true+ let disposed = false+ const pending: NormalizedAgentEvent[] = []+ const flush = (): void => {+ waiting = false+ if (!disposed) for (const e of pending) listener(e)+ pending.length = 0+ }+ const unsub = subscribe((e) => {+ if (pending.length >= 512) flush()+ if (waiting && (e.kind === 'subagent-start' || e.kind === 'subagent-end' || e.kind === 'session')) pending.push(e)+ else listener(e)+ })+ // Bound both the wait and retained queue on an unresponsive/older host.+ const timer = setTimeout(flush, 3000)+ void Promise.resolve().then(snapshot).then((events) => {+ if (disposed || !waiting) return+ if (Array.isArray(events)) for (const e of events) {+ if (e.kind === 'subagent-start') listener(e)+ }+ }).catch(() => {}).finally(() => { clearTimeout(timer); flush() })+ return () => { disposed = true; pending.length = 0; clearTimeout(timer); unsub() }+}diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.tsindex 2d3374ee7..620bdfd53 100644--- a/src/shared/agents/normalize.ts+++ b/src/shared/agents/normalize.ts@@ -73,6 +73,8 @@ export interface NormalizedAgentEvent {// subagenttoolUseId?: stringsubagentType?: string+ /** Host-observed start time for display-only renderer reload replay. */+ subagentStartedAt?: number// grok StopCancelled only: normalized state-less so the mirror can make the session-aware badge// decision (a subagent cancellation must not end its parent session).cancelReason?:diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 5854e1dec..a448a2510 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -155,6 +155,7 @@ export const IPC = {* Edition's browser tab has no raw input stream and keeps the heuristics. */canvasTrackpadGesture: 'canvas:trackpad-gesture',agentStatus: 'agent:status',+ agentSubagentSnapshot: 'agent:subagent-snapshot',/** Renderer → main/server: answer a held Claude permission hook (deterministic approvals).* Payload: `{ nodeId, pendingId, decision: 'allow'|'deny' }`; resolves boolean. See* docs/hook-reply-approvals.md. */