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): never quit a CLI whose pane we cannot watch
enesb73222caff10
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 1278cd4b7..c7a539d33 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -161,6 +161,7 @@ import {canTransferFrom,canContextLink,canControlCanvas,+ createdAgentId,resumeCommand,withPermissionMode,AGENT_CONFIG,@@ -352,19 +353,14 @@ const ropeEdge = (id: string, source: string, target: string, color: string): Edconst minimapNodeColor = (n: Node): string =>(n.data as { color?: string })?.color ?? '#0a84ff'-/** The agent a terminal node was CREATED as — `data.agentId` with the legacy `tags` fallback.- * Deliberately NOT `agentIdOf`, whose extra hook-status fallback also reports a plain terminal- * someone typed `claude` into by hand: TerminalNode's restart closure captures exactly the- * derivation below, so a node offered a restart on the strength of the wider one would get a row- * whose closure refuses every click. Anything else (a shell, a sticky, an editor) is undefined,- * which `restartEligibility` reads as `not-resumable`. */-const restartAgentIdOf = (n: Node | undefined): string | undefined => {- if (!n || n.type !== 'terminal') return undefined- return (- (n.data.agentId as string | undefined) ??- (((n.data.tags as string[]) ?? []).includes('claude') ? 'claude' : undefined)- )-}+/** The agent a terminal node was CREATED as. Deliberately NOT `agentIdOf`, whose extra hook-status+ * fallback also reports a plain terminal someone typed `claude` into by hand: TerminalNode's+ * restart closure captures `createdAgentId` too — the ONE shared derivation — so a node offered a+ * restart on the strength of the wider one would get a row whose closure refuses every click.+ * Anything that is not a terminal (a sticky, an editor) is undefined, which `restartEligibility`+ * reads as `not-resumable`. */+const restartAgentIdOf = (n: Node | undefined): string | undefined =>+ !n || n.type !== 'terminal' ? undefined : createdAgentId(n.data)// The minimap subscribes to agent status HERE, in its own tiny component — not in Canvas.// Canvas must not subscribe to the whole status map (every working/waiting flip would re-render@@ -3633,17 +3629,26 @@ export function Canvas() {: outcome === 'exit-timeout'? {kind: 'error',- text: 'Restart failed: the CLI did not quit in time. The session was left running.'+ // 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:+ 'Restart failed: the pane did not return to a shell in time, so the CLI was not ' ++ 'relaunched. Nothing was killed — check the pane.'}: {kind: 'error',// 'not-eligible' is every "not a target right now": the gate re-checked and refused,// the tmux session is closed / ended / gone (which the menu row cannot see — only the- // node knows its session state), or a restart of this node was already in flight (the+ // node knows its session state), the pane cannot be observed at all (persistent tmux+ // sessions off, or no tmux on this machine — the restart needs to watch the pane to+ // know when the CLI has quit), or a restart of this node was already in flight (the// per-node action and the bulk one can reach the same node).text:- 'Restart skipped: this session is busy, already restarting, or no longer attached ' +- '(closed, ended, or nothing to resume). Nothing was written to the pane.'+ 'Restart skipped: this session is busy, already restarting, not attached ' ++ '(closed, ended, or nothing to resume), or its pane cannot be watched without ' ++ 'persistent tmux sessions. Nothing was written to the pane.'})}, [])@@ -4078,9 +4083,11 @@ export function Canvas() {: !agentRestartFn(ids[0])? 'This terminal is not attached right now.': // Not every dead end is visible from here: the closure ALSO refuses a tmux- // session that is closed / ended / gone, and only the node itself knows that. So- // that case reaches the user through `restartAgentNode`'s skip notice, which- // names it, rather than through a hint this row cannot compute.+ // session that is closed / ended / gone, and a pane it cannot observe at all+ // (tmux off / absent — it pre-flights one `pane_current_command` before writing+ // anything). Only the node knows the first, and the second costs an IPC that must+ // not run per menu RENDER. Both reach the user through `restartAgentNode`'s skip+ // notice, which names them, rather than through a hint this row cannot compute.undefinedreturn [{diff --git a/src/renderer/terminal/agent-restart.test.ts b/src/renderer/terminal/agent-restart.test.tsindex 287583754..c0fe40336 100644--- a/src/renderer/terminal/agent-restart.test.ts+++ b/src/renderer/terminal/agent-restart.test.ts@@ -119,7 +119,7 @@ describe('performRestartResume', () => {pane = 'zsh'await vi.advanceTimersByTimeAsync(5000)expect(await p).toBe('restarted')- expect(written[0]).toBe('/exit\r')+ expect(written.slice(0, 2)).toEqual(['\x15', '/exit\r'])expect(written.join('')).toContain('claude --resume sid-1')})@@ -138,13 +138,20 @@ describe('performRestartResume', () => {expect(written.join('')).not.toContain('--resume')})- it('gives up when the pane query itself never settles', async () => {+ it('gives up when the pane query wedges after the exit was sent', async () => {const { written, io } = fakeIo()+ let first = trueconst p = performRestartResume({agentId: 'claude',sessionId: 'sid-1',io,- paneCommand: () => new Promise<string | null>(() => {}), // wedged tmux server: never settles+ // The pre-flight answers, so the exit IS written; then the tmux server wedges and no poll+ // ever settles. The deadline, not the query, has to end the restart.+ paneCommand: () => {+ if (!first) return new Promise<string | null>(() => {})+ first = false+ return Promise.resolve('claude')+ },timeoutMs: 1000,pollMs: 100})@@ -153,6 +160,126 @@ describe('performRestartResume', () => {expect(written.join('')).not.toContain('--resume')})+ it('writes NOTHING when the pane cannot be observed at all (tmux off / no tmux binary)', async () => {+ const { written, io } = fakeIo()+ const p = performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ paneCommand: async () => null, // no tmux session to query — the poll could never end+ timeoutMs: 1000,+ pollMs: 100+ })+ await vi.advanceTimersByTimeAsync(2000)+ // Quitting a CLI whose pane we cannot watch would leave it dead and never resumed, and then+ // report a 6-second "the session was left running".+ expect(await p).toBe('not-eligible')+ expect(written).toEqual([])+ })++ it('writes nothing when the pre-flight pane query itself wedges', async () => {+ const { written, io } = fakeIo()+ const p = performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ paneCommand: () => new Promise<string | null>(() => {}),+ timeoutMs: 1000,+ pollMs: 100+ })+ await vi.advanceTimersByTimeAsync(3000)+ expect(await p).toBe('not-eligible')+ expect(written).toEqual([])+ })++ it('clears the pending input line before asking the CLI to quit', async () => {+ const { written, io } = fakeIo()+ let pane = 'claude'+ const p = performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ paneCommand: async () => pane,+ timeoutMs: 6000,+ pollMs: 100+ })+ await vi.advanceTimersByTimeAsync(250)+ pane = 'zsh'+ await vi.advanceTimersByTimeAsync(5000)+ expect(await p).toBe('restarted')+ // Half-typed user text in the prompt would otherwise be SUBMITTED as `…the/exit`.+ expect(written[0]).toBe('\x15')+ expect(written[1]).toBe('/exit\r')+ })++ it('takes a pane command that CHANGED away from the CLI as proof it quit', async () => {+ const { written, io } = fakeIo()+ let pane = 'claude'+ const p = performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ paneCommand: async () => pane,+ timeoutMs: 6000,+ pollMs: 100+ })+ await vi.advanceTimersByTimeAsync(250)+ pane = 'nu' // a shell outside the allowlist — the user's `defaultShell`+ await vi.advanceTimersByTimeAsync(5000)+ expect(await p).toBe('restarted')+ expect(written.join('')).toContain('claude --resume sid-1')+ })++ it('does not take a one-poll flicker for a quit (never types into a live CLI)', async () => {+ const { written, io } = fakeIo()+ let pane = 'claude'+ const p = performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ paneCommand: async () => pane,+ timeoutMs: 1000,+ pollMs: 100+ })+ await vi.advanceTimersByTimeAsync(150)+ pane = 'node' // a momentary foreground child of the CLI, not its exit+ await vi.advanceTimersByTimeAsync(100)+ pane = 'claude'+ await vi.advanceTimersByTimeAsync(2000)+ expect(await p).toBe('exit-timeout')+ expect(written.join('')).not.toContain('--resume')+ })++ it("launches with the caller's command when one is given (permission mode)", async () => {+ const { written, io } = fakeIo()+ const p = performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ command: 'claude --resume sid-1 --permission-mode plan',+ paneCommand: async () => 'zsh',+ timeoutMs: 1000,+ pollMs: 100+ })+ await vi.advanceTimersByTimeAsync(5000)+ expect(await p).toBe('restarted')+ expect(written.join('')).toContain('claude --resume sid-1 --permission-mode plan')+ })++ it('ignores an override for a session id that could never be resumed', async () => {+ const { written, io } = fakeIo()+ expect(+ await performRestartResume({+ agentId: 'claude',+ sessionId: '-bad',+ io,+ command: 'claude --resume -bad --permission-mode plan',+ paneCommand: async () => 'zsh'+ })+ ).toBe('not-eligible')+ expect(written).toEqual([])+ })+it('refuses an agent without an exit sequence', async () => {const { io } = fakeIo()expect(@@ -257,6 +384,35 @@ describe('performRestartResume', () => {expect(written.join('')).not.toContain('--resume')})+ it('never reports a restart whose resume line the transport refused', async () => {+ // A relay socket still CONNECTING throws InvalidStateError on the very first write. The+ // delivery ends itself (command-delivery.ts) — but ending is not delivering, so the restart+ // must come back as a REJECTION the caller counts as a failure, not as 'restarted'.+ const written: string[] = []+ const io = {+ write(dta: string) {+ written.push(dta)+ if (dta.includes('--resume'))+ throw new DOMException('Still in CONNECTING state.', 'InvalidStateError')+ },+ onData: () => () => {}+ }+ const p = performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ paneCommand: async () => 'zsh',+ timeoutMs: 1000,+ pollMs: 100+ })+ const settled = p.then(+ (o) => ({ ok: true, o }),+ (e) => ({ ok: false, e })+ )+ await vi.advanceTimersByTimeAsync(30_000)+ expect(await settled).toEqual({ ok: false, e: expect.any(DOMException) })+ })+it('hands out no cancel when nothing was delivered', async () => {const { io } = fakeIo()const handles: Array<() => void> = []@@ -275,6 +431,48 @@ describe('performRestartResume', () => {})})+describe('performRestartResume — the delivery await is bounded', () => {+ beforeEach(() => {+ vi.resetModules()+ vi.useFakeTimers()+ })+ afterEach(() => {+ vi.useRealTimers()+ vi.doUnmock('./command-delivery')+ vi.resetModules()+ })++ it('stops waiting on a delivery that never announces it settled', async () => {+ // A transport whose write() throws used to kill deliverCommand's retry callback before it+ // could submit — `onSettled` then never fired, this await never settled, the node stayed+ // locked out by guardConcurrentRestart for the app's life and the bulk loop hung with no+ // summary. The transport is fixed in command-delivery.ts; this is the belt to that braces —+ // NOTHING may wait forever, whatever the delivery does.+ vi.doMock('./command-delivery', () => ({+ VERIFY_TIMEOUT_MS: 2000,+ DELIVERY_ATTEMPTS: 3,+ KILL_LINE: '\x15',+ deliverCommand: () => () => {} // started, never settles+ }))+ const mod = await import('./agent-restart')+ let outcome: string | undefined+ void mod+ .performRestartResume({+ agentId: 'claude',+ sessionId: 'sid-1',+ io: { write: () => {}, onData: () => () => {} },+ paneCommand: async () => 'zsh',+ timeoutMs: 1000,+ pollMs: 100+ })+ .then((o) => (outcome = o))+ await vi.advanceTimersByTimeAsync(200)+ expect(outcome).toBeUndefined() // still holding the node, as designed+ await vi.advanceTimersByTimeAsync(60_000)+ expect(outcome).toBe('restarted')+ })+})+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.diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.tsindex aec04a41c..b1a72e696 100644--- a/src/renderer/terminal/agent-restart.ts+++ b/src/renderer/terminal/agent-restart.ts@@ -5,7 +5,13 @@* filter and the restart choreography can all share exactly one set of rules.*/import { canResume, resumeCommand } from '../../shared/agents/config'-import { deliverCommand, type DeliveryIo } from './command-delivery'+import {+ DELIVERY_ATTEMPTS,+ KILL_LINE,+ VERIFY_TIMEOUT_MS,+ deliverCommand,+ type DeliveryIo+} from './command-delivery'/** In-band exit command per agent CLI. Only agents listed here can be restarted in place —* an unknown CLI has no safe way to be asked to quit. */@@ -57,11 +63,46 @@ export type RestartOutcome = 'restarted' | 'exit-timeout' | 'not-eligible'export const RESTART_EXIT_TIMEOUT_MS = 6000export const RESTART_POLL_MS = 250+/** 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+ * restart may wait forever — the awaiting node is held un-restartable and, in a bulk run, every+ * 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+/**- * In-place CLI restart: ask the agent to quit, wait until a SHELL owns the pane, then+ * 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+ * empty query reads as `null`: "we cannot see this pane right now".+ */+async function queryPane(fn: () => Promise<string | null>, ms: number): Promise<string | null> {+ let lapse: ReturnType<typeof setTimeout> | undefined+ try {+ return await Promise.race([+ fn(),+ new Promise<null>((r) => {+ lapse = setTimeout(() => r(null), ms)+ })+ ])+ } catch {+ return null // transient IPC failure — same reading as "cannot see it"+ } finally {+ clearTimeout(lapse)+ }+}++/**+ * In-place CLI restart: ask the agent to quit, wait until the CLI has let go of the pane, then* 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.+ * running and the caller reports the node. Once the exit has been sent, `paneCommand` errors count+ * as "not a shell yet"; the timeout is the backstop.+ *+ * NOTHING is written until one `paneCommand` has come back non-null. The exit command is+ * irreversible — the conversation is only recoverable through the `--resume` that follows it — so+ * a pane we cannot WATCH must never be quit: with tmux switched off in Settings, or absent from+ * the machine, the query answers null forever, and quitting first would leave the agent dead, the+ * relaunch never sent, and the user told (after 6s of polling) that "the session was left+ * running". The pre-flight makes that state a plain `'not-eligible'`, with an untouched pane.** 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@@ -74,8 +115,21 @@ export async function performRestartResume(d: {sessionId: stringio: DeliveryIopaneCommand: () => Promise<string | null>+ /**+ * The exact launch line to relaunch with, when the caller has one. `withPermissionMode` is the+ * app's single funnel for every CLI launch, and it needs the ACTIVE mode — an async read that+ * belongs to the node, not to this module. Without it a canvas running in `acceptEdits` / `plan`+ * would come back from a bulk restart in the default mode and start prompting.+ *+ * Eligibility is still decided by the bare `resumeCommand` below: a session id this app would+ * not put on a command line (SAFE_SESSION_ID) refuses the restart before anything is written,+ * whatever the caller passes.+ */+ command?: stringtimeoutMs?: numberpollMs?: number+ /** Backstop for the resume delivery; see RESTART_DELIVERY_TIMEOUT_MS. */+ deliveryTimeoutMs?: 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@@ -85,15 +139,18 @@ export async function performRestartResume(d: {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.+ * poll, and once more after the delivery, before a restart is reported. 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 base = resumeCommand(d.agentId, d.sessionId)+ // The BARE command is the gate even when the caller overrides it: `resumeCommand` is what+ // validates the session id before it reaches a command line.+ if (!exit || !base) return 'not-eligible'+ const cmd = d.command ?? baseconst 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'`@@ -101,42 +158,74 @@ export async function performRestartResume(d: {// 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'+ // ── Pre-flight: prove we can SEE this pane before quitting anything in it (see the header).+ // Reported as `'not-eligible'`, the outcome that means "not a target right now" and is the one+ // the menu and the notice already have wording for. Nothing has been written at this point.+ const before = await queryPane(d.paneCommand, timeoutMs)+ if (before === null || gone()) return 'not-eligible'+ // Clear the prompt before typing the exit command. The pane is a REPL the user types into: a+ // half-written prompt left in it would otherwise be submitted as `…refactor the/exit` — the+ // draft lost and a real turn started (tokens, possibly edits) — and the CLI, still running,+ // would then be reported as an exit timeout.+ //+ // ASSUMPTION, unverified on a real build: Ctrl-U is "clear line" inside the Claude and codex+ // TUIs (it is in every readline/ZLE prompt, and it is what command-delivery.ts already relies on+ // for its rewrites). If a TUI binds it to something else this becomes one stray keystroke before+ // the exit command — no worse than today's blind write. Belongs in the manual test matrix.+ d.io.write(KILL_LINE)d.io.write(exit + '\r')const deadline = Date.now() + timeoutMs+ let last: string | null = nullfor (;;) {await new Promise((r) => setTimeout(r, pollMs))- let pane: string | null = null- let lapse: ReturnType<typeof setTimeout> | undefined- try {- // The query must be bounded, not just its rejection: a wedged tmux server can leave it- // pending forever, and the deadline below is only read once it settles — an unbounded- // await would hang this restart, and with it the bulk run's summary, permanently. A- // lapsed query resolves null, which reads as "not a shell yet".- const remaining = Math.max(0, deadline - Date.now())- pane = await Promise.race([- d.paneCommand(),- new Promise<null>((r) => {- lapse = setTimeout(() => r(null), remaining)- })- ])- } catch {- // transient IPC failure — keep polling until the deadline- } finally {- clearTimeout(lapse)- }+ const pane = await queryPane(d.paneCommand, Math.max(0, deadline - 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+ // exit" — covers the shells the allowlist cannot know (`nu`, `xonsh`, `pwsh`, anything the+ // user set as `defaultShell`), where waiting for a listed shell would time out with the agent+ // already quit and never resumed. It is required on two CONSECUTIVE polls: a single changed+ // reading can be a momentary foreground child of a still-running CLI, and typing the resume+ // line into a live CLI would send it as a message.if (isShellCommand(pane)) break+ if (pane !== null && pane !== before && pane === last) break+ last = paneif (Date.now() > deadline) return 'exit-timeout'}// 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)+ // end of the delivery — submitted, fail-open or cancelled — through `settle`.+ await new Promise<void>((resolve, reject) => {+ let lapse: ReturnType<typeof setTimeout> | undefined+ let settled = false+ let started = false+ // A settle announced from INSIDE deliverCommand's synchronous body is only applied below,+ // after it has returned: that body can announce the end of the delivery and then throw (a+ // transport that rejects the very first write ends the delivery, then reports), and a promise+ // resolved first could no longer be rejected — the restart would claim success for a resume+ // line that never reached the pane.+ const settle = (): void => {+ settled = true+ if (!started) return+ clearTimeout(lapse)+ resolve()+ }+ try {+ // 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, settle)+ started = true+ d.onDelivery?.(cancelDelivery)+ } catch (e) {+ reject(e) // the caller counts a failure; no timer has been armed yet+ return+ }+ if (settled) return resolve() // an io that echoes inside write() finishes the delivery there+ // Bounded even so. The delivery's own retry chain is finite, but this await holds the node+ // (and, in a bulk run, every node after it and the summary), so it must not depend on a third+ // party announcing itself.+ lapse = setTimeout(resolve, d.deliveryTimeoutMs ?? RESTART_DELIVERY_TIMEOUT_MS)})// 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.