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(restart): hold the node until the resume line has left the pane
enes5e2c9467a33f
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex dc3df1fb0..19268938d 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -1198,15 +1198,22 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN},onData: (cb) => (sessionId && !life.dead ? transport.onData(sessionId, cb) : () => {})}+ // Is there still a pane to restart in? A spawn in flight has no session yet; a real teardown+ // flips `life.dead`; and a session another client DESTROYED (or one recycled with no+ // replacement) is gone while this component happily stays mounted showing the overlay — the+ // same states the park branch in the cleanup below refuses to park. Writing `/exit` into any of+ // them reaches nothing and would be reported as a 6-second "failed (exit timeout)".+ const restartTarget = (): boolean => {+ const coNow = getCo(termKey)+ return !!sessionId && !life.dead && !coNow.closed && !coNow.ended+ }const unregisterRestart = registerAgentRestart(id,guardConcurrentRestart(id, async () => {const st = useAgentStatus.getState().byId[id]const agentSessionId = st?.sessionIdconst 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'+ if (!gate.ok || !agentId || !agentSessionId || !restartTarget()) return 'not-eligible'return performRestartResume({agentId,sessionId: agentSessionId,@@ -1214,9 +1221,12 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN// 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.+ // Re-asked on every poll: a session that dies under the restart reports honestly instead+ // of counting a phantom, and stops polling a pane that no longer exists.+ isLive: restartTarget,+ // The delivery has its own (echo-verify) lifetime, so hand it 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)diff --git a/src/renderer/terminal/agent-restart.test.ts b/src/renderer/terminal/agent-restart.test.tsindex ffebc468d..27ed78377 100644--- a/src/renderer/terminal/agent-restart.test.ts+++ b/src/renderer/terminal/agent-restart.test.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import {+ __resetAgentRestartForTests,agentRestartFn,exitSequence,guardConcurrentRestart,@@ -77,6 +78,24 @@ function fakeIo() {}}+/** An io the shell never echoes back: deliverCommand cannot verify the line, so it sits+ * un-submitted in the pane for its whole retry window — the state a second restart must never+ * write into. */+function silentIo() {+ const written: string[] = []+ return {+ written,+ io: {+ write(d: string) {+ written.push(d)+ },+ onData() {+ return () => {}+ }+ }+ }+}+describe('performRestartResume', () => {beforeEach(() => vi.useFakeTimers())afterEach(() => vi.useRealTimers())@@ -156,10 +175,7 @@ describe('performRestartResume', () => {})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: () => () => {} }+ const { written, io } = silentIo()let cancel: (() => void) | undefinedconst p = performRestartResume({agentId: 'claude',@@ -173,15 +189,70 @@ describe('performRestartResume', () => {}})await vi.advanceTimersByTimeAsync(200)- expect(await p).toBe('restarted')- expect(typeof cancel).toBe('function')+ expect(typeof cancel).toBe('function') // handed out as the delivery STARTS, not when it endsconst delivered = written.lengthcancel?.()+ expect(await p).toBe('restarted') // cancelling settles the delivery, and with it the restartawait vi.advanceTimersByTimeAsync(30_000)// No rewrite retries, no fail-open submit: nothing more reaches the torn-down transport.expect(written.length).toBe(delivered)})+ it('resolves only once the resume line has left the pane', async () => {+ const { io } = silentIo()+ let settled = false+ const p = performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ paneCommand: async () => 'zsh',+ timeoutMs: 1000,+ pollMs: 100+ }).then((o) => {+ settled = true+ return o+ })+ await vi.advanceTimersByTimeAsync(200)+ expect(settled).toBe(false) // written, but still un-submitted through the verify retries+ await vi.advanceTimersByTimeAsync(10_000) // the last attempt submits fail-open+ expect(await p).toBe('restarted')+ })++ it('writes nothing when the session is already gone', async () => {+ const { written, io } = fakeIo()+ expect(+ await performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ paneCommand: async () => 'zsh',+ isLive: () => false+ })+ ).toBe('not-eligible')+ expect(written).toEqual([])+ })++ it('reports no restart when the session dies while we wait for the shell', async () => {+ const { written, io } = fakeIo()+ let live = true+ const p = performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ paneCommand: async () => 'claude',+ timeoutMs: 5000,+ pollMs: 100,+ isLive: () => live+ })+ await vi.advanceTimersByTimeAsync(150)+ live = false // the node was deleted / its tmux session destroyed under us+ await vi.advanceTimersByTimeAsync(200)+ // Not 'exit-timeout': nothing timed out, the pane simply stopped existing — and not+ // 'restarted', which would put a phantom in the bulk summary.+ expect(await p).toBe('not-eligible')+ expect(written.join('')).not.toContain('--resume')+ })+it('hands out no cancel when nothing was delivered', async () => {const { io } = fakeIo()const handles: Array<() => void> = []@@ -201,6 +272,41 @@ describe('performRestartResume', () => {})describe('guardConcurrentRestart', () => {+ // The in-flight set is module-global: a test that leaves a restart running would otherwise+ // refuse the next test's restart of the same node id.+ beforeEach(() => {+ __resetAgentRestartForTests()+ vi.useFakeTimers()+ })+ afterEach(() => vi.useRealTimers())++ it('holds the node until the delivery settles, not merely until the restart resolves', async () => {+ const { written, io } = silentIo()+ const run = guardConcurrentRestart('n-overlap', () =>+ performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ paneCommand: async () => 'zsh',+ timeoutMs: 1000,+ pollMs: 100+ })+ )+ const probe = guardConcurrentRestart('n-overlap', async () => 'restarted')+ const first = run()+ await vi.advanceTimersByTimeAsync(150)+ // The resume line is in the pane but NOT submitted (no echo to verify it).+ expect(written.join('')).toContain('claude --resume sid-1')+ // A second menu/bulk click landing in that window would splice `/exit` into the pending line+ // and submit `claude --resume sid-1/exit`.+ expect(await run()).toBe('not-eligible')+ expect(await probe()).toBe('not-eligible')+ expect(written.filter((w) => w === '/exit\r')).toHaveLength(1)+ await vi.advanceTimersByTimeAsync(10_000) // the fail-open submit ends the delivery+ expect(await first).toBe('restarted')+ expect(await probe()).toBe('restarted') // pane free again+ })+it('refuses a second call while one is in flight, without running it twice', async () => {let runs = 0let release: (o: RestartOutcome) => void = () => {}@@ -240,6 +346,8 @@ describe('guardConcurrentRestart', () => {})describe('agent restart registry', () => {+ beforeEach(() => __resetAgentRestartForTests())+it('registers, resolves and unregisters; re-register supersedes', () => {const a = async (): Promise<RestartOutcome> => 'restarted'const un = registerAgentRestart('n1', a)diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.tsindex 626e2f520..fee1136cc 100644--- a/src/renderer/terminal/agent-restart.ts+++ b/src/renderer/terminal/agent-restart.ts@@ -62,6 +62,12 @@ export const RESTART_POLL_MS = 250* echo-deliver the resume command into it. Never force-kills — on timeout the CLI is left* running and the caller reports the node. `paneCommand` errors count as "not a shell yet";* the timeout is the backstop.+ *+ * Resolves only once the resume line has actually LEFT the pane (deliverCommand's echo-verify+ * retries run for up to DELIVERY_ATTEMPTS × VERIFY_TIMEOUT_MS after the first write). The+ * un-submitted line is the pane's most fragile moment — anything typed into it during that window+ * is spliced into the command — so "this restart is over" must mean the delivery settled, not that+ * it was started. `guardConcurrentRestart` frees the node on exactly that boundary.*/export async function performRestartResume(d: {agentId: string@@ -77,12 +83,24 @@ export async function performRestartResume(d: {* a retry rewrite, or the fail-open submit, land in a dead session.*/onDelivery?: (cancel: () => void) => void+ /**+ * "Is the pane we are restarting still there?" — asked before the exit is written, on every+ * poll, and once more before the delivery. A session can die under a restart (the node is+ * deleted or respawned, or another client destroys the tmux session): its io then silently+ * no-ops and reporting `'restarted'` would put a phantom in the bulk summary.+ */+ isLive?: () => boolean}): Promise<RestartOutcome> {const exit = exitSequence(d.agentId)const cmd = resumeCommand(d.agentId, d.sessionId)if (!exit || !cmd) return 'not-eligible'const timeoutMs = d.timeoutMs ?? RESTART_EXIT_TIMEOUT_MSconst pollMs = d.pollMs ?? RESTART_POLL_MS+ // A dead session is not a restart that failed — there is no pane left to fail in. `'not-eligible'`+ // (uncounted) rather than `'exit-timeout'`, which claims something sharper and false: that the CLI+ // is still running and refused to quit, sending the user to look at a pane that is gone.+ const gone = (): boolean => !!d.isLive && !d.isLive()+ if (gone()) return 'not-eligible'd.io.write(exit + '\r')const deadline = Date.now() + timeoutMsfor (;;) {@@ -106,14 +124,23 @@ export async function performRestartResume(d: {} finally {clearTimeout(lapse)}+ if (gone()) return 'not-eligible' // stop polling a pane that no longer existsif (isShellCommand(pane)) breakif (Date.now() > deadline) return 'exit-timeout'}- // 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'+ // Awaited, not fire-and-forget: see the header. `deliverCommand` is started inside the executor+ // (synchronously, so `onDelivery` still hands the cancel out before any await) and announces the+ // end of the delivery — submitted, fail-open or cancelled — through `resolve`.+ await new Promise<void>((resolve) => {+ // Two statements on purpose: `d.onDelivery?.(deliverCommand(…))` short-circuits the ARGUMENT+ // too when no callback was passed — nothing would be delivered and this promise would never+ // settle.+ const cancelDelivery = deliverCommand(d.io, cmd, resolve)+ d.onDelivery?.(cancelDelivery)+ })+ // The session can have died while the line was being verified — the delivery is then cancelled by+ // the teardown and nothing reached the pane, so don't claim a restart.+ return gone() ? 'not-eligible' : 'restarted'}// ── One restart at a time, per node ──────────────────────────────────────────────────────@@ -124,6 +151,11 @@ const inFlight = new Set<string>()* 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 node is held for the WHOLE run, delivery included (see performRestartResume's header): a+ * second `/exit` arriving while the resume line sits un-submitted in the pane would be spliced+ * into it and submit `claude --resume <sid>/exit` — the exact mangled line command-delivery.ts+ * exists to prevent, and likeliest precisely when echo verification is being slow.+ ** 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@@ -161,6 +193,14 @@ export function agentRestartFn(nodeId: string): (() => Promise<RestartOutcome>)return restartFns.get(nodeId)}+/** TEST ONLY (house pattern: webgl-budget's `__resetWebglBudgetForTests`): both maps above are+ * module-global, so a test that leaves a restart in flight would otherwise refuse the next+ * test's restart of the same node id. */+export function __resetAgentRestartForTests(): void {+ inFlight.clear()+ restartFns.clear()+}+/** One toast line for the bulk action; zero-count parts are omitted. */export function summarizeOutcomes(outcomes: RestartOutcome[],diff --git a/src/renderer/terminal/command-delivery.test.ts b/src/renderer/terminal/command-delivery.test.tsindex f1506cbdd..fb81f7d91 100644--- a/src/renderer/terminal/command-delivery.test.ts+++ b/src/renderer/terminal/command-delivery.test.ts@@ -120,6 +120,33 @@ describe('deliverCommand', () => {expect(vi.getTimerCount()).toBe(0)})+ it('announces the end of the delivery exactly once, however it ends', () => {+ // Verified submit.+ const a = fakeIo()+ let ends = 0+ deliverCommand(a.io, CMD, () => (ends += 1))+ expect(ends).toBe(0) // started, but the line is still un-submitted in the pane+ a.emit(CMD)+ expect(ends).toBe(1)+ a.emit(CMD) // late echo+ expect(ends).toBe(1)++ // Fail-open submit after the last attempt.+ const b = fakeIo()+ ends = 0+ deliverCommand(b.io, CMD, () => (ends += 1))+ vi.advanceTimersByTime(VERIFY_TIMEOUT_MS * DELIVERY_ATTEMPTS)+ expect(ends).toBe(1)++ // Cancelled (node teardown), and a repeat cancel must not announce twice.+ const c = fakeIo()+ ends = 0+ const cancel = deliverCommand(c.io, CMD, () => (ends += 1))+ cancel()+ cancel()+ expect(ends).toBe(1)+ })+it('ignores echo arriving after submit (no double Enter)', () => {const f = fakeIo()deliverCommand(f.io, CMD)diff --git a/src/renderer/terminal/command-delivery.ts b/src/renderer/terminal/command-delivery.tsindex 339a814ed..a67b21e08 100644--- a/src/renderer/terminal/command-delivery.ts+++ b/src/renderer/terminal/command-delivery.ts@@ -38,8 +38,12 @@ export interface DeliveryIo {}/** Deliver `cmd` + Enter, echo-verified with bounded retries. Returns a cancel function- * (call on node teardown). */-export function deliverCommand(io: DeliveryIo, cmd: string): () => void {+ * (call on node teardown). `onSettled` fires exactly once when the delivery is over — submitted+ * (verified or fail-open) or cancelled — for callers that must know when the LINE has left the+ * pane, not merely when it was started: the retries run for up to+ * DELIVERY_ATTEMPTS × VERIFY_TIMEOUT_MS, and anything typed into the pane during that window+ * lands inside the un-submitted line. */+export function deliverCommand(io: DeliveryIo, cmd: string, onSettled?: () => void): () => void {let done = falselet attempt = 0let echoed = ''@@ -47,9 +51,11 @@ export function deliverCommand(io: DeliveryIo, cmd: string): () => void {let unsub: (() => void) | undefinedconst finish = (): void => {+ if (done) return // a cancel after the submit must not re-announce the deliverydone = trueif (timer) clearTimeout(timer)unsub?.()+ onSettled?.()}// Close the delivery BEFORE writing Enter: an io whose write echoes back synchronously (the// in-place restart choreography feeds one) would otherwise re-enter the listener below while