The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Round 35: a held event loop no longer reads as gone panes, dropped messages or unbound agents (#806)
Dee4d868cde63ba
diff --git a/cli/e2e/stall.e2e.ts b/cli/e2e/stall.e2e.tsnew file mode 100644index 000000000..babe772cd--- /dev/null+++ b/cli/e2e/stall.e2e.ts@@ -0,0 +1,246 @@+/**+ * The core's event loop held still for seconds at a time while agents work, for Claude Code and Codex.+ * A synchronous read of a huge file, a heap paged out under memory pressure, a laptop deep in swap: each+ * holds every timer, socket and child of the core at once. When the hold ends, Node runs the timers that+ * came due before it reads the answers that arrived meanwhile, so a probe in flight (`ps`, `tmux`) times+ * out with its answer sitting unread. That says nothing about any agent. A timeout is "could not tell",+ * and only "known gone" may unbind, retire, stop, relaunch or forget.+ *+ * The core is held 2-8 s at a time (core/stall.ts), each hold landing as it starts a child process, so+ * a probe is always in flight: at random, and on purpose while it binds new agents, takes turns,+ * restarts an agent, resumes one, adopts an engine typed into a terminal, reconciles, and restores and+ * attaches every agent after a daemon restart. Every agent must stay bound and active and take its next+ * turn, no engine may run twice, and the master must never take the held core for hung (every hold is+ * far inside its 40 s).+ */+import { execFileSync } from 'node:child_process'+import { mkdirSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'+import { LocalClient, type Frame } from './harness/client.js'+import { IsolatedDaemon, until } from './harness/daemon.js'++type Engine = 'claude' | 'codex'+type Row = Record<string, any>++const STALLS = 'core.stall:2000-8000@12000/spawn'+const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms))+const rows = async (client: LocalClient): Promise<Row[]> =>+ (await client.request<{ agents: Row[] }>('agents_list', { includeStopped: true }, 60_000)).agents+const row = async (client: LocalClient, agentId: string) => (await rows(client)).find((agent) => agent.id === agentId)+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId++/** Hold the core at the next child process it starts, as a test chooses the moment. */+function hold(d: IsolatedDaemon): void {+ const core = d.corePid()+ if (core) process.kill(core, 'SIGUSR2')+}++async function folder(d: IsolatedDaemon, name: string): Promise<string> {+ const cwd = join(d.projectsDir, name)+ mkdirSync(cwd, { recursive: true })+ return cwd+}++const bound = (client: LocalClient, agentId: string, sessionId?: string) =>+ until(`${agentId.slice(0, 8)} to be bound and active`, async () => {+ const now = await row(client, agentId)+ return now?.status === 'active' && now.sessionId && (!sessionId || now.sessionId === sessionId) ? now : null+ }, 120_000, 500)++/** A turn that starts with what was sent and ends once. */+async function turn(client: LocalClient, agentId: string, content: string, during?: () => void): Promise<void> {+ const from = client.frames.length+ const started = client.next(isTurn('turn_started', agentId), 90_000, `turn_started (${content})`)+ const ended = client.next(isTurn('turn_ended', agentId), 120_000, `turn_ended (${content})`)+ client.send('message', { agentId, content })+ during?.()+ expect((await started).payload?.userMessage).toBe(content)+ await ended+ // A turn the held core could not see end must not end again when it looks.+ await sleep(1_000)+ expect(client.frames.slice(from).filter(isTurn('turn_ended', agentId)), `${content}: ended once`).toHaveLength(1)+}++/** The engine processes in each tmux pane, by pid, from tmux's own pane list and the process table. The+ * fake engines take their engine's name as their process title. */+async function enginePids(d: IsolatedDaemon): Promise<Map<string, number[]>> {+ const panes = (await d.tmux.run('list-panes', '-a', '-F', '#{pane_id} #{pane_pid}')).trim().split('\n')+ .map((line) => line.split(' ')).map(([id, pid]) => ({ id, pid: Number(pid) }))+ const table = execFileSync('ps', ['-A', '-o', 'pid=,ppid=,command=']).toString().trim().split('\n')+ .map((line) => line.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/)).filter(Boolean) as RegExpMatchArray[]+ const children = new Map<number, number[]>()+ for (const [, pid, ppid] of table) children.set(Number(ppid), [...(children.get(Number(ppid)) ?? []), Number(pid)])+ const result = new Map<string, number[]>()+ for (const pane of panes) {+ const tree = new Set<number>([pane.pid])+ for (const pid of tree) for (const child of children.get(pid) ?? []) tree.add(child)+ result.set(pane.id, table.filter(([, pid, , command]) => tree.has(Number(pid)) && /^(claude|codex)$/.test(command.trim()))+ .map(([, pid]) => Number(pid)))+ }+ return result+}+const enginesByPane = async (d: IsolatedDaemon): Promise<Map<string, number>> =>+ new Map([...(await enginePids(d))].map(([pane, pids]) => [pane, pids.length]))++/** Every agent in `expected` active, on the conversation it had, with one engine in its pane, and no+ * engine anywhere else. */+async function intact(d: IsolatedDaemon, client: LocalClient, expected: Row[]): Promise<void> {+ const all = await rows(client)+ for (const agent of expected) {+ const now = all.find((one) => one.id === agent.id)+ expect(now?.status, `${agent.id.slice(0, 8)} (${agent.engine}) is active`).toBe('active')+ expect(now?.sessionId, `${agent.id.slice(0, 8)} (${agent.engine}) is on its conversation`).toBe(agent.sessionId)+ }+ // Nothing was minted beside them for a pane or an engine they already own.+ expect(all.filter((one) => one.status === 'active').map((one) => one.id).sort()).toEqual(expected.map((one) => one.id).sort())+ const engines = await until('one engine per agent', async () => {+ const counts = await enginesByPane(d)+ const ok = expected.every((agent) => counts.get(agent.tmuxPane) === 1)+ && [...counts.values()].reduce((sum, n) => sum + n, 0) === expected.length+ return ok ? counts : null+ }, 20_000, 500).catch(async () => enginesByPane(d))+ for (const agent of expected) expect(engines.get(agent.tmuxPane), `${agent.id.slice(0, 8)}: engines in its pane`).toBe(1)+ expect([...engines.values()].reduce((sum, n) => sum + n, 0), 'engines on the tmux server').toBe(expected.length)+}++/** The holds the core logged: there were some, and each was far inside the master's patience. */+function holds(d: IsolatedDaemon): number[] {+ return [...d.log().matchAll(/\[stall\] holding the event loop for (\d+) ms/g)].map((match) => Number(match[1]))+}++/** Nothing on the way was decided from a probe that could not answer. A core held as it is stopped+ * outlives its grace and is killed, which is a stop doing its job; one killed for silence is not. */+function nothingRetired(d: IsolatedDaemon): void {+ const log = d.log()+ expect(log).not.toMatch(/\[harnessd\] core (sent no heartbeat|.*hung)/)+ expect(log).not.toMatch(/\[discovery\] \S+ (retained|dormant|removed|kept) · /)+ expect(log).not.toMatch(/ENGINE_DID_NOT_START|START_TIMEOUT|restored pane disappeared/)+}++describe('the core held still while agents work', () => {+ let daemon: IsolatedDaemon | undefined+ afterEach(async () => { await daemon?.close(); daemon = undefined })+ const fresh = async () => {+ const d = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: STALLS } })+ daemon = d+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-250).join('\n')}`) })+ await d.start()+ await until('the stalls to be armed', () => /\[stall\] armed/.test(d.log()) || null, 30_000, 100)+ return d+ }++ it('creating, turns, a restart, a resume and an engine typed into a terminal: nothing is lost or retired', async () => {+ const d = await fresh()+ const client = await LocalClient.connect(d)++ // Two agents created at once, the core held while their engines start and bind.+ const asked = (['claude', 'codex'] as const).map(async (engine: Engine) =>+ client.request('agent_create', { engine, cwd: await folder(d, `held-${engine}`), bypassPermission: true }, 120_000))+ await sleep(300)+ hold(d)+ const created = await Promise.all(asked)+ for (const answer of created) expect(answer.error, JSON.stringify(answer)).toBeUndefined()+ const agents = await Promise.all(created.map((answer) => bound(client, answer.agent.id)))+ const [claude, codex] = agents++ // Turns, held while they run.+ for (const agent of agents) await turn(client, agent.id, `held during a turn (${agent.engine})`, () => hold(d))+ await turn(client, claude.id, '!slow 6000', () => setTimeout(() => hold(d), 1_500))++ // A restart, held the moment its new engine is up, and a message sent right then by a client that+ // sees the agent still active. The restart may not have recorded the new engine yet: such a message+ // used to be dropped as "no longer running", and an attach then unbound the agent (e2e/races.e2e.ts,+ // a restart nobody waited for).+ for (const agent of agents) {+ const before = (await enginePids(d)).get(agent.tmuxPane) ?? []+ const restarting = client.request('agent_restart', { agentId: agent.id }, 120_000)+ await until('the new engine to start', async () =>+ ((await enginePids(d)).get(agent.tmuxPane) ?? []).some((pid) => !before.includes(pid)) || null, 60_000, 50)+ hold(d)+ await turn(client, agent.id, `while a held restart finishes (${agent.engine})`)+ const restarted = await restarting+ expect(restarted.error, JSON.stringify(restarted)).toBeUndefined()+ await bound(client, agent.id, agent.sessionId)+ await turn(client, agent.id, `after a held restart (${agent.engine})`)+ }++ // A stop and a resume, held while the resumed engine starts.+ expect((await client.request('agent_delete', { agentId: codex.id }, 120_000)).error).toBeUndefined()+ await until('codex to stop', async () => (await row(client, codex.id))?.status === 'stopped' || null, 90_000, 500)+ const resuming = client.request('agent_resume', { agentId: codex.id }, 120_000)+ await sleep(200)+ hold(d)+ const resumed = await resuming+ expect(resumed.error, JSON.stringify(resumed)).toBeUndefined()+ const back = await bound(client, codex.id, codex.sessionId)+ await turn(client, codex.id, 'after a held resume')++ // An engine somebody typed into a terminal, adopted while the core is held.+ const tile = await client.request('agent_create', { engine: 'terminal', cwd: await folder(d, 'held-terminal') }, 120_000)+ expect(tile.error, JSON.stringify(tile)).toBeUndefined()+ const shell = await until('the terminal to have its pane', async () => {+ const now = await row(client, tile.agent.id)+ return now?.tmuxPane && now.status === 'active' ? now : null+ }, 60_000, 500)+ await sleep(2_000)+ await d.tmux.run('send-keys', '-t', shell.tmuxPane, `${join(d.root, 'bin', 'claude')} --dangerously-skip-permissions`, 'Enter')+ await sleep(300)+ hold(d)+ const adopted = await until('the typed engine to be adopted and bound', async () => {+ const now = await row(client, tile.agent.id)+ return now?.engine === 'claude' && now.sessionId && now.status === 'active' ? now : null+ }, 120_000, 500)+ await turn(client, adopted.id, 'typed into a terminal, then held')++ // Reconciles go on under the random holds; nothing may be retired by one that could not answer.+ const everyone = [{ ...claude }, { ...back }, { ...adopted }]+ for (const agent of everyone) agent.tmuxPane = (await row(client, agent.id))!.tmuxPane+ await sleep(40_000)+ await intact(d, client, everyone)+ for (const agent of everyone) await turn(client, agent.id, `still here (${agent.engine})`)++ const held = holds(d)+ expect(held.length, 'the core was held, again and again').toBeGreaterThanOrEqual(8)+ for (const ms of held) expect(ms).toBeLessThanOrEqual(8_000)+ expect(d.coresStarted()).toBe(1)+ nothingRetired(d)+ client.close()+ }, 900_000)++ it('restarted while held: restore and attach find every agent, bound and active, and each takes a turn', async () => {+ const d = await fresh()+ let client = await LocalClient.connect(d)+ const created = await Promise.all((['claude', 'codex'] as const).map(async (engine: Engine) =>+ client.request('agent_create', { engine, cwd: await folder(d, `restart-${engine}`), bypassPermission: true }, 120_000)))+ for (const answer of created) expect(answer.error, JSON.stringify(answer)).toBeUndefined()+ const agents = await Promise.all(created.map((answer) => bound(client, answer.agent.id)))+ for (const agent of agents) await turn(client, agent.id, `before the restarts (${agent.engine})`)++ for (let restart = 1; restart <= 3; restart++) {+ // A turn in flight as the daemon goes, every other time.+ if (restart % 2) client.send('message', { agentId: agents[restart % 2].id, content: '!slow 4000' })+ client.close()+ await d.stop()+ const from = d.log().length+ await d.start({ ready: 'none' })+ // Held as soon as the new core can be (before it listens for the signal, SIGUSR2 would end it), and+ // again while it restores and attaches.+ await until('the new core to arm its stalls', () => /\[stall\] armed/.test(d.log().slice(from)) || null, 60_000, 50)+ hold(d)+ await until('the daemon to be ready', () => /\[cli\] ready/.test(d.log().slice(from)) || null, 120_000, 100)+ hold(d)+ client = await LocalClient.connect(d)+ for (const agent of agents) await bound(client, agent.id, agent.sessionId)+ for (const agent of agents) await turn(client, agent.id, `after held restart ${restart} (${agent.engine})`, () => hold(d))+ await intact(d, client, agents)+ }++ const held = holds(d)+ expect(held.length).toBeGreaterThanOrEqual(6)+ for (const ms of held) expect(ms).toBeLessThanOrEqual(8_000)+ expect(d.coresStarted()).toBe(4)+ nothingRetired(d)+ client.close()+ }, 900_000)+})diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjsindex d945eb8f3..e736e9555 100644--- a/cli/hook/notify.mjs+++ b/cli/hook/notify.mjs@@ -242,11 +242,23 @@ function boundedPrompt(prompt) {return Buffer.byteLength(JSON.stringify(prompt)) <= 128 * 1024 ? prompt : ''}+/**+ * POST one hook event to the daemon. Resolves true when it answered 2xx, false when it could not be+ * reached or refused, and 'late' when it took the request but did not answer within the budget.+ *+ * 'late' is not "the daemon is down", and nothing may be written behind its back for it: the request is+ * in its socket, and it handles it once it gets to it. A daemon whose event loop is held for a few+ * seconds (or one simply slow to answer a session-start, which waits for a discovery pass) used to get+ * the offline fallback on every hook meanwhile, each a registry row rebuilt without the name, launch,+ * permission mode or close plan the daemon kept, merged over its own at its next save+ * (e2e/stall.e2e.ts).+ */function post(port, path, body, onResponse) {return new Promise((resolve) => {const payload = JSON.stringify(body)const credential = readHookCredential()if (!credential) { resolve(false); return }+ let connected = falseconst req = http.request({host: '127.0.0.1',@@ -273,10 +285,14 @@ function post(port, path, body, onResponse) {})})+ req.on('socket', (socket) => {+ if (!socket.connecting) connected = true+ else socket.once('connect', () => { connected = true })+ })req.on('error', () => resolve(false))req.on('timeout', () => {req.destroy()- resolve(false)+ resolve(connected ? 'late' : false)})req.write(payload)req.end()@@ -1353,7 +1369,7 @@ async function main() {const cwd = input.cwdif (copilotEvent === 'sessionEnd') {const ok = await post(port, '/api/hook/session-end', { sessionId, reason: input.reason, ...mutationFields })- if (!ok) await fallbackSessionEnd(sessionId, input.reason, engine, tmuxPane)+ if (ok === false) await fallbackSessionEnd(sessionId, input.reason, engine, tmuxPane)return}if (copilotEvent === 'agentStop') {@@ -1373,7 +1389,7 @@ async function main() {...terminalHookFields(tmuxPane),}const registered = await post(port, '/api/hook/session-start', body)- if (!registered) {+ if (registered === false) {await fallbackRegister({...input, hook_event_name: 'SessionStart', session_id: sessionId, transcript_path: transcriptPath, cwd,}, engine, tmuxPane)@@ -1428,7 +1444,7 @@ async function main() {model: modelName(input.modelName),}const registered = await post(port, '/api/hook/session-start', body)- if (!registered) {+ if (registered === false) {await fallbackRegister({...input,hook_event_name: 'SessionStart',@@ -1447,7 +1463,7 @@ async function main() {const transcriptPath = grokTranscriptPath(paths(), cwd, sessionId)if (grokEventName === 'SessionEnd') {const ok = await post(port, '/api/hook/session-end', { sessionId, reason: input.reason, ...mutationFields })- if (!ok) await fallbackSessionEnd(sessionId, input.reason, engine, tmuxPane)+ if (ok === false) await fallbackSessionEnd(sessionId, input.reason, engine, tmuxPane)return}if (grokEventName === 'StopFailure') {@@ -1467,7 +1483,7 @@ async function main() {cliVersion: input.cliVersion || input.version,}const registered = await post(port, '/api/hook/session-start', body)- if (!registered) {+ if (registered === false) {await fallbackRegister({...input,hook_event_name: grokEventName,@@ -1486,7 +1502,7 @@ async function main() {reason: input.reason,...mutationFields,})- if (!ok) await fallbackSessionEnd(input.session_id || input.conversation_id, input.reason, engine, tmuxPane)+ if (ok === false) await fallbackSessionEnd(input.session_id || input.conversation_id, input.reason, engine, tmuxPane)if (engine === 'cursor' && ok) await clearCursorTasks(input.session_id || input.conversation_id)return}@@ -1528,14 +1544,14 @@ async function main() {cliVersion: input.cursor_version || input.version,}const registered = await post(port, '/api/hook/session-start', body)- if (!registered) await fallbackRegister(input, engine, tmuxPane)+ if (registered === false) await fallbackRegister(input, engine, tmuxPane)const stopped = await post(port, '/api/hook/turn-stop', {sessionId,status: input.status,transcriptPath: input.transcript_path,...mutationFields,})- if (stopped) await clearCursorTasks(sessionId)+ if (stopped === true) await clearCursorTasks(sessionId)return}@@ -1563,7 +1579,7 @@ async function main() {model: modelName(input.model),cliVersion: input.cli_version || input.version,})- if (!registered) await fallbackRegister(input, engine, tmuxPane)+ if (registered === false) await fallbackRegister(input, engine, tmuxPane)}await post(port, '/api/hook/turn-stop', {sessionId: input.session_id,@@ -1603,7 +1619,7 @@ async function main() {cliVersion: input.cli_version || input.cursor_version || input.version,}const ok = await post(port, '/api/hook/session-start', body)- if (!ok) await fallbackRegister(input, engine, tmuxPane)+ if (ok === false) await fallbackRegister(input, engine, tmuxPane)}main()diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 24aad6eb0..139068eff 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -88,7 +88,7 @@ import { claudeProcessSession, findLiveSession, findResumedTranscript } from './import { handoffProviderDeps } from './lib/handoffDiscovery.js'import { TmuxBackend } from './lib/tmuxBackend.js'import { DEFAULT_HOST_THEME, loadHostTheme, saveHostTheme, type HostTheme } from './lib/hostTheme.js'-import { restoreAgents } from './lib/restoreAgents.js'+import { restoreAgents, tmuxSurvey } from './lib/restoreAgents.js'import { createRetainExitedSession } from './lib/retainExitedSession.js'import { createKeepAbandonedConversation } from './lib/keepAbandonedConversation.js'import { OpenTabProtection } from './lib/openTabProtection.js'@@ -112,6 +112,7 @@ import { prepareApiInstructions } from './lib/apiInstructions.js'import type { AgentDshContext } from './lib/agentFrame.js'import {clearPaneRemainOnExit,+ lookupPaneEngineProcess,resolvePaneEngineProcess,tmuxPaneInfo,tmuxPaneState,@@ -170,6 +171,7 @@ import { createCursorTaskHooks } from './core/engines/cursorTasks.js'import { databaseHistory } from './core/transcripts/databaseHistory.js'import { createCoreApi, emptyPorts, FLEET_FALLBACKS, MODELS_FALLBACKS, SEARCH_FALLBACKS, TEAMS_FALLBACKS, VIEWERS_FALLBACKS, WORKSPACES_FALLBACKS, type TeamsPort } from './core/api.js'import { createServiceHost, testFaults } from './core/serviceHost.js'+import { startStalls } from './core/stall.js'import { createServiceLinks } from './core/serviceLinks.js'import { createViewersLink } from './core/viewersLink.js'import { createWorkspacesLink } from './core/workspacesLink.js'@@ -3294,7 +3296,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {// restore never got to, so the next daemon can put them back.try {const backend = tmuxBackend- let paneInventory: ReturnType<typeof listTmuxPanes> | null = nullconst summary = await restoreAgents({retainStopped: retainExitedSession,keepAbandoned: keepAbandonedConversation,@@ -3303,16 +3304,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// A new tmux server hands out `%N` from zero again, so a stale id can name someone's shell;// and a pane that outlived the daemon in a session discovery no longer lists still has its// engine, which a second pane resuming the same session would collide with.- liveProcess: (entry, runtime) => resolvePaneEngineProcess(runtime.paneId, entry.engine),- livePane: async (runtime) => {- // One inventory for the whole restore, not one `tmux list-panes` per row: this runs between- // the control port binding and the first reconcile pass, i.e. on the app's "starting" screen.- paneInventory ??= listTmuxPanes()- const inventory = await paneInventory- // Only a harness pane counts (the inventory is already that whitelist): a new tmux server- // hands out `%N` from zero again, and a stale id can name somebody's own shell.- return inventory.ok && inventory.panes.some((pane) => pane.tmuxPane === runtime.paneId)- },+ ...tmuxSurvey(() => listTmuxPanes(), lookupPaneEngineProcess),buildLaunch: async (entry, opts) => {// A folder that went away with the reboot (an unmounted volume, a workspace deleted while the// daemon was down) is a named failure on the tile, not a pane that prints an error and exits.@@ -3374,6 +3366,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {triggerHint: (runtime, engine) => agentReconciler.triggerHint(runtime, engine),log: (message) => console.log(message),})+ // A row restore could not look at keeps its pane for discovery to judge, but not to retire this boot.+ if (summary.unsurveyed.length) restoreDegraded = trueif (summary.restored.length || summary.failed.length || registry.rebootedSinceLastRun) {console.log(`[restore] restored ${summary.restored.length} · skipped ${summary.skipped.length} · failed ${summary.failed.length}`+ (registry.rebootedSinceLastRun ? ' · after reboot' : ''))@@ -3575,6 +3569,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {keepAbandonedConversation,})const restartJobs = paneSwap.restartJobs+ // A message sent while an engine is being replaced waits for the new one instead of being refused.+ terminals.whileChanging((agentId) => restartJobs.busy(agentId))const sameRestartTarget = paneSwap.sameRestartTargetconst paneSwapDeps = paneSwap.paneSwapDepsconst liveBypassPermission = paneSwap.liveBypassPermission@@ -5544,6 +5540,8 @@ switch (cmd) {break}case '__run': // internal: the detached daemon child reads the durable SSO session — or runs without one+ // Inert unless the end-to-end suite asks for its event loop to be held (core/stall.ts).+ startStalls(testFaults(process.env.HARNESSD_TEST_FAULTS))// NOT `onError`: a daemon that dies here can never be updated. See `enterSafeMode`.runForeground(readAuthSession()).catch(enterSafeMode)breakdiff --git a/cli/src/core/agents/discovery.spec.ts b/cli/src/core/agents/discovery.spec.tsindex 9668bab7d..bbf341a67 100644--- a/cli/src/core/agents/discovery.spec.ts+++ b/cli/src/core/agents/discovery.spec.ts@@ -4,7 +4,7 @@ import type { DiscoveredTerminalAgent } from '../../lib/terminalAgentDiscovery.jimport { bypassPermissionActive, permissionModeFromArgv, tmuxPaneState } from '../../lib/tmux.js'import { createDiscoveryHandlers, type DiscoveryDeps } from './discovery.js'-vi.mock('../../lib/tmux.js', async (real) => ({ ...await real<object>(), tmuxPaneState: vi.fn(async () => null) }))+vi.mock('../../lib/tmux.js', async (real) => ({ ...await real<object>(), tmuxPaneState: vi.fn(async () => 'gone') }))const row = (over: Partial<RegisteredSession> = {}): RegisteredSession =>({ agentId: 'a1', sessionId: 's1', engine: 'claude', active: true, ...over }) as RegisteredSession@@ -65,7 +65,7 @@ const grid = (name: string) => ({ grid: name, baseUrl: `http://${name}.local`, mdescribe('discovery', () => {beforeEach(() => {vi.spyOn(console, 'log').mockImplementation(() => {})- vi.mocked(tmuxPaneState).mockReset().mockResolvedValue(null)+ vi.mocked(tmuxPaneState).mockReset().mockResolvedValue('gone')})afterEach(() => vi.restoreAllMocks())@@ -233,7 +233,10 @@ describe('discovery', () => {it('holds a failed resume while its pane may still be about to launch the engine', async () => {const run = setup()const failed = row({ resumeOnly: true, tmuxPane: '%0', launch: { state: 'failed' } } as Partial<RegisteredSession>)- await run.handlers.onDormant(failed, 'x') // no pane state at all+ await run.handlers.onDormant(failed, 'x') // the pane is gone: the reconciler's to remove+ // tmux could not be asked, as when the daemon's event loop was held: no news either way.+ vi.mocked(tmuxPaneState).mockResolvedValueOnce('unknown')+ await run.handlers.onDormant(failed, 'x')vi.mocked(tmuxPaneState).mockResolvedValueOnce({ dead: false, engineExit: null } as never)await run.handlers.onDormant(failed, 'x') // a live shell, no engine exitexpect(run.deps.retainExitedSession).not.toHaveBeenCalled()diff --git a/cli/src/core/agents/discovery.ts b/cli/src/core/agents/discovery.tsindex a8283ba4a..6f1e7ebf9 100644--- a/cli/src/core/agents/discovery.ts+++ b/cli/src/core/agents/discovery.ts@@ -188,8 +188,9 @@ export function createDiscoveryHandlers({if (agent.resumeOnly && agent.launch?.state === 'failed') {const pane = await tmuxPaneState(agent.tmuxPane)// An unconfirmed install/startup can still be about to launch the engine. Do not- // turn its live shell into permission to start another one.- if (!pane || (!pane.dead && pane.engineExit == null)) return+ // turn its live shell into permission to start another one. A pane that is gone is the+ // reconciler's to remove, and one tmux could not read says nothing: both stay as they are.+ if (typeof pane === 'string' || (!pane.dead && pane.engineExit == null)) return}if (agent.launch?.state !== 'starting') {retainExitedSession(agent, true)diff --git a/cli/src/core/agents/newPane.spec.ts b/cli/src/core/agents/newPane.spec.tsindex 119f52241..8ba270839 100644--- a/cli/src/core/agents/newPane.spec.ts+++ b/cli/src/core/agents/newPane.spec.ts@@ -89,12 +89,24 @@ describe('watching a new pane', () => {it('marks the terminal unavailable when the pane is gone', async () => {const { deps, watch } = setup()- vi.mocked(tmuxPaneState).mockResolvedValueOnce(null)+ vi.mocked(tmuxPaneState).mockResolvedValueOnce('gone')await watch('claude', pending, spawned, ['claude'], undefined)expect(deps.registry.setTerminalAvailable).toHaveBeenCalledWith('a1', false)expect(deps.announceSession).toHaveBeenCalledWith(pending)})+ it('asks again when tmux could not say, and finds the engine once it can', async () => {+ // A read that timed out while the daemon's event loop was held, then the engine it was looking for.+ const { deps, watch } = setup()+ vi.mocked(tmuxPaneState).mockResolvedValueOnce('unknown')+ vi.mocked(resolvePaneEngineProcess).mockResolvedValueOnce(null).mockResolvedValueOnce({ pid: 7, executable: 'claude', startMarker: 'm' })+ const done = watch('claude', pending, spawned, ['claude'], undefined)+ await vi.advanceTimersByTimeAsync(50)+ await done+ expect(deps.registry.setTerminalAvailable).not.toHaveBeenCalled()+ expect(deps.registry.setLaunch).toHaveBeenCalledWith('a1', { state: 'ready' })+ })+it('fails a launch whose pane died: not installed, or did not start', async () => {const { deps, watch } = setup()vi.mocked(tmuxPaneState).mockResolvedValue({ dead: true, engineExit: null } as never)diff --git a/cli/src/core/agents/newPane.ts b/cli/src/core/agents/newPane.tsindex da52cd8ae..4891e187a 100644--- a/cli/src/core/agents/newPane.ts+++ b/cli/src/core/agents/newPane.ts@@ -24,6 +24,11 @@ export interface PaneWatcherDeps {retainExitedSession: (session: RegisteredSession, announce: boolean) => void}+const sleep = (ms: number): Promise<void> => new Promise((resolve) => {+ const timer = setTimeout(resolve, ms)+ timer.unref?.()+})+export function createPaneWatcher({ registry, announceSession, triggerHint, captureTerminal, retainExitedSession }: PaneWatcherDeps) {/*** Watch a pane this daemon just opened until its engine process shows up (ready), dies (failed), or@@ -48,11 +53,18 @@ export function createPaneWatcher({ registry, announceSession, triggerHint, captreturn}const paneState = await tmuxPaneState(spawned.runtime.paneId)- if (!paneState) {+ if (paneState === 'gone') {registry.setTerminalAvailable(pending.agentId, false)announceSession(pending)return}+ // A pane tmux could not read is asked again, as one still starting is: a call that timed out+ // says nothing about it, and giving up here left a working agent's launch unconfirmed.+ if (paneState === 'unknown') {+ await sleep(delayMs)+ delayMs = Math.min(delayMs * 2, 750)+ continue+ }if (paneState.dead) {const installed = await commandAvailableInInteractiveShell(command[0], undefined, installIfMissing)const error = installed ? 'ENGINE_DID_NOT_START' : 'ENGINE_NOT_INSTALLED'@@ -101,10 +113,7 @@ export function createPaneWatcher({ registry, announceSession, triggerHint, captconsole.warn(`[agent] create · ${engine} exited (${paneState.engineExit}) before ready · agent ${pending.agentId} kept as a terminal`)return}- await new Promise<void>((resolve) => {- const timer = setTimeout(resolve, delayMs)- timer.unref?.()- })+ await sleep(delayMs)delayMs = Math.min(delayMs * 2, 750)}const detail = `${engine} did not expose an engine process within ${Math.round(budgetMs / 60_000)} minutes. The terminal remains available.`diff --git a/cli/src/core/stall.spec.ts b/cli/src/core/stall.spec.tsnew file mode 100644index 000000000..aa27ae5f5--- /dev/null+++ b/cli/src/core/stall.spec.ts@@ -0,0 +1,155 @@+import { channel } from 'node:diagnostics_channel'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { testFaults } from './serviceHost.js'+import { processStallDeps, startStalls, type StallDeps } from './stall.js'++function deps(randoms: number[] = []) {+ const held: number[] = []+ const lines: string[] = []+ let signal: (() => void) | null = null+ let spawn: (() => void) | null = null+ let unsubscribed = 0+ const fake: StallDeps = {+ hold: (ms) => { held.push(ms) },+ random: () => randoms.shift() ?? 0.5,+ onSignal: (listener) => {+ signal = listener+ return () => { unsubscribed++; signal = null }+ },+ onSpawn: (listener) => {+ spawn = listener+ return () => { unsubscribed++; spawn = null }+ },+ log: (line) => lines.push(line),+ }+ return { fake, held, lines, signal: () => signal?.(), spawn: () => spawn?.(), unsubscribed: () => unsubscribed }+}++// Holds run in the check phase; this lets one turn of the loop pass.+const turn = () => new Promise((resolve) => setImmediate(resolve))++describe('holding the core\'s event loop on demand, for the stall tests', () => {+ afterEach(() => { vi.useRealTimers() })++ it('is inert unless the faults name it', () => {+ const d = deps()+ expect(startStalls(testFaults(undefined), d.fake)).toBeNull()+ expect(startStalls(testFaults('search,viewers.attach'), d.fake)).toBeNull()+ expect(d.lines).toEqual([])+ })++ it('a fixed length holds for exactly that, on every SIGUSR2, in the check phase', async () => {+ const d = deps()+ const stalls = startStalls(testFaults('search, core.stall:3000'), d.fake)!+ expect(d.lines).toEqual(['[stall] armed: holds of 3000 ms, and on SIGUSR2'])+ d.signal()+ d.signal()+ expect(d.held).toEqual([])+ await turn()+ expect(d.held).toEqual([3000, 3000])+ expect(d.lines.slice(1)).toEqual(['[stall] holding the event loop for 3000 ms', '[stall] holding the event loop for 3000 ms'])+ stalls.stop()+ expect(d.unsubscribed()).toBe(1)+ })++ it('a range picks each length at random within it, and stall() holds at once', async () => {+ const d = deps([0, 1, 0.25])+ const stalls = startStalls(testFaults('core.stall:2000-8000'), d.fake)!+ expect(d.lines[0]).toBe('[stall] armed: holds of 2000-8000 ms, and on SIGUSR2')+ expect(stalls.stall()).toBe(2000)+ expect(stalls.stall()).toBe(8000)+ d.signal()+ await turn()+ expect(d.held).toEqual([2000, 8000, 3500])+ })++ it('with a period, holds come again and again at random intervals averaging it, until stopped', () => {+ vi.useFakeTimers()+ // The first interval (0.5 + 0) × 10 s, the next (0.5 + 1) × 10 s, a length of 2000 + 0.5 × 2000.+ const d = deps([0, 1, 0.5])+ const stalls = startStalls(testFaults('core.stall:2000-4000@10000'), d.fake)!+ expect(d.lines[0]).toBe('[stall] armed: holds of 2000-4000 ms about every 10000 ms, and on SIGUSR2')+ vi.advanceTimersByTime(4_999)+ expect(d.held).toEqual([])+ // Due at 5 s, held in the check phase that follows.+ vi.advanceTimersByTime(1)+ vi.advanceTimersByTime(1)+ expect(d.held).toEqual([3000])+ vi.advanceTimersByTime(14_998)+ expect(d.held).toEqual([3000])+ vi.advanceTimersByTime(1)+ vi.advanceTimersByTime(1)+ expect(d.held).toHaveLength(2)+ stalls.stop()+ vi.advanceTimersByTime(60_000)+ expect(d.held).toHaveLength(2)+ expect(d.unsubscribed()).toBe(1)+ // Stopping twice is harmless.+ stalls.stop()+ })++ it.each([+ 'core.stall', 'core.stall:', 'core.stall:abc', 'core.stall:5000-2000', 'core.stall:2000@0', 'core.stall:2000@',+ 'core.stall:2000@1000/fork',+ ])('a malformed %s is said out loud and holds nothing', (entry) => {+ const d = deps()+ expect(startStalls(testFaults(entry), d.fake)).toBeNull()+ expect(d.lines).toEqual([`[stall] ignored ${entry}: the form is core.stall:<ms>[-<maxMs>][@<periodMs>][/spawn]`])+ expect(d.held).toEqual([])+ })++ it('with /spawn, each hold waits for the next child process and begins once it is running', async () => {+ vi.useFakeTimers()+ // The first interval (0.5 + 0) × 10 s, the next (0.5 + 0.5) × 10 s, a length of 1000 + 0.5 × 2000.+ const d = deps([0, 0.5, 0.5])+ const stalls = startStalls(testFaults('core.stall:1000-3000@10000/spawn'), d.fake)!+ expect(d.lines[0]).toBe('[stall] armed: holds of 1000-3000 ms about every 10000 ms, and on SIGUSR2, each as the core starts a child process')+ // A child with no hold asked for passes untouched.+ d.spawn()+ vi.advanceTimersByTime(1)+ expect(d.held).toEqual([])+ // The period comes due, and a signal asks too: one hold, at the next child, after the code that+ // started it has run on.+ vi.advanceTimersByTime(4_999)+ d.signal()+ expect(d.held).toEqual([])+ d.spawn()+ expect(d.held).toEqual([])+ vi.advanceTimersByTime(1)+ expect(d.held).toEqual([2000])+ d.spawn()+ vi.advanceTimersByTime(1)+ expect(d.held).toEqual([2000])+ stalls.stop()+ expect(d.unsubscribed()).toBe(2)+ })++ it('the process\'s own deps hold the thread for real and listen for SIGUSR2', async () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const before = process.listenerCount('SIGUSR2')+ const stalls = startStalls(testFaults('core.stall:30'), processStallDeps)!+ expect(process.listenerCount('SIGUSR2')).toBe(before + 1)+ const started = performance.now()+ process.emit('SIGUSR2')+ await turn()+ expect(performance.now() - started).toBeGreaterThanOrEqual(25)+ stalls.stop()+ expect(process.listenerCount('SIGUSR2')).toBe(before)+ expect(log).toHaveBeenCalledWith('[stall] holding the event loop for 30 ms')+ expect(processStallDeps.random()).toBeLessThan(1)+ log.mockRestore()+ })++ it('the process\'s own deps see every child process started', async () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const stalls = startStalls(testFaults('core.stall:5/spawn'), processStallDeps)!+ process.emit('SIGUSR2')+ expect(log).not.toHaveBeenCalledWith('[stall] holding the event loop for 5 ms')+ channel('child_process').publish({ process: null })+ await turn()+ expect(log).toHaveBeenCalledWith('[stall] holding the event loop for 5 ms')+ stalls.stop()+ expect(channel('child_process').hasSubscribers).toBe(false)+ log.mockRestore()+ })+})diff --git a/cli/src/core/stall.ts b/cli/src/core/stall.tsnew file mode 100644index 000000000..082540dca--- /dev/null+++ b/cli/src/core/stall.ts@@ -0,0 +1,116 @@+/**+ * A test-only fault: the core's event loop held still for seconds at a time, the way a synchronous read+ * of a huge file, a heap paged out under memory pressure or a debugger pause holds it. Nothing runs while+ * it is held: no timer, no socket, no child's exit. When it lets go, Node runs every timer that came due+ * before it reads the answers that arrived meanwhile, so a probe whose deadline passed during the hold+ * times out with its answer sitting unread. That is "could not tell", and it must never be taken for+ * "gone" (e2e/stall.e2e.ts).+ *+ * `HARNESSD_TEST_FAULTS` names it `core.stall:<ms>[-<maxMs>][@<periodMs>][/spawn]`. Each hold lasts+ * `ms`, or a random length from `ms` to `maxMs`. Holds come at random intervals averaging `periodMs` when+ * one is given, and whenever the core receives SIGUSR2, so a test can hold the loop at the moment it+ * chooses. With `/spawn`, each hold waits for the next child process the core starts and begins as soon+ * as that child is running: a `ps` or `tmux` probe is then always in flight, which a hold that lands+ * anywhere hits only by luck. Under a master, keep every hold well inside its heartbeat limit (40 s by+ * default), or the master rightly takes the core for hung.+ *+ * Every hold runs in the check phase (setImmediate), the one just before the timers. A hold there, like+ * one in an I/O callback, wakes to every deadline that passed during it before the loop reads the+ * answers that arrived. A hold in a timer's own callback would not: Node reads I/O before it runs the+ * timers that came due meanwhile, and the probes in flight would answer as if nothing had happened.+ */+import { subscribe, unsubscribe } from 'node:diagnostics_channel'++export interface StallDeps {+ /** Block the event loop for `ms`. */+ hold: (ms: number) => void+ random: () => number+ /** Call `listener` on every SIGUSR2; returns the unsubscribe. */+ onSignal: (listener: () => void) => () => void+ /** Call `listener` whenever this process starts a child process; returns the unsubscribe. */+ onSpawn: (listener: () => void) => () => void+ log: (line: string) => void+}++export interface Stalls {+ /** Hold the loop now, for a length picked from the range; returns it. */+ stall: () => number+ stop: () => void+}++export const processStallDeps: StallDeps = {+ // Atomics.wait sleeps the thread without spinning, and Node allows it on the main thread.+ hold: (ms) => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) },+ random: Math.random,+ onSignal: (listener) => {+ process.on('SIGUSR2', listener)+ return () => { process.off('SIGUSR2', listener) }+ },+ onSpawn: (listener) => {+ const each = (): void => { listener() }+ subscribe('child_process', each)+ return () => { unsubscribe('child_process', each) }+ },+ log: (line) => console.log(line),+}++const FORM = /^core\.stall:(\d+)(?:-(\d+))?(?:@(\d+))?(\/spawn)?$/++/** Arm the fault when `faults` names it (`testFaults` in ./serviceHost.ts); null when it does not. */+export function startStalls(faults: ReadonlySet<string>, deps: StallDeps = processStallDeps): Stalls | null {+ const entry = [...faults].find((name) => name.startsWith('core.stall'))+ if (!entry) return null+ const match = FORM.exec(entry)+ const minMs = Number(match?.[1])+ const maxMs = match?.[2] === undefined ? minMs : Number(match[2])+ const periodMs = match?.[3] === undefined ? null : Number(match[3])+ // Said out loud: a test that misspells its fault must not pass because nothing was ever held.+ if (!match || maxMs < minMs || periodMs === 0) {+ deps.log(`[stall] ignored ${entry}: the form is core.stall:<ms>[-<maxMs>][@<periodMs>][/spawn]`)+ return null+ }+ const atSpawn = match[4] !== undefined+ const stall = (): number => {+ const ms = Math.round(minMs + deps.random() * (maxMs - minMs))+ deps.log(`[stall] holding the event loop for ${ms} ms`)+ deps.hold(ms)+ return ms+ }+ const holdSoon = (): void => { setImmediate(() => { stall() }) }+ // A hold waiting for the next child; several asked for meanwhile are one.+ let pending = false+ const hold = (): void => {+ if (atSpawn) pending = true+ else holdSoon()+ }+ const stopSpawns = atSpawn+ ? deps.onSpawn(() => {+ if (!pending) return+ pending = false+ // Later in this turn of the loop, once the code that started the child has armed its timeout: the+ // child runs, answers and exits while the loop is held, and its deadline passes unread.+ holdSoon()+ })+ : () => {}+ let timer: NodeJS.Timeout | null = null+ // Random intervals rather than a fixed beat: a beat would land on the same moment of every periodic+ // task, every time, and miss the races between them.+ const schedule = (period: number): void => {+ timer = setTimeout(() => { hold(); schedule(period) }, Math.round(period * (0.5 + deps.random())))+ timer.unref()+ }+ if (periodMs !== null) schedule(periodMs)+ const stopSignals = deps.onSignal(hold)+ const range = minMs === maxMs ? `${minMs}` : `${minMs}-${maxMs}`+ deps.log(`[stall] armed: holds of ${range} ms${periodMs === null ? '' : ` about every ${periodMs} ms`}, and on SIGUSR2`+ + `${atSpawn ? ', each as the core starts a child process' : ''}`)+ return {+ stall,+ stop: () => {+ if (timer) clearTimeout(timer)+ timer = null+ stopSignals()+ stopSpawns()+ },+ }+}diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.tsindex 0315f64e0..1b5c83510 100644--- a/cli/src/hookNotify.spec.ts+++ b/cli/src/hookNotify.spec.ts@@ -715,6 +715,44 @@ describe('hook notify terminal scope', () => {expect(() => readFileSync(join(dataDir, 'registry.json'), 'utf-8')).toThrow()})+ it('does not fall back when the daemon took the event but answers late, as a held daemon does', async () => {+ // A daemon whose event loop is held, or one slow to answer a session-start: the request is in its+ // socket and it handles it once it gets to it. A registry row written behind its back meanwhile was+ // merged over the row the daemon kept, without its name, launch or close plan (e2e/stall.e2e.ts).+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-late-'))+ tmpDirs.push(dir)+ const claudeProjectsDir = join(dir, 'claude-projects')+ const dataDir = join(dir, 'data')+ const transcriptPath = join(claudeProjectsDir, 'demo', 'session-late.jsonl')+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })+ mkdirSync(dataDir, { recursive: true })+ chmodSync(dataDir, 0o755)+ writeLegacyStateFile(join(dataDir, 'registry.json'), '[]')+ writeFileSync(transcriptPath, '{}\n')+ const received: string[] = []+ // Takes every request and answers none of them in time.+ const server = createServer((req, res) => {+ received.push(req.url ?? '')+ setTimeout(() => { try { res.end('{}') } catch { /* the hook has gone */ } }, 2_000).unref()+ })+ servers.push(server)+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()))+ const address = server.address()+ if (!address || typeof address === 'string') throw new Error('test server did not bind a TCP port')++ await runHook({+ port: address.port,+ tmuxPane: '%7',+ processEngine: 'claude',+ dataDir,+ claudeProjectsDir,+ input: { hook_event_name: 'SessionStart', session_id: 'session-late', transcript_path: transcriptPath, cwd: '/tmp/demo' },+ })++ expect(received).toContain('/api/hook/session-start')+ expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toEqual([])+ })+it('does not write fallback registry entries outside tmux or outside the transcript root', async () => {const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-invalid-'))tmpDirs.push(dir)diff --git a/cli/src/lib/autonomous-device/input.spec.ts b/cli/src/lib/autonomous-device/input.spec.tsindex 8273a5792..ec669ad6d 100644--- a/cli/src/lib/autonomous-device/input.spec.ts+++ b/cli/src/lib/autonomous-device/input.spec.ts@@ -296,6 +296,26 @@ describe('native input write evidence', () => {})})+it('lets the next message through once a write could not be checked after its paste', async () => {+ // The check before pressing Enter again could not see the agent (gone, or a probe that failed): the+ // first message is unknown, and the one behind it used to wait until a turn began or ended.+ vi.useFakeTimers()+ const answers = [true, false]+ const inject = vi.fn(async (_target: string, _text: string): Promise<TerminalActionResult> => ({ state: 'succeeded', dispatch: 'executed' }))+ const onDelivery = vi.fn()+ const device = makeDevice({+ getSession: () => ({ agentId: 'agent', engine: 'codex', cliVersion: '0.106.0' }) as RegisteredSession,+ validateRuntime: async () => answers.length ? answers.shift()! : true,+ inject, capture: async () => '› A', onDelivery,+ })+ device.submit('agent', 'A', 'delivery-A')+ device.submit('agent', 'B', 'delivery-B')+ await vi.advanceTimersByTimeAsync(5_000)+ expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'delivery-A', state: 'unknown', reason: 'runtime_gone_post_paste' }))+ expect(inject).toHaveBeenLastCalledWith('agent', 'B')+ device.forget('agent')+})+it('preserves A/B order if a dialog appears during the first preflight check', async () => {vi.useFakeTimers()let release!: (blocked: boolean) => voiddiff --git a/cli/src/lib/autonomous-device/input.ts b/cli/src/lib/autonomous-device/input.tsindex 4f7641b01..aea482f3a 100644--- a/cli/src/lib/autonomous-device/input.ts+++ b/cli/src/lib/autonomous-device/input.ts@@ -223,7 +223,13 @@ export class AutonomousDeviceInput {if (allowRetry && evidence === 'pending' && item.retry && item.retries < 2 && !state.userAction) {state.writing = trueconst session = this.deps.getSession(id)- if (!session || !await this.deps.validateRuntime(session)) { this.delivery(id, item, 'unknown', 'runtime_gone_post_paste'); return }+ // The write is over either way: left active, it held every message behind it until a turn began+ // or ended, and an agent that had gone, or could not be checked, never gave one.+ if (!session || !await this.deps.validateRuntime(session)) {+ this.delivery(id, item, 'unknown', 'runtime_gone_post_paste')+ this.finishWrite(id, state, item)+ return+ }const blocked = await this.deps.isAwaitingUser?.(session)if (this.states.get(id) !== state || state.active !== item || item.started) returnif (!blocked) {diff --git a/cli/src/lib/patientExec.spec.ts b/cli/src/lib/patientExec.spec.tsnew file mode 100644index 000000000..e8d814fa4--- /dev/null+++ b/cli/src/lib/patientExec.spec.ts@@ -0,0 +1,113 @@+import { execFile } from 'node:child_process'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { HELD_MS, MAX_WINDOWS, patientDeadline, patientExec } from './patientExec.js'++const hold = (ms: number) => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) }+const run = patientExec(execFile)+const answer = (file: string, args: string[], timeout: number) =>+ new Promise<{ error: (Error & { killed?: boolean; code?: unknown; signal?: unknown }) | null; stdout: string }>((resolve) => {+ run(file, args, { timeout }, (error, stdout) => resolve({ error, stdout }))+ })++describe('execFile whose timeout a held event loop cannot fool', () => {+ afterEach(() => { vi.useRealTimers() })++ it('reads the answer a child gave while the loop was held, where Node\'s own timeout loses it', async () => {+ // Node's own: held in the check phase past the deadline, the answer is thrown away and the exit+ // reported as a success with nothing in it.+ const lost = new Promise<{ error: Error | null; stdout: string }>((resolve) => {+ execFile('echo', ['still here'], { timeout: 100 }, (error, stdout) => resolve({ error, stdout }))+ })+ setImmediate(() => hold(400))+ expect(await lost).toEqual({ error: null, stdout: '' })++ const kept = answer('echo', ['still here'], 100)+ setImmediate(() => hold(400))+ expect(await kept).toEqual({ error: null, stdout: 'still here\n' })+ })++ it('still times out a child that does not answer, and says so the way Node does', async () => {+ const { error } = await answer('sleep', ['5'], 100)+ expect(error).toMatchObject({ killed: true, code: 'ETIMEDOUT', signal: 'SIGTERM' })+ expect(error!.message).toBe('sleep did not answer within 100 ms')+ })++ it('passes a failure through as it is', async () => {+ const { error } = await answer('false', [], 1_000)+ expect(error).toMatchObject({ code: 1 })+ expect(error).not.toMatchObject({ code: 'ETIMEDOUT' })+ })++ it('arms nothing for a call that answered before it returned, or with no timeout', () => {+ vi.useFakeTimers()+ const done = vi.fn()+ // A test's stand-in that answers at once, and returns no child.+ patientExec((_file: string, _args: string[], _options: object, callback: (...a: unknown[]) => void) => callback(null, 'at once', ''))('x', [], { timeout: 50 }, done)+ expect(done).toHaveBeenCalledWith(null, 'at once', '')+ expect(vi.getTimerCount()).toBe(0)+ patientExec(() => undefined)('x', [], {}, done)+ expect(vi.getTimerCount()).toBe(0)+ // One that calls back with nothing but its error, as some stand-ins do.+ patientExec((_file: string, _args: string[], _options: object, callback: (...a: unknown[]) => void) => callback(null))('x', [], {}, done)+ expect(done).toHaveBeenLastCalledWith(null, '', '')+ })++ it('a stand-in with no child to kill times out without throwing', async () => {+ let callback: ((error: Error | null, stdout: string, stderr: string) => void) | null = null+ const done = vi.fn()+ patientExec((_file: string, _args: string[], _options: object, given: typeof callback) => { callback = given })('x', [], { timeout: 10 }, done)+ await new Promise((resolve) => setTimeout(resolve, 50))+ callback!(new Error('killed'), undefined as never, undefined as never)+ expect(done.mock.calls[0][0]).toMatchObject({ code: 'ETIMEDOUT' })+ expect(done.mock.calls[0].slice(1)).toEqual(['', ''])+ })+})++describe('a deadline that counts only running time', () => {+ afterEach(() => { vi.useRealTimers() })++ it('expires after its time, in the check phase that follows, unless cancelled first', async () => {+ vi.useFakeTimers()+ const expire = vi.fn()+ patientDeadline(100, expire, () => 0)+ vi.advanceTimersByTime(100)+ expect(expire).not.toHaveBeenCalled()+ vi.advanceTimersByTime(1)+ expect(expire).toHaveBeenCalledTimes(1)++ const cancelled = vi.fn()+ const cancel = patientDeadline(100, cancelled, () => 0)+ vi.advanceTimersByTime(100)+ cancel()+ vi.advanceTimersByTime(1)+ expect(cancelled).not.toHaveBeenCalled()+ })++ it('gives the window again from now when the loop was held past it, a few times at most', () => {+ vi.useFakeTimers()+ const expire = vi.fn()+ // Every timer fires a full hold late by this clock.+ let now = 0+ const clock = () => now+ patientDeadline(100, expire, clock)+ for (let window = 1; window < MAX_WINDOWS; window++) {+ now += 100 + HELD_MS + 1+ vi.advanceTimersByTime(100)+ vi.advanceTimersByTime(1)+ expect(expire).not.toHaveBeenCalled()+ }+ now += 100 + HELD_MS + 1+ vi.advanceTimersByTime(100)+ vi.advanceTimersByTime(1)+ expect(expire).toHaveBeenCalledTimes(1)+ })++ it('reads the monotonic clock by default', () => {+ vi.useFakeTimers()+ const expire = vi.fn()+ patientDeadline(10, expire)+ vi.advanceTimersByTime(11)+ vi.advanceTimersByTime(1)+ expect(expire).toHaveBeenCalledTimes(1)+ })+})diff --git a/cli/src/lib/patientExec.ts b/cli/src/lib/patientExec.tsnew file mode 100644index 000000000..994f72b95--- /dev/null+++ b/cli/src/lib/patientExec.ts@@ -0,0 +1,88 @@+/**+ * `execFile` whose timeout is not fooled by a held event loop.+ *+ * When the daemon's event loop is held for a few seconds (a synchronous read of a huge file, a heap+ * paged out, a laptop deep in swap), every child it started keeps running, answers and exits. When the+ * loop wakes it runs the timers that came due before it reads the answers that arrived, so Node's own+ * `timeout` fires on a child that answered long ago. Node then throws the unread output away and reports+ * the exit, 0, as a success with an empty stdout (measured on Node 22: a hold in an I/O or setImmediate+ * callback, `err` null, stdout ""). Every probe read that as an answer: no such pane, no panes at all,+ * no processes. A held core took live agents for gone and acted on it (e2e/stall.e2e.ts).+ *+ * The deadline here counts only time the loop was running. A timer that fires well past its due time+ * was held up with everything else, so the child gets its window again from now. One that fires on+ * time still waits for the check phase before it kills, so an answer that landed in the same instant is+ * read first. A child that really does not answer is killed after `timeout`, and the error says it+ * timed out, as Node's does (`killed`, `signal`).+ */+import type { ExecFileException } from 'node:child_process'++/** A timer this much later than its due time was held up: the loop did not run meanwhile. */+export const HELD_MS = 250+/** At most this many windows for one call, so a loop held again and again still ends the wait. */+export const MAX_WINDOWS = 4++export type ExecDone = (error: ExecFileException | null, stdout: string, stderr: string) => void++export interface PatientExecOptions {+ timeout?: number+ killSignal?: NodeJS.Signals+ maxBuffer?: number+ env?: NodeJS.ProcessEnv+ cwd?: string+}++/**+ * Call `expire` once `ms` of running time has passed, unless cancelled first; returns the cancel.+ * `clock` is a monotonic millisecond clock.+ */+export function patientDeadline(ms: number, expire: () => void, clock: () => number = () => performance.now()): () => void {+ let cancelled = false+ let windows = 0+ let timer: NodeJS.Timeout | undefined+ const arm = (): void => {+ windows+++ const due = clock() + ms+ timer = setTimeout(() => {+ if (clock() - due > HELD_MS && windows < MAX_WINDOWS) { arm(); return }+ setImmediate(() => { if (!cancelled) expire() })+ }, ms)+ }+ arm()+ return () => {+ cancelled = true+ clearTimeout(timer)+ }+}++/**+ * Wrap a module's own `execFile` (passed in, so a test's mock of `child_process` still applies) as one+ * that takes the same arguments and calls back the same way, with the timeout above.+ */+export function patientExec(execFile: (...args: any[]) => unknown) {+ return (file: string, args: readonly string[], options: PatientExecOptions, done: ExecDone): void => {+ const { timeout = 0, killSignal = 'SIGTERM', ...rest } = options+ let finished = false+ let timedOut = false+ let cancel = (): void => {}+ const child = execFile(file, [...args], { ...rest, encoding: 'utf8' }, (error: ExecFileException | null, stdout: string, stderr: string) => {+ finished = true+ cancel()+ // Exit 0 is an answer even when the kill raced it: unlike Node's own timeout, this one never+ // throws the output away.+ if (error && timedOut) {+ done(Object.assign(new Error(`${file} did not answer within ${timeout} ms`), {+ killed: true, signal: killSignal, code: 'ETIMEDOUT', cmd: [file, ...args].join(' '),+ }), stdout ?? '', stderr ?? '')+ return+ }+ done(error, stdout ?? '', stderr ?? '')+ }) as { kill?: (signal: NodeJS.Signals) => boolean } | undefined+ if (timeout > 0 && !finished) {+ cancel = patientDeadline(timeout, () => {+ timedOut = true+ child?.kill?.(killSignal)+ })+ }+ }+}diff --git a/cli/src/lib/restoreAgents.spec.ts b/cli/src/lib/restoreAgents.spec.tsindex 84c66c87d..71dedcb6e 100644--- a/cli/src/lib/restoreAgents.spec.ts+++ b/cli/src/lib/restoreAgents.spec.ts@@ -1,7 +1,7 @@import { describe, expect, it, vi } from 'vitest'import type { AgentLaunch, ProcessIdentity, RegisteredSession } from './registry.js'import type { TerminalRuntimeRef, TmuxRuntimeRef } from './terminalTypes.js'-import { GRID_CREDENTIAL_REQUIRED, restoreAgents, type RestoreAgentsDeps, type RestoreLaunch } from './restoreAgents.js'+import { GRID_CREDENTIAL_REQUIRED, restoreAgents, tmuxSurvey, type RestoreAgentsDeps, type RestoreLaunch } from './restoreAgents.js'import type { GridLaunchOverride } from './gridLaunch.js'const GRID: GridLaunchOverride = {@@ -50,7 +50,7 @@ interface Harness {launched: Array<{ agentId: string; launch: RestoreLaunch }>/** Per-pane scripted answers for probeProcess; shifted on each call. */probes: Map<string, Array<ProcessIdentity | null>>- states: Map<string, Array<{ dead: boolean; engineExit?: number | null } | null>>+ states: Map<string, Array<{ dead: boolean; engineExit?: number | null } | 'gone' | 'unknown'>>nextPane: string[]paneCreates: numberrespawns: number@@ -157,6 +157,59 @@ function harness(rows: RegisteredSession[], opts: { livePanes?: string[]; alivePconst settled = (h: Harness, watches: number, successes = 0) =>vi.waitFor(() => { expect(h.released.length).toBe(watches + successes) })+describe('restoreAgents — a survey that could not tell', () => {+ it('asks a probe that could not answer again, and judges the row by the answer it then gives', async () => {+ const h = harness([row()])+ const asked: string[] = []+ const panes: Array<boolean | 'unknown'> = ['unknown', 'unknown', true]+ const engines: Array<ProcessIdentity | null | 'unknown'> = ['unknown', identity(7)]+ h.deps.livePane = async () => { asked.push('pane'); return panes.shift()! }+ h.deps.liveProcess = async () => { asked.push('engine'); return engines.shift()! }+ const summary = await restoreAgents(h.deps)+ // Its engine is still running: left alone, re-identified, and no second pane opened beside it.+ expect(summary).toEqual({ restored: [], skipped: [], failed: [], unsurveyed: [] })+ expect(asked).toEqual(['pane', 'pane', 'pane', 'engine', 'engine'])+ expect(h.paneCreates).toBe(0)+ expect(h.calls).toContain('updateIdentity:agent-a:7')+ })++ it('leaves a row alone when tmux or ps cannot say, however often it is asked', async () => {+ // Still unknown after every wait: neither archived as exited nor given a second pane resuming the+ // conversation its first may still be in. The caller keeps discovery from retiring it this boot.+ const alive = row({ agentId: 'alive' })+ const gone = row({ agentId: 'gone', tmuxPane: '%4', runtimes: [{ backend: 'tmux', paneId: '%4' }], primaryRuntimeKey: 'tmux\u0000%4' })+ const h = harness([alive, gone])+ h.deps.livePane = async (runtime) => runtime.paneId === '%3' ? true : false+ let asked = 0+ h.deps.liveProcess = async () => { asked++; return 'unknown' }+ h.deps.surveyRetryMs = [1, 1]+ const summary = await restoreAgents(h.deps)+ expect(summary.unsurveyed).toEqual(['alive', 'gone'])+ // The waits are spent once: the second row, after them, is asked once and left alone.+ expect(asked).toBe(3 + 1)+ expect(summary.failed).toEqual([])+ expect(h.paneCreates).toBe(0)+ expect(h.calls.filter((call) => /releaseEngine|createPane/.test(call))).toEqual([])+ })++ it('the tmux survey reads one pane listing, again only after a read that failed', async () => {+ const listings: Array<{ ok: true; panes: Array<{ tmuxPane: string }> } | { ok: false }> = [+ { ok: false }, { ok: true, panes: [{ tmuxPane: '%3' }] },+ ]+ let reads = 0+ const survey = tmuxSurvey(async () => { reads++; return listings.shift()! }, async (pane) =>+ pane === '%1' ? { ok: true, identity: identity(1) } : { ok: false, unknown: pane === '%2' })+ const runtime = (paneId: string): TmuxRuntimeRef => ({ backend: 'tmux', paneId })+ expect(await survey.livePane!(runtime('%3'))).toBe('unknown')+ expect(await survey.livePane!(runtime('%3'))).toBe(true)+ expect(await survey.livePane!(runtime('%5'))).toBe(false)+ expect(reads).toBe(2)+ expect(await survey.liveProcess(row(), runtime('%1'))).toEqual(identity(1))+ expect(await survey.liveProcess(row(), runtime('%2'))).toBe('unknown')+ expect(await survey.liveProcess(row(), runtime('%3'))).toBeNull()+ })+})+describe('restoreAgents — which agents get a pane back', () => {it('recreates a missing pane with a resume launch and hands the row over to discovery', async () => {const h = harness([row()])@@ -164,7 +217,7 @@ describe('restoreAgents — which agents get a pane back', () => {const summary = await restoreAgents(h.deps)- expect(summary).toEqual({ restored: ['agent-a'], skipped: [], failed: [] })+ expect(summary).toEqual({ restored: ['agent-a'], skipped: [], failed: [], unsurveyed: [] })expect(h.launches).toEqual([{ agentId: 'agent-a', resumeSessionId: 'session-a' }])// Every registry write of phase 1 happens inside the one transaction, in this order.expect(h.calls.slice(0, 5)).toEqual([@@ -197,7 +250,7 @@ describe('restoreAgents — which agents get a pane back', () => {it('leaves a pane that still runs its engine alone, re-identifying a row that lost its pid', async () => {const h = harness([row()], { livePanes: ['%3'] })const summary = await restoreAgents(h.deps)- expect(summary).toEqual({ restored: [], skipped: [], failed: [] })+ expect(summary).toEqual({ restored: [], skipped: [], failed: [], unsurveyed: [] })expect(h.paneCreates).toBe(0)// No identity on the row (a misread reboot, a tmux server that outlived the daemon): the live// pid is written back so discovery adopts by process rather than by route.@@ -225,7 +278,7 @@ describe('restoreAgents — which agents get a pane back', () => {const h = harness([row({ agentId: 'gridded', grid: { baseUrl: GRID.baseUrl, model: null }, gridLaunch: GRID })])h.probes.set('%0', [identity(7)])const summary = await restoreAgents(h.deps)- expect(summary).toEqual({ restored: ['gridded'], skipped: [], failed: [] })+ expect(summary).toEqual({ restored: ['gridded'], skipped: [], failed: [], unsurveyed: [] })expect(h.launched).toEqual([{ agentId: 'gridded', launch: { argv: ['claude', '--resume', 'session-a', '--grid', 'grid-abc'], env: { GRID_API_KEY: 'gridkey-abc123' } } }])await settled(h, 1, 1)})@@ -390,12 +443,36 @@ describe('restoreAgents — waiting for the engine', () => {it('fails the launch when the pane vanishes entirely', async () => {const h = harness([row()])- h.states.set('%0', [null])+ h.states.set('%0', ['gone'])await restoreAgents(h.deps)await settled(h, 1)expect(h.rows.get('agent-a')?.launch).toMatchObject({ state: 'failed', error: 'ENGINE_DID_NOT_START' })})+ it('asks again when tmux could not say how the pane is, and binds the engine once it shows', async () => {+ // A read that timed out while the daemon's event loop was held: it failed the restore on the spot.+ const h = harness([row()])+ h.probes.set('%0', [null, null, identity(500)])+ h.states.set('%0', ['unknown', 'unknown'])+ await restoreAgents(h.deps)+ await settled(h, 1, 1)+ expect(h.calls).toContain('updateIdentity:agent-a:500')+ expect(h.calls.some((call) => call.startsWith('setLaunch:agent-a:failed'))).toBe(false)+ })++ it('a pane tmux could not read while the resumed engine settles is no reason to start it over', async () => {+ // The relaunch this used to set off unbound the conversation and respawned the pane over an engine+ // that was working.+ const h = harness([row()], { settleMs: 50 })+ h.probes.set('%0', [identity(500)])+ h.states.set('%0', ['unknown', 'unknown', 'unknown'])+ await restoreAgents(h.deps)+ await settled(h, 1, 1)+ expect(h.respawns).toBe(0)+ expect(h.calls.some((call) => call.startsWith('unbind:'))).toBe(false)+ expect(h.calls).toContain('triggerHint:%0')+ })+it('times out with the launch marked, never leaving the route held', async () => {const h = harness([row()], { budgetMs: 0 })await restoreAgents(h.deps)@@ -423,7 +500,7 @@ describe('restoreAgents — terminals', () => {it('leaves a terminal whose pane is still there alone — a shell has no engine process to look for', async () => {const h = harness([terminal()], { alivePanes: ['%3'] })const summary = await restoreAgents(h.deps)- expect(summary).toEqual({ restored: [], skipped: [], failed: [] })+ expect(summary).toEqual({ restored: [], skipped: [], failed: [], unsurveyed: [] })expect(h.paneCreates).toBe(0)expect(h.calls).toEqual([])})@@ -431,7 +508,7 @@ describe('restoreAgents — terminals', () => {it('recreates a terminal whose pane is gone as a ready shell: no hold, no engine watch', async () => {const h = harness([terminal()])const summary = await restoreAgents(h.deps)- expect(summary).toEqual({ restored: ['term-1'], skipped: [], failed: [] })+ expect(summary).toEqual({ restored: ['term-1'], skipped: [], failed: [], unsurveyed: [] })expect(h.launches).toEqual([{ agentId: 'term-1' }])expect(h.calls).toEqual(['clearIdentity:term-1@tx',@@ -446,7 +523,7 @@ describe('restoreAgents — terminals', () => {it('puts a terminal whose adopted engine exited while the daemon was down back to a shell, pane kept', async () => {const h = harness([terminal({ engine: 'claude', sessionId: 'session-t', boundAt: 1, processIdentity: identity(7) })], { alivePanes: ['%3'] })const summary = await restoreAgents(h.deps)- expect(summary).toEqual({ restored: [], skipped: [], failed: [] })+ expect(summary).toEqual({ restored: [], skipped: [], failed: [], unsurveyed: [] })expect(h.calls).toEqual(['releaseEngine:term-1'])expect(h.rows.get('term-1')).toMatchObject({ engine: 'terminal', sessionId: '' })})@@ -454,7 +531,7 @@ describe('restoreAgents — terminals', () => {it('keeps a terminal whose adopted engine is still running exactly as an agent', async () => {const h = harness([terminal({ engine: 'claude', sessionId: 'session-t', boundAt: 1 })], { alivePanes: ['%3'], livePanes: ['%3'] })const summary = await restoreAgents(h.deps)- expect(summary).toEqual({ restored: [], skipped: [], failed: [] })+ expect(summary).toEqual({ restored: [], skipped: [], failed: [], unsurveyed: [] })expect(h.calls).toEqual(['updateIdentity:term-1:1003'])expect(h.rows.get('term-1')?.engine).toBe('claude')})@@ -463,7 +540,7 @@ describe('restoreAgents — terminals', () => {const h = harness([row({ agentId: 'agent-a', terminalHost: true })], { alivePanes: ['%3'] })// `terminalHost` is what releaseEngine's stub keys on; the real registry sets it for any row.const summary = await restoreAgents(h.deps)- expect(summary).toEqual({ restored: [], skipped: [], failed: [] })+ expect(summary).toEqual({ restored: [], skipped: [], failed: [], unsurveyed: [] })expect(h.paneCreates).toBe(0)expect(h.calls).toEqual(['releaseEngine:agent-a'])expect(h.rows.get('agent-a')).toMatchObject({ engine: 'terminal', sessionId: '' })@@ -482,7 +559,7 @@ describe('restoreAgents — terminals', () => {it('brings a terminal whose adopted engine AND pane are gone back as a shell, never as the engine', async () => {const h = harness([terminal({ engine: 'claude', sessionId: 'session-t', boundAt: 1 })])const summary = await restoreAgents(h.deps)- expect(summary).toEqual({ restored: ['term-1'], skipped: [], failed: [] })+ expect(summary).toEqual({ restored: ['term-1'], skipped: [], failed: [], unsurveyed: [] })expect(h.calls[0]).toBe('releaseEngine:term-1')expect(h.launches).toEqual([{ agentId: 'term-1' }])expect(h.launched[0].launch.argv[0]).toBe('terminal')diff --git a/cli/src/lib/restoreAgents.ts b/cli/src/lib/restoreAgents.tsindex d76c15cc0..a7fec7ba6 100644--- a/cli/src/lib/restoreAgents.ts+++ b/cli/src/lib/restoreAgents.ts@@ -64,12 +64,14 @@ export interface RestoreAgentsDeps {* Whether the row's PANE is still there — a live pane in a session this daemon created. Every* pane is a shell with the engine inside it, so a pane can outlive its engine: that is a terminal* (a bare one has no engine process to find at all), not a pane to rebuild. Optional so a caller- * without tmux inventory (tests) treats a pane with no engine process as gone.+ * without tmux inventory (tests) treats a pane with no engine process as gone. `'unknown'` when the+ * inventory could not be read.*/- livePane?: (runtime: TmuxRuntimeRef) => Promise<boolean>+ livePane?: (runtime: TmuxRuntimeRef) => Promise<boolean | 'unknown'>/** The engine process still running in this row's pane, or null when tmux does not know the pane- * at all — including when no tmux server is running — or the pane has become something else. */- liveProcess: (entry: RegisteredSession, runtime: TmuxRuntimeRef) => Promise<ProcessIdentity | null>+ * at all — including when no tmux server is running — or the pane has become something else.+ * `'unknown'` when tmux or `ps` could not be asked. */+ liveProcess: (entry: RegisteredSession, runtime: TmuxRuntimeRef) => Promise<ProcessIdentity | null | 'unknown'>/** The pane's launch — engine argv plus whatever puts it back on its grid / profile. A grid the* machine cannot honour (unsupported engine, tmux too old, config dir unwritable) is a refusal. */buildLaunch: (entry: RegisteredSession, opts: { resumeSessionId?: string }) => Promise<RestoreLaunchResult>@@ -81,9 +83,10 @@ export interface RestoreAgentsDeps {respawn: (runtime: TmuxRuntimeRef, launch: RestoreLaunch) => Promise<{ ok: boolean; reason?: string }>/** One probe of the pane for a recognizable engine process. */probeProcess: (runtime: TmuxRuntimeRef, engine: AgentEngine) => Promise<ProcessIdentity | null>- /** Null when tmux no longer knows the pane. `engineExit` set: the engine left and the pane is a- * shell now (`ENGINE_EXIT_PANE_OPTION`), which for a restore is the same news as `dead`. */- paneState: (runtime: TmuxRuntimeRef) => Promise<{ dead: boolean; engineExit?: number | null } | null>+ /** `'gone'` when tmux no longer knows the pane, `'unknown'` when it could not be asked (`tmuxPaneState`).+ * `engineExit` set: the engine left and the pane is a shell now (`ENGINE_EXIT_PANE_OPTION`), which for+ * a restore is the same news as `dead`. */+ paneState: (runtime: TmuxRuntimeRef) => Promise<{ dead: boolean; engineExit?: number | null } | 'gone' | 'unknown'>clearRemainOnExit: (runtime: TmuxRuntimeRef) => Promise<void>holdRoute: (routeKey: string, autoReleaseMs: number) => voidreleaseRoute: (routeKey: string) => void@@ -93,6 +96,8 @@ export interface RestoreAgentsDeps {budgetMs?: number/** How long the engine must stay up after appearing before the pane is handed over. */settleMs?: number+ /** The waits between asking a survey probe again (`SURVEY_RETRY_MS`). */+ surveyRetryMs?: readonly number[]sleep?: (ms: number) => Promise<void>}@@ -101,6 +106,60 @@ export interface RestoreSummary {restored: string[]skipped: Array<{ agentId: string; reason: string }>failed: Array<{ agentId: string; reason: string }>+ /** Agents left as they were because tmux or `ps` could not say whether their pane or engine lives.+ * Discovery must not retire them this boot: a pane restore never looked at is not one that closed. */+ unsurveyed: string[]+}++/** The waits between asking again when the survey's probes could not answer: about 8 s in all, the+ * longest a held event loop is expected to keep their answers unread (e2e/stall.e2e.ts). */+export const SURVEY_RETRY_MS: readonly number[] = [250, 500, 1_000, 2_000, 4_000]++class Unsurveyed extends Error {}++/** A probe asked again while it answers `'unknown'`; still unknown after the last wait, the row is left+ * alone. Restore is the one place a wrong "gone" is paid for at once: it archives a running agent,+ * or opens a second pane resuming the conversation the first is still in. The waits are spent once+ * per restore: tmux or `ps` still failing after them is broken, not held, and every row asked after+ * that is left alone at once rather than holding the app's "starting" screen for 8 s a row. */+async function surveyed<T>(deps: RestoreAgentsDeps, patience: { left: boolean }, probe: () => Promise<T | 'unknown'>): Promise<T> {+ const sleep = deps.sleep ?? defaultSleep+ let answer = await probe()+ for (const ms of patience.left ? deps.surveyRetryMs ?? SURVEY_RETRY_MS : []) {+ if (answer !== 'unknown') return answer+ await sleep(ms)+ answer = await probe()+ }+ if (answer !== 'unknown') return answer+ patience.left = false+ throw new Unsurveyed('tmux or ps could not say whether its pane or engine is alive')+}++/**+ * The survey's two questions, asked of tmux: one pane listing for the whole survey, read again only+ * after a read that failed, and the engine in a pane as `lookupPaneEngineProcess` finds it.+ */+export function tmuxSurvey(+ listPanes: () => Promise<{ ok: true; panes: Array<{ tmuxPane: string }> } | { ok: false }>,+ lookup: (pane: string, engine: AgentEngine) => Promise<{ ok: true; identity: ProcessIdentity } | { ok: false; unknown: boolean }>,+): Pick<RestoreAgentsDeps, 'livePane' | 'liveProcess'> {+ let inventory: ReturnType<typeof listPanes> | null = null+ return {+ livePane: async (runtime) => {+ // One inventory for the whole restore, not one `tmux list-panes` per row: this runs between the+ // control port binding and the first reconcile pass, i.e. on the app's "starting" screen.+ inventory ??= listPanes()+ const read = await inventory+ if (!read.ok) { inventory = null; return 'unknown' }+ // Only a harness pane counts (the inventory is already that whitelist): a new tmux server hands+ // out `%N` from zero again, and a stale id can name somebody's own shell.+ return read.panes.some((pane) => pane.tmuxPane === runtime.paneId)+ },+ liveProcess: async (entry, runtime) => {+ const found = await lookup(runtime.paneId, entry.engine)+ return found.ok ? found.identity : found.unknown ? 'unknown' : null+ },+ }}const DEFAULT_BUDGET_MS = 10 * 60_000@@ -120,15 +179,22 @@ function defaultSleep(ms: number): Promise<void> {})}+/** Whether tmux reported the pane's engine gone: the pane dead or forgotten, or its engine exited. A+ * pane tmux could not read is not. */+function engineGone(state: Awaited<ReturnType<RestoreAgentsDeps['paneState']>>): boolean {+ if (state === 'unknown') return false+ return state === 'gone' || state.dead || state.engineExit != null+}+/** Watch a pane whose engine just appeared: 'settled' once it has stayed up for `settleMs`, 'gone' the- * moment tmux reports it dead or forgotten. */+ * moment tmux reports it dead or forgotten. A read that could not answer is no news: the relaunch it+ * used to set off killed a resumed engine that was working, and started its conversation over. */async function waitForSettle(deps: RestoreAgentsDeps, runtime: TmuxRuntimeRef, settleMs: number): Promise<'settled' | 'gone'> {const sleep = deps.sleep ?? defaultSleepconst until = Date.now() + settleMswhile (Date.now() < until) {await sleep(Math.min(SETTLE_POLL_MS, until - Date.now()))- const state = await deps.paneState(runtime)- if (!state || state.dead || state.engineExit != null) return 'gone'+ if (engineGone(await deps.paneState(runtime))) return 'gone'}return 'settled'}@@ -138,7 +204,8 @@ async function waitForSettle(deps: RestoreAgentsDeps, runtime: TmuxRuntimeRef, s* background; the summary says which agents that is happening for.*/export async function restoreAgents(deps: RestoreAgentsDeps): Promise<RestoreSummary> {- const summary: RestoreSummary = { restored: [], skipped: [], failed: [] }+ const summary: RestoreSummary = { restored: [], skipped: [], failed: [], unsurveyed: [] }+ const patience = { left: true }const missing: Array<{ entry: RegisteredSession; runtime: TmuxRuntimeRef }> = []// Per row, because a survey that gives up on the first bad one gives up on every row behind it —@@ -154,9 +221,9 @@ export async function restoreAgents(deps: RestoreAgentsDeps): Promise<RestoreSum// — exactly the exit the reconciler would have caught — and the row is put back to a terminal// here rather than a second pane being opened beside the first. A bare terminal has no engine// process to look for at all.- const paneAlive = await deps.livePane?.(runtime) ?? false+ const paneAlive = deps.livePane ? await surveyed(deps, patience, () => deps.livePane!(runtime)) : falseif (paneAlive) {- const engineLive = isTerminalEngine(entry.engine) ? null : await deps.liveProcess(entry, runtime)+ const engineLive = isTerminalEngine(entry.engine) ? null : await surveyed(deps, patience, () => deps.liveProcess(entry, runtime))if (engineLive) {// Still running. A row that lost its identity without losing its pane (a reboot the boot// clock misread; a tmux server that outlived the daemon) is re-identified right here, so the@@ -189,7 +256,7 @@ export async function restoreAgents(deps: RestoreAgentsDeps): Promise<RestoreSummissing.push({ entry: deps.registry.byAgent(entry.agentId) ?? entry, runtime })continue}- const live = await deps.liveProcess(entry, runtime)+ const live = await surveyed(deps, patience, () => deps.liveProcess(entry, runtime))if (live) {// Still running. A row that lost its identity without losing its pane (a reboot the boot// clock misread; a tmux server that outlived the daemon) is re-identified right here, so the@@ -216,7 +283,8 @@ export async function restoreAgents(deps: RestoreAgentsDeps): Promise<RestoreSummissing.push({ entry, runtime })} catch (error) {const reason = error instanceof Error ? error.message : String(error)- summary.failed.push({ agentId: entry.agentId, reason })+ if (error instanceof Unsurveyed) summary.unsurveyed.push(entry.agentId)+ else summary.failed.push({ agentId: entry.agentId, reason })deps.log(`[restore] ${entry.engine} · agent ${entry.agentId} · could not be surveyed · ${reason}`)}}@@ -350,11 +418,12 @@ async function watchRestoredPane(return}const state = await deps.paneState(runtime)- if (!state) {+ if (state === 'gone') {fail('ENGINE_DID_NOT_START', `${engine}'s restored pane disappeared before its engine process became ready.`)return}- if (state.dead || state.engineExit != null) {+ // A pane tmux could not read is asked again, like one still starting.+ if (engineGone(state)) {if (!await relaunchFresh()) returndelayMs = 50continuediff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.tsindex 5b446da53..e434622a7 100644--- a/cli/src/lib/resumeAgentService.spec.ts+++ b/cli/src/lib/resumeAgentService.spec.ts@@ -433,8 +433,19 @@ describe('existing runtime and readiness verification', () => {if (mode === 'exit dead pane') vi.mocked(tmuxPaneState).mockResolvedValueOnce({ dead: true } as any)if (mode === 'exit unknown process') vi.mocked(checkPidRuntime).mockResolvedValue({ state: 'unknown', reason: 'fixture' })if (mode === 'cancel process probe') vi.mocked(checkPidRuntime).mockImplementation(async () => { deps.restartJobs.cancel(saved.agentId); return { state: 'gone', reason: 'fixture' } })- if (mode === 'cancel pane probe') vi.mocked(tmuxPaneState).mockImplementationOnce(async () => { deps.restartJobs.cancel(saved.agentId); return null })+ if (mode === 'cancel pane probe') vi.mocked(tmuxPaneState).mockImplementationOnce(async () => { deps.restartJobs.cancel(saved.agentId); return 'gone' })expect(await start()).toMatchObject({ ok: false })expect(create).not.toHaveBeenCalled(); expect(deps.stoppedAgents.get(saved.agentId)).not.toBeNull()})+ it.each([+ ['gone', false], ['unknown', true],+ ] as const)('an exited engine whose pane tmux reads as %s keeps its row as a terminal: %s', async (pane, kept) => {+ // Only a pane known to be gone loses its row. One tmux could not read (a call that timed out while+ // the daemon's event loop was held) keeps it, for the reconciler to judge with scans that agree.+ live()+ vi.mocked(resolvePaneEngineProcess).mockResolvedValue(null)+ vi.mocked(tmuxPaneState).mockResolvedValueOnce({ dead: false, engineExit: 1 } as any).mockResolvedValueOnce(pane)+ expect(await start()).toMatchObject({ ok: false, error: 'RESUME_FAILED' })+ expect(deps.retainExitedSession).toHaveBeenCalledWith(expect.objectContaining({ agentId: saved.agentId }), kept)+ })})diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.tsindex d42d52b35..3a3c3a9c1 100644--- a/cli/src/lib/resumeAgentService.ts+++ b/cli/src/lib/resumeAgentService.ts@@ -136,7 +136,9 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {if (!ownsRoute()) return resumeChangedconst pane = await tmuxPaneState(saved.tmuxPane)if (!ownsRoute()) return resumeChanged- retainExitedSession(row, !!pane && !pane.dead)+ // Only a pane known to be gone or dead loses its row. One tmux could not read keeps it, as a+ // terminal: the reconciler removes it once its scans agree the pane is gone.+ retainExitedSession(row, pane === 'unknown' || (pane !== 'gone' && !pane.dead))stoppedAgents.finishResume(saved.agentId)}}diff --git a/cli/src/lib/resumeStoppedAgent.spec.ts b/cli/src/lib/resumeStoppedAgent.spec.tsindex 61adab620..1b3a9b675 100644--- a/cli/src/lib/resumeStoppedAgent.spec.ts+++ b/cli/src/lib/resumeStoppedAgent.spec.ts@@ -149,7 +149,7 @@ describe('exact conversation readiness', () => {current: vi.fn(() => true),session: () => row,process: vi.fn(async (): Promise<typeof process | null> => process),- pane: vi.fn(async (): Promise<{ dead: boolean; engineExit?: number } | null> => ({ dead: false })),+ pane: vi.fn(async (): Promise<{ dead: boolean; engineExit?: number } | 'gone' | 'unknown'> => ({ dead: false })),sleep: vi.fn(async (ms: number) => { now += ms }),now: () => now,budgetMs: 1000,@@ -206,11 +206,18 @@ describe('exact conversation readiness', () => {.resolves.toMatchObject({ ok: true, resumed: false })})- it.each([null, { dead: true }, { dead: false, engineExit: 1 }])('reports early exit without a fresh fallback: %s', async pane => {+ it.each(['gone' as const, { dead: true }, { dead: false, engineExit: 1 }])('reports early exit without a fresh fallback: %s', async pane => {const deps = readiness()deps.pane.mockResolvedValue(pane)await expect(waitForResumedAgent(saved, deps)).resolves.toMatchObject({ ok: false, error: 'RESUME_FAILED' })})+ it('asks again when tmux could not say whether the pane is there, and confirms once it can', async () => {+ // A read that timed out while the daemon's event loop was held used to fail the resume on the spot.+ const deps = readiness()+ deps.pane.mockResolvedValueOnce('unknown')+ await expect(waitForResumedAgent(saved, deps)).resolves.toMatchObject({ ok: true, resumed: true })+ expect(deps.sleep).toHaveBeenCalledWith(250)+ })// A row whose bound conversation is no longer the one being resumed is still refused — that check// is on the row, ahead of any proof, and is what `registry.register`'s mismatch guard feeds.it('still refuses a row that reports another conversation', async () => {@@ -289,7 +296,7 @@ describe('resume refusal and readiness edge cases', () => {expect(result.ok).toBe(mode === 'missing launch' || mode === 'different start')})it('uses the production clock and timeout defaults', async () => {- expect(await waitForResumedAgent(saved, { current: () => false, session: () => undefined, process: async () => null, pane: async () => null, sleep: async () => {} })).toMatchObject({ error: 'AGENT_CHANGED' })+ expect(await waitForResumedAgent(saved, { current: () => false, session: () => undefined, process: async () => null, pane: async () => 'gone', sleep: async () => {} })).toMatchObject({ error: 'AGENT_CHANGED' })})})diff --git a/cli/src/lib/resumeStoppedAgent.ts b/cli/src/lib/resumeStoppedAgent.tsindex be4d1feb2..54c3d5b96 100644--- a/cli/src/lib/resumeStoppedAgent.ts+++ b/cli/src/lib/resumeStoppedAgent.ts@@ -86,7 +86,8 @@ export interface ResumeReadinessDeps {current: () => booleansession: () => RegisteredSession | undefinedprocess: () => Promise<ProcessIdentity | null>- pane: () => Promise<{ dead: boolean; engineExit?: number | null } | null>+ /** `'gone'`: tmux has no such pane; `'unknown'`: it could not be asked (`tmuxPaneState`). */+ pane: () => Promise<{ dead: boolean; engineExit?: number | null } | 'gone' | 'unknown'>sleep: (ms: number) => Promise<void>now?: () => numberbudgetMs?: number@@ -114,7 +115,13 @@ export async function waitForResumedAgent(saved: RegisteredSession, deps: Resumeif (!row) return { ok: false, error: 'RESUME_FAILED', detail: 'The resume runtime disappeared. The saved conversation is still retained.' }if (row.sessionId !== saved.sessionId || row.engine !== saved.engine) return resumeChangedif (row.launch?.state === 'failed') return { ok: false, error: row.launch.error, detail: row.launch.detail }- if (!pane || pane.dead || pane.engineExit != null) {+ // A pane tmux could not read is asked again: a call that timed out while the daemon's event loop+ // was held said the harness had exited, and a resume that was coming up was failed for it.+ if (pane === 'unknown') {+ await deps.sleep(250)+ continue+ }+ if (pane === 'gone' || pane.dead || pane.engineExit != null) {return { ok: false, error: 'RESUME_FAILED', detail: 'The harness exited before confirming the saved conversation. Its terminal output and conversation have been retained.' }}// ONE proof, for every engine: this row's own engine process, running in this row's own pane,diff --git a/cli/src/lib/terminalBackendCoordinator.spec.ts b/cli/src/lib/terminalBackendCoordinator.spec.tsindex 5aee42394..f2da6fb90 100644--- a/cli/src/lib/terminalBackendCoordinator.spec.ts+++ b/cli/src/lib/terminalBackendCoordinator.spec.ts@@ -216,4 +216,60 @@ describe('TerminalBackendCoordinator', () => {expect(coordinator.leaseIsCurrent(acquired.value, current)).toBe(true)await expect(coordinator.validateLease(acquired.value, current)).resolves.toBe(true)})++ describe('a validation that cannot answer yet is asked again', () => {+ const waits: number[] = []+ const patient = (validate: TerminalBackend['validate']) => {+ const tmuxBackend = { ...backend('tmux:default', vi.fn()), validate: vi.fn(validate) }+ waits.length = 0+ const coordinator = new TerminalBackendCoordinator([tmuxBackend], ['tmux'], {+ unknownRetryMs: [10, 20, 30], sleep: async (ms) => { waits.push(ms) },+ })+ return { coordinator, tmuxBackend }+ }++ it('a probe that failed (a held event loop timed it out) is not taken for a dead terminal', async () => {+ const answers = [{ state: 'unknown' as const, reason: 'tmux runtime probe failed' }, { state: 'alive' as const }]+ const { coordinator } = patient(async () => answers.shift()!)+ await expect(coordinator.validate(session())).resolves.toEqual({ state: 'alive' })+ expect(waits).toEqual([10])+ })++ it('an engine restarted in place is waited for until the row records it', async () => {+ // A message sent while a restart is between starting the new engine and recording it: the pane+ // holds a process the row does not know yet. It used to be dropped as "no longer running".+ const current = session()+ const { coordinator, tmuxBackend } = patient(async (_runtime, expected) =>+ expected.processIdentity?.pid === 43 ? { state: 'alive' } : { state: 'gone', reason: 'process changed under tmux pane', replaced: true })+ const acquiring = coordinator.acquireLease(current)+ await Promise.resolve()+ current.processIdentity = { pid: 43, executable: 'claude', startMarker: 'Sat Aug 15 10:01:00 2026' }+ await expect(acquiring).resolves.toMatchObject({ state: 'succeeded' })+ expect(tmuxBackend.validate).toHaveBeenLastCalledWith(tmux, expect.objectContaining({ processIdentity: current.processIdentity }))+ })++ it('waits on a terminal with no engine in it while a restart is replacing that engine', async () => {+ const answers = [{ state: 'gone' as const, reason: 'no claude process under pane %1' }, { state: 'alive' as const }]+ const { coordinator } = patient(async () => answers.shift()!)+ const current = session()+ current.runtimes = [tmux]+ coordinator.whileChanging((agentId) => agentId === current.agentId)+ await expect(coordinator.validate(current)).resolves.toEqual({ state: 'alive' })+ expect(waits).toEqual([10])+ })++ it('gives the last answer once the waits run out, and never waits on a terminal known to be gone', async () => {+ const unknown = patient(async () => ({ state: 'unknown' as const, reason: 'still failing' }))+ const current = session()+ current.runtimes = [tmux]+ await expect(unknown.coordinator.validate(current)).resolves.toEqual({ state: 'unknown', reason: 'still failing' })+ expect(waits).toEqual([10, 20, 30])+ const lease = { agentId: current.agentId, runtime: tmux, placementKey: 'tmux:default\u0000%1', generation: '' }+ const gone = patient(async () => ({ state: 'gone' as const, reason: 'tmux has no pane %1' }))+ await expect(gone.coordinator.validate(current)).resolves.toEqual({ state: 'gone', reason: 'no configured terminal runtime is alive' })+ await expect(gone.coordinator.validateLease(lease, current)).resolves.toBe(false)+ await expect(gone.coordinator.submitText(current, 'hello')).resolves.toMatchObject({ dispatch: 'not_started' })+ expect(waits).toEqual([])+ })+ })})diff --git a/cli/src/lib/terminalBackendCoordinator.ts b/cli/src/lib/terminalBackendCoordinator.tsindex 1be11526a..9c4e88434 100644--- a/cli/src/lib/terminalBackendCoordinator.ts+++ b/cli/src/lib/terminalBackendCoordinator.ts@@ -42,17 +42,72 @@ export function terminalLogicalKey(key: string): TerminalLogicalKey | null {return LEGACY_KEYS[key] ?? null}+/** How long to wait before asking a runtime again when its validation could not answer: about 8 s in+ * all, the longest a held event loop is expected to keep a probe's answer unread (e2e/stall.e2e.ts). */+export const UNKNOWN_RETRY_MS: readonly number[] = [250, 500, 1_000, 2_000, 4_000]++export interface TerminalBackendCoordinatorOptions {+ unknownRetryMs?: readonly number[]+ sleep?: (ms: number) => Promise<void>+}++const defaultSleep = (ms: number): Promise<void> => new Promise((resolve) => {+ const timer = setTimeout(resolve, ms)+ timer.unref?.()+})+/** Resolves all terminal I/O through validated backend-scoped locators. */export class TerminalBackendCoordinator {private readonly byInstance = new Map<string, TerminalBackend>()+ private readonly unknownRetryMs: readonly number[]+ private readonly sleep: (ms: number) => Promise<void>+ private changing: (agentId: string) => boolean = () => falseconstructor(backends: readonly TerminalBackend[],private readonly backendOrder: readonly string[],+ options: TerminalBackendCoordinatorOptions = {},) {+ this.unknownRetryMs = options.unknownRetryMs ?? UNKNOWN_RETRY_MS+ this.sleep = options.sleep ?? defaultSleepthis.replaceBackends(backends)}+ /** Whether a lifecycle operation (restart, retarget, resume) is replacing an agent's engine right now.+ * Set by cli.ts once those exist: they are made long after this coordinator. */+ whileChanging(test: (agentId: string) => boolean): void {+ this.changing = test+ }++ /**+ * One runtime's validation, asked again while it cannot answer yet. Every caller gives up on anything+ * but `alive`, and three answers are only "not yet":+ *+ * - `unknown`, a probe that failed: tmux or `ps` timed out, most often because the core's own event+ * loop was held and woke to the deadline before it read the answer (e2e/stall.e2e.ts). A held loop+ * used to drop the message it was about to type into an engine that was fine ("This agent process+ * is no longer running.") and fail the lease a question's answer was typed through.+ * - `replaced`, the engine in the pane is not the process the row recorded: what a restart looks like+ * between the new engine starting and the restart recording it. A message sent then, by a client+ * that saw the agent still active, was dropped the same way (e2e/races.e2e.ts, a restart nobody+ * waited for).+ * - any `gone` while a lifecycle operation is replacing the engine: between the old engine's exit and+ * the new one's start there is no engine in the pane at all.+ *+ * The row is read again on every ask: `session` is the registry's own, and a restart records the new+ * process on it.+ */+ private async validateRuntime(backend: TerminalBackend, runtime: TerminalRuntimeRef, session: RegisteredSession): Promise<RuntimeValidation> {+ const ask = () => backend.validate(runtime, { engine: session.engine, processIdentity: session.processIdentity ?? undefined })+ let result = await ask()+ for (const ms of this.unknownRetryMs) {+ if (result.state === 'alive' || (result.state === 'gone' && !result.replaced && !this.changing(session.agentId))) return result+ await this.sleep(ms)+ result = await ask()+ }+ return result+ }+replaceBackends(backends: readonly TerminalBackend[]): void {this.byInstance.clear()for (const backend of backends) this.byInstance.set(backend.instanceId, backend)@@ -102,11 +157,7 @@ export class TerminalBackendCoordinator {if (!session.active) return { state: 'gone', reason: 'terminal agent is dormant' }let unknown: RuntimeValidation | null = nullfor (const runtime of this.orderedRuntimes(session)) {- const backend = this.backendFor(runtime)!- const result = await backend.validate(runtime, {- engine: session.engine,- processIdentity: session.processIdentity ?? undefined,- })+ const result = await this.validateRuntime(this.backendFor(runtime)!, runtime, session)if (result.state === 'alive') return resultif (result.state === 'unknown') unknown = result}@@ -116,11 +167,7 @@ export class TerminalBackendCoordinator {async acquireLease(session: RegisteredSession): Promise<TerminalReadResult<TerminalControlLease>> {if (!session.active) return { state: 'failed', reason: 'terminal agent is dormant' }for (const runtime of this.orderedRuntimes(session)) {- const backend = this.backendFor(runtime)!- const validation = await backend.validate(runtime, {- engine: session.engine,- processIdentity: session.processIdentity ?? undefined,- })+ const validation = await this.validateRuntime(this.backendFor(runtime)!, runtime, session)if (validation.state === 'alive') {return {state: 'succeeded',@@ -148,10 +195,7 @@ export class TerminalBackendCoordinator {if (!this.leaseIsCurrent(lease, session)) return falseconst backend = this.backendFor(lease.runtime)if (!backend) return false- return (await backend.validate(lease.runtime, {- engine: session.engine,- processIdentity: session.processIdentity ?? undefined,- })).state === 'alive'+ return (await this.validateRuntime(backend, lease.runtime, session)).state === 'alive'}async capture(session: RegisteredSession, options?: TerminalCaptureOptions): Promise<TerminalReadResult<string>> {@@ -234,10 +278,7 @@ export class TerminalBackendCoordinator {for (const runtime of candidates) {const backend = this.backendFor(runtime)if (!backend) continue- const validation = await backend.validate(runtime, {- engine: session.engine,- processIdentity: session.processIdentity ?? undefined,- })+ const validation = await this.validateRuntime(backend, runtime, session)if (validation.state !== 'alive') continueconst result = await backend.submitText(runtime, text)if (result.state === 'succeeded') {@@ -270,10 +311,7 @@ export class TerminalBackendCoordinator {let last: TerminalActionResult = terminalActionNotStarted('no configured terminal runtime is available')for (const runtime of this.orderedRuntimes(session)) {const backend = this.backendFor(runtime)!- const validation = await backend.validate(runtime, {- engine: session.engine,- processIdentity: session.processIdentity ?? undefined,- })+ const validation = await this.validateRuntime(backend, runtime, session)if (validation.state !== 'alive') continueconst result = await action(backend, runtime)if (result.state === 'succeeded' || result.dispatch === 'possibly_executed') return resultdiff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.tsindex fe7a11ea1..185b897bd 100644--- a/cli/src/lib/terminalTypes.ts+++ b/cli/src/lib/terminalTypes.ts@@ -34,7 +34,9 @@ export type TerminalInventoryResult =export type RuntimeValidation =| { state: 'alive' }- | { state: 'gone'; reason: string }+ /** `replaced`: the pane runs this engine, but not the process the row recorded. An engine restarted,+ * retargeted or resumed in place reads this way until its new identity is recorded. */+ | { state: 'gone'; reason: string; replaced?: true }| { state: 'unknown'; reason: string }/**diff --git a/cli/src/lib/tmux.paneState.spec.ts b/cli/src/lib/tmux.paneState.spec.tsnew file mode 100644index 000000000..a675573bb--- /dev/null+++ b/cli/src/lib/tmux.paneState.spec.ts@@ -0,0 +1,62 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++// `tmux display-message` and `ps` as each version and failure answers them. An empty success is what+// Node hands back when its own timeout fires on an answer a held event loop had not read yet, and each+// reader must take it for no answer, never for "no such pane" or "no processes" (e2e/stall.e2e.ts).+const answer = vi.hoisted(() => ({ err: null as (Error & { killed?: boolean }) | null, stdout: '', stderr: '' }))+vi.mock('child_process', async (real) => {+ const actual = await real<typeof import('child_process')>()+ return {+ ...actual,+ execFile: (file: string, args: string[], _options: unknown, done: (err: Error | null, stdout: string, stderr: string) => void) => {+ if (file === 'tmux' || file === 'ps') { queueMicrotask(() => done(answer.err, answer.stdout, answer.stderr)); return {} }+ return (actual.execFile as unknown as (...a: unknown[]) => unknown)(file, args, _options, done)+ },+ }+})++const { tmuxPaneState, lookupPaneEngineProcess, processRows } = await import('./tmux.js')++describe('what tmux says about a pane', () => {+ afterEach(() => { answer.err = null; answer.stdout = ''; answer.stderr = '' })++ it('reads a live pane, a dead one and one whose engine left it to a shell', async () => {+ answer.stdout = '0|||claude\n'+ expect(await tmuxPaneState('%1')).toEqual({ dead: false, exitStatus: null, engineExit: null, command: 'claude' })+ answer.stdout = '1|2||zsh\n'+ expect(await tmuxPaneState('%1')).toEqual({ dead: true, exitStatus: 2, engineExit: null, command: 'zsh' })+ answer.stdout = '0||1|zsh\n'+ expect(await tmuxPaneState('%1')).toMatchObject({ dead: false, engineExit: 1 })+ })++ it('is gone when tmux says it has no such pane, as every version says it, or has no server', async () => {+ answer.stdout = '|||\n'+ expect(await tmuxPaneState('%9')).toBe('gone')+ answer.err = new Error('Command failed')+ answer.stdout = ''+ answer.stderr = "can't find pane: %9\n"+ expect(await tmuxPaneState('%9')).toBe('gone')+ // No server this process ever read from, so there is no socket to ask back: no pane either.+ answer.stderr = 'no server running on /tmp/tmux-501/default\n'+ expect(await tmuxPaneState('%9')).toBe('gone')+ })++ it('is unknown when tmux could not be asked, or its answer was lost', async () => {+ answer.err = Object.assign(new Error('timed out'), { killed: true })+ expect(await tmuxPaneState('%9')).toBe('unknown')+ answer.err = null+ answer.stdout = ''+ expect(await tmuxPaneState('%9')).toBe('unknown')+ })++ it('takes a lost answer to the pane-pid question for unknown, not for a pane that is gone', async () => {+ answer.stdout = ''+ expect(await lookupPaneEngineProcess('%9', 'claude')).toMatchObject({ ok: false, unknown: true })+ })++ it('takes a process table with nobody in it for a read that failed', async () => {+ // `ps` lists itself at the least. An empty table read as an answer says every engine has exited.+ answer.stdout = ''+ expect(await processRows()).toBeNull()+ })+})diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.tsindex a3184bcef..da3b8431d 100644--- a/cli/src/lib/tmux.ts+++ b/cli/src/lib/tmux.ts@@ -18,8 +18,13 @@ import { BYPASS_PERMISSION_FLAGS, PERMISSION_MODES, permissionModeApproves } froimport { psEnv } from './childLocale.js'import { nativeProcessImages } from './nativeProcessImages.js'import { neutralizePasteControls } from './pasteText.js'+import { patientExec } from './patientExec.js'export { captureTmuxPane, tmuxCaptureArgs } from './tmuxCapture.js'+// Every tmux and `ps` call here: a held event loop must not turn a timeout into an empty answer+// (patientExec.ts).+const run = patientExec(execFile)+function cleanPaneTitle(title: string): string | null {const cleaned = title.trim()@@ -32,7 +37,7 @@ function cleanPaneTitle(title: string): string | null {/** Current tmux pane titles keyed by pane id. AI CLIs update this with their live session title. */export function listPaneTitles(): Promise<Map<string, string>> {return new Promise((resolve) => {- execFile('tmux', ['list-panes', '-a', '-F', '#{pane_id}|#{pane_title}'], { timeout: 2000 }, (err, stdout) => {+ run('tmux', ['list-panes', '-a', '-F', '#{pane_id}|#{pane_title}'], { timeout: 2000 }, (err, stdout) => {const titles = new Map<string, string>()if (err) { resolve(titles); return }for (const line of stdout.split('\n')) {@@ -297,14 +302,16 @@ export function processRows(): Promise<ProcessRow[] | null> {async function readProcessRows(): Promise<ProcessRow[] | null> {const rows = await new Promise<ProcessRow[] | null>((resolve) => {- execFile('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], { timeout: 3000, env: psEnv() }, (err, stdout) => {+ run('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], { timeout: 3000, env: psEnv() }, (err, stdout) => {if (err) { resolve(null); return }const rows: ProcessRow[] = []for (const line of stdout.split('\n')) {const row = parseProcessRow(line)if (row) rows.push(row)}- resolve(rows)+ // `ps` lists itself at the least: a table with nobody in it is a read that failed, and taken for+ // an answer it says every engine on the machine has exited.+ resolve(rows.length ? rows : null)})})return rows ? liveProcessRows(repairMangledRows(rows)) : null@@ -313,8 +320,11 @@ async function readProcessRows(): Promise<ProcessRow[] | null> {function execText(command: string, args: string[], timeout: number): Promise<string | null> {return new Promise((resolve) => {// `lsof -p pid1,pid2` exits 1 when even one process disappears or is inaccessible, while still- // returning complete records for the surviving PIDs. Keep that usable partial snapshot.- execFile(command, args, { timeout }, (err, stdout) => resolve(err && !stdout ? null : stdout))+ // returning complete records for the surviving PIDs. Keep that usable partial snapshot. Node's own+ // timeout, for a deadline shared across calls: `killed` without an error is that timeout throwing+ // away an answer that had arrived (patientExec.ts), so it is no answer, not an empty one.+ let child: { killed?: boolean } | undefined+ child = execFile(command, args, { timeout }, (err, stdout) => resolve((err && !stdout) || child?.killed ? null : stdout))})}@@ -482,7 +492,7 @@ let knownServer: number | null = nullfunction isTmuxProcess(pid: number): Promise<boolean> {try { process.kill(pid, 0) } catch { return Promise.resolve(false) }return new Promise((resolve) => {- execFile('ps', ['-o', 'comm=', '-p', String(pid)], { timeout: 2_000, env: psEnv() }, (err, stdout) => {+ run('ps', ['-o', 'comm=', '-p', String(pid)], { timeout: 2_000, env: psEnv() }, (err, stdout) => {resolve(!err && basename(String(stdout ?? '').trim()) === 'tmux')})})@@ -497,7 +507,7 @@ export async function rememberTmuxServer(): Promise<void> {try { process.kill(knownServer, 0); return } catch { knownServer = null }}await new Promise<void>((resolve) => {- execFile('tmux', ['display-message', '-p', '#{pid}'], { timeout: 2_000 }, (err, stdout) => {+ run('tmux', ['display-message', '-p', '#{pid}'], { timeout: 2_000 }, (err, stdout) => {const pid = Number(String(stdout ?? '').trim())if (!err && Number.isSafeInteger(pid) && pid > 0) knownServer = pidresolve()@@ -534,11 +544,13 @@ export function forgetTmuxServer(): void { knownServer = null }*/function panePidLookup(pane: string, revived = false): Promise<number | 'missing' | null> {return new Promise((resolve) => {- execFile('tmux', ['display-message', '-p', '-t', pane, '#{pane_pid}'], { timeout: 2000 }, (err, stdout, stderr) => {+ run('tmux', ['display-message', '-p', '-t', pane, '#{pane_pid}'], { timeout: 2000 }, (err, stdout, stderr) => {const text = String(stdout ?? '').trim()const pid = Number(text)if (!err && Number.isSafeInteger(pid) && pid > 0) resolve(pid)- else if (!err && text === '') resolve('missing')+ // A pane tmux does not know is an empty LINE: tmux always ends its answer with a newline, and no+ // bytes at all is an answer that was lost (patientExec.ts), never "no such pane".+ else if (!err && text === '' && String(stdout ?? '') !== '') resolve('missing')else if (err && /can't find pane/.test(String(stderr ?? ''))) resolve('missing')else if (err && isNoTmuxServerError(String(stderr ?? ''))) {// A server whose socket was removed is still running this pane: ask it back, then read again.@@ -1086,7 +1098,7 @@ function sleep(ms: number): Promise<void> {function tmuxEnter(pane: string): Promise<boolean> {return new Promise((resolve) => {- execFile('tmux', ['send-keys', '-t', pane, 'Enter'], { timeout: 2000 }, (err) => {+ run('tmux', ['send-keys', '-t', pane, 'Enter'], { timeout: 2000 }, (err) => {if (err) console.error(`[tmux] Enter to ${pane} failed:`, err.message)resolve(!err)})@@ -1114,7 +1126,7 @@ function tmuxLoadBuffer(name: string, content: string): Promise<boolean> {*/export function setPaneMouseOn(pane: string): Promise<void> {return new Promise((resolve) => {- execFile('tmux', ['set-option', '-t', pane, 'mouse', 'on'], { timeout: 2_000 }, () => resolve())+ run('tmux', ['set-option', '-t', pane, 'mouse', 'on'], { timeout: 2_000 }, () => resolve())})}@@ -1126,7 +1138,7 @@ export function setPaneMouseOn(pane: string): Promise<void> {*/export function setPaneWindowStyle(pane: string, style: string): Promise<boolean> {return new Promise((resolve) => {- execFile('tmux', ['set-option', '-w', '-t', pane, 'window-style', style], { timeout: 2_000 }, (error) => resolve(!error))+ run('tmux', ['set-option', '-w', '-t', pane, 'window-style', style], { timeout: 2_000 }, (error) => resolve(!error))})}@@ -1149,18 +1161,46 @@ export interface TmuxPaneState {}/**- * Pane liveness plus, for a pane kept alive by `remain-on-exit`, how its process ended.+ * What tmux said about a pane: its state, `'gone'`, or `'unknown'`.*- * Returns null when tmux does not know the pane — which is itself the answer: the process exited and- * took its window (and, for a one-pane session, the session) with it.+ * `'gone'` when tmux does not know the pane, or no server is running: the process exited and took its+ * window (and, for a one-pane session, the session) with it. `'unknown'` when tmux could not be asked+ * (a timeout, a socket it may not use), which says nothing about the pane, and a caller acts on+ * `'gone'` only. The two used to be one null. A core whose event loop was held for a few seconds wakes+ * to every timer that came due before it reads the answers that arrived meanwhile, so a call in flight+ * times out with its answer sitting unread, and the null read as "gone" failed restored agents,+ * relaunched a resumed engine fresh over its conversation, and stopped a new agent's watcher+ * (e2e/stall.e2e.ts).*/-export function tmuxPaneState(pane: string): Promise<TmuxPaneState | null> {+export type TmuxPaneRead = TmuxPaneState | 'gone' | 'unknown'++/** Pane liveness plus, for a pane kept alive by `remain-on-exit`, how its process ended (see TmuxPaneRead). */+export function tmuxPaneState(pane: string): Promise<TmuxPaneRead> {+ return readPaneState(pane, false)+}++function readPaneState(pane: string, revived: boolean): Promise<TmuxPaneRead> {return new Promise((resolve) => {const format = `#{pane_dead}|#{pane_dead_status}|#{${ENGINE_EXIT_PANE_OPTION}}|#{pane_current_command}`- execFile('tmux', ['display-message', '-p', '-t', pane, format], { timeout: 2_000 }, (err, stdout) => {- if (err) { resolve(null); return }- const fields = stdout.trim().split('|')- if (fields.length < 4) { resolve(null); return }+ run('tmux', ['display-message', '-p', '-t', pane, format], { timeout: 2_000 }, (err, stdout, stderr) => {+ if (err) {+ const said = String(stderr ?? '')+ if (/can't find pane/.test(said)) { resolve('gone'); return }+ if (!isNoTmuxServerError(said)) { resolve('unknown'); return }+ // A server whose socket was removed is still running this pane: ask it back, then read again.+ if (revived) { resolve('gone'); return }+ void reviveRemovedTmuxSocket().then((asked) => {+ if (asked) void readPaneState(pane, true).then(resolve)+ else resolve('gone')+ })+ return+ }+ const fields = String(stdout ?? '').trim().split('|')+ // Not the four fields asked for (no bytes at all is an answer that was lost): nothing to go on.+ if (fields.length < 4) { resolve('unknown'); return }+ // tmux 3.7 answers a pane it does not know with the four fields empty and exit 0; a pane it knows+ // is dead or not, 1 or 0. Older versions say "can't find pane", above.+ if (fields[0] === '') { resolve('gone'); return }const status = Number(fields[1])const engineExit = Number(fields[2])resolve({@@ -1189,7 +1229,7 @@ export function tmuxPaneInfo(pane: string, socket?: string): Promise<TmuxPaneInfconst format = '#{pane_current_command}\n#{pane_pid}\n#{pane_tty}\n#{pane_current_path}'// `socket` names a server outright (tests pass their own); without it, the daemon's server.const args = [...(socket ? ['-S', socket] : []), 'display-message', '-p', '-t', pane, format]- execFile('tmux', args, { timeout: 2_000 }, (err, stdout) => {+ run('tmux', args, { timeout: 2_000 }, (err, stdout) => {if (err) { resolve(null); return }const [command = '', pid = '', tty = '', ...path] = stdout.replace(/\n$/, '').split('\n')const n = Number(pid)@@ -1208,13 +1248,13 @@ export function tmuxPaneInfo(pane: string, socket?: string): Promise<TmuxPaneInf*/export function clearPaneRemainOnExit(pane: string): Promise<void> {return new Promise((resolve) => {- execFile('tmux', ['set-option', '-w', '-t', pane, 'remain-on-exit', 'off'], { timeout: 2_000 }, () => resolve())+ run('tmux', ['set-option', '-w', '-t', pane, 'remain-on-exit', 'off'], { timeout: 2_000 }, () => resolve())})}function tmuxDeleteBuffer(name: string): Promise<void> {return new Promise((resolve) => {- execFile('tmux', ['delete-buffer', '-b', name], { timeout: 2_000 }, () => resolve())+ run('tmux', ['delete-buffer', '-b', name], { timeout: 2_000 }, () => resolve())})}@@ -1232,7 +1272,7 @@ async function tmuxPasteText(pane: string, content: string, bracketed: boolean):if (bracketed) args.push('-p')args.push('-d')const pasted = await new Promise<boolean>((resolve) => {- execFile('tmux', args, { timeout: 2_000 }, (err) => {+ run('tmux', args, { timeout: 2_000 }, (err) => {if (err) console.error(`[tmux] paste-buffer to ${pane} failed:`, err.message)resolve(!err)})@@ -1289,6 +1329,6 @@ export function pasteRawIntoTmux(pane: string, text: string): Promise<boolean> {export function sendKeyToTmux(pane: string, key: string): Promise<boolean> {return new Promise((resolve) => {- execFile('tmux', ['send-keys', '-t', pane, key], { timeout: 2000 }, (err) => resolve(!err))+ run('tmux', ['send-keys', '-t', pane, key], { timeout: 2000 }, (err) => resolve(!err))})}diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.tsindex 38d22c35e..c3c2c83ff 100644--- a/cli/src/lib/tmuxAgentDiscovery.ts+++ b/cli/src/lib/tmuxAgentDiscovery.ts@@ -7,6 +7,7 @@*/import { execFile } from 'node:child_process'+import { patientExec } from './patientExec.js'import {agentAliasOwner,agentCommandOwnershipSnapshot,@@ -88,6 +89,9 @@ const MISS_LIMIT = 2// The rule for "no server is running", shared with every other tmux read (lib/tmux.ts).export { isNoTmuxServerError } from './tmux.js'+// A held event loop must not turn a timeout into an empty answer (patientExec.ts).+const run = patientExec(execFile)+function execText(command: string,args: string[],@@ -95,7 +99,7 @@ function execText(env?: NodeJS.ProcessEnv,): Promise<{ ok: true; stdout: string } | { ok: false; error: string }> {return new Promise((resolve) => {- execFile(command, args, { timeout, ...(env && { env }) }, (err, stdout) => {+ run(command, args, { timeout, ...(env && { env }) }, (err, stdout) => {if (err) { resolve({ ok: false, error: err.message }); return }resolve({ ok: true, stdout })})@@ -159,6 +163,9 @@ export async function listTmuxPanes(owner: string = harnessPaneOwner(env.ADAPTERif (isNoTmuxServerError(result.error)) return { ok: true, panes: [] }return result}+ // A running server has a pane at the least (it exits with its last session): a listing with no bytes+ // in it is one that was lost, and read as an answer it says every agent's pane is gone.+ if (!result.stdout) return { ok: false, error: 'tmux listed no panes' }return {ok: true,panes: parsePanes(result.stdout).filter((pane) => ownedHere(pane.owner ?? '', pane.tmuxSessionName, owner)),diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.tsindex 18d41fe4e..03d5f175e 100644--- a/cli/src/lib/tmuxBackend.spec.ts+++ b/cli/src/lib/tmuxBackend.spec.ts@@ -61,10 +61,12 @@ esac])})- it.each(['gone', 'present', 'unknown', 'malformed', 'no server', 'no socket'] as const)('verifies %s inventory after a failed pane-close reply', async mode => {+ it.each(['gone', 'present', 'unknown', 'malformed', 'no server', 'no socket', 'empty'] as const)('verifies %s inventory after a failed pane-close reply', async mode => {const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-close-'))dirs.push(dir)+ // `empty`: a listing with nothing in it, which a running server never gives: an answer that was lost.const inventory = mode === 'gone' ? "printf '%%43\\n'" : mode === 'present' ? "printf '%%42\\n'"+ : mode === 'empty' ? 'exit 0': mode === 'malformed' ? "printf 'not a pane\\n'" : mode === 'no server'? "printf 'no server running on /tmp/fixture\\n' >&2; exit 1": mode === 'no socket' ? `printf 'error connecting to ${join(dir, 'gone')} (No such file or directory)\\n' >&2; exit 1` : 'exit 1'@@ -78,6 +80,16 @@ esacexpect(discovery).not.toHaveBeenCalled()})+ it('takes a pane listing with nothing in it for a read that was lost, never for no panes', async () => {+ // What Node hands back when its timeout fires on an answer a held event loop had not read yet:+ // success, and nothing. Read as an answer, it said every agent's pane was gone (e2e/stall.e2e.ts).+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-empty-'))+ dirs.push(dir)+ writeFileSync(join(dir, 'tmux'), '#!/bin/sh\nexit 0\n', { mode: 0o700 })+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`+ expect(await new TmuxBackend(undefined, () => 'daemon-a').inventory()).toEqual({ state: 'unavailable', reason: 'tmux listed no panes' })+ })+it('sees the panes it tagged wherever they moved, untagged ones only in its sessions, never another daemon\'s', async () => {// A dev daemon beside the release one, on one tmux server (2026-10-03): each opened an agent for the// other's panes until a pane said whose it was. And the person moves panes: a renamed session, a panediff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.tsindex 56f069c95..3157b4d13 100644--- a/cli/src/lib/tmuxBackend.ts+++ b/cli/src/lib/tmuxBackend.ts@@ -1,4 +1,5 @@import { execFile } from 'node:child_process'+import { patientExec } from './patientExec.js'import type { TerminalBackend } from './terminalBackend.js'import {TERMINAL_ACTION_SUCCEEDED,@@ -38,6 +39,10 @@ import { DEFAULT_HOST_THEME, windowStyleOf, type HostTheme } from './hostTheme.jimport { isNoTmuxServerError, listTmuxPanes } from './tmuxAgentDiscovery.js'import { terminalRouteKey } from './terminalRuntime.js'+// Every tmux call here: a held event loop must not turn a timeout into a failure, or into an empty+// answer that reads as a pane that was never made (patientExec.ts).+const run = patientExec(execFile)+const TMUX_KEYS: Record<TerminalLogicalKey, string> = {enter: 'Enter',escape: 'Escape',@@ -145,7 +150,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {// `killed`/`signal` come from execFile's own error shape, which ErrnoException alone does not declare.type ExecError = NodeJS.ErrnoException & { killed?: boolean; signal?: NodeJS.Signals | null }const result = await new Promise<{ error: ExecError | null; stdout: string; stderr: string }>((resolve) => {- execFile('tmux', args, { timeout: 5_000 }, (error, stdout, stderr) => resolve({+ run('tmux', args, { timeout: 5_000 }, (error, stdout, stderr) => resolve({error: error as ExecError | null,stdout,stderr,@@ -192,7 +197,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {for (const [key, value] of Object.entries(request.env ?? {})) args.push('-e', `${key}=${value}`)args.push('-t', runtime.paneId, ...request.command)const result = await new Promise<{ error: NodeJS.ErrnoException | null; stderr: string }>((resolve) => {- execFile('tmux', args, { timeout: 5_000 }, (error, _stdout, stderr) => resolve({+ run('tmux', args, { timeout: 5_000 }, (error, _stdout, stderr) => resolve({error: error as NodeJS.ErrnoException | null,stderr,}))@@ -210,7 +215,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {// Discovered harnesses can share a tmux session with unrelated work. The// canonical pane id is the entire target; never widen this to kill-session.const ok = await new Promise<boolean>((resolve) => {- execFile('tmux', ['kill-pane', '-t', runtime.paneId], { timeout: 5_000 }, (error) => resolve(!error))+ run('tmux', ['kill-pane', '-t', runtime.paneId], { timeout: 5_000 }, (error) => resolve(!error))})if (ok) return TERMINAL_ACTION_SUCCEEDED// The engine may have exited and removed its pane before the parallel PID@@ -218,10 +223,11 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {// Use all panes here: discovery deliberately hides sessions that were renamed// or created elsewhere, and their absence from discovery is not proof of exit.const absent = await new Promise<boolean>(resolve => {- execFile('tmux', ['list-panes', '-a', '-F', '#{pane_id}'], { timeout: 2_000 }, (error, stdout) => {+ run('tmux', ['list-panes', '-a', '-F', '#{pane_id}'], { timeout: 2_000 }, (error, stdout) => {if (error) { resolve(isNoTmuxServerError(error.message)); return }const ids = stdout.trim().split('\n').filter(Boolean)- resolve(ids.every(id => /^%\d+$/.test(id)) && !ids.includes(runtime.paneId))+ // A running server lists a pane at the least: an empty listing is a read that was lost, not proof.+ resolve(ids.length > 0 && ids.every(id => /^%\d+$/.test(id)) && !ids.includes(runtime.paneId))})})if (absent) return TERMINAL_ACTION_SUCCEEDED@@ -240,7 +246,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {const sessionId = await this.resolveSessionId(runtime.paneId)if (!sessionId) return terminalActionNotStarted('tmux session could not be resolved from pane')const ok = await new Promise<boolean>((resolve) => {- execFile('tmux', clearEnvArgs(sessionId, names), { timeout: 5_000 }, (error) => resolve(!error))+ run('tmux', clearEnvArgs(sessionId, names), { timeout: 5_000 }, (error) => resolve(!error))})return legacyActionResult(ok, 'tmux clear environment')}@@ -248,7 +254,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {/** The id of the session that owns [paneId], or null when tmux will not say. */private resolveSessionId(paneId: string): Promise<string | null> {return new Promise((resolve) => {- execFile('tmux', ['display-message', '-p', '-t', paneId, '#{session_id}'], { timeout: 2_000 }, (error, stdout) => {+ run('tmux', ['display-message', '-p', '-t', paneId, '#{session_id}'], { timeout: 2_000 }, (error, stdout) => {const value = stdout.trim()resolve(!error && /^\$\d+$/.test(value) ? value : null)})@@ -265,7 +271,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {*/async holdOpen(runtime: TmuxRuntimeRef): Promise<TerminalActionResult> {const ok = await new Promise<boolean>((resolve) => {- execFile('tmux', ['set-option', '-w', '-t', runtime.paneId, 'remain-on-exit', 'on'], { timeout: 2_000 }, (error) => {+ run('tmux', ['set-option', '-w', '-t', runtime.paneId, 'remain-on-exit', 'on'], { timeout: 2_000 }, (error) => {resolve(!error)})})@@ -347,7 +353,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {}if (expected.processIdentity&& (expected.processIdentity.pid !== live.pid || expected.processIdentity.startMarker !== live.startMarker)) {- return { state: 'gone', reason: 'process changed under tmux pane' }+ return { state: 'gone', reason: 'process changed under tmux pane', replaced: true }}return { state: 'alive' }} catch {@@ -379,7 +385,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {async setTitle(runtime: TmuxRuntimeRef, title: string): Promise<TerminalActionResult> {const ok = await new Promise<boolean>((resolve) => {- execFile('tmux', ['select-pane', '-t', runtime.paneId, '-T', title.slice(0, 200)], { timeout: 2_000 }, (error) => {+ run('tmux', ['select-pane', '-t', runtime.paneId, '-T', title.slice(0, 200)], { timeout: 2_000 }, (error) => {resolve(!error)})})@@ -389,7 +395,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {async notify(runtime: TmuxRuntimeRef, title: string, body: string): Promise<TerminalActionResult> {const message = `${title.slice(0, 200)}: ${body.slice(0, 1_000)}`const ok = await new Promise<boolean>((resolve) => {- execFile('tmux', ['display-message', '-t', runtime.paneId, '--', message], { timeout: 2_000 }, (error) => {+ run('tmux', ['display-message', '-t', runtime.paneId, '--', message], { timeout: 2_000 }, (error) => {resolve(!error)})})diff --git a/cli/src/lib/tmuxCapture.spec.ts b/cli/src/lib/tmuxCapture.spec.tsindex 3eb38aa61..21e508c08 100644--- a/cli/src/lib/tmuxCapture.spec.ts+++ b/cli/src/lib/tmuxCapture.spec.ts@@ -37,8 +37,9 @@ describe('fresh tmux capture batching', () => {childProcess.execFile.mockImplementation((_file, _args, _options, done) => done(null, 'default screen\n'))expect(await captureTmuxPane('%7', 40, { ansi: false })).toBe('default screen\n')expect(childProcess.execFile).toHaveBeenCalledOnce()+ // Its 2 s deadline is patientExec's own, which a held event loop cannot fool, not Node's `timeout`.expect(childProcess.execFile.mock.calls[0].slice(0, 3)).toEqual([- 'tmux', tmuxCaptureArgs('%7', 40, { ansi: false }), { timeout: 2_000, maxBuffer: 1024 * 1024 },+ 'tmux', tmuxCaptureArgs('%7', 40, { ansi: false }), { maxBuffer: 1024 * 1024, encoding: 'utf8' },])})diff --git a/cli/src/lib/tmuxCapture.ts b/cli/src/lib/tmuxCapture.tsindex 1e272faec..f1ff796a7 100644--- a/cli/src/lib/tmuxCapture.ts+++ b/cli/src/lib/tmuxCapture.ts@@ -1,5 +1,6 @@import { execFile } from 'node:child_process'import { randomUUID } from 'node:crypto'+import { patientExec } from './patientExec.js'type CaptureOptions = { visible?: boolean; ansi?: boolean }type CaptureExecutor = (args: string[], options: { timeout: number; maxBuffer: number },@@ -24,8 +25,9 @@ export function tmuxCaptureArgs(pane: string, historyLines = 100, options: Captuexport class TmuxCaptureBatcher {private pending: PendingCapture[] = []+ // A held event loop must not turn a timeout into an empty screen (patientExec.ts).constructor(private readonly execute: CaptureExecutor = (args, options, done) => {- execFile('tmux', args, options, done)+ patientExec(execFile)('tmux', args, options, done)}) {}capture(pane: string, historyLines = 100, options: CaptureOptions = {}): Promise<string | null> {diff --git a/cli/src/lib/tmuxStream.ts b/cli/src/lib/tmuxStream.tsindex 14dd163ef..c8e738119 100644--- a/cli/src/lib/tmuxStream.ts+++ b/cli/src/lib/tmuxStream.ts@@ -1,4 +1,5 @@import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'+import { patientDeadline } from './patientExec.js'import { pasteRawIntoTmux } from './tmux.js'import {TERMINAL_ACTION_SUCCEEDED,@@ -301,7 +302,8 @@ interface PendingControlCommand {command: stringlines: Buffer[]commandNumber: string | null- timer: ReturnType<typeof setTimeout> | null+ /** Cancels the head's deadline (`armHead`). */+ timer: (() => void) | nullonEnd?: () => voidresolve: (result: ControlCommandResult) => void}@@ -373,7 +375,7 @@ export class ControlCommandQueue {const head = this.outstanding[0]if (!head || head.commandNumber !== commandNumber) return falsethis.outstanding.shift()- if (head.timer) clearTimeout(head.timer)+ head.timer?.()head.timer = nullif (kind === 'end') head.onEnd?.()head.resolve({ ok: kind === 'end', stdout: decodeControlResponse(head.lines) })@@ -384,7 +386,7 @@ export class ControlCommandQueue {failAll(): void {const abandoned = [...this.outstanding.splice(0), ...this.waiting.splice(0)]for (const command of abandoned) {- if (command.timer) clearTimeout(command.timer)+ command.timer?.()command.timer = nullcommand.resolve(CONTROL_COMMAND_FAILED)}@@ -417,10 +419,13 @@ export class ControlCommandQueue {private armHead(): void {const head = this.outstanding[0]if (!head || head.timer) return- head.timer = setTimeout(() => {+ // Running time, not wall time: a daemon whose event loop was held wakes to this deadline before it+ // reads the reply tmux sent meanwhile, and took the stream down for a command that had answered+ // (patientExec.ts, e2e/stall.e2e.ts).+ head.timer = patientDeadline(this.timeoutMs, () => {if (this.outstanding[0] !== head) returnthis.deps.onFatal('tmux control command timed out')- }, this.timeoutMs)+ })}}diff --git a/cli/src/startupOrder.spec.ts b/cli/src/startupOrder.spec.tsindex 703ba68d6..62ad51e36 100644--- a/cli/src/startupOrder.spec.ts+++ b/cli/src/startupOrder.spec.ts@@ -141,7 +141,9 @@ describe('cli.ts start-up order', () => {it('the daemon arm survives its own start-up failure', () => {const source = code(SOURCE)- const arm = source.slice(source.indexOf("case '__run'"), source.indexOf("case '__run'") + 400)+ // The whole arm, to its break: a fixed window read past it as the arm grew a line (the stall fault).+ const start = source.indexOf("case '__run'")+ const arm = source.slice(start, source.indexOf('break', start))expect(arm).toContain('catch(enterSafeMode)')expect(arm, 'a daemon that exits here can never be updated').not.toContain('catch(onError)')})