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): keep watching a CLI that is slow to quit, and hand over the resume line
review1a1c5285e60f
diff --git a/CLAUDE.md b/CLAUDE.mdindex 47b5da05e..0af5a4764 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -795,7 +795,12 @@ Lifecycle, by intent:(250 ms) until a SHELL owns the pane, then echo-deliver `resumeCommand(...)` — the same`claude --resume` / `codex resume` the cold restore uses. **Nothing is ever killed**: if the CLIhas not quit within `RESTART_EXIT_TIMEOUT_MS` (6 s) the run reports `exit-timeout` and leaves the- session running. A `working` **or `blocked`** session is refused — `/exit` typed into a+ session running. **A user-asked restart gets a late window on top** (`RESTART_LATE_EXIT_MS`, 60 s,+ spent only while the pane still reads): issue #899 was a 19 h cron session whose CLI quit a moment+ AFTER the 6 s, with nothing left watching — the node sat at a bare shell with no agent and no+ resume. The Eco sweep and Pause keep the bare 6 s (the sweep is serialized canvas-wide). The+ exit-timeout notice (`exitTimeoutNotice`) hands over the bare resume line for exactly that+ late-quit case. A `working` **or `blocked`** session is refused — `/exit` typed into apermission prompt would ANSWER it, not quit — and a node is held one-restart-at-a-time until theresume line has actually LEFT the pane (an un-submitted line is where a second `/exit` would bespliced in). The bulk action runs the same per-node closure sequentially over every idle agentdiff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 96ef668ae..5b07998ba 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -334,6 +334,7 @@ import {agentHibernateFns,agentPauseFns,agentRestartFn,+ exitTimeoutNotice,guardConcurrentRestart,planBulkRestart,clearEnvEligibility,@@ -6354,6 +6355,18 @@ export function Canvas() {)markDirty()}+ // The bare resume line for the exit-timeout notice, read from the same two sources the node's+ // restart closure used (live hook id, else the persisted minted one). Null when either is+ // unknown or unusable — `resumeCommand` refuses an unsafe id and has no line for a custom agent.+ const exitTimeoutResumeLine = (id: string): string | null => {+ const node = nodesRef.current.find((n) => n.id === id)+ const agentId = node?.data.agentId as AgentId | undefined+ const sid = restartSessionId(+ useAgentStatus.getState().byId[id]?.sessionId,+ node?.data.agentSessionId+ )+ return agentId && sid ? resumeCommand(agentId, sid) : null+ }const targetLabel =targetAgentId == null? undefined@@ -6379,11 +6392,9 @@ export function Canvas() {kind: 'error',// Deliberately does NOT claim the session is still running: what we know is that the// pane never came back to a shell within the timeout, so the resume was not sent.- // Nothing is ever force-killed, so the pane is exactly as the CLI left it — which is- // what the user has to go and look at.- text:- `${action} failed: the pane did not return to a shell in time, so the CLI was not ` +- 'relaunched. Nothing was killed — check the pane.'+ // Nothing is ever force-killed — but a CLI that quits AFTER we stopped watching leaves+ // a bare shell with no agent (issue #899), so the notice carries the resume line.+ text: exitTimeoutNotice(action, exitTimeoutResumeLine(nodeId))}: {kind: 'error',diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 8dc591ce2..32ee99456 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -154,6 +154,7 @@ import {restartEligibility,restartSessionId,RESTART_EXIT_TIMEOUT_MS,+ RESTART_LATE_EXIT_MS,type ExitPhaseOutcome,type PauseOutcome,type ResumePhaseOutcome@@ -3916,6 +3917,9 @@ export function TerminalNode({sessionId: agentSessionId,io: restartIo,paneCommand: () => api.pty.paneCommand(id),+ // A user-asked restart, like performRestartResume: a CLI that is slow to quit is+ // waited on rather than left to quit unwatched (issue #899 was this exact action).+ lateExitMs: RESTART_LATE_EXIT_MS,isLive: restartTarget})if (exited !== 'exited') return exiteddiff --git a/src/renderer/terminal/agent-restart.test.ts b/src/renderer/terminal/agent-restart.test.tsindex b4656b736..de2c7de2d 100644--- a/src/renderer/terminal/agent-restart.test.ts+++ b/src/renderer/terminal/agent-restart.test.ts@@ -8,12 +8,15 @@ import {agentRestartFn,clearEnvEligibility,exitSequence,+ exitTimeoutNotice,guardConcurrentRestart,isShellCommand,performExitPhase,performRestartResume,performResumePhase,planBulkRestart,+ RESTART_EXIT_TIMEOUT_MS,+ RESTART_LATE_EXIT_MS,registerAgentHibernate,registerAgentRestart,restartEligibility,@@ -188,7 +191,8 @@ describe('performRestartResume', () => {timeoutMs: 1000,pollMs: 100})- await vi.advanceTimersByTimeAsync(2000)+ // past the base window AND the restart's late window (RESTART_LATE_EXIT_MS)+ await vi.advanceTimersByTimeAsync(62_000)expect(await p).toBe('exit-timeout')expect(written.join('')).not.toContain('--resume')})@@ -300,7 +304,8 @@ describe('performRestartResume', () => {pane = 'node' // a momentary foreground child of the CLI, not its exitawait vi.advanceTimersByTimeAsync(100)pane = 'claude'- await vi.advanceTimersByTimeAsync(2000)+ // past the base window AND the restart's late window (RESTART_LATE_EXIT_MS)+ await vi.advanceTimersByTimeAsync(62_000)expect(await p).toBe('exit-timeout')expect(written.join('')).not.toContain('--resume')})@@ -482,12 +487,94 @@ describe('performRestartResume', () => {pollMs: 100,onDelivery: (c) => handles.push(c)})- await vi.advanceTimersByTimeAsync(2000)+ // past the base window AND the restart's late window (RESTART_LATE_EXIT_MS)+ await vi.advanceTimersByTimeAsync(62_000)expect(await p).toBe('exit-timeout')expect(handles).toEqual([])})})+describe('performRestartResume — a CLI that is slow to quit (issue #899)', () => {+ beforeEach(() => vi.useFakeTimers())+ afterEach(() => vi.useRealTimers())++ it('keeps watching past the base window and resumes a CLI that quits late', async () => {+ const { written, io } = fakeIo()+ let pane = '2.1.280' // what tmux reports for a running claude: its version, not `node`+ const p = performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ paneCommand: async () => pane,+ pollMs: 250+ })+ await vi.advanceTimersByTimeAsync(RESTART_EXIT_TIMEOUT_MS + 14_000) // well past the base window+ pane = 'zsh' // the CLI finally lets go+ await vi.advanceTimersByTimeAsync(5000)+ expect(await p).toBe('restarted')+ expect(written.slice(0, 2)).toEqual(['\x15', '/exit\r'])+ expect(written.join('')).toContain('claude --resume sid-1')+ })++ it('is still bounded: a CLI that never quits is reported once the late window runs out', async () => {+ const { written, io } = fakeIo()+ let settled = false+ const p = performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ paneCommand: async () => 'claude',+ pollMs: 250+ }).finally(() => {+ settled = true+ })+ await vi.advanceTimersByTimeAsync(RESTART_EXIT_TIMEOUT_MS + 1000)+ expect(settled).toBe(false) // the base window alone no longer ends a restart+ await vi.advanceTimersByTimeAsync(RESTART_LATE_EXIT_MS)+ expect(await p).toBe('exit-timeout')+ expect(written.join('')).not.toContain('--resume')+ })++ it('does not spend the late window on a pane it can no longer read', async () => {+ const { io } = fakeIo()+ let pane: string | null = 'claude'+ let settled = false+ const p = performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ paneCommand: async () => pane,+ pollMs: 250+ }).finally(() => {+ settled = true+ })+ await vi.advanceTimersByTimeAsync(RESTART_EXIT_TIMEOUT_MS + 1000)+ pane = null+ await vi.advanceTimersByTimeAsync(1000)+ expect(settled).toBe(true)+ expect(await p).toBe('exit-timeout')+ })+})++describe('exitTimeoutNotice', () => {+ it('hands over the resume line for a CLI that may quit after we stopped watching (#899)', () => {+ const text = exitTimeoutNotice('Restart', resumeCommand('claude', 'sid-1'))+ expect(text).toContain('Restart failed')+ expect(text).toContain('Nothing was killed')+ // The window it names is the one a restart actually waited, not the base 6s.+ expect(text).toContain(`${(RESTART_EXIT_TIMEOUT_MS + RESTART_LATE_EXIT_MS) / 1000}s`)+ expect(text).toContain('claude --resume sid-1')+ })++ it('falls back to "check the pane" when there is no resume line to offer', () => {+ for (const line of [null, undefined, '']) {+ const text = exitTimeoutNotice('Restart', line)+ expect(text).toContain('Check the pane.')+ expect(text).not.toContain('resume the conversation')+ }+ })+})+describe('performExitPhase', () => {beforeEach(() => vi.useFakeTimers())afterEach(() => vi.useRealTimers())@@ -528,6 +615,16 @@ describe('performExitPhase', () => {expect(written).toEqual([])})+ it('has no late window unless the caller asks for one (Eco sweep, Pause)', async () => {+ const { io } = fakeIo()+ let pane = 'claude'+ const p = performExitPhase({ agentId: 'claude', sessionId: 'sid-1', io, paneCommand: async () => pane })+ await vi.advanceTimersByTimeAsync(RESTART_EXIT_TIMEOUT_MS + 1000)+ pane = 'zsh'+ await vi.advanceTimersByTimeAsync(1000)+ expect(await p).toBe('exit-timeout')+ })+it('reports exit-timeout, without a resume, when the CLI never lets go of the pane', async () => {const { written, io } = fakeIo()const p = performExitPhase({diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.tsindex ad32c5975..2db0830a3 100644--- a/src/renderer/terminal/agent-restart.ts+++ b/src/renderer/terminal/agent-restart.ts@@ -123,6 +123,20 @@ export type RestartOutcome = 'restarted' | 'exit-timeout' | 'not-eligible'export const RESTART_EXIT_TIMEOUT_MS = 6000export const RESTART_POLL_MS = 250+/**+ * How much longer a user-asked RESTART keeps watching after RESTART_EXIT_TIMEOUT_MS, as long as+ * the pane can still be read (issue #899). The exit is irreversible and the resume is the only way+ * back, so giving up at 6s on a CLI that is merely slow to quit is the worst outcome available: it+ * DID quit a moment later, nothing was watching, and the node was left at a bare shell with no+ * agent and no resume. Reported on a 19-hour cron session with a 28 MB transcript; a fresh claude+ * quits in well under a second, so the base window stays short for the common case and only a CLI+ * that is still visibly shutting down is waited on.+ *+ * Restart only. The Eco sweep and Pause keep the base window: the sweep is serialized across the+ * canvas and must not stall on one node, and neither resumes into the pane afterwards.+ */+export const RESTART_LATE_EXIT_MS = 60_000+/** How long the resume delivery may take before this restart stops waiting for it. The delivery's* own retry chain is bounded (DELIVERY_ATTEMPTS × VERIFY_TIMEOUT_MS, then a fail-open submit), so* the slack is only there to let the last attempt land. A backstop, not a policy: nothing in a@@ -130,6 +144,24 @@ export const RESTART_POLL_MS = 250* node after it is blocked and the summary the user is waiting for never arrives. */export const RESTART_DELIVERY_TIMEOUT_MS = DELIVERY_ATTEMPTS * VERIFY_TIMEOUT_MS + 1000+/**+ * The notice for an `'exit-timeout'` restart. It keeps the two facts the old sentence carried —+ * the relaunch was not sent, and nothing was killed — and adds the one the user actually needs+ * (issue #899): the CLI may still quit on its own a moment later, and with nothing watching any+ * more, the pane is then a bare shell with no agent in it. So it hands over the exact resume line+ * to type there. `resumeLine` is the BARE resume command (no permission mode, no launcher); a+ * custom agent without one gets the sentence without the command rather than a guessed line.+ */+export function exitTimeoutNotice(action: string, resumeLine: string | null | undefined): string {+ const waited = Math.round((RESTART_EXIT_TIMEOUT_MS + RESTART_LATE_EXIT_MS) / 1000)+ const head =+ `${action} failed: the pane did not return to a shell within ${waited}s, so the CLI was not ` ++ 'relaunched. Nothing was killed.'+ return resumeLine+ ? `${head} If the CLI has quit since, resume the conversation in that pane with: ${resumeLine}`+ : `${head} Check the pane.`+}+/*** One bounded pane query. Unbounded, a wedged tmux server (or a relay whose IPC never answers)* would hang the restart — and with it the bulk run's summary — forever. A lapsed, failed or@@ -192,6 +224,12 @@ export async function performExitPhase(d: {paneCommand: () => Promise<string | null>timeoutMs?: numberpollMs?: number+ /**+ * Extra time past `timeoutMs` to keep waiting for a CLI that has not let go of the pane yet+ * (see RESTART_LATE_EXIT_MS). Only spent while the pane still READS: a pane we cannot see after+ * the base window is given up on exactly as before. Absent = 0 = the base window alone.+ */+ lateExitMs?: number/*** "Is the pane we are quitting still there?" — asked before the exit is written and on every* poll. A session can die under a restart (the node is deleted or respawned, or another client@@ -248,10 +286,15 @@ export async function performExitPhase(d: {d.io.write(exit + '\r')}const deadline = Date.now() + timeoutMs+ // Equal to `deadline` when no late window was asked for, so every bound below is unchanged.+ const lateDeadline = deadline + Math.max(0, d.lateExitMs ?? 0)let last: string | null = nullfor (;;) {await new Promise((r) => setTimeout(r, pollMs))- const pane = await queryPaneWithin(d.paneCommand, Math.max(0, deadline - Date.now()))+ // Each query is bounded by the window it runs in: a query wedged inside the base window still+ // lapses at `deadline` (and its null ends the run there), exactly as without a late window.+ const until = Date.now() <= deadline ? deadline : lateDeadline+ const pane = await queryPaneWithin(d.paneCommand, Math.max(0, until - Date.now()))if (gone()) return 'not-eligible' // stop polling a pane that no longer exists// Two ways to know the CLI let go of the pane. The allowlist is the confident one and is// taken immediately. The other — "the foreground command is no longer what it was before the@@ -263,7 +306,10 @@ export async function performExitPhase(d: {if (isShellCommand(pane)) return 'exited'if (pane !== null && pane !== before && pane === last) return 'exited'last = pane- if (Date.now() > deadline) return 'exit-timeout'+ // Past the base window, keep going only inside the late window and only while the pane is+ // still readable — i.e. the CLI we asked to quit is visibly still there (or a changed reading+ // is waiting for its confirming second poll). A pane we can no longer see is not "slow".+ if (Date.now() >= deadline && (Date.now() > lateDeadline || pane === null)) return 'exit-timeout'}}@@ -390,6 +436,8 @@ export async function performRestartResume(d: {command?: stringtimeoutMs?: numberpollMs?: number+ /** See `performExitPhase`; defaults to RESTART_LATE_EXIT_MS — this IS the user-asked restart. */+ lateExitMs?: number/** Backstop for the resume delivery; see RESTART_DELIVERY_TIMEOUT_MS. */deliveryTimeoutMs?: numberkillLine?: string@@ -410,6 +458,7 @@ export async function performRestartResume(d: {paneCommand: d.paneCommand,timeoutMs: d.timeoutMs,pollMs: d.pollMs,+ lateExitMs: d.lateExitMs ?? RESTART_LATE_EXIT_MS,isLive: d.isLive})// `'exit-timeout'` / `'not-eligible'` mean the same things they always did, so they are the