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(agent): a cold-restore resume that resolves nothing starts the agent fresh
enescec516e69cb7
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 472693909..25c0921fd 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -106,7 +106,12 @@ import {validCellSize,type Vec2} from '../lib/glyphGridNode'-import { deliverCommand, KILL_LINE, type DeliveryIo } from '../terminal/command-delivery'+import { cleanEcho, deliverCommand, KILL_LINE, type DeliveryIo } from '../terminal/command-delivery'+import {+ RESUME_MISS_WINDOW_MS,+ detectsResumeMiss,+ resumeSessionMissing+} from '../terminal/resume-fallback'import {agentHibernateFns,exitSequence,@@ -3387,7 +3392,82 @@ export function TerminalNode({// the exact line it launched with. Empty on browser/relay by design.agentEnvSnapshot())+ /**+ * Watch the pane for the CLI's own "that conversation does not exist" line and, if it+ * comes, launch the agent FRESH in the same pane.+ *+ * Everything it does is a refusal until proven otherwise:+ * - it only reads output for `RESUME_MISS_WINDOW_MS`, because the CLI answers at once;+ * - it matches the message against THIS id, not a bare substring;+ * - it re-reads the pane and requires a SHELL to own it before writing, the same gate+ * the hibernation wake uses — the CLI exits after printing, so anything else in that+ * pane is something we must not type into;+ * - it fires at most once, and the fallback command carries NO session id, so it can+ * never arm a second watcher.+ * The dead id is forgotten on both sides afterwards (the live one from hooks and the+ * minted one on the node), so the next cold restore does not replay it.+ */+ const watchResumeMiss = (deadId: string): void => {+ let fired = false+ let seen = ''+ // `unsub` is assigned on the line after the timer is armed, and `stop` is pushed to+ // `cleanups` where an unmount can call it at any moment — a `const` read before its+ // assignment would throw out of a teardown path. Optional call, idempotent.+ let unsub: (() => void) | undefined+ const stop = (): void => {+ clearTimeout(timer)+ unsub?.()+ unsub = undefined+ }+ const timer = setTimeout(() => stop(), RESUME_MISS_WINDOW_MS)+ unsub = transport.onData(sid, (chunk) => {+ if (fired) return+ // Escape sequences and line breaks removed: the CLI colours its own output and tmux+ // re-wraps it at the pane width, so a raw match would miss a line that straddles a+ // column boundary. Bounded, so a chatty pane cannot grow this without limit.+ seen = (seen + cleanEcho(chunk)).slice(-4096)+ if (!resumeSessionMissing(agentId, deadId, seen)) return+ fired = true+ stop()+ void (async () => {+ const pane = await queryPaneWithin(+ () => api.pty.paneCommand(id),+ RESTART_EXIT_TIMEOUT_MS+ )+ // `null` is "we could not see the pane", never "nothing is running in it" — the+ // same contract every other reader of this query keeps.+ if (!isShellCommand(pane)) return+ const { command: fresh } = assembleResumeCommand(+ {+ agentId,+ customAgent,+ sessionId: undefined,+ permissionMode: mode,+ model: data.agentModel,+ sharedIdentity: shared,+ launchCmdOverride: agentLaunchOverride(agentId, ownerProjectId)+ },+ agentEnvSnapshot()+ )+ if (!fresh) return+ useAgentStatus.getState().setSessionId(id, undefined)+ if (data.agentSessionId) updateNodeData(id, { agentSessionId: undefined })+ writeWhenShellReady(fresh)+ })()+ })+ cleanups.push(stop)+ }if (cmd) writeWhenShellReady(cmd) // same shell-startup race as initialCommand+ // A resume can name a conversation that does not exist — the minted id whose launch+ // never ran (an armed `--after` node, a truncated launch line), or a hook-fed id whose+ // transcript is gone. The CLI then prints one line, exits, and the node keeps its agent+ // badge over a pane sitting at a bare shell (issue #707). Watch for the CLI's own+ // refusal, naming THIS id, and start the agent fresh instead. Armed only when we+ // actually asked to resume something and only for an agent whose message we measured;+ // everything else is byte-identical to before. See terminal/resume-fallback.ts.+ if (cmd && priorId && detectsResumeMiss(agentId)) {+ watchResumeMiss(priorId)+ }} else if (fresh && pausedNow) {// The auto-resume above was skipped (that's the feature), but this mount's PANE is// brand new either way — tmux respawned it, whether from the deep "pause & end session"diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.tsindex 6f8602598..b3842f958 100644--- a/src/renderer/state/agentStatus.ts+++ b/src/renderer/state/agentStatus.ts@@ -220,7 +220,10 @@ export interface AgentStatusStore {/** Clear `working` entries whose last event is older than `staleMs` (lost-Stop safety net). */sweepStaleWorking(staleMs?: number): voidsetSession(id: string, session: string): void- setSessionId(id: string, sessionId: string): void+ /** Record — or, with `undefined`, FORGET — this node's agent session id. Forgetting is what a+ * cold-restore resume does when the CLI reports the conversation does not exist (issue #707):+ * keeping a proven-dead id would make the next cold restore replay the same failed `--resume`. */+ setSessionId(id: string, sessionId: string | undefined): void/** Record the Claude account a hook event says this node is running under. Persisted; see* `account`. Idempotent — a re-assert of the same account writes nothing. */setAccount(id: string, account: ObservedClaudeAccount): voiddiff --git a/src/renderer/terminal/resume-fallback.test.ts b/src/renderer/terminal/resume-fallback.test.tsnew file mode 100644index 000000000..76e609f6d--- /dev/null+++ b/src/renderer/terminal/resume-fallback.test.ts@@ -0,0 +1,112 @@+import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'+import {+ RESUME_MISS_WINDOW_MS,+ detectsResumeMiss,+ resumeSessionMissing+} from './resume-fallback'+import { cleanEcho } from './command-delivery'++const DEAD = '6c0e1b2a-1111-4222-8333-444455556666'+/** Verbatim, from `claude --resume <unknown-uuid>` on claude 2.1.266 (exit 1). */+const CLAUDE_MISS = `No conversation found with session ID: ${DEAD}`++describe('recognising a resume that resolved nothing (issue #707)', () => {+ it('matches claude’s own line for the id WE asked for', () => {+ expect(resumeSessionMissing('claude', DEAD, `% claude --resume ${DEAD}\n${CLAUDE_MISS}\n%`)).toBe(+ true+ )+ })++ it('does NOT match the same sentence about a DIFFERENT session', () => {+ // The user resuming another conversation by hand in the same pane, or a transcript quoting the+ // message, must not make us type a second CLI launch into a pane that is busy with one.+ const other = 'No conversation found with session ID: 99999999-0000-4000-8000-000000000000'+ expect(resumeSessionMissing('claude', DEAD, other)).toBe(false)+ })++ it('survives the wrapping and colouring the pane actually applies', () => {+ // tmux re-wraps at the pane width and the CLI colours its own output, so the raw bytes carry+ // escape sequences and hard line breaks through the middle of the sentence. The caller feeds+ // `cleanEcho`-stripped text for exactly this reason; assert the pairing holds.+ const cut = 30+ const raw =+ '\x1b[31m' + CLAUDE_MISS.slice(0, cut) + '\x1b[0m\r\n' + CLAUDE_MISS.slice(cut) + '\x1b[K'+ expect(resumeSessionMissing('claude', DEAD, raw)).toBe(false)+ expect(resumeSessionMissing('claude', DEAD, cleanEcho(raw))).toBe(true)+ })++ it('answers false for every agent whose message has not been measured', () => {+ // codex needs a tty to answer at all and gemini was never captured. A guess here does not+ // degrade to nothing — it types a launch into a pane that already has a live CLI.+ for (const agentId of ['codex', 'gemini', 'grok', 'copilot', 'opencode', 'custom:x']) {+ expect(detectsResumeMiss(agentId)).toBe(false)+ expect(resumeSessionMissing(agentId, DEAD, CLAUDE_MISS)).toBe(false)+ }+ expect(detectsResumeMiss('claude')).toBe(true)+ expect(detectsResumeMiss(undefined)).toBe(false)+ })++ it('is not fooled by a prototype key — `agentId` comes from git-shared, hand-editable JSON', () => {+ // `data.agentId` is read straight out of `.nodeterm/project.json`. An `in`/index lookup on an+ // object literal answers for these and hands back a Function where a message builder is+ // expected; the table is a Map so there is no prototype chain to walk.+ for (const forged of ['constructor', '__proto__', 'toString', 'hasOwnProperty']) {+ expect(detectsResumeMiss(forged)).toBe(false)+ expect(resumeSessionMissing(forged, DEAD, CLAUDE_MISS)).toBe(false)+ }+ })++ it('needs an id to compare against — no id, no verdict', () => {+ expect(resumeSessionMissing('claude', undefined, CLAUDE_MISS)).toBe(false)+ expect(resumeSessionMissing('claude', '', CLAUDE_MISS)).toBe(false)+ })++ it('watches for a bounded window, not forever', () => {+ expect(RESUME_MISS_WINDOW_MS).toBeGreaterThan(0)+ expect(RESUME_MISS_WINDOW_MS).toBeLessThanOrEqual(60_000)+ })+})++/**+ * The watcher itself lives inside TerminalNode's lifecycle effect, which is impractical to mount+ * (xterm, a live PTY, a dozen stores) — the same split `session-ready-signal.test.ts` uses. These+ * pin the four properties that make the fallback safe; each is a line whose removal turns a+ * self-healing node back into either a dead pane or a double launch.+ */+const src = readFileSync(join(__dirname, '..', 'nodes', 'TerminalNode.tsx'), 'utf8')++describe('how the fallback is wired (source pins)', () => {+ it('is armed only when we actually asked to resume something we can recognise', () => {+ expect(src).toContain('if (cmd && priorId && detectsResumeMiss(agentId)) {')+ })++ it('re-reads the pane and requires a SHELL before it writes anything', () => {+ // The CLI exits after printing, so a shell is what SHOULD own the pane. Anything else means+ // we misread the situation, and `null` ("could not see the pane") is not evidence either.+ expect(src).toMatch(+ /resumeSessionMissing\(agentId, deadId, seen\)[\s\S]{0,900}?if \(!isShellCommand\(pane\)\) return/+ )+ })++ it('relaunches with NO session id — a fresh start, and one that cannot re-arm the watcher', () => {+ expect(src).toMatch(+ /const \{ command: fresh \} = assembleResumeCommand\(\s*\{\s*agentId,\s*customAgent,\s*sessionId: undefined,/+ )+ })++ it('forgets the proven-dead id on BOTH sides, so the next cold restore does not replay it', () => {+ // The live id from hooks and the id minted at node creation are separate fallbacks for the+ // same slot (`priorId = st?.sessionId || data.agentSessionId`) — clearing one leaves the other+ // to fail identically on the next mount.+ expect(src).toContain('useAgentStatus.getState().setSessionId(id, undefined)')+ expect(src).toContain("updateNodeData(id, { agentSessionId: undefined })")+ })++ it('stops on unmount and after the window, and fires at most once', () => {+ expect(src).toMatch(/const timer = setTimeout\(\(\) => stop\(\), RESUME_MISS_WINDOW_MS\)/)+ expect(src).toMatch(/if \(fired\) return[\s\S]{0,600}?fired = true/)+ expect(src).toMatch(/cleanups\.push\(stop\)/)+ })+})diff --git a/src/renderer/terminal/resume-fallback.ts b/src/renderer/terminal/resume-fallback.tsnew file mode 100644index 000000000..1e196bed0--- /dev/null+++ b/src/renderer/terminal/resume-fallback.ts@@ -0,0 +1,86 @@+/**+ * A COLD-RESTORE RESUME THAT RESOLVES NOTHING FALLS BACK TO A FRESH LAUNCH (issue #707).+ *+ * On a `fresh` mount of an agent node the renderer re-launches the CLI with `--resume <id>`, taking+ * the id from hooks or, failing that, from the one nodeterm MINTED at node creation+ * (`data.agentSessionId`). Both can name a conversation that does not exist:+ *+ * - the minted id is stamped at creation and the session is only created when the launch actually+ * RUNS, so anything that stops that launch — an armed `--after` node whose command is still+ * held, a launch line the tty truncated (#706), an app closed between the two — leaves an id+ * with nothing behind it;+ * - a hook-fed id outlives its transcript. Measured on the reporting host of #616: 9 of 149 panes+ * sat at a bare shell because exactly this had happened.+ *+ * What the user sees either way is one line and then nothing:+ *+ * No conversation found with session ID: 6c0e…-…+ *+ * The CLI has exited, tmux's shell owns the pane, and the node keeps its agent badge over a session+ * that was never started. The fix is to notice that line and start the agent fresh.+ *+ * MEASURED (claude 2.1.266, this box): `claude --resume <unknown-uuid>` prints exactly+ * `No conversation found with session ID: <id>` and exits **1**. That is the whole detector — no+ * exit-code plumbing, because the line is what reaches the renderer.+ *+ * Three rules keep it from firing on a healthy pane, and each is a refusal:+ *+ * 1. **Only an agent whose message we have measured.** The table below has one entry. codex needs+ * a tty to answer at all and gemini was not captured, so they get `false` — the CLI keeps its+ * pane and the node keeps its badge, which is exactly today's behaviour. Adding an id without+ * first capturing its wording is the "guess that degrades to something wrong" this repo warns+ * about: a false positive types a second CLI launch into a pane that already has one.+ * 2. **The message must name the id WE asked for.** A bare substring would also match the user+ * resuming some other session by hand in the same pane, and a transcript that happens to quote+ * the sentence. Binding it to `sessionId` makes the evidence specific to our own launch.+ * 3. **Only inside a bounded window after the resume was delivered.** The CLI prints this+ * immediately or not at all; a watcher left running would fire on output that arrives minutes+ * later from something else entirely.+ *+ * The caller owes a fourth: verify a SHELL owns the pane before writing, exactly as the hibernation+ * wake does. This module decides nothing about delivery.+ */++/**+ * How long after delivering a resume we keep watching for its refusal. The CLI answers in+ * milliseconds; this is generous only so a slow cold boot cannot miss it, and bounded so the+ * watcher is not still armed when the user starts working in the pane.+ */+export const RESUME_MISS_WINDOW_MS = 20_000++/**+ * Per-agent: the line the CLI prints when the session id it was handed names no conversation.+ * **Only add an entry you have run the CLI to capture** — see rule 1.+ *+ * A `Map`, not an object literal, because `agentId` is `data.agentId` — a value out of+ * `.nodeterm/project.json`, which is hand-editable and git-shared. An `in`/index lookup on a plain+ * object answers for `constructor` and `toString` too, returning a **Function** where this code+ * expects a message builder; that is the same hole `approvalFlags` closes with `isPermissionMode`+ * at the interpolation site. A Map has no prototype chain to walk.+ */+const RESUME_MISS_LINES = new Map<string, (sessionId: string) => string>([+ // Measured on claude 2.1.266: `claude --resume <unknown>` → this line, exit 1.+ ['claude', (sessionId) => `No conversation found with session ID: ${sessionId}`]+])++/** Does this agent report a missing session in a way we can recognise? */+export function detectsResumeMiss(agentId: string | undefined): boolean {+ return !!agentId && RESUME_MISS_LINES.has(agentId)+}++/**+ * Did the pane say the conversation we asked to resume does not exist?+ *+ * `text` is expected to be the pane output with escape sequences and line breaks removed (the CLI+ * wraps and colours its own output, and tmux re-wraps it at the pane width, so a raw `includes`+ * would miss the line whenever it happened to straddle a column boundary).+ */+export function resumeSessionMissing(+ agentId: string | undefined,+ sessionId: string | undefined,+ text: string+): boolean {+ if (!agentId || !sessionId) return false+ const line = RESUME_MISS_LINES.get(agentId)+ return !!line && text.includes(line(sessionId))+}