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
feat(restart): terminal nodes register their in-place restart closure
enes1b21816849c2
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 70bccbec0..dc3df1fb0 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -50,7 +50,13 @@ import {type SessionLife} from '../terminal/terminal-config'import { loseWebglContexts, registerWebglClient, type WebglClientHandle } from '../terminal/webgl-budget'-import { deliverCommand } from '../terminal/command-delivery'+import { deliverCommand, type DeliveryIo } from '../terminal/command-delivery'+import {+ guardConcurrentRestart,+ performRestartResume,+ registerAgentRestart,+ restartEligibility+} from '../terminal/agent-restart'import { FindBar } from '../components/FindBar'import { IconSearch, IconChat, IconMic } from '../components/icons'import { NodeTags } from '../components/NodeTags'@@ -1171,6 +1177,54 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN})})()+ // In-place agent restart (Canvas node menu / bulk palette): ask the CLI to quit, wait until a+ // shell owns the pane again, then relaunch it with the provider's own `--resume` — so a newly+ // released model shows up in the CLI's model list without losing the conversation.+ //+ // Registered HERE, in the effect body, not in the spawn continuation above: an ADOPTED terminal+ // (park → remount) returns from that continuation immediately and never reaches it, yet its+ // agent is just as restartable. The effect body runs on every mount, fresh or adopted.+ //+ // Everything the closure needs is read at CALL time. The provider session id and the agent+ // state arrive asynchronously over the agent-status hooks — usually well after mount — and+ // `sessionId` (this effect's PTY session) is still null while `create()` is in flight.+ const restartIo: DeliveryIo = {+ // The SAME write path the cold-restore delivery above uses, gated on the session's own+ // lifetime: a delivery still running when this session is torn down must neither write into+ // nor subscribe to a dead transport. A PARK deliberately does not trip `life.dead` — the PTY+ // is alive and adoptable, so a restart that began before the unmount still lands in its pane.+ write: (d) => {+ if (sessionId && !life.dead) transport.write(sessionId, d)+ },+ onData: (cb) => (sessionId && !life.dead ? transport.onData(sessionId, cb) : () => {})+ }+ const unregisterRestart = registerAgentRestart(+ id,+ guardConcurrentRestart(id, async () => {+ const st = useAgentStatus.getState().byId[id]+ const agentSessionId = st?.sessionId+ const gate = restartEligibility(agentId, st?.state, agentSessionId)+ // No live PTY session (spawn still in flight, or the node is closed/ended) means there is+ // no pane to restart in — the same "nothing to do here" the gate reports.+ if (!gate.ok || !agentId || !agentSessionId || !sessionId || life.dead) return 'not-eligible'+ return performRestartResume({+ agentId,+ sessionId: agentSessionId,+ io: restartIo,+ // Session-scoped (`api`, not the global preload), like readScrollback above: a relay+ // tab's pane lives on the host, and only its own api can see it.+ paneCommand: () => api.pty.paneCommand(id),+ // The delivery outlives this promise (echo-verify timers), so hand its lifetime to the+ // session: a real teardown runs `cleanups`, and a session that died while we waited for+ // the shell cancels it outright rather than parking a timer on a corpse.+ onDelivery: (cancel) => {+ if (life.dead) cancel()+ else cleanups.push(cancel)+ }+ })+ })+ )+// Coalesce observer bursts: dragging the NodeResizer fires per animation frame, and every// call is a full cell-geometry measure + a resize IPC → node-pty → tmux (which redraws the// whole pane). One trailing fit per settle is enough — the canvas node frame itself still@@ -1207,6 +1261,9 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNreturn () => {disposed = true+ // Nothing may restart a node that is no longer mounted — park, respawn and real teardown all+ // pass through here. A remount re-registers (superseding, so a stale unregister is inert).+ unregisterRestart()observer.disconnect()visibilityObserver.disconnect()if (resizeTimer) clearTimeout(resizeTimer)diff --git a/src/renderer/terminal/agent-restart.test.ts b/src/renderer/terminal/agent-restart.test.tsindex 9e5bacaa6..ffebc468d 100644--- a/src/renderer/terminal/agent-restart.test.ts+++ b/src/renderer/terminal/agent-restart.test.ts@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import {agentRestartFn,exitSequence,+ guardConcurrentRestart,isShellCommand,performRestartResume,registerAgentRestart,@@ -153,6 +154,89 @@ describe('performRestartResume', () => {).toBe('not-eligible')expect(written).toEqual([]) // quitting a CLI we cannot resume would just lose the session})++ it('hands the delivery cancel to the caller, which stops it writing (node teardown)', async () => {+ // An io that never echoes back: the delivery stays alive on its verify timer, exactly the+ // window in which a node can unmount under it.+ const written: string[] = []+ const io = { write: (d: string) => written.push(d), onData: () => () => {} }+ let cancel: (() => void) | undefined+ const p = performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ paneCommand: async () => 'zsh',+ timeoutMs: 1000,+ pollMs: 100,+ onDelivery: (c) => {+ cancel = c+ }+ })+ await vi.advanceTimersByTimeAsync(200)+ expect(await p).toBe('restarted')+ expect(typeof cancel).toBe('function')+ const delivered = written.length+ cancel?.()+ await vi.advanceTimersByTimeAsync(30_000)+ // No rewrite retries, no fail-open submit: nothing more reaches the torn-down transport.+ expect(written.length).toBe(delivered)+ })++ it('hands out no cancel when nothing was delivered', async () => {+ const { io } = fakeIo()+ const handles: Array<() => void> = []+ const p = performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ paneCommand: async () => 'claude',+ timeoutMs: 1000,+ pollMs: 100,+ onDelivery: (c) => handles.push(c)+ })+ await vi.advanceTimersByTimeAsync(2000)+ expect(await p).toBe('exit-timeout')+ expect(handles).toEqual([])+ })+})++describe('guardConcurrentRestart', () => {+ it('refuses a second call while one is in flight, without running it twice', async () => {+ let runs = 0+ let release: (o: RestartOutcome) => void = () => {}+ const guarded = guardConcurrentRestart('n1', () => {+ runs += 1+ return new Promise<RestartOutcome>((r) => (release = r))+ })+ const first = guarded()+ expect(await guarded()).toBe('not-eligible') // menu + bulk hitting one node+ expect(runs).toBe(1)+ release('restarted')+ expect(await first).toBe('restarted')+ const second = guarded() // guard released once the run settled+ expect(runs).toBe(2)+ release('exit-timeout')+ expect(await second).toBe('exit-timeout')+ })++ it('guards per node, not globally', async () => {+ const pending = (): Promise<RestartOutcome> => new Promise(() => {})+ const a = guardConcurrentRestart('n1', pending)+ const b = guardConcurrentRestart('n2', async () => 'restarted')+ void a()+ expect(await b()).toBe('restarted')+ })++ it('releases the guard when the run throws', async () => {+ let runs = 0+ const guarded = guardConcurrentRestart('n3', async () => {+ runs += 1+ throw new Error('ipc died')+ })+ await expect(guarded()).rejects.toThrow('ipc died')+ await expect(guarded()).rejects.toThrow('ipc died')+ expect(runs).toBe(2)+ })})describe('agent restart registry', () => {diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.tsindex 13e5b7ce0..626e2f520 100644--- a/src/renderer/terminal/agent-restart.ts+++ b/src/renderer/terminal/agent-restart.ts@@ -70,6 +70,13 @@ export async function performRestartResume(d: {paneCommand: () => Promise<string | null>timeoutMs?: numberpollMs?: number+ /**+ * Handed `deliverCommand`'s cancel the moment a delivery starts — and only then. The delivery+ * outlives this promise (it runs on its own echo-verify timers), so its lifetime belongs to+ * whoever owns the transport: a node torn down mid-restart cancels it here instead of letting+ * a retry rewrite, or the fail-open submit, land in a dead session.+ */+ onDelivery?: (cancel: () => void) => void}): Promise<RestartOutcome> {const exit = exitSequence(d.agentId)const cmd = resumeCommand(d.agentId, d.sessionId)@@ -102,10 +109,43 @@ export async function performRestartResume(d: {if (isShellCommand(pane)) breakif (Date.now() > deadline) return 'exit-timeout'}- deliverCommand(d.io, cmd)+ // Two statements on purpose: `d.onDelivery?.(deliverCommand(…))` short-circuits the ARGUMENT+ // too when no callback was passed, which would deliver nothing at all.+ const cancelDelivery = deliverCommand(d.io, cmd)+ d.onDelivery?.(cancelDelivery)return 'restarted'}+// ── One restart at a time, per node ──────────────────────────────────────────────────────+const inFlight = new Set<string>()++/**+ * Serialize a node's restarts. The per-node menu action and the bulk palette action can both+ * reach the same node, and two runs against one pane would write two `/exit` lines (the second+ * typed INTO the CLI the first is resuming) and two resume commands.+ *+ * The refused call reports `'not-eligible'` deliberately: the run already in flight owns this+ * node's outcome and will report it, and `'not-eligible'` is the one outcome `summarizeOutcomes`+ * does not count — so a doubled request is neither counted twice as restarted nor reported as a+ * failure the user could act on. (The alternative, a fifth outcome, would break that frozen line.)+ */+export function guardConcurrentRestart(+ nodeId: string,+ fn: () => Promise<RestartOutcome>+): () => Promise<RestartOutcome> {+ return async () => {+ if (inFlight.has(nodeId)) return 'not-eligible'+ inFlight.add(nodeId)+ try {+ return await fn()+ } finally {+ // Released on rejection too: a transport that threw once must not leave the node+ // permanently un-restartable for the rest of the app's run.+ inFlight.delete(nodeId)+ }+ }+}+// ── Node registry (same park-surviving pattern as TerminalNode's restartSubs) ────────────const restartFns = new Map<string, () => Promise<RestartOutcome>>()