Skip to content

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.

Verify harness resume with native lifecycle acceptance tests

dee086ade9b9625
diff --git a/cli/package.json b/cli/package.json
index a61eadc83..79dbc4cb5 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -19,7 +19,9 @@
"test:remote-viewers": "vitest run --config vitest.viewer.config.ts",
"test:cursor-e2e": "RUN_CURSOR_E2E=1 vitest run src/engines/cursor/localE2e.spec.ts",
"test:tmux-real": "RUN_REAL_TMUX_DISCOVERY=1 vitest run src/lib/tmuxAgentDiscovery.real.spec.ts --reporter=verbose",
- "test:herdr-real": "RUN_REAL_HERDR=1 vitest run src/lib/herdrBackend.real.spec.ts --reporter=verbose"
+ "test:herdr-real": "RUN_REAL_HERDR=1 vitest run src/lib/herdrBackend.real.spec.ts --reporter=verbose",
+ "test:resume": "vitest run src/lib/resumeStoppedAgent.spec.ts src/lib/resumeAgentService.spec.ts src/lib/stoppedAgents.spec.ts src/lib/stopAgentService.spec.ts --coverage --coverage.include=src/lib/resumeStoppedAgent.ts --coverage.include=src/lib/resumeAgentService.ts --coverage.include=src/lib/stoppedAgents.ts --coverage.include=src/lib/stopAgentService.ts --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.branches=100 --coverage.thresholds.functions=100 --coverage.reporter=text --coverage.reporter=json --coverage.reportsDirectory=coverage/resume",
+ "test:resume-native": "tsx scripts/resume-native-e2e.ts"
},
"dependencies": {
"@noble/ciphers": "^1.3.0",
diff --git a/cli/scripts/resume-native-e2e.ts b/cli/scripts/resume-native-e2e.ts
new file mode 100644
index 000000000..b603a1678
--- /dev/null
+++ b/cli/scripts/resume-native-e2e.ts
@@ -0,0 +1,227 @@
+/** Real Claude/Codex + production resume handler, registry, hooks and tmux.
+ * Native TUIs load disposable local history. Codex defers SessionStart until input;
+ * its test prompt targets a deliberately unavailable loopback provider, never a paid API.
+ * Run: node --import tsx scripts/resume-native-e2e.ts
+ * Every service, profile, conversation and tmux socket belongs to this fixture.
+ */
+import { execFile as execCallback } from 'node:child_process'
+import { promisify } from 'node:util'
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, realpathSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, resolve } from 'node:path'
+import { randomUUID } from 'node:crypto'
+import assert from 'node:assert/strict'
+const exec = promisify(execCallback)
+const root = realpathSync(mkdtempSync(join(tmpdir(), 'harness-resume-native-')))
+const cliRoot = resolve('.')
+const tmuxBinary = (await exec('/usr/bin/which', ['tmux'])).stdout.trim()
+const claudeBinary = realpathSync((await exec('/usr/bin/which', ['claude'])).stdout.trim())
+const codexBinary = realpathSync((await exec('/usr/bin/which', ['codex'])).stdout.trim())
+const socket = `resume-e2e-${process.pid}`
+const quote = (value: string) => `'${value.replace(/'/g, `'\\''`)}'`
+const bin = join(root, 'bin'); mkdirSync(bin)
+writeFileSync(join(bin, 'tmux'), `#!/bin/sh\nexec ${quote(tmuxBinary)} -L ${quote(socket)} -f /dev/null "$@"\n`, { mode: 0o700 })
+Object.assign(process.env, {
+ PATH: `${bin}:${process.env.PATH}`, ADAPTER_DATA_DIR: join(root, 'data'), ADAPTER_RUNTIME_DIR: join(root, 'runtime'),
+ ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'), HARNESS_AUTH_DIR: join(root, 'auth'), DSH_DIR: join(root, 'dsh'),
+ CLAUDE_PROJECTS_DIR: join(root, 'claude', 'projects'), CODEX_HOME: join(root, 'codex'), CLAUDE_PATH: claudeBinary, CODEX_PATH: codexBinary,
+ HARNESS_STORE_CATALOG_URL: 'http://127.0.0.1:9/catalog.json',
+})
+const tmux = async (...args: string[]) => (await exec(tmuxBinary, ['-L', socket, '-f', '/dev/null', ...args], { timeout: 5000 })).stdout
+const { registry } = await import('../src/lib/registry.js')
+const { stoppedAgents } = await import('../src/lib/stoppedAgents.js')
+const { TmuxBackend } = await import('../src/lib/tmuxBackend.js')
+const { createStopAgentService } = await import('../src/lib/stopAgentService.js')
+const { createResumeAgentService } = await import('../src/lib/resumeAgentService.js')
+const { AgentRestartCoordinator } = await import('../src/lib/restartAgent.js')
+const { resolvePaneEngineProcess, checkSessionRuntime } = await import('../src/lib/tmux.js')
+const { checkPidRuntime } = await import('../src/lib/deleteAgentFallback.js')
+const { startHookServer } = await import('../src/hookServer.js')
+const { BackendSocket } = await import('../src/backendSocket.js')
+const { installCodexHooks } = await import('../src/lib/hooks.js')
+const backend = new TmuxBackend()
+const socketBackend = new BackendSocket('fixture-only')
+const hooks: Array<{ engine: string; sessionId: string }> = []
+const server = await startHookServer(0, {
+ onSessionEnd: () => {},
+ onRegistered: row => { stoppedAgents.save(row); hooks.push({ engine: row.engine, sessionId: row.sessionId }); if (row.resumeOnly) stoppedAgents.finishResume(row.agentId) },
+ resolveHookAgent: async input => {
+ if (!input.tmuxPane) return null
+ const identity = await resolvePaneEngineProcess(input.tmuxPane, input.engine)
+ if (!identity) { console.error('[fixture] no process for', input); return null }
+ const row = registry.byPaneEngine(input.tmuxPane, input.engine)
+ if (!row || row.engine !== input.engine) { console.error('[fixture] no registry route', input, identity, registry.list().map(r => ({ id: r.agentId, pane: r.tmuxPane }))); return null }
+ return registry.openProcessAgent({ engine: input.engine, processIdentity: identity, runtimes: row.runtimes, primaryRuntimeKey: row.primaryRuntimeKey, cwd: row.cwd })?.entry ?? null
+ },
+})
+const replies = new Map<string, any>()
+socketBackend.registerLocalClient('local:resume-e2e', { sendFrame: frame => { const f = frame as any; if (f.payload?.requestId) replies.set(f.payload.requestId, f.payload); return true }, sendBinary: () => true })
+const rpc = async (type: string, payload: Record<string, unknown>) => {
+ const requestId = randomUUID(); socketBackend.handleLocalFrame('local:resume-e2e', { type, payload: { ...payload, requestId } })
+ const until = Date.now() + 55000
+ while (!replies.has(requestId) && Date.now() < until) await new Promise(r => setTimeout(r, 20))
+ const response = replies.get(requestId); assert(response, `missing ${type} reply`); return response
+}
+const log = (msg: string) => console.log(`[resume-native] ${msg}`)
+try {
+ // Anchor keeps pane IDs monotonic even after Stop removes the last engine session.
+ await tmux('new-session', '-d', '-s', 'fixture-anchor', '/bin/sh')
+ for (const engine of ['claude', 'codex'] as const) {
+ const cwd = join(root, engine, 'workspace'); mkdirSync(cwd, { recursive: true })
+ const profile = join(root, engine)
+ const sessionId = randomUUID(); const marker = `RESUME_HISTORY_${engine}_${sessionId.slice(0, 8)}`
+ const timestamp = new Date().toISOString()
+ let transcriptPath: string
+ if (engine === 'claude') {
+ const project = join(profile, 'projects', cwd.replace(/[^a-zA-Z0-9]/g, '-')); mkdirSync(project, { recursive: true })
+ transcriptPath = join(project, `${sessionId}.jsonl`)
+ const user = randomUUID()
+ writeFileSync(transcriptPath, [
+ { type: 'user', uuid: user, parentUuid: null, sessionId, cwd, version: '2.1.278', timestamp, isSidechain: false, userType: 'external', message: { role: 'user', content: marker } },
+ { type: 'assistant', uuid: randomUUID(), parentUuid: user, sessionId, cwd, version: '2.1.278', timestamp, isSidechain: false, message: { id: 'msg_fixture', type: 'message', role: 'assistant', model: 'claude-sonnet-4-6', content: [{ type: 'text', text: `Retained ${marker}` }], stop_reason: 'end_turn', usage: { input_tokens: 1, output_tokens: 1 } } },
+ ].map(row => JSON.stringify(row)).join('\n') + '\n')
+ writeFileSync(join(profile, '.claude.json'), JSON.stringify({ hasCompletedOnboarding: true, theme: 'dark', projects: { [cwd]: { hasTrustDialogAccepted: true, allowedTools: [] } } }))
+ const cmd = [process.execPath, join(cliRoot, 'hook', 'notify.mjs'), '--port', String(server.port), '--data-dir', process.env.ADAPTER_DATA_DIR!, '--claude-projects-dir', process.env.CLAUDE_PROJECTS_DIR!].map(quote).join(' ')
+ writeFileSync(join(profile, 'settings.json'), JSON.stringify({ apiKeyHelper: 'printf fixture-never-used', hooks: { SessionStart: [{ hooks: [{ type: 'command', command: cmd, timeout: 5 }] }] } }))
+ } else {
+ const folder = join(profile, 'sessions', timestamp.slice(0,4), timestamp.slice(5,7), timestamp.slice(8,10)); mkdirSync(folder, { recursive: true })
+ transcriptPath = join(folder, `rollout-${timestamp.replace(/:/g, '-')}-${sessionId}.jsonl`)
+ writeFileSync(transcriptPath, [
+ { timestamp, type: 'session_meta', payload: { id: sessionId, timestamp, cwd, originator: 'codex_cli_rs', cli_version: '0.154.0', source: 'cli', model_provider: 'fixture' } },
+ { timestamp, type: 'event_msg', payload: { type: 'task_started', turn_id: sessionId, model_context_window: 100000 } },
+ { timestamp, type: 'event_msg', payload: { type: 'user_message', message: marker, images: [], local_images: [], text_elements: [] } },
+ { timestamp, type: 'response_item', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: marker }] } },
+ { timestamp, type: 'response_item', payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: `Retained ${marker}` }] } },
+ { timestamp, type: 'event_msg', payload: { type: 'agent_message', message: `Retained ${marker}`, phase: 'final_answer' } },
+ { timestamp, type: 'event_msg', payload: { type: 'task_complete', turn_id: sessionId, last_agent_message: `Retained ${marker}` } },
+ ].map(row => JSON.stringify(row)).join('\n') + '\n')
+ writeFileSync(join(profile, 'config.toml'), `model_provider = "fixture"\n[model_providers.fixture]\nname = "Local fixture"\nbase_url = "http://127.0.0.1:9/v1"\nwire_api = "responses"\nrequires_openai_auth = false\n[projects.${JSON.stringify(cwd)}]\ntrust_level = "trusted"\n[features]\nhooks = true\n`)
+ installCodexHooks(server.port, profile)
+
+ }
+ const old = registry.openPendingAgent({ engine, runtimes: [{ backend: 'tmux', paneId: '%99999' }], cwd, codexHome: engine === 'codex' ? profile : null, defaultName: `Native ${engine} fixture` })!
+ const saved = { ...old, sessionId, transcriptPath, launch: { state: 'ready' as const }, processIdentity: null }
+ stoppedAgents.save(saved); registry.removeAgent(old.agentId)
+ const launchEnv: Record<string, string> = {
+ CLAUDE_CONFIG_DIR: join(root, 'claude'), CODEX_HOME: join(root, 'codex'), ZDOTDIR: root,
+ DISABLE_AUTOUPDATER: '1', DISABLE_NONESSENTIAL_TRAFFIC: '1', DISABLE_TELEMETRY: '1',
+ ANTHROPIC_BASE_URL: 'http://127.0.0.1:9', OPENAI_BASE_URL: 'http://127.0.0.1:9/v1',
+ PATH: `${bin}:${process.env.PATH}`, HARNESS_HOOK_DATA_DIR: process.env.ADAPTER_DATA_DIR!,
+ }
+ if (engine === 'codex') {
+ const bootstrap = await backend.create({ cwd, label: 'fixture-hook-trust', command: [codexBinary, '--no-alt-screen'], env: launchEnv })
+ assert.equal(bootstrap.state, 'succeeded')
+ if (bootstrap.state === 'succeeded') {
+ const until = Date.now() + 15000
+ let trusted = false
+ while (Date.now() < until) {
+ const screen = await tmux('capture-pane', '-p', '-t', bootstrap.runtime.paneId)
+ if (/Hooks need review/.test(screen)) await tmux('send-keys', '-t', bootstrap.runtime.paneId, 'Down', 'Enter')
+ if (readFileSync(join(profile, 'config.toml'), 'utf8').includes('trusted_hash')) { trusted = true; break }
+ await new Promise(r => setTimeout(r, 200))
+ }
+ assert(trusted, 'Codex must trust fixture hooks through its native review UI')
+ await backend.kill(bootstrap.runtime)
+ }
+ }
+ const jobs = new AgentRestartCoordinator()
+ const stopJobs = new Map<string, Promise<void>>()
+ socketBackend.onDeleteAgent = createStopAgentService({
+ registry, stoppedAgents, restartJobs: jobs, stopJobs, tmuxBackend: backend,
+ agentReconciler: { suppress: () => {}, trigger: async () => {} },
+ forgetSession: id => registry.removeAgent(id), markDeleted: () => {}, clearDeleted: () => {},
+ })
+ socketBackend.onResumeAgent = createResumeAgentService({
+ registry, stoppedAgents, tmuxBackend: backend, restartJobs: jobs, stopJobs, pinnedControls: new Set(),
+ announceSession: () => {}, relaunchOverrides: async () => ({ ok: true, overrides: { env: launchEnv, extraArgs: [], clearEnv: ['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'CLAUDECODE'] } }),
+ prepareSessionResume: () => {}, refreshGridWebSearch: () => {}, clearDeleted: () => {}, attachDsh: () => {},
+ retainExitedSession: (row, alive) => { stoppedAgents.save(row); if (alive) registry.releaseEngine(row.agentId, true); else registry.removeAgent(row.agentId) },
+ })
+ const inventory = await rpc('agents_list', { includeStopped: true })
+ assert(inventory.agents.some((a: any) => a.id === old.agentId && a.status === 'stopped'))
+ const openSaved = async (creationId: string) => {
+ let settled = false, submitted = false
+ const hookCount = hooks.length
+ const opening = rpc('agent_resume', { agentId: old.agentId, creationId }).finally(() => { settled = true })
+ const deadline = Date.now() + 45000
+ while (!settled && Date.now() < deadline) {
+ const row = registry.byAgent(old.agentId)
+ if (row) {
+ await tmux('resize-window', '-t', row.tmuxPane, '-x', '140', '-y', '45')
+ const screen = await tmux('capture-pane', '-p', '-S', '-500', '-t', row.tmuxPane)
+ writeFileSync(join(root, `${engine}-screen.txt`), screen)
+ if (/Hooks need review/.test(screen)) await tmux('send-keys', '-t', row.tmuxPane, 'Down', 'Enter')
+ if (/trust this folder|trust the files|Yes, I trust|confirm.*API key/i.test(screen)) await tmux('send-keys', '-t', row.tmuxPane, 'Enter')
+ // Codex 0.154 defers SessionStart until the next submitted turn. First prove
+ // that opening alone restored visible history, then simulate user input so
+ // the real hook can confirm the receipt. Production never submits a prompt.
+ if (engine === 'codex' && row.launch?.state === 'starting' && !submitted && hooks.length === hookCount && screen.includes(marker) && /Ask Codex/.test(screen)) {
+ assert.equal(row.launch?.state, 'starting')
+ submitted = true
+ log('Codex history is visible before input; verifying its deferred native hook')
+ await tmux('send-keys', '-t', row.tmuxPane, '-l', 'Fixture verification only. Do not use tools.')
+ await new Promise(r => setTimeout(r, 600))
+ await tmux('send-keys', '-t', row.tmuxPane, 'Enter')
+ }
+ }
+ await new Promise(r => setTimeout(r, 250))
+ }
+ assert(settled, `${engine} did not confirm: ${readFileSync(join(root, `${engine}-screen.txt`), 'utf8')}`)
+ return opening
+ }
+ const creationId = randomUUID()
+ const result = await openSaved(creationId)
+ assert.equal(result.state, 'created', JSON.stringify(result)); assert.equal(result.resumed, true)
+ const live = registry.byAgent(old.agentId)!
+ assert.equal(live.sessionId, sessionId); assert.equal(live.launch?.state, 'ready'); assert(live.processIdentity)
+ assert(hooks.some(h => h.engine === engine && h.sessionId === sessionId), 'native SessionStart must confirm saved id')
+ const screen = await tmux('capture-pane', '-p', '-S', '-500', '-t', live.tmuxPane)
+ assert(screen.includes(marker), 'restored conversation text must be visible')
+ const pid = live.processIdentity!.pid; const route = live.tmuxPane
+ assert.equal((await checkSessionRuntime(live)).state, 'alive')
+ assert.equal((await rpc('agent_resume', { agentId: old.agentId, creationId: randomUUID() })).resumed, true)
+ assert.equal(registry.byAgent(old.agentId)!.processIdentity!.pid, pid); assert.equal(registry.byAgent(old.agentId)!.tmuxPane, route)
+ assert.equal((await rpc('agent_create_status', { creationId })).state, 'created')
+ // Stop uses a known fixture-owned tmux session; its saved row survives a registry reload.
+ assert.equal((await rpc('agent_delete', { agentId: live.agentId })).deleted, true)
+ assert.equal((await checkPidRuntime(live)).state, 'gone')
+ registry.load(); assert(!registry.byAgent(old.agentId)); assert.equal(stoppedAgents.get(old.agentId)!.sessionId, sessionId)
+ assert((await rpc('agents_list', { includeStopped: true })).agents.some((a: any) => a.id === old.agentId && a.status === 'stopped'))
+ const reopened = await openSaved(randomUUID())
+ assert.equal(reopened.state, 'created', JSON.stringify(reopened))
+ assert.equal(registry.byAgent(old.agentId)!.sessionId, sessionId)
+ assert.notEqual(registry.byAgent(old.agentId)!.tmuxPane, route)
+ assert.notEqual(registry.byAgent(old.agentId)!.processIdentity!.pid, pid)
+ // A native engine exit is different from Stop: preserve the surviving shell
+ // and prove that resuming the conversation never replaces that shell's work.
+ const exited = { ...registry.byAgent(old.agentId)! }
+ assert.equal((await checkSessionRuntime(exited)).state, 'alive')
+ assert(exited.cwd?.startsWith(root), 'only a fixture-owned process may be signaled')
+ process.kill(exited.processIdentity!.pid, 'SIGTERM')
+ const exitDeadline = Date.now() + 10000
+ while ((await checkPidRuntime(exited)).state !== 'gone' && Date.now() < exitDeadline) await new Promise(r => setTimeout(r, 100))
+ assert.equal((await checkPidRuntime(exited)).state, 'gone')
+ const shellMarker = `SURVIVING_SHELL_${engine}`
+ await new Promise(r => setTimeout(r, 300))
+ await tmux('send-keys', '-t', exited.tmuxPane, '-l', `printf '${shellMarker}\\n'; sleep 30`)
+ await tmux('send-keys', '-t', exited.tmuxPane, 'Enter')
+ const shellPid = (await tmux('display-message', '-p', '-t', exited.tmuxPane, '#{pane_pid}')).trim()
+ const afterExit = await openSaved(randomUUID())
+ assert.equal(afterExit.state, 'created')
+ assert.equal(registry.byAgent(old.agentId)!.sessionId, sessionId)
+ assert.notEqual(registry.byAgent(old.agentId)!.tmuxPane, exited.tmuxPane)
+ const shell = registry.byRuntimeTerminal({ backend: 'tmux', paneId: exited.tmuxPane })!
+ assert.equal(shell.engine, 'terminal'); assert.notEqual(shell.agentId, old.agentId)
+ assert.equal((await tmux('display-message', '-p', '-t', exited.tmuxPane, '#{pane_pid}')).trim(), shellPid)
+ assert((await tmux('capture-pane', '-p', '-t', exited.tmuxPane)).includes(shellMarker))
+ assert.equal((await rpc('agent_delete', { agentId: old.agentId })).deleted, true)
+ log(`PASS ${engine}: native history + hook, new tmux runtime, same id, attach same PID, receipt replay, stop persistence, surviving shell preserved`)
+ }
+} finally {
+ await tmux('kill-server').catch(() => {})
+ server.server.closeAllConnections(); await new Promise<void>(r => server.server.close(() => r()))
+ await socketBackend.stop()
+ // Keep fixture diagnostics when requested; contains only synthetic history, no credentials.
+ if (process.env.KEEP_RESUME_FIXTURE === '1') log(`fixture: ${root}`)
+ else rmSync(root, { recursive: true, force: true })
+}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index d552269e6..e6ba8283f 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -43,7 +43,7 @@ import { DaemonCableHost, cableEventFor, cableQuestionFor, cableQuestionCloseFor
import { MachineListCache, machineListCachePath, withStaleMarker } from './device/machineList.js'
import { DeviceLink } from './device/deviceLink.js'
import { DeviceFleet } from './device/deviceFleet.js'
-import { registry, projectDisplayName, validTranscriptPath, type RegisteredSession } from './lib/registry.js'
+import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
import { engineSessionTitle } from './lib/sessionTitle.js'
import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installGrokHooks, installAgyHooks, installCopilotHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'
import { PID_FILE, daemonPort, isAlive, isDaemonRunning, readPid } from './lib/daemonState.js'
@@ -85,7 +85,8 @@ import { createAndRegisterPane } from './lib/createAgentPane.js'
import { forkName, planFork } from './lib/forkAgent.js'
import { restoreAgents } from './lib/restoreAgents.js'
import { stoppedAgents } from './lib/stoppedAgents.js'
-import { resumeStoppedAgent, waitForResumedAgent, resumeChanged, resumeUnconfirmed } from './lib/resumeStoppedAgent.js'
+import { createStopAgentService } from './lib/stopAgentService.js'
+import { createResumeAgentService } from './lib/resumeAgentService.js'
import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from './lib/launchOverrides.js'
import { prepareCodexResume } from './engines/codex/portableHistory.js'
import { buildHarnessSessionLabel } from './lib/harnessSessionLabel.js'
@@ -4522,7 +4523,6 @@ async function runForeground(session: AuthSession): Promise<void> {
* half that drifts is the half nobody ran today.
*/
const restartJobs = new AgentRestartCoordinator()
- const resumeConversations = new Set<string>()
const sameRestartTarget = (session: RegisteredSession): boolean => {
const current = registry.byAgent(session.agentId)
return !!current && current.registeredAt === session.registeredAt
@@ -4808,194 +4808,16 @@ async function runForeground(session: AuthSession): Promise<void> {
* SIGTERM/SIGKILL fallback. Engine conversation files, recaps and the Harness name remain on disk.
*/
const stopJobs = new Map<string, Promise<void>>()
- backend.onDeleteAgent = (target) => {
- const sessionId = registry.resolve(target)?.agentId ?? target
- const existing = stopJobs.get(sessionId)
- if (existing) return existing
- restartJobs.cancel(sessionId)
- const job = Promise.resolve().then(async () => {
- const s = registry.resolve(sessionId)
- if (!s) return
- // Saving precedes every mutation. A storage failure leaves the live agent alone.
- stoppedAgents.save(s)
- markDeleted(sessionId)
- if (s.sessionId) markDeleted(s.sessionId)
- if (s.processIdentity) agentReconciler.suppress(s)
- forgetSession(sessionId, { force: true })
- const paneStop = tmuxBackend
- ? Promise.all(s.runtimes.filter((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')
- .map(runtime => tmuxBackend!.kill(runtime)))
- : Promise.resolve([])
- const processStop = isTerminalEngine(s.engine) ? Promise.resolve('gone' as const)
- : terminateDeletedAgent(s, {
- checkRuntime: checkPidRuntime,
- kill: (pid, signal) => process.kill(pid, signal),
- sleep: ms => new Promise(resolve => { const timer = setTimeout(resolve, ms); timer.unref?.() }),
- log: message => console.log(message),
- }, 0)
- const [paneOutcomes, outcome] = await Promise.all([paneStop, processStop])
- if (outcome !== 'failed') {
- if (paneOutcomes.every(result => result.state === 'succeeded')) stoppedAgents.finishResume(sessionId)
- clearDeleted(sessionId)
- if (s.sessionId) clearDeleted(s.sessionId)
- }
- void agentReconciler.trigger()
- }).finally(() => {
- if (stopJobs.get(sessionId) === job) stopJobs.delete(sessionId)
- })
- stopJobs.set(sessionId, job)
- return job
- }
-
- const waitForResume = async (saved: RegisteredSession, current: () => boolean) => {
- const result = await waitForResumedAgent(saved, {
- current: () => current() && registry.byAgent(saved.agentId)?.tmuxPane === saved.tmuxPane,
- session: () => registry.byAgent(saved.agentId),
- process: () => resolvePaneEngineProcess(saved.tmuxPane, saved.engine),
- pane: () => tmuxPaneState(saved.tmuxPane),
- sleep: ms => new Promise(resolve => { const timer = setTimeout(resolve, ms); timer.unref?.() }),
- })
- if (!current()) return resumeChanged
- if (result.ok) {
- await clearPaneRemainOnExit(saved.tmuxPane)
- if (!current()) return resumeChanged
- stoppedAgents.finishResume(saved.agentId)
- announceSession(result.session)
- } else if (result.error !== 'AGENT_CHANGED') {
- const row = registry.byAgent(saved.agentId)
- if (row && row.tmuxPane === saved.tmuxPane) {
- const failed = registry.setLaunch(row.agentId, { state: 'failed', error: result.error, detail: result.detail })
- if (failed) announceSession(failed)
- // A verified exit releases the reservation and keeps the shell/output. Unknown startup
- // keeps both runtime and reservation; another Enter cannot launch a duplicate process.
- if (result.error === 'RESUME_FAILED' && (await checkPidRuntime(row)).state === 'gone') {
- if (!current()) return resumeChanged
- const pane = await tmuxPaneState(saved.tmuxPane)
- if (!current()) return resumeChanged
- retainExitedSession(row, !!pane && !pane.dead)
- stoppedAgents.finishResume(saved.agentId)
- }
- }
- }
- return result
- }
-
- const resumeStopped = (agentId: string, current: () => boolean) => resumeStoppedAgent({
- live: () => registry.byAgent(agentId),
- saved: () => stoppedAgents.get(agentId),
- current,
- checkLive: async entry => {
- if (!entry.tmuxPane) return { state: 'unknown', reason: 'Only tmux resume is supported.' }
- const inventory = await listTmuxPanes()
- if (!inventory.ok) return { state: 'unknown', reason: 'Terminal inventory is unavailable.' }
- const paneAlive = inventory.panes.some(pane => pane.tmuxPane === entry.tmuxPane)
- if (isTerminalEngine(entry.engine)) return paneAlive ? { state: 'alive' } : { state: 'gone', reason: 'Shell pane is gone.' }
- const process = await checkPidRuntime(entry)
- if (process.state !== 'gone') {
- if (!paneAlive || process.state === 'unknown') return { state: 'unknown', reason: 'The previous process is not available through its saved terminal.' }
- return checkSessionRuntime(entry)
- }
- if (!entry.processIdentity && paneAlive) return { state: 'unknown', reason: 'The engine has not been identified yet.' }
- return process
- },
- retain: async entry => {
- const inventory = await listTmuxPanes()
- if (!inventory.ok) throw new Error('Could not verify the previous terminal. Try again.')
- if (!current()) return
- retainExitedSession(entry, inventory.panes.some(pane => pane.tmuxPane === entry.tmuxPane))
- },
- waitForReady: saved => waitForResume(saved, current),
- canLaunch: async saved => {
- await stopJobs.get(agentId)
- return !registry.bySession(saved.sessionId) && (await checkPidRuntime(saved)).state === 'gone'
- },
- launch: async (saved, resumeSessionId) => {
- if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
- if (saved.grid && !saved.gridLaunch) return { ok: false, error: 'GRID_CREDENTIAL_REQUIRED', detail: 'The saved provider configuration is unavailable.' }
- if (saved.dsh && !installedDsh(saved.dsh)) return { ok: false, error: 'INVALID_DSH', detail: 'Install this harness from the Harness Store before resuming it.' }
- try {
- if (!saved.cwd || !statSync(saved.cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND', detail: 'The saved project folder is no longer available.' }
- } catch { return { ok: false, error: 'CWD_NOT_FOUND', detail: 'The saved project folder is no longer available.' } }
- if (resumeSessionId && (!saved.transcriptPath || !validTranscriptPath(saved.engine, saved.transcriptPath, saved.codexHome ?? undefined))) {
- return { ok: false, error: 'RESUME_UNAVAILABLE', detail: 'The saved conversation file is unavailable. Start a new conversation separately.' }
- }
- // Match the registry's globally unique conversation index, including aliases/profiles.
- const key = saved.sessionId || saved.agentId
- if (resumeConversations.has(key)) return { ok: false, error: 'AGENT_BUSY' }
- resumeConversations.add(key)
- let token: string | null = null
- let allocationAttempted = false
- try {
- // Reserve before preparing history or rewriting launch configuration: an unknown previous
- // allocation may still have a writer using those files.
- token = stoppedAgents.beginResume(agentId)
- if (!token) return resumeUnconfirmed
- const built = await relaunchOverrides(saved)
- if (!built.ok) return { ok: false, error: built.error, detail: built.detail }
- if (!current()) return resumeChanged
- if (resumeSessionId) {
- try { prepareSessionResume(saved) } catch {
- return { ok: false, error: 'RESUME_PREPARATION_FAILED', detail: 'Could not prepare the saved conversation. Its history has been retained.' }
- }
- }
- if (saved.sessionId && registry.bySession(saved.sessionId)) return { ok: false, error: 'AGENT_BUSY' }
- const { env: launchEnv, extraArgs, clearEnv } = built.overrides
- const options = {
- resumeSessionId,
- bypassPermission: saved.bypassPermission === true,
- ...(saved.permissionMode ? { permissionMode: saved.permissionMode } : {}),
- ...(saved.cwd ? { cwd: saved.cwd } : {}),
- ...(extraArgs.length ? { extraArgs } : {}),
- ...(clearEnv.length ? { clearEnv } : {}),
- ...(launchEnv.HARNESS_DSH ? { harnessNode: true } : {}),
- installIfMissing: enginePathOverride(saved.engine) ? undefined : engineInstallRecipe(saved.engine),
- }
- clearDeleted(agentId)
- if (saved.sessionId) clearDeleted(saved.sessionId)
- allocationAttempted = true
- const result = await createAndRegisterPane({
- tmuxBackend,
- registry: { openPendingAgent: input => current() ? registry.resumePendingAgent(saved, input.runtimes) : null },
- maxAttempts: 1,
- engine: saved.engine,
- sessionLabel: buildHarnessSessionLabel(saved.engine),
- argv: buildEngineLaunchArgv(saved.engine, options),
- ...(Object.keys(launchEnv).length ? { env: launchEnv } : {}),
- })
- if (!result.ok) {
- if (result.error === 'TMUX_UNAVAILABLE') {
- stoppedAgents.finishResume(agentId, token)
- return { ok: false, error: result.error, detail: result.detail }
- }
- return resumeUnconfirmed
- }
- if (!current()) return resumeChanged
- const { pending, spawned } = result
- refreshGridWebSearch(pending.agentId, built.overrides)
- announceSession(pending)
- if (isTerminalEngine(saved.engine)) {
- await clearPaneRemainOnExit(spawned.runtime.paneId)
- if (!current()) return resumeChanged
- const ready = registry.setLaunch(pending.agentId, { state: 'ready' })!
- stoppedAgents.finishResume(agentId, token)
- announceSession(ready)
- return { ok: true, session: ready, resumed: true }
- }
- if (pending.dsh) attachDsh(pending)
- return await waitForResume(pending, current)
- } finally {
- if (token && !allocationAttempted) stoppedAgents.finishResume(agentId, token)
- resumeConversations.delete(key)
- }
- },
+ backend.onDeleteAgent = createStopAgentService({
+ registry, stoppedAgents, restartJobs, stopJobs, tmuxBackend, agentReconciler,
+ forgetSession, markDeleted, clearDeleted,
})
- backend.onResumeAgent = agentId => restartJobs.run(agentId, async current => {
- await stopJobs.get(agentId)
- if (!current()) return resumeChanged
- if (pinnedControls.has(agentId)) return { ok: false, error: 'AGENT_BUSY' }
- return resumeStopped(agentId, current)
- }, 'resume')
+ backend.onResumeAgent = createResumeAgentService({
+ registry, stoppedAgents, tmuxBackend, restartJobs, stopJobs, pinnedControls,
+ retainExitedSession, announceSession, relaunchOverrides, prepareSessionResume,
+ refreshGridWebSearch, clearDeleted, attachDsh,
+ })
/**
* Web or device restarted an agent (`agent_restart`): exit the live engine process and relaunch it in
diff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.ts
new file mode 100644
index 000000000..e99bbe35a
--- /dev/null
+++ b/cli/src/lib/resumeAgentService.spec.ts
@@ -0,0 +1,247 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { createResumeAgentService, type ResumeAgentServiceDeps } from './resumeAgentService.js'
+import { registry, validTranscriptPath, type RegisteredSession } from './registry.js'
+import { env } from '../config/env.js'
+import { StoppedAgentStore } from './stoppedAgents.js'
+import { AgentRestartCoordinator } from './restartAgent.js'
+import { checkPidRuntime } from './deleteAgentFallback.js'
+import { listTmuxPanes } from './tmuxAgentDiscovery.js'
+import { checkSessionRuntime, clearPaneRemainOnExit, resolvePaneEngineProcess, tmuxPaneState } from './tmux.js'
+import { buildEngineLaunchArgv } from './engineLaunch.js'
+import { enginePathOverride } from './engineBin.js'
+import { installedDsh } from '../dsh/installed.js'
+
+vi.mock('./deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn() }))
+vi.mock('./tmuxAgentDiscovery.js', () => ({ listTmuxPanes: vi.fn() }))
+vi.mock('./tmux.js', () => ({ checkSessionRuntime: vi.fn(), clearPaneRemainOnExit: vi.fn(), resolvePaneEngineProcess: vi.fn(), tmuxPaneState: vi.fn() }))
+vi.mock('./engineLaunch.js', () => ({ buildEngineLaunchArgv: vi.fn(() => ['fixture-engine']) }))
+vi.mock('./engineBin.js', () => ({ enginePathOverride: vi.fn(() => undefined) }))
+vi.mock('./engineInstall.js', () => ({ engineInstallRecipe: () => ({ command: 'fixture-install' }) }))
+vi.mock('../dsh/installed.js', () => ({ installedDsh: vi.fn() }))
+vi.mock('./registry.js', async original => ({ ...await original<object>(), validTranscriptPath: vi.fn(() => true) }))
+
+let dir: string
+let saved: RegisteredSession
+let deps: ResumeAgentServiceDeps
+const identity = { pid: 54321, startMarker: 'new-process', executable: 'codex' }
+const pane = '%99'
+const create = vi.fn()
+const kill = vi.fn()
+const inventory = () => ({ ok: true as const, panes: [{ tmuxPane: pane }] as any[] })
+function live(extra: Partial<RegisteredSession> = {}) {
+ return Object.assign(registry.resumePendingAgent(saved, [{ backend: 'tmux', paneId: pane }])!, extra)
+}
+function rewrite(extra: Partial<RegisteredSession>) { saved = { ...saved, ...extra }; rmSync(join(dir, 'saved', `${saved.agentId}.json`)); deps.stoppedAgents.save(saved) }
+function start() { return createResumeAgentService(deps)(saved.agentId) }
+function deferred<T>() { let resolve!: (v: T) => void; const promise = new Promise<T>(r => { resolve = r }); return { promise, resolve } }
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ for (const row of registry.list()) registry.removeAgent(row.agentId)
+ dir = mkdtempSync(join(tmpdir(), 'resume-service-'))
+ const original = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%8' }], cwd: dir })!
+ saved = { ...original, sessionId: 'original-session', transcriptPath: join(dir, 'history.jsonl'), processIdentity: identity, launch: { state: 'ready' } }
+ registry.removeAgent(original.agentId)
+ const store = new StoppedAgentStore(join(dir, 'saved'))
+ store.save(saved)
+ create.mockReset().mockResolvedValue({ state: 'succeeded', runtime: { backend: 'tmux', paneId: pane } })
+ kill.mockReset().mockResolvedValue({ state: 'succeeded' })
+ vi.mocked(validTranscriptPath).mockReturnValue(true)
+ vi.mocked(enginePathOverride).mockReturnValue(undefined)
+ vi.mocked(installedDsh).mockReturnValue(undefined)
+ vi.mocked(listTmuxPanes).mockReset().mockResolvedValue(inventory())
+ vi.mocked(checkPidRuntime).mockReset().mockResolvedValue({ state: 'gone', reason: 'fixture' })
+ vi.mocked(checkSessionRuntime).mockReset().mockResolvedValue({ state: 'alive' })
+ vi.mocked(tmuxPaneState).mockReset().mockResolvedValue({ dead: false } as any)
+ vi.mocked(clearPaneRemainOnExit).mockReset().mockResolvedValue(undefined)
+ vi.mocked(resolvePaneEngineProcess).mockReset().mockImplementation(async () => {
+ const row = registry.byAgent(saved.agentId)
+ if (row) { Object.assign(row, { processIdentity: identity, lastHookAt: Date.now(), launch: { state: 'ready' } }) }
+ return identity
+ })
+ deps = {
+ registry, stoppedAgents: store, tmuxBackend: { create, kill }, restartJobs: new AgentRestartCoordinator(),
+ stopJobs: new Map(), pinnedControls: new Set(),
+ retainExitedSession: vi.fn((row, alive) => { store.save(row); if (alive) registry.releaseEngine(row.agentId, true); else registry.removeAgent(row.agentId) }),
+ announceSession: vi.fn(), relaunchOverrides: vi.fn(async () => ({ ok: true as const, overrides: { env: {}, extraArgs: [], clearEnv: [] } })),
+ prepareSessionResume: vi.fn(), refreshGridWebSearch: vi.fn(), clearDeleted: vi.fn(), attachDsh: vi.fn(),
+ }
+})
+afterEach(() => { vi.useRealTimers(); for (const row of registry.list()) registry.removeAgent(row.agentId); rmSync(dir, { recursive: true, force: true }) })
+
+describe('production resume handler', () => {
+ it.each(['claude', 'codex'] as const)('resumes exact %s conversation on a new route and persists it', async engine => {
+ rewrite({ engine, codexHome: '/profile', permissionMode: 'plan', bypassPermission: true, dsh: 'fixture' })
+ vi.mocked(installedDsh).mockReturnValue({} as any)
+ vi.mocked(enginePathOverride).mockReturnValue('/fixture/bin')
+ vi.mocked(deps.relaunchOverrides).mockResolvedValue({ ok: true, overrides: { env: { CODEX_HOME: '/profile', HARNESS_DSH: 'fixture' }, extraArgs: ['--fixture'], clearEnv: ['OLD'] } })
+ const result = await start()
+ expect(result).toMatchObject({ ok: true, resumed: true, session: { agentId: saved.agentId, sessionId: saved.sessionId, tmuxPane: pane, launch: { state: 'ready' } } })
+ expect(buildEngineLaunchArgv).toHaveBeenCalledWith(engine, expect.objectContaining({ resumeSessionId: saved.sessionId, cwd: dir, permissionMode: 'plan', bypassPermission: true, extraArgs: ['--fixture'], clearEnv: ['OLD'], harnessNode: true, installIfMissing: undefined }))
+ expect(create).toHaveBeenCalledTimes(1)
+ expect(create.mock.calls[0][0].env).toEqual({ CODEX_HOME: '/profile', HARNESS_DSH: 'fixture' })
+ expect(deps.attachDsh).toHaveBeenCalledTimes(1)
+ expect(deps.stoppedAgents.get(saved.agentId)?.sessionId).toBe(saved.sessionId)
+ expect(deps.stoppedAgents.beginResume(saved.agentId)).not.toBeNull()
+ const disk = JSON.parse(readFileSync(join(env.ADAPTER_DATA_DIR, 'registry.json'), 'utf8'))
+ expect(JSON.stringify(disk)).toContain(saved.sessionId)
+ expect(JSON.stringify(disk)).toContain('resumeOnly')
+ })
+ it('opens a retained terminal as a new shell without a vendor resume argument', async () => {
+ rewrite({ engine: 'terminal', sessionId: '', transcriptPath: '' })
+ expect(await start()).toMatchObject({ ok: true, resumed: true, session: { engine: 'terminal', launch: { state: 'ready' } } })
+ expect(buildEngineLaunchArgv).toHaveBeenCalledWith('terminal', expect.objectContaining({ resumeSessionId: undefined }))
+ expect(deps.prepareSessionResume).not.toHaveBeenCalled()
+ })
+ it('joins two clients and waits for Stop to finish before allocating', async () => {
+ const stop = deferred<void>(); (deps.stopJobs as Map<string, Promise<void>>).set(saved.agentId, stop.promise)
+ const resume = createResumeAgentService(deps); const one = resume(saved.agentId); const two = resume(saved.agentId)
+ expect(two).toBe(one); await Promise.resolve(); expect(create).not.toHaveBeenCalled()
+ stop.resolve(); expect(await one).toMatchObject({ ok: true }); expect(create).toHaveBeenCalledTimes(1)
+ })
+ it('honors cancellation while waiting for Stop', async () => {
+ const stop = deferred<void>(); (deps.stopJobs as Map<string, Promise<void>>).set(saved.agentId, stop.promise)
+ const result = start(); await Promise.resolve(); deps.restartJobs.cancel(saved.agentId); stop.resolve()
+ expect(await result).toMatchObject({ error: 'AGENT_CHANGED' }); expect(create).not.toHaveBeenCalled()
+ })
+ it('refuses a conflicting pinned terminal control', async () => {
+ (deps.pinnedControls as Set<string>).add(saved.agentId)
+ expect(await start()).toMatchObject({ error: 'AGENT_BUSY' }); expect(create).not.toHaveBeenCalled()
+ })
+ it.each([
+ ['missing tmux', () => { deps.tmuxBackend = null }, 'TMUX_UNAVAILABLE'],
+ ['missing provider', () => rewrite({ grid: { baseUrl: 'https://fixture.invalid', model: null }, gridLaunch: null }), 'GRID_CREDENTIAL_REQUIRED'],
+ ['missing DSH', () => rewrite({ dsh: 'missing' }), 'INVALID_DSH'],
+ ['missing cwd', () => rewrite({ cwd: null }), 'CWD_NOT_FOUND'],
+ ['removed cwd', () => rewrite({ cwd: join(dir, 'gone') }), 'CWD_NOT_FOUND'],
+ ['file cwd', () => { const file = join(dir, 'file'); writeFileSync(file, 'file'); rewrite({ cwd: file }) }, 'CWD_NOT_FOUND'],
+ ['missing transcript', () => rewrite({ transcriptPath: '' }), 'RESUME_UNAVAILABLE'],
+ ['invalid transcript', () => vi.mocked(validTranscriptPath).mockReturnValue(false), 'RESUME_UNAVAILABLE'],
+ ['old process alive', () => vi.mocked(checkPidRuntime).mockResolvedValue({ state: 'alive' }), 'AGENT_BUSY'],
+ ['old process unknown', () => vi.mocked(checkPidRuntime).mockResolvedValue({ state: 'unknown', reason: 'fixture' }), 'AGENT_BUSY'],
+ ] as const)('refuses %s without allocating or losing history', async (_label, setup, error) => {
+ setup(); expect(await start()).toMatchObject({ ok: false, error }); expect(create).not.toHaveBeenCalled()
+ expect(deps.stoppedAgents.get(saved.agentId)?.agentId).toBe(saved.agentId)
+ })
+ it('does not rewrite a profile while an earlier allocation is unconfirmed', async () => {
+ deps.stoppedAgents.beginResume(saved.agentId)
+ expect(await start()).toMatchObject({ error: 'RESUME_UNCONFIRMED' })
+ expect(deps.relaunchOverrides).not.toHaveBeenCalled(); expect(deps.prepareSessionResume).not.toHaveBeenCalled()
+ })
+ it.each(['provider', 'prepare', 'cancel', 'conversation'] as const)('releases the reservation before allocation after %s failure', async reason => {
+ if (reason === 'provider') vi.mocked(deps.relaunchOverrides).mockResolvedValue({ ok: false, error: 'PROVIDER_FAILED', detail: 'fixture' })
+ if (reason === 'prepare') vi.mocked(deps.prepareSessionResume).mockImplementation(() => { throw new Error('fixture') })
+ if (reason === 'cancel') vi.mocked(deps.relaunchOverrides).mockImplementation(async () => { deps.restartJobs.cancel(saved.agentId); return { ok: true, overrides: { env: {}, extraArgs: [], clearEnv: [] } } })
+ if (reason === 'conversation') vi.mocked(deps.prepareSessionResume).mockImplementation(() => { registry.resumePendingAgent({ ...saved, agentId: 'other' }, [{ backend: 'tmux', paneId: '%101' }]) })
+ expect(await start()).toMatchObject({ ok: false })
+ expect(create).not.toHaveBeenCalled(); expect(deps.stoppedAgents.beginResume(saved.agentId)).not.toBeNull()
+ })
+ it.each(['tmux is unavailable', 'allocation reply lost'])('handles allocation error: %s', async reason => {
+ create.mockResolvedValue({ state: 'failed', reason })
+ expect(await start()).toMatchObject({ error: reason === 'tmux is unavailable' ? 'TMUX_UNAVAILABLE' : 'RESUME_UNCONFIRMED' })
+ expect(deps.stoppedAgents.beginResume(saved.agentId) === null).toBe(reason !== 'tmux is unavailable')
+ expect(registry.byAgent(saved.agentId)).toBeUndefined()
+ })
+ it('cancels a tmux allocation without registering or reusing its pane', async () => {
+ create.mockImplementation(async () => { deps.restartJobs.cancel(saved.agentId); return { state: 'succeeded', runtime: { backend: 'tmux', paneId: pane } } })
+ expect(await start()).toMatchObject({ error: 'AGENT_CHANGED' }); expect(kill).toHaveBeenCalledTimes(1)
+ expect(registry.byAgent(saved.agentId)).toBeUndefined()
+ })
+ it.each([true, false])('cancels after a registry claim, cleanup confirmed=%s', async confirmed => {
+ kill.mockResolvedValue(confirmed ? { state: 'succeeded' } : { state: 'failed' })
+ const claim = registry.resumePendingAgent.bind(registry)
+ deps.registry = { ...deps.registry, byAgent: registry.byAgent.bind(registry), bySession: registry.bySession.bind(registry), setLaunch: registry.setLaunch.bind(registry), resumePendingAgent: (row, routes) => { const pending = claim(row, routes); deps.restartJobs.cancel(saved.agentId); return pending } }
+ expect(await start()).toMatchObject({ error: 'AGENT_CHANGED' }); expect(deps.announceSession).not.toHaveBeenCalled()
+ expect(kill).toHaveBeenCalledTimes(1)
+ expect(registry.byAgent(saved.agentId) === undefined).toBe(confirmed)
+ })
+ it('serializes two saved identities for the same conversation', async () => {
+ const second = { ...saved, agentId: 'alias' }; deps.stoppedAgents.save(second)
+ const build = deferred<any>(); vi.mocked(deps.relaunchOverrides).mockReturnValue(build.promise)
+ const resume = createResumeAgentService(deps); const one = resume(saved.agentId)
+ await vi.waitFor(() => expect(deps.relaunchOverrides).toHaveBeenCalledTimes(1))
+ expect(await resume(second.agentId)).toMatchObject({ error: 'AGENT_BUSY' })
+ build.resolve({ ok: true, overrides: { env: {}, extraArgs: [], clearEnv: [] } })
+ expect(await one).toMatchObject({ ok: true }); expect(create).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('existing runtime and readiness verification', () => {
+ it.each(['claude', 'terminal'] as const)('attaches a verified live %s without a new pane', async engine => {
+ if (engine === 'terminal') rewrite({ engine, sessionId: '', transcriptPath: '' })
+ live({ engine, resumeOnly: undefined, launch: { state: 'ready' } }); vi.mocked(checkPidRuntime).mockResolvedValue({ state: 'alive' })
+ expect(await start()).toMatchObject({ ok: true }); expect(create).not.toHaveBeenCalled()
+ })
+ it.each(['no route', 'no inventory', 'process unknown', 'process detached', 'unidentified engine'] as const)('does not disturb %s', async reason => {
+ live({ resumeOnly: undefined, launch: { state: 'ready' }, ...(reason === 'no route' ? { tmuxPane: '' } : {}) })
+ if (reason === 'no inventory') vi.mocked(listTmuxPanes).mockResolvedValue({ ok: false, error: 'fixture' })
+ if (reason === 'process unknown') vi.mocked(checkPidRuntime).mockResolvedValue({ state: 'unknown', reason: 'fixture' })
+ if (reason === 'process detached') { vi.mocked(checkPidRuntime).mockResolvedValue({ state: 'alive' }); vi.mocked(listTmuxPanes).mockResolvedValue({ ok: true, panes: [] }) }
+ expect(await start()).toMatchObject({ error: 'RESUME_UNCONFIRMED' }); expect(create).not.toHaveBeenCalled()
+ })
+ it.each([true, false])('retains a confirmed engine exit, surviving shell = %s', async alive => {
+ live({ resumeOnly: undefined, processIdentity: identity, launch: { state: 'ready' } })
+ vi.mocked(listTmuxPanes).mockResolvedValue({ ok: true, panes: alive ? [{ tmuxPane: pane }] as any[] : [] })
+ // New pane must be distinct from the shell retained by this scenario.
+ create.mockResolvedValue({ state: 'succeeded', runtime: { backend: 'tmux', paneId: '%100' } })
+ expect(await start()).toMatchObject({ ok: true }); expect(deps.retainExitedSession).toHaveBeenCalledWith(expect.objectContaining({ agentId: saved.agentId }), alive)
+ if (alive) expect(registry.byRuntimeTerminal({ backend: 'tmux', paneId: pane })?.engine).toBe('terminal')
+ })
+ it('resumes a missing shell', async () => {
+ rewrite({ engine: 'terminal', sessionId: '', transcriptPath: '' }); live({ resumeOnly: undefined, launch: { state: 'ready' } })
+ vi.mocked(listTmuxPanes).mockResolvedValue({ ok: true, panes: [] })
+ expect(await start()).toMatchObject({ ok: true }); expect(create).toHaveBeenCalledTimes(1)
+ })
+ it.each(['unknown', 'cancel'] as const)('refuses to retire the old route when its second probe is %s', async mode => {
+ live({ resumeOnly: undefined, processIdentity: identity, launch: { state: 'ready' } })
+ vi.mocked(listTmuxPanes).mockResolvedValueOnce(inventory()).mockImplementationOnce(async () => {
+ if (mode === 'cancel') deps.restartJobs.cancel(saved.agentId)
+ return mode === 'unknown' ? { ok: false, error: 'fixture' } : inventory()
+ })
+ if (mode === 'unknown') await expect(start()).rejects.toThrow('Could not verify')
+ else expect(await start()).toMatchObject({ error: 'AGENT_CHANGED' })
+ expect(deps.retainExitedSession).not.toHaveBeenCalled(); expect(create).not.toHaveBeenCalled()
+ })
+ it('rechecks a pending allocation after reconnect without spawning again', async () => {
+ live(); expect(await start()).toMatchObject({ ok: true }); expect(create).not.toHaveBeenCalled()
+ })
+ it('waits for a real readiness observation before replying', async () => {
+ vi.useFakeTimers(); vi.mocked(resolvePaneEngineProcess).mockResolvedValueOnce(null)
+ const result = start(); await vi.advanceTimersByTimeAsync(500)
+ expect(await result).toMatchObject({ ok: true }); expect(resolvePaneEngineProcess).toHaveBeenCalledTimes(2)
+ })
+ it.each([true, false])('cancels while clearing remain-on-exit, terminal=%s', async terminal => {
+ if (terminal) rewrite({ engine: 'terminal', sessionId: '', transcriptPath: '' })
+ vi.mocked(clearPaneRemainOnExit).mockImplementation(async () => { deps.restartJobs.cancel(saved.agentId) })
+ expect(await start()).toMatchObject({ error: 'AGENT_CHANGED' })
+ })
+ it('does not finish a reservation when the route changes during final readiness cleanup', async () => {
+ vi.mocked(clearPaneRemainOnExit).mockImplementation(async () => { registry.byAgent(saved.agentId)!.tmuxPane = '%102' })
+ expect(await start()).toMatchObject({ error: 'AGENT_CHANGED' })
+ expect(deps.stoppedAgents.beginResume(saved.agentId)).toBeNull()
+ })
+ it.each(['operation', 'route'] as const)('cancels a readiness check when %s changes', async mode => {
+ live()
+ vi.mocked(resolvePaneEngineProcess).mockImplementation(async () => { if (mode === 'operation') deps.restartJobs.cancel(saved.agentId); else registry.byAgent(saved.agentId)!.tmuxPane = '%102'; return identity })
+ expect(await start()).toMatchObject({ error: 'AGENT_CHANGED' })
+ })
+ it.each(['missing row', 'exit dead pane', 'exit surviving pane', 'exit unknown process', 'mismatched session', 'failed hook', 'cancel process probe', 'cancel pane probe'] as const)('preserves work on %s', async mode => {
+ live()
+ vi.mocked(resolvePaneEngineProcess).mockImplementation(async () => {
+ if (mode === 'missing row') registry.removeAgent(saved.agentId)
+ if (mode === 'mismatched session') registry.byAgent(saved.agentId)!.sessionId = 'other'
+ if (mode === 'failed hook') registry.setLaunch(saved.agentId, { state: 'failed', error: 'RESUME_SESSION_MISMATCH', detail: 'fixture' })
+ return null
+ })
+ vi.mocked(tmuxPaneState).mockResolvedValueOnce({ dead: false, engineExit: 1 } as any)
+ 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 })
+ expect(await start()).toMatchObject({ ok: false })
+ expect(create).not.toHaveBeenCalled(); expect(deps.stoppedAgents.get(saved.agentId)).not.toBeNull()
+ })
+})
diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.ts
new file mode 100644
index 000000000..4ba3da2ed
--- /dev/null
+++ b/cli/src/lib/resumeAgentService.ts
@@ -0,0 +1,200 @@
+/** Exact-resume lifecycle shared by the daemon and its isolated acceptance tests. */
+import { statSync } from 'node:fs'
+import { isTerminalEngine } from '../engines/types.js'
+import { installedDsh } from '../dsh/installed.js'
+import { registry as liveRegistry, validTranscriptPath, type RegisteredSession } from './registry.js'
+import type { StoppedAgentStore } from './stoppedAgents.js'
+import { resumeStoppedAgent, waitForResumedAgent, resumeChanged, resumeUnconfirmed } from './resumeStoppedAgent.js'
+import { checkPidRuntime } from './deleteAgentFallback.js'
+import { checkSessionRuntime, clearPaneRemainOnExit, resolvePaneEngineProcess, tmuxPaneState } from './tmux.js'
+import { listTmuxPanes } from './tmuxAgentDiscovery.js'
+import { enginePathOverride } from './engineBin.js'
+import { engineInstallRecipe } from './engineInstall.js'
+import { buildEngineLaunchArgv } from './engineLaunch.js'
+import { buildHarnessSessionLabel } from './harnessSessionLabel.js'
+import { createAndRegisterPane, type CreateAgentPaneDeps } from './createAgentPane.js'
+import type { LaunchOverrides, LaunchOverridesResult } from './launchOverrides.js'
+import type { AgentRestartCoordinator } from './restartAgent.js'
+
+export interface ResumeAgentServiceDeps {
+ registry: Pick<typeof liveRegistry, 'byAgent' | 'bySession' | 'resumePendingAgent' | 'setLaunch'>
+ stoppedAgents: StoppedAgentStore
+ tmuxBackend: CreateAgentPaneDeps['tmuxBackend'] | null
+ restartJobs: AgentRestartCoordinator
+ stopJobs: ReadonlyMap<string, Promise<void>>
+ pinnedControls: { has(agentId: string): boolean }
+ retainExitedSession(session: RegisteredSession, paneAlive: boolean): void
+ announceSession(session: RegisteredSession): void
+ relaunchOverrides(session: RegisteredSession): Promise<LaunchOverridesResult>
+ prepareSessionResume(session: RegisteredSession): void
+ refreshGridWebSearch(agentId: string, overrides: LaunchOverrides): void
+ clearDeleted(agentId: string): void
+ attachDsh(session: RegisteredSession): void
+}
+
+export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
+ const { registry, stoppedAgents, tmuxBackend, restartJobs, stopJobs, pinnedControls,
+ retainExitedSession, announceSession, relaunchOverrides, prepareSessionResume,
+ refreshGridWebSearch, clearDeleted, attachDsh } = deps
+ const resumeConversations = new Set<string>()
+ const waitForResume = async (entry: RegisteredSession, current: () => boolean) => {
+ // Registry observations may update the same object; pin the route being verified.
+ const saved = { ...entry }
+ const ownsRoute = () => current() && registry.byAgent(saved.agentId)?.tmuxPane === saved.tmuxPane
+ const result = await waitForResumedAgent(saved, {
+ current: ownsRoute,
+ session: () => registry.byAgent(saved.agentId),
+ process: () => resolvePaneEngineProcess(saved.tmuxPane, saved.engine),
+ pane: () => tmuxPaneState(saved.tmuxPane),
+ sleep: ms => new Promise(resolve => { const timer = setTimeout(resolve, ms); timer.unref?.() }),
+ })
+ if (!ownsRoute()) return resumeChanged
+ if (result.ok) {
+ await clearPaneRemainOnExit(saved.tmuxPane)
+ if (!ownsRoute()) return resumeChanged
+ stoppedAgents.finishResume(saved.agentId)
+ announceSession(result.session)
+ } else if (result.error !== 'AGENT_CHANGED') {
+ const row = registry.byAgent(saved.agentId)!
+ const failed = registry.setLaunch(row.agentId, { state: 'failed', error: result.error, detail: result.detail })
+ announceSession(failed!)
+ // A verified exit releases the reservation and keeps the shell/output. Unknown startup
+ // keeps both runtime and reservation; another Enter cannot launch a duplicate process.
+ if (result.error === 'RESUME_FAILED' && (await checkPidRuntime(row)).state === 'gone') {
+ if (!ownsRoute()) return resumeChanged
+ const pane = await tmuxPaneState(saved.tmuxPane)
+ if (!ownsRoute()) return resumeChanged
+ retainExitedSession(row, !!pane && !pane.dead)
+ stoppedAgents.finishResume(saved.agentId)
+ }
+ }
+ return result
+ }
+
+ const resumeStopped = (agentId: string, current: () => boolean) => resumeStoppedAgent({
+ live: () => registry.byAgent(agentId),
+ saved: () => stoppedAgents.get(agentId),
+ current,
+ checkLive: async entry => {
+ if (!entry.tmuxPane) return { state: 'unknown', reason: 'Only tmux resume is supported.' }
+ const inventory = await listTmuxPanes()
+ if (!inventory.ok) return { state: 'unknown', reason: 'Terminal inventory is unavailable.' }
+ const paneAlive = inventory.panes.some(pane => pane.tmuxPane === entry.tmuxPane)
+ if (isTerminalEngine(entry.engine)) return paneAlive ? { state: 'alive' } : { state: 'gone', reason: 'Shell pane is gone.' }
+ const process = await checkPidRuntime(entry)
+ if (process.state !== 'gone') {
+ if (!paneAlive || process.state === 'unknown') return { state: 'unknown', reason: 'The previous process is not available through its saved terminal.' }
+ return checkSessionRuntime(entry)
+ }
+ if (!entry.processIdentity && paneAlive) return { state: 'unknown', reason: 'The engine has not been identified yet.' }
+ return process
+ },
+ retain: async entry => {
+ const inventory = await listTmuxPanes()
+ if (!inventory.ok) throw new Error('Could not verify the previous terminal. Try again.')
+ if (!current()) return
+ retainExitedSession(entry, inventory.panes.some(pane => pane.tmuxPane === entry.tmuxPane))
+ },
+ waitForReady: saved => waitForResume(saved, current),
+ canLaunch: async saved => {
+ await stopJobs.get(agentId)
+ return !registry.bySession(saved.sessionId) && (await checkPidRuntime(saved)).state === 'gone'
+ },
+ launch: async (saved, resumeSessionId) => {
+ if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
+ if (saved.grid && !saved.gridLaunch) return { ok: false, error: 'GRID_CREDENTIAL_REQUIRED', detail: 'The saved provider configuration is unavailable.' }
+ if (saved.dsh && !installedDsh(saved.dsh)) return { ok: false, error: 'INVALID_DSH', detail: 'Install this harness from the Harness Store before resuming it.' }
+ try {
+ if (!saved.cwd || !statSync(saved.cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND', detail: 'The saved project folder is no longer available.' }
+ } catch { return { ok: false, error: 'CWD_NOT_FOUND', detail: 'The saved project folder is no longer available.' } }
+ if (resumeSessionId && (!saved.transcriptPath || !validTranscriptPath(saved.engine, saved.transcriptPath, saved.codexHome ?? undefined))) {
+ return { ok: false, error: 'RESUME_UNAVAILABLE', detail: 'The saved conversation file is unavailable. Start a new conversation separately.' }
+ }
+ // Match the registry's globally unique conversation index, including aliases/profiles.
+ const key = saved.sessionId || saved.agentId
+ if (resumeConversations.has(key)) return { ok: false, error: 'AGENT_BUSY' }
+ resumeConversations.add(key)
+ let token: string | null = null
+ let allocationAttempted = false
+ try {
+ // Reserve before preparing history or rewriting launch configuration: an unknown previous
+ // allocation may still have a writer using those files.
+ token = stoppedAgents.beginResume(agentId)
+ if (!token) return resumeUnconfirmed
+ const built = await relaunchOverrides(saved)
+ if (!built.ok) return { ok: false, error: built.error, detail: built.detail }
+ if (!current()) return resumeChanged
+ if (resumeSessionId) {
+ try { prepareSessionResume(saved) } catch {
+ return { ok: false, error: 'RESUME_PREPARATION_FAILED', detail: 'Could not prepare the saved conversation. Its history has been retained.' }
+ }
+ }
+ if (saved.sessionId && registry.bySession(saved.sessionId)) return { ok: false, error: 'AGENT_BUSY' }
+ const { env: launchEnv, extraArgs, clearEnv } = built.overrides
+ const options = {
+ resumeSessionId,
+ bypassPermission: saved.bypassPermission === true,
+ ...(saved.permissionMode ? { permissionMode: saved.permissionMode } : {}),
+ cwd: saved.cwd,
+ ...(extraArgs.length ? { extraArgs } : {}),
+ ...(clearEnv.length ? { clearEnv } : {}),
+ ...(launchEnv.HARNESS_DSH ? { harnessNode: true } : {}),
+ installIfMissing: enginePathOverride(saved.engine) ? undefined : engineInstallRecipe(saved.engine),
+ }
+ clearDeleted(agentId)
+ if (saved.sessionId) clearDeleted(saved.sessionId)
+ allocationAttempted = true
+ const result = await createAndRegisterPane({
+ tmuxBackend,
+ registry: { openPendingAgent: input => current() ? registry.resumePendingAgent(saved, input.runtimes) : null },
+ maxAttempts: 1,
+ engine: saved.engine,
+ sessionLabel: buildHarnessSessionLabel(saved.engine),
+ argv: buildEngineLaunchArgv(saved.engine, options),
+ ...(Object.keys(launchEnv).length ? { env: launchEnv } : {}),
+ })
+ if (!result.ok) {
+ if (result.error === 'TMUX_UNAVAILABLE') {
+ stoppedAgents.finishResume(agentId, token)
+ return { ok: false, error: result.error, detail: result.detail }
+ }
+ return resumeUnconfirmed
+ }
+ const { pending, spawned } = result
+ if (!current()) {
+ // Stop may have completed while allocation was awaiting its tmux reply.
+ // The newly claimed runtime still belongs to this cancelled operation.
+ const killed = await tmuxBackend.kill(spawned.runtime)
+ if (killed.state === 'succeeded') {
+ retainExitedSession(pending, false)
+ stoppedAgents.finishResume(agentId, token)
+ }
+ return resumeChanged
+ }
+ refreshGridWebSearch(pending.agentId, built.overrides)
+ announceSession(pending)
+ if (isTerminalEngine(saved.engine)) {
+ await clearPaneRemainOnExit(spawned.runtime.paneId)
+ if (!current()) return resumeChanged
+ const ready = registry.setLaunch(pending.agentId, { state: 'ready' })!
+ stoppedAgents.finishResume(agentId, token)
+ announceSession(ready)
+ return { ok: true, session: ready, resumed: true }
+ }
+ if (pending.dsh) attachDsh(pending)
+ return await waitForResume(pending, current)
+ } finally {
+ if (token && !allocationAttempted) stoppedAgents.finishResume(agentId, token)
+ resumeConversations.delete(key)
+ }
+ },
+ })
+
+ return (agentId: string) => restartJobs.run(agentId, async current => {
+ await stopJobs.get(agentId)
+ if (!current()) return resumeChanged
+ if (pinnedControls.has(agentId)) return { ok: false, error: 'AGENT_BUSY' }
+ return resumeStopped(agentId, current)
+ }, 'resume')
+
+}
diff --git a/cli/src/lib/resumeStoppedAgent.spec.ts b/cli/src/lib/resumeStoppedAgent.spec.ts
index 3d73f4b9e..bce9fa610 100644
--- a/cli/src/lib/resumeStoppedAgent.spec.ts
+++ b/cli/src/lib/resumeStoppedAgent.spec.ts
@@ -179,3 +179,51 @@ describe('exact conversation readiness', () => {
await expect(waitForResumedAgent(saved, deps)).resolves.toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
})
})
+
+describe('resume refusal and readiness edge cases', () => {
+ it('reports a missing saved identity', async () => {
+ const deps = fixture(); deps.saved.mockReturnValue(null as any)
+ expect(await resumeStoppedAgent(deps)).toMatchObject({ error: 'AGENT_NOT_FOUND' })
+ })
+ it('opens a shell without a conversation id', async () => {
+ const deps = fixture(); const shell = { ...saved, engine: 'terminal' as const, sessionId: '' }; deps.saved.mockReturnValue(shell)
+ expect(await resumeStoppedAgent(deps)).toMatchObject({ ok: true }); expect(deps.launch).toHaveBeenCalledWith(shell, undefined)
+ })
+ it.each(['during check', 'row replacement', 'during retain', 'during launch check'] as const)('does not launch after %s', async when => {
+ const deps = fixture()
+ if (when === 'during launch check') deps.canLaunch.mockImplementation(async () => { deps.current.mockReturnValue(false); return true })
+ else {
+ deps.live.mockReturnValue(saved)
+ deps.checkLive.mockImplementation(async () => {
+ if (when === 'during check') deps.current.mockReturnValue(false)
+ if (when === 'row replacement') deps.live.mockReturnValue({ ...saved })
+ return { state: 'gone', reason: 'fixture' }
+ })
+ deps.retain.mockImplementation(async () => { deps.current.mockReturnValue(false) })
+ }
+ expect(await resumeStoppedAgent(deps)).toMatchObject({ error: 'AGENT_CHANGED' }); expect(deps.launch).not.toHaveBeenCalled()
+ })
+ it('does not call an unconfirmed failed process ready', async () => {
+ const deps = fixture(); deps.live.mockReturnValue({ ...saved, resumeOnly: true, launch: { state: 'failed', error: 'RESUME_UNCONFIRMED' } })
+ expect(await resumeStoppedAgent(deps)).toMatchObject({ error: 'RESUME_UNCONFIRMED' })
+ })
+ it.each(['cancelled', 'removed', 'failed', 'different engine', 'no process', 'different start', 'missing launch'] as const)('handles readiness: %s', async mode => {
+ const process = { pid: 4, startMarker: 'now', executable: 'codex' }
+ let row: RegisteredSession | undefined = { ...saved, processIdentity: process, lastHookAt: 1, launch: { state: 'ready' } }
+ if (mode === 'removed') row = undefined
+ if (mode === 'failed') row!.launch = { state: 'failed', error: 'RESUME_SESSION_MISMATCH', detail: 'fixture' }
+ if (mode === 'different engine') row!.engine = 'claude'
+ if (mode === 'different start') row!.processIdentity = { ...process, startMarker: 'old' }
+ if (mode === 'missing launch') row!.launch = undefined
+ let time = 0
+ const result = await waitForResumedAgent(saved, {
+ current: () => mode !== 'cancelled', session: () => row,
+ process: async () => mode === 'no process' ? null : process, pane: async () => ({ dead: false }),
+ sleep: async ms => { time += ms }, now: () => time, budgetMs: 250,
+ })
+ expect(result.ok).toBe(mode === 'missing launch')
+ })
+ 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' })
+ })
+})
diff --git a/cli/src/lib/stopAgentService.spec.ts b/cli/src/lib/stopAgentService.spec.ts
new file mode 100644
index 000000000..8d3fb7c1f
--- /dev/null
+++ b/cli/src/lib/stopAgentService.spec.ts
@@ -0,0 +1,60 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { createStopAgentService, type StopAgentServiceDeps } from './stopAgentService.js'
+import { registry, type RegisteredSession } from './registry.js'
+import { stoppedAgents } from './stoppedAgents.js'
+import { AgentRestartCoordinator } from './restartAgent.js'
+import { checkPidRuntime, terminateDeletedAgent } from './deleteAgentFallback.js'
+vi.mock('./deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn(), terminateDeletedAgent: vi.fn() }))
+let row: RegisteredSession
+let deps: StopAgentServiceDeps
+beforeEach(() => {
+ vi.clearAllMocks()
+ row = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%44' }], cwd: '/tmp' })!
+ Object.assign(row, { sessionId: 'saved', processIdentity: { pid: 77, executable: 'codex', startMarker: 'fixture' } })
+ deps = { registry, stoppedAgents, restartJobs: new AgentRestartCoordinator(), stopJobs: new Map(),
+ tmuxBackend: { kill: vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const })) },
+ agentReconciler: { suppress: vi.fn(), trigger: vi.fn(async () => {}) },
+ forgetSession: vi.fn(id => registry.removeAgent(id)), markDeleted: vi.fn(), clearDeleted: vi.fn(),
+ }
+ vi.mocked(terminateDeletedAgent).mockResolvedValue('gone')
+})
+afterEach(() => { vi.restoreAllMocks(); for (const entry of registry.list()) registry.removeAgent(entry.agentId) })
+
+it('saves history before removing the runtime, joins concurrent stops, and clears confirmed reservations', async () => {
+ const token = stoppedAgents.beginResume(row.agentId); expect(token).toBeTruthy()
+ const original = row.agentId
+ vi.mocked(deps.forgetSession).mockImplementation(id => { expect(stoppedAgents.get(id)?.sessionId).toBe('saved'); registry.removeAgent(id) })
+ const stop = createStopAgentService(deps); const one = stop(original); expect(stop(original)).toBe(one); await one
+ expect(stoppedAgents.get(original)).toMatchObject({ active: false, sessionId: 'saved' })
+ expect(registry.byAgent(original)).toBeUndefined(); expect(deps.stopJobs.size).toBe(0)
+ expect(stoppedAgents.beginResume(original)).not.toBeNull(); expect(deps.agentReconciler.suppress).toHaveBeenCalledWith(row)
+})
+it('missing identities are harmless and never allocate or signal anything', async () => {
+ await createStopAgentService(deps)('missing'); expect(deps.forgetSession).not.toHaveBeenCalled(); expect(terminateDeletedAgent).not.toHaveBeenCalled()
+})
+it('storage failure leaves the live process and registry untouched', async () => {
+ vi.spyOn(stoppedAgents, 'save').mockImplementation(() => { throw new Error('disk full') })
+ await expect(createStopAgentService(deps)(row.agentId)).rejects.toThrow('disk full')
+ expect(registry.byAgent(row.agentId)).toBe(row); expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled(); expect(deps.markDeleted).not.toHaveBeenCalled()
+})
+it.each(['terminal', 'without tmux', 'failed process', 'failed tmux'] as const)('retains work when stopping %s', async mode => {
+ stoppedAgents.beginResume(row.agentId)
+ if (mode === 'terminal') Object.assign(row, { engine: 'terminal', sessionId: '', processIdentity: null })
+ if (mode === 'without tmux') { deps.tmuxBackend = null; row.runtimes = [{ backend: 'herdr', endpointId: 'fixture', paneId: '1' } as any] }
+ if (mode === 'failed process') vi.mocked(terminateDeletedAgent).mockResolvedValue('failed')
+ if (mode === 'failed tmux') vi.mocked(deps.tmuxBackend!.kill).mockResolvedValue({ state: 'unknown', dispatch: 'possibly_executed', reason: 'fixture' })
+ await createStopAgentService(deps)(row.agentId)
+ expect(stoppedAgents.get(row.agentId)).not.toBeNull(); expect(deps.agentReconciler.trigger).toHaveBeenCalledOnce()
+ expect(stoppedAgents.beginResume(row.agentId) === null).toBe(mode === 'failed process' || mode === 'failed tmux')
+})
+it('only signals through the validated process deleter and does not erase a newer stop job', async () => {
+ const signal = vi.spyOn(process, 'kill').mockReturnValue(true)
+ vi.mocked(terminateDeletedAgent).mockImplementation(async (entry, actions) => {
+ await actions.checkRuntime(entry); actions.kill(77, 'SIGTERM'); await actions.sleep(1); actions.log('fixture stop')
+ deps.stopJobs.set(row.agentId, Promise.resolve()); return 'terminated'
+ })
+ row.runtimes.push({ backend: 'herdr', endpointId: 'fixture', paneId: '2' } as any)
+ await createStopAgentService(deps)(row.agentId)
+ expect(signal).toHaveBeenCalledExactlyOnceWith(77, 'SIGTERM'); expect(deps.stopJobs.has(row.agentId)).toBe(true)
+ expect(deps.tmuxBackend!.kill).toHaveBeenCalledExactlyOnceWith({ backend: 'tmux', paneId: '%44' })
+})
diff --git a/cli/src/lib/stopAgentService.ts b/cli/src/lib/stopAgentService.ts
new file mode 100644
index 000000000..75ab7eb22
--- /dev/null
+++ b/cli/src/lib/stopAgentService.ts
@@ -0,0 +1,62 @@
+/** Stop retains the logical session before retiring its process and terminal. */
+import { isTerminalEngine } from '../engines/types.js'
+import type { registry as liveRegistry, RegisteredSession } from './registry.js'
+import type { StoppedAgentStore } from './stoppedAgents.js'
+import type { AgentRestartCoordinator } from './restartAgent.js'
+import type { TerminalBackend } from './terminalBackend.js'
+import type { TmuxRuntimeRef } from './terminalTypes.js'
+import { checkPidRuntime, terminateDeletedAgent } from './deleteAgentFallback.js'
+
+export interface StopAgentServiceDeps {
+ registry: Pick<typeof liveRegistry, 'resolve'>
+ stoppedAgents: StoppedAgentStore
+ restartJobs: AgentRestartCoordinator
+ stopJobs: Map<string, Promise<void>>
+ tmuxBackend: Pick<TerminalBackend<TmuxRuntimeRef>, 'kill'> | null
+ agentReconciler: { suppress(session: RegisteredSession): void; trigger(): Promise<unknown> }
+ forgetSession(agentId: string, options: { force: true }): void
+ markDeleted(agentId: string): void
+ clearDeleted(agentId: string): void
+}
+export function createStopAgentService(deps: StopAgentServiceDeps) {
+ const { registry, stoppedAgents, restartJobs, stopJobs, tmuxBackend, agentReconciler,
+ forgetSession, markDeleted, clearDeleted } = deps
+ return (target: string) => {
+ const sessionId = registry.resolve(target)?.agentId ?? target
+ const existing = stopJobs.get(sessionId)
+ if (existing) return existing
+ restartJobs.cancel(sessionId)
+ const job = Promise.resolve().then(async () => {
+ const s = registry.resolve(sessionId)
+ if (!s) return
+ // Saving precedes every mutation. A storage failure leaves the live agent alone.
+ stoppedAgents.save(s)
+ markDeleted(sessionId)
+ if (s.sessionId) markDeleted(s.sessionId)
+ if (s.processIdentity) agentReconciler.suppress(s)
+ forgetSession(sessionId, { force: true })
+ const paneStop = tmuxBackend
+ ? Promise.all(s.runtimes.filter((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')
+ .map(runtime => tmuxBackend!.kill(runtime)))
+ : Promise.resolve([])
+ const processStop = isTerminalEngine(s.engine) ? Promise.resolve('gone' as const)
+ : terminateDeletedAgent(s, {
+ checkRuntime: checkPidRuntime,
+ kill: (pid, signal) => process.kill(pid, signal),
+ sleep: ms => new Promise(resolve => { const timer = setTimeout(resolve, ms); timer.unref?.() }),
+ log: message => console.log(message),
+ }, 0)
+ const [paneOutcomes, outcome] = await Promise.all([paneStop, processStop])
+ if (outcome !== 'failed') {
+ if (paneOutcomes.every(result => result.state === 'succeeded')) stoppedAgents.finishResume(sessionId)
+ clearDeleted(sessionId)
+ if (s.sessionId) clearDeleted(s.sessionId)
+ }
+ void agentReconciler.trigger()
+ }).finally(() => {
+ if (stopJobs.get(sessionId) === job) stopJobs.delete(sessionId)
+ })
+ stopJobs.set(sessionId, job)
+ return job
+ }
+}
diff --git a/cli/src/lib/stoppedAgents.spec.ts b/cli/src/lib/stoppedAgents.spec.ts
index a4951034f..e0305c7c3 100644
--- a/cli/src/lib/stoppedAgents.spec.ts
+++ b/cli/src/lib/stoppedAgents.spec.ts
@@ -1,9 +1,11 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
+import { chmodSync, constants, openSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import type { RegisteredSession } from './registry.js'
+vi.mock('node:fs', async original => { const fs = await original<typeof import('node:fs')>(); return { ...fs, openSync: vi.fn(fs.openSync) } })
+
let directory = ''
beforeEach(() => {
vi.resetModules()
@@ -11,6 +13,7 @@ beforeEach(() => {
vi.stubEnv('ADAPTER_DATA_DIR', directory)
})
afterEach(() => {
+ vi.mocked(openSync).mockRestore()
vi.unstubAllEnvs()
rmSync(directory, { recursive: true, force: true })
})
@@ -109,3 +112,63 @@ it('reserves allocation across daemon restarts and different receipt IDs', async
restarted.finishResume(saved.agentId, token)
expect(store.beginResume(saved.agentId)).not.toBeNull()
})
+
+it('keeps readable archives discoverable beside corrupt, unsupported and mismatched records', async () => {
+ const { saved, store } = await fixture()
+ expect(store.list()).toEqual([])
+ store.save(saved)
+ const base = join(directory, 'stopped-agents')
+ for (const [id, content] of Object.entries({ corrupt: '{', version: JSON.stringify({ version: 99 }), invalid: JSON.stringify({ version: 1, session: {} }), mismatch: JSON.stringify({ version: 1, session: saved }) })) {
+ writeFileSync(join(base, `${id}.json`), content, { mode: 0o600 })
+ }
+ writeFileSync(join(base, 'unrelated.tmp'), 'skip')
+ expect(store.list().map(row => row.agentId)).toEqual([saved.agentId])
+ expect(store.get('missing')).toBeNull()
+ expect(store.get('../invalid')).toBeNull()
+ expect(() => store.save({ ...saved, agentId: '../invalid' })).toThrow()
+ expect(() => store.beginResume('../invalid')).toThrow()
+ store.finishResume('../invalid')
+ store.finishResume('absent')
+ chmodSync(base, 0o777)
+ expect(() => store.list()).toThrow()
+})
+
+it('persists a standalone shell and a runtime without the legacy tmux alias', async () => {
+ const { saved, store } = await fixture()
+ store.save({ ...saved, engine: 'terminal', sessionId: '', tmuxPane: '', runtimes: [{ backend: 'herdr', endpointId: 'fixture', paneId: '1' } as any], primaryRuntimeKey: ['herdr', 'fixture', '1'].join('\0'), codexHome: null })
+ const disk = JSON.parse(readFileSync(join(directory, 'stopped-agents', `${saved.agentId}.json`), 'utf8'))
+ expect(disk.session).not.toHaveProperty('tmuxPane')
+ expect(disk.session.sessionId).toBe('')
+ store.save({ ...saved, agentId: 'null-profile', codexHome: null })
+ expect(store.available([{ ...saved, agentId: 'live', codexHome: null }]).some(row => row.agentId === 'null-profile')).toBe(false)
+ expect(store.available([{ ...saved, sessionId: '' }])).toBeDefined()
+})
+
+it('fails closed on corrupt reservation data and unsafe reservation files', async () => {
+ const { saved, store } = await fixture()
+ const token = store.beginResume(saved.agentId)!
+ const marker = join(directory, 'stopped-agents', `${saved.agentId}.resume`)
+ writeFileSync(marker, '{')
+ expect(() => store.finishResume(saved.agentId, token)).toThrow()
+ expect(store.beginResume(saved.agentId)).toBeNull()
+ rmSync(marker)
+ // A directory in place of the reservation cannot be unlinked as a file.
+ symlinkSync('/dev/null', marker)
+ expect(() => store.finishResume(saved.agentId)).toThrow()
+ rmSync(marker)
+ // Fail before allocation if private-state traversal itself is unsafe.
+ chmodSync(join(directory, 'stopped-agents'), 0o777)
+ expect(() => store.beginResume(saved.agentId)).toThrow()
+})
+
+it('does not allocate when reserving disk space fails', async () => {
+ const { saved, store } = await fixture()
+ store.save(saved)
+ const real = await vi.importActual<typeof import('node:fs')>('node:fs')
+ vi.mocked(openSync).mockImplementation((file, flags, mode) => {
+ if (typeof flags === 'number' && (flags & constants.O_EXCL)) throw Object.assign(new Error('disk full'), { code: 'ENOSPC' })
+ return real.openSync(file, flags, mode)
+ })
+ expect(() => store.beginResume(saved.agentId)).toThrow('disk full')
+ expect(store.get(saved.agentId)?.sessionId).toBe(saved.sessionId)
+})