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.

Capture conversation identity before stopping harnesses

deeff47d43ae1c9
diff --git a/cli/package.json b/cli/package.json
index 79dbc4cb5..9d04685fb 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -20,7 +20,7 @@
"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: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": "vitest run src/lib/sessionRepair.spec.ts src/lib/captureResumeIdentity.spec.ts 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/captureResumeIdentity.ts --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": {
diff --git a/cli/scripts/resume-native-e2e.ts b/cli/scripts/resume-native-e2e.ts
index b603a1678..04880bb8e 100644
--- a/cli/scripts/resume-native-e2e.ts
+++ b/cli/scripts/resume-native-e2e.ts
@@ -10,6 +10,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, realpathSy
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { randomUUID } from 'node:crypto'
+import { createServer } from 'node:http'
import assert from 'node:assert/strict'
const exec = promisify(execCallback)
const root = realpathSync(mkdtempSync(join(tmpdir(), 'harness-resume-native-')))
@@ -35,6 +36,8 @@ 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 { captureResumeIdentity } = await import('../src/lib/captureResumeIdentity.js')
+const { claudeProcessSession } = await import('../src/lib/sessionRepair.js')
const { checkPidRuntime } = await import('../src/lib/deleteAgentFallback.js')
const { startHookServer } = await import('../src/hookServer.js')
const { BackendSocket } = await import('../src/backendSocket.js')
@@ -54,6 +57,7 @@ const server = await startHookServer(0, {
return registry.openProcessAgent({ engine: input.engine, processIdentity: identity, runtimes: row.runtimes, primaryRuntimeKey: row.primaryRuntimeKey, cwd: row.cwd })?.entry ?? null
},
})
+const fixtures: Array<{ agentId: string; engine: string; sessionId: string; marker: string }> = []
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>) => {
@@ -102,6 +106,7 @@ try {
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)
+ fixtures.push({ agentId: old.agentId, engine, sessionId, marker })
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',
@@ -182,6 +187,18 @@ try {
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')
+ // Reproduce a legacy daemon row whose hook binding was lost. Remove the earlier
+ // archive too, so Stop must recover from the real process, not the seeded snapshot.
+ registry.unbindSession(sessionId)
+ rmSync(join(root, 'data', 'stopped-agents', `${old.agentId}.json`))
+ const unbound = registry.byAgent(old.agentId)!
+ assert.equal(unbound.sessionId, '')
+ assert.equal((await captureResumeIdentity(unbound)).sessionId, sessionId)
+ if (engine === 'claude') {
+ assert.equal((await claudeProcessSession(unbound.processIdentity!.pid, cwd,
+ Date.parse(unbound.processIdentity!.startMarker)))?.sessionId, sessionId,
+ 'Claude native process metadata identifies the conversation before Stop')
+ }
// 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')
@@ -215,7 +232,94 @@ try {
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`)
+ log(`PASS ${engine}: native history + hook, new tmux runtime, same id, attach same PID, receipt replay, missing-ID recovery before Stop, stop persistence, surviving shell preserved`)
+ }
+ if (process.argv.includes('--serve')) {
+ // The desktop acceptance test uses the real local WS transport and terminal streams.
+ // HTTP supplies only fixture metadata and assertions, never fabricated RPC results.
+ const { attachLocalWsServer } = await import('../src/localWsServer.js')
+ const { TerminalStreamManager } = await import('../src/lib/terminalStreamManager.js')
+ const { TerminalBackendCoordinator } = await import('../src/lib/terminalBackendCoordinator.js')
+ const { agentFrame } = await import('../src/lib/agentFrame.js')
+ const streams = new TerminalStreamManager({
+ terminals: new TerminalBackendCoordinator([backend], ['tmux'], []),
+ resolveAgent: id => registry.byAgent(id), streamingAvailable: true,
+ sendTarget: (id, type, payload) => socketBackend.sendTerminalTo(id, type, payload),
+ sendBinaryTarget: (id, frame) => socketBackend.sendTerminalBinaryTo(id, frame),
+ isLoopback: () => true,
+ })
+ socketBackend.setTerminalStreamManager(streams)
+ const anchorPane = (await tmux('display-message', '-p', '-t', 'fixture-anchor', '#{pane_id}')).trim()
+ const anchor = registry.openPendingAgent({ engine: 'terminal', runtimes: [{ backend: 'tmux', paneId: anchorPane }], cwd: root, defaultName: 'Keep this work open' })!
+ registry.setLaunch(anchor.agentId, { state: 'ready' })
+ const resume = socketBackend.onResumeAgent!
+ socketBackend.onResumeAgent = async id => {
+ const fixture = fixtures.find(f => f.agentId === id); assert(fixture, 'only fixture sessions may resume')
+ let done = false, submitted = false
+ const result = resume(id).finally(() => { done = true })
+ let announced = ''
+ while (!done) {
+ const row = registry.byAgent(id)
+ if (row) {
+ const state = `${row.tmuxPane}:${row.launch?.state}`
+ if (state !== announced) {
+ announced = state
+ socketBackend.send({ type: 'agent_synced', payload: { agent: await agentFrame(row, { selectedModel: null, terminalAvailable: true, dsh: null }) } })
+ }
+ if (fixture.engine === 'codex' && !submitted) {
+ const screen = await tmux('capture-pane', '-p', '-S', '-500', '-t', row.tmuxPane)
+ if (screen.includes(fixture.marker) && /Ask Codex/.test(screen)) {
+ submitted = true
+ 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, 100))
+ }
+ return result
+ }
+ const stop = socketBackend.onDeleteAgent!
+ socketBackend.onDeleteAgent = async id => {
+ assert(fixtures.some(f => f.agentId === id), 'never stop the anchor or a non-fixture session')
+ await stop(id)
+ socketBackend.send({ type: 'agent_deleted', payload: { agentId: id, retained: true } })
+ }
+ let finish!: () => void
+ const finished = new Promise<void>(resolve => { finish = resolve })
+ const http = createServer((req, res) => { void (async () => {
+ res.setHeader('content-type', 'application/json')
+ const url = new URL(req.url!, 'http://127.0.0.1')
+ if (url.pathname === '/fixtures') { res.end(JSON.stringify({ fixtures, anchorId: anchor.agentId })); return }
+ if (url.pathname === '/shutdown' && req.method === 'POST') { res.end('{}'); finish(); return }
+ if (url.pathname === '/verify') {
+ const id = url.searchParams.get('id')!
+ const fixture = fixtures.find(f => f.agentId === id); assert(fixture)
+ const row = registry.byAgent(id)
+ const saved = stoppedAgents.get(id)
+ assert.equal(saved?.sessionId, fixture.sessionId)
+ if (row) {
+ assert.equal(row.sessionId, fixture.sessionId)
+ const screen = await tmux('capture-pane', '-p', '-S', '-500', '-t', row.tmuxPane)
+ assert(screen.includes(fixture.marker), 'native terminal must show original history')
+ }
+ const persisted = JSON.parse(readFileSync(join(root, 'data', 'registry.json'), 'utf8'))
+ assert.equal(persisted.some((r: any) => r.agentId === id), !!row)
+ res.end(JSON.stringify({ stopped: !row, sessionId: saved!.sessionId, pane: row?.tmuxPane, pid: row?.processIdentity?.pid, ready: row?.launch?.state === 'ready' })); return
+ }
+ res.statusCode = 404; res.end('{}')
+ })().catch(error => { res.statusCode = 500; res.end(JSON.stringify({ error: String(error) })) }) })
+ const local = attachLocalWsServer(http, { machineId: 'm', backend: socketBackend })
+ await new Promise<void>(resolve => http.listen(0, '127.0.0.1', resolve))
+ const endpoint = `http://127.0.0.1:${(http.address() as { port: number }).port}`
+ writeFileSync(join(tmpdir(), 'harness-resume-ui-endpoint.json'), JSON.stringify({ endpoint, root }))
+ log(`desktop fixture ready: ${endpoint}`)
+ const expiry = setTimeout(finish, 10 * 60_000)
+ process.once('SIGINT', finish); process.once('SIGTERM', finish)
+ await finished
+ clearTimeout(expiry); process.off('SIGINT', finish); process.off('SIGTERM', finish)
+ await local.close(); http.closeAllConnections(); await new Promise<void>(resolve => http.close(() => resolve()))
}
} finally {
await tmux('kill-server').catch(() => {})
diff --git a/cli/src/lib/captureResumeIdentity.spec.ts b/cli/src/lib/captureResumeIdentity.spec.ts
new file mode 100644
index 000000000..a6c6e1a0f
--- /dev/null
+++ b/cli/src/lib/captureResumeIdentity.spec.ts
@@ -0,0 +1,67 @@
+import { beforeEach, expect, it, vi } from 'vitest'
+import { captureResumeIdentity } from './captureResumeIdentity.js'
+import { validTranscriptPath, type RegisteredSession } from './registry.js'
+import { claudeProcessSession, findLiveSession, findResumedTranscript } from './sessionRepair.js'
+import { processRows, resumeSessionId } from './tmux.js'
+vi.mock('./registry.js', () => ({ validTranscriptPath: vi.fn(() => true) }))
+vi.mock('./sessionRepair.js', () => ({ claudeProcessSession: vi.fn(), findLiveSession: vi.fn(), findResumedTranscript: vi.fn() }))
+vi.mock('./tmux.js', () => ({ processRows: vi.fn(), resumeSessionId: vi.fn() }))
+let row: RegisteredSession
+beforeEach(() => {
+ vi.resetAllMocks()
+ row = { engine: 'claude', sessionId: '', cwd: '/work', codexHome: null,
+ processIdentity: { pid: 77, executable: '/bin/claude', startMarker: 'Mon Sep 21 01:00:00 2026' } } as RegisteredSession
+ vi.mocked(processRows).mockResolvedValue([{ ...row.processIdentity!, args: 'claude', parentPid: 1 }])
+ vi.mocked(validTranscriptPath).mockReturnValue(true)
+ vi.mocked(resumeSessionId).mockReturnValue(null)
+ vi.mocked(claudeProcessSession).mockResolvedValue(null)
+ vi.mocked(findLiveSession).mockResolvedValue(null)
+ vi.mocked(findResumedTranscript).mockResolvedValue(null)
+})
+it('leaves unsupported engines and complete bindings unchanged', async () => {
+ row.engine = 'terminal'; expect(await captureResumeIdentity(row)).toBe(row)
+ row.engine = 'codex'; row.sessionId = 'known'; row.transcriptPath = '/history'
+ expect(await captureResumeIdentity(row)).toBe(row); expect(processRows).not.toHaveBeenCalled()
+})
+it.each([null, '/stale'])('repairs a known id with missing or invalid path %s', async transcriptPath => {
+ Object.assign(row, { sessionId: 'known', transcriptPath, codexHome: '/profile' })
+ vi.mocked(validTranscriptPath).mockImplementation((_, path) => path === '/found')
+ vi.mocked(findResumedTranscript).mockResolvedValue('/found')
+ expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: 'known', transcriptPath: '/found' })
+ expect(findResumedTranscript).toHaveBeenCalledWith('claude', 'known', { codexHome: '/profile' })
+})
+it.each([null, '/unsafe'])('retains the known id when its file is unavailable: %s', async path => {
+ row.sessionId = 'known'; vi.mocked(findResumedTranscript).mockResolvedValue(path)
+ vi.mocked(validTranscriptPath).mockReturnValue(false); expect(await captureResumeIdentity(row)).toBe(row)
+})
+it.each(['identity', 'cwd', 'unknown', 'gone', 'pid', 'executable', 'start'])('refuses missing or changed process evidence: %s', async mode => {
+ if (mode === 'identity') row.processIdentity = null
+ if (mode === 'cwd') row.cwd = null
+ if (mode === 'unknown') vi.mocked(processRows).mockResolvedValue(null)
+ if (mode === 'gone') vi.mocked(processRows).mockResolvedValue([])
+ if (mode === 'pid') row.processIdentity!.pid++
+ if (mode === 'executable') row.processIdentity!.executable = 'other'
+ if (mode === 'start') row.processIdentity!.startMarker = 'later'
+ expect(await captureResumeIdentity(row)).toBe(row); expect(findLiveSession).not.toHaveBeenCalled()
+})
+it.each(['claude', 'codex'] as const)('captures an explicit %s resume without guessing by directory', async engine => {
+ row.engine = engine; vi.mocked(resumeSessionId).mockReturnValue('exact')
+ vi.mocked(findResumedTranscript).mockResolvedValue('/exact')
+ expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: 'exact', transcriptPath: '/exact', source: 'stop-repair' })
+ expect(findLiveSession).not.toHaveBeenCalled()
+})
+it('prefers current Claude native metadata to old resume argv', async () => {
+ vi.mocked(resumeSessionId).mockReturnValue('old')
+ vi.mocked(claudeProcessSession).mockResolvedValue({ sessionId: 'current', transcriptPath: '/current' })
+ expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: 'current' }); expect(findResumedTranscript).not.toHaveBeenCalled()
+})
+it('captures a unique fresh session before its first hook arrives', async () => {
+ vi.mocked(findLiveSession).mockResolvedValue({ sessionId: 'new', transcriptPath: '/new' })
+ expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: 'new', transcriptPath: '/new' })
+ expect(row.sessionId).toBe('')
+ expect(findLiveSession).toHaveBeenCalledWith('claude', '/work', Date.parse(row.processIdentity!.startMarker), { pid: 77, bornOnly: true, codexHome: undefined })
+})
+it.each([null, { sessionId: 'missing' }, { sessionId: 'unsafe', transcriptPath: '/unsafe' }])('does not bind ambiguous or unsafe history: %s', async found => {
+ vi.mocked(findLiveSession).mockResolvedValue(found); vi.mocked(validTranscriptPath).mockReturnValue(false)
+ expect(await captureResumeIdentity(row)).toBe(row)
+})
diff --git a/cli/src/lib/captureResumeIdentity.ts b/cli/src/lib/captureResumeIdentity.ts
new file mode 100644
index 000000000..468100f42
--- /dev/null
+++ b/cli/src/lib/captureResumeIdentity.ts
@@ -0,0 +1,30 @@
+/** Save an exact conversation identity while its native process still exists. */
+import { validTranscriptPath, type RegisteredSession } from './registry.js'
+import { claudeProcessSession, findLiveSession, findResumedTranscript } from './sessionRepair.js'
+import { processRows, resumeSessionId } from './tmux.js'
+
+export async function captureResumeIdentity(session: RegisteredSession): Promise<RegisteredSession> {
+ if (session.engine !== 'claude' && session.engine !== 'codex') return session
+ const options = { codexHome: session.codexHome ?? undefined }
+ if (session.sessionId) {
+ if (session.transcriptPath && validTranscriptPath(session.engine, session.transcriptPath, options.codexHome)) return session
+ const transcriptPath = await findResumedTranscript(session.engine, session.sessionId, options)
+ return transcriptPath && validTranscriptPath(session.engine, transcriptPath, options.codexHome)
+ ? { ...session, transcriptPath } : session
+ }
+ const expected = session.processIdentity
+ if (!expected || !session.cwd) return session
+ const live = (await processRows())?.find(row => row.pid === expected.pid
+ && row.executable === expected.executable && row.startMarker === expected.startMarker)
+ if (!live) return session
+ const explicit = resumeSessionId(session.engine, live.args)
+ const native = session.engine === 'claude'
+ ? await claudeProcessSession(expected.pid, session.cwd, Date.parse(expected.startMarker)) : null
+ const found = native ?? (explicit
+ ? { sessionId: explicit, transcriptPath: await findResumedTranscript(session.engine, explicit, options) }
+ : await findLiveSession(session.engine, session.cwd, Date.parse(expected.startMarker), {
+ ...options, pid: expected.pid, bornOnly: true,
+ }))
+ if (!found?.transcriptPath || !validTranscriptPath(session.engine, found.transcriptPath, options.codexHome)) return session
+ return { ...session, sessionId: found.sessionId, transcriptPath: found.transcriptPath, source: 'stop-repair', boundAt: Date.now() }
+}
diff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.ts
index 461f1a8c1..ebb3a967f 100644
--- a/cli/src/lib/sessionRepair.spec.ts
+++ b/cli/src/lib/sessionRepair.spec.ts
@@ -413,3 +413,30 @@ describe('findResumedTranscript', () => {
await expect(findResumedTranscript('cursor', 'f56f0a36-aa58-4af1-a6e2-a77386122332')).resolves.toBeNull()
})
})
+
+it.each(['local', 'utc'])('recovers an old Claude process in a busy project from its native %s record', async zone => {
+ const home = tempRoot(); const root = join(home, 'projects')
+ const id = '11111111-2222-4333-8444-555555555555'
+ writeTranscript(root, 'project', id, CWD, STARTED_AT)
+ writeTranscript(root, 'project', 'another-session', CWD, STARTED_AT)
+ mkdirSync(join(home, 'sessions'))
+ const procStart = zone === 'utc' ? new Date(STARTED_AT).toUTCString().replace(/ GMT$/, '') : new Date(STARTED_AT).toString()
+ writeFileSync(join(home, 'sessions', '77.json'), JSON.stringify({ pid: 77, cwd: CWD, sessionId: id, procStart }))
+ const { findLiveSession } = await load(root)
+ expect(await findLiveSession('claude', CWD, STARTED_AT, { pid: 77, bornOnly: true })).toMatchObject({ sessionId: id })
+})
+it.each(['bad pid', 'bad start', 'missing file', 'bad json', 'different pid', 'different start', 'missing start', 'different cwd', 'missing cwd', 'missing id', 'invalid id', 'missing history'])('refuses stale/invalid Claude native metadata: %s', async mode => {
+ const home = tempRoot(); const root = join(home, 'projects'); mkdirSync(root)
+ const { claudeProcessSession } = await load(root)
+ const record: Record<string, unknown> = { pid: 77, cwd: CWD, sessionId: '11111111-2222-4333-8444-555555555555', procStart: new Date(STARTED_AT).toUTCString() }
+ if (mode === 'different pid') record.pid = 78
+ if (mode === 'different start') record.procStart = new Date(STARTED_AT + 1000).toUTCString()
+ if (mode === 'missing start') delete record.procStart
+ if (mode === 'different cwd') record.cwd = '/different'
+ if (mode === 'missing cwd') delete record.cwd
+ if (mode === 'missing id') delete record.sessionId
+ if (mode === 'invalid id') record.sessionId = '../escape'
+ mkdirSync(join(home, 'sessions'))
+ if (mode !== 'missing file') writeFileSync(join(home, 'sessions', '77.json'), mode === 'bad json' ? '{' : JSON.stringify(record))
+ expect(await claudeProcessSession(mode === 'bad pid' ? -1 : 77, CWD, mode === 'bad start' ? NaN : STARTED_AT)).toBeNull()
+})
diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.ts
index c17b87266..20195b7f4 100644
--- a/cli/src/lib/sessionRepair.ts
+++ b/cli/src/lib/sessionRepair.ts
@@ -252,8 +252,12 @@ export async function findLiveSession(
const dirs = real === cwd ? [cwd] : [cwd, real]
const dirList = dirs.map(quote).join(', ')
switch (engine) {
- case 'claude':
- return fileEngineSession(env.CLAUDE_PROJECTS_DIR, cwd, startedAtMs, readTranscriptMeta, opts)
+ case 'claude': {
+ // Native Claude publishes a PID-to-conversation record even before a hook binds it.
+ // Unlike a directory scan this also identifies an old process in a busy project.
+ const exact = opts?.pid ? await claudeProcessSession(opts.pid, cwd, startedAtMs) : null
+ return exact ?? fileEngineSession(env.CLAUDE_PROJECTS_DIR, cwd, startedAtMs, readTranscriptMeta, opts)
+ }
case 'codex':
// Codex writes no `cwd` on line one; its rollout meta carries it — and says whether the rollout
// belongs to a subagent, which must never become an agent of its own.
@@ -461,3 +465,19 @@ export async function findResumedTranscript(
}
return null
}
+
+/** Claude's native process record is removed at exit; capture it before Stop signals the engine. */
+export async function claudeProcessSession(pid: number, cwd: string, startedAtMs: number): Promise<RepairedSession | null> {
+ if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isFinite(startedAtMs)) return null
+ try {
+ const record = JSON.parse(await readFile(join(dirname(env.CLAUDE_PROJECTS_DIR), 'sessions', `${pid}.json`), 'utf8'))
+ // procStart is UTC in current Claude, while older builds used the host's local ps format.
+ // Both represent the exact second, not the metadata file's modification time or a recycled PID.
+ if (record.pid !== pid || typeof record.procStart !== 'string'
+ || ![Date.parse(record.procStart), Date.parse(`${record.procStart} UTC`)].includes(startedAtMs)
+ || typeof record.cwd !== 'string' || !await sameDir(record.cwd, cwd)
+ || typeof record.sessionId !== 'string') return null
+ const transcriptPath = await findResumedTranscript('claude', record.sessionId)
+ return transcriptPath ? { sessionId: record.sessionId, transcriptPath } : null
+ } catch { return null }
+}
diff --git a/cli/src/lib/stopAgentService.spec.ts b/cli/src/lib/stopAgentService.spec.ts
index 8d3fb7c1f..577331b87 100644
--- a/cli/src/lib/stopAgentService.spec.ts
+++ b/cli/src/lib/stopAgentService.spec.ts
@@ -1,14 +1,17 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { captureResumeIdentity } from './captureResumeIdentity.js'
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('./captureResumeIdentity.js', () => ({ captureResumeIdentity: vi.fn(async session => session) }))
vi.mock('./deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn(), terminateDeletedAgent: vi.fn() }))
let row: RegisteredSession
let deps: StopAgentServiceDeps
beforeEach(() => {
vi.clearAllMocks()
+ vi.mocked(captureResumeIdentity).mockReset().mockImplementation(async session => session)
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(),
@@ -58,3 +61,35 @@ it('only signals through the validated process deleter and does not erase a newe
expect(signal).toHaveBeenCalledExactlyOnceWith(77, 'SIGTERM'); expect(deps.stopJobs.has(row.agentId)).toBe(true)
expect(deps.tmuxBackend!.kill).toHaveBeenCalledExactlyOnceWith({ backend: 'tmux', paneId: '%44' })
})
+
+it.each(['claude', 'codex'] as const)('captures an unbound %s conversation before deleting its process', async engine => {
+ Object.assign(row, { engine, sessionId: '', transcriptPath: null })
+ vi.mocked(captureResumeIdentity).mockImplementation(async session => {
+ expect(registry.byAgent(row.agentId)).toBe(row)
+ expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled()
+ return { ...session, sessionId: 'recovered', transcriptPath: '/history.jsonl', boundAt: 1, source: 'stop-repair' }
+ })
+ await createStopAgentService(deps)(row.agentId)
+ expect(stoppedAgents.get(row.agentId)).toMatchObject({ engine, sessionId: 'recovered', transcriptPath: '/history.jsonl' })
+ expect(deps.markDeleted).toHaveBeenCalledWith('recovered')
+})
+it.each(['removed', 'replaced'] as const)('does not stop a process that was %s during identity capture', async mode => {
+ vi.mocked(captureResumeIdentity).mockImplementation(async session => {
+ if (mode === 'removed') registry.removeAgent(row.agentId)
+ else row.processIdentity = { ...row.processIdentity!, pid: 88 }
+ return session
+ })
+ await expect(createStopAgentService(deps)(row.agentId)).rejects.toThrow('Harness changed')
+ expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled()
+ expect(terminateDeletedAgent).not.toHaveBeenCalled()
+ expect(stoppedAgents.get(row.agentId)).toBeNull()
+})
+it('keeps the newer hook binding that arrives during capture', async () => {
+ row.sessionId = ''
+ vi.mocked(captureResumeIdentity).mockImplementation(async session => {
+ row.sessionId = 'latest'
+ return { ...session, sessionId: 'older' }
+ })
+ await createStopAgentService(deps)(row.agentId)
+ expect(stoppedAgents.get(row.agentId)?.sessionId).toBe('latest')
+})
diff --git a/cli/src/lib/stopAgentService.ts b/cli/src/lib/stopAgentService.ts
index 75ab7eb22..36f76a9d8 100644
--- a/cli/src/lib/stopAgentService.ts
+++ b/cli/src/lib/stopAgentService.ts
@@ -1,4 +1,5 @@
/** Stop retains the logical session before retiring its process and terminal. */
+import { captureResumeIdentity } from './captureResumeIdentity.js'
import { isTerminalEngine } from '../engines/types.js'
import type { registry as liveRegistry, RegisteredSession } from './registry.js'
import type { StoppedAgentStore } from './stoppedAgents.js'
@@ -27,8 +28,18 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
if (existing) return existing
restartJobs.cancel(sessionId)
const job = Promise.resolve().then(async () => {
- const s = registry.resolve(sessionId)
- if (!s) return
+ const live = registry.resolve(sessionId)
+ if (!live) return
+ const identity = JSON.stringify([live.engine, live.processIdentity, live.runtimes])
+ const captured = await captureResumeIdentity({ ...live })
+ // Discovery or a hook may have updated this row while reading the native store.
+ // A replacement process must never be stopped using an older snapshot.
+ if (registry.resolve(sessionId) !== live
+ || JSON.stringify([live.engine, live.processIdentity, live.runtimes]) !== identity) {
+ throw new Error('Harness changed while saving its conversation. Try Stop again.')
+ }
+ const s = live.sessionId && live.sessionId !== captured.sessionId ? { ...live } : { ...live, sessionId: captured.sessionId,
+ transcriptPath: captured.transcriptPath, boundAt: captured.boundAt, source: captured.source }
// Saving precedes every mutation. A storage failure leaves the live agent alone.
stoppedAgents.save(s)
markDeleted(sessionId)
diff --git a/cli/src/lib/stoppedAgents.spec.ts b/cli/src/lib/stoppedAgents.spec.ts
index e0305c7c3..52d08f4c9 100644
--- a/cli/src/lib/stoppedAgents.spec.ts
+++ b/cli/src/lib/stoppedAgents.spec.ts
@@ -172,3 +172,21 @@ it('does not allocate when reserving disk space fails', async () => {
expect(() => store.beginResume(saved.agentId)).toThrow('disk full')
expect(store.get(saved.agentId)?.sessionId).toBe(saved.sessionId)
})
+
+it('an unbound observation of the same process keeps its confirmed conversation', async () => {
+ const { saved, store } = await fixture()
+ saved.transcriptPath = '/history.jsonl'; saved.boundAt = 1; saved.source = 'hook'; store.save(saved)
+ store.save({ ...saved, sessionId: '', transcriptPath: null, title: 'Renamed', boundAt: null, source: null })
+ expect(store.get(saved.agentId)).toMatchObject({ sessionId: saved.sessionId, transcriptPath: '/history.jsonl', title: 'Renamed', boundAt: 1, source: 'hook' })
+})
+it.each(['engine', 'missing', 'previous missing', 'pid', 'start', 'executable'])('does not transfer a binding to a different process: %s', async mode => {
+ const { saved, store } = await fixture()
+ store.save(mode === 'previous missing' ? { ...saved, processIdentity: null } : saved)
+ const next = { ...saved, sessionId: '', processIdentity: { ...saved.processIdentity! } } as RegisteredSession
+ if (mode === 'engine') next.engine = 'claude'
+ if (mode === 'missing') next.processIdentity = null
+ if (mode === 'pid') next.processIdentity!.pid++
+ if (mode === 'start') next.processIdentity!.startMarker = 'new'
+ if (mode === 'executable') next.processIdentity!.executable = 'other'
+ store.save(next); expect(store.get(saved.agentId)?.sessionId).toBe('')
+})
diff --git a/cli/src/lib/stoppedAgents.ts b/cli/src/lib/stoppedAgents.ts
index afcfb7f5f..085dafcb4 100644
--- a/cli/src/lib/stoppedAgents.ts
+++ b/cli/src/lib/stoppedAgents.ts
@@ -47,7 +47,18 @@ export class StoppedAgentStore {
if (!SAFE_ID.test(session.agentId)) throw new Error('Invalid stopped harness identity.')
// An exited engine leaves its pane as a shell. Stopping that shell must keep
// the conversation saved before releaseEngine cleared its binding/profile.
- if (isTerminalEngine(session.engine) && this.get(session.agentId)) return
+ const previous = this.get(session.agentId)
+ if (isTerminalEngine(session.engine) && previous) return
+ // A temporarily unbound observation of the SAME process cannot erase a known conversation.
+ // A replacement process must earn its own binding; never carry history across PID reuse.
+ if (!session.sessionId && previous?.sessionId && previous.engine === session.engine
+ && session.processIdentity && previous.processIdentity
+ && session.processIdentity.pid === previous.processIdentity.pid
+ && session.processIdentity.startMarker === previous.processIdentity.startMarker
+ && session.processIdentity.executable === previous.processIdentity.executable) {
+ session = { ...session, sessionId: previous.sessionId, transcriptPath: previous.transcriptPath,
+ boundAt: previous.boundAt, source: previous.source }
+ }
secureStateDirectory(dirname(this.directory))
secureStateDirectory(this.directory)
const snapshot = {
diff --git a/desktop/design/agent-lifecycle-map.md b/desktop/design/agent-lifecycle-map.md
index a49460b1b..676e1af23 100644
--- a/desktop/design/agent-lifecycle-map.md
+++ b/desktop/design/agent-lifecycle-map.md
@@ -74,8 +74,13 @@ as live routes/processes when resuming.
The stop/resume transition is:
-1. Save the Harness ID, engine conversation ID, cwd, name, profile and launch
- settings before removing the live row.
+1. Capture the conversation before stopping the process. If its binding is missing,
+ verify the PID/start marker and recover from Claude's native process record,
+ explicit resume arguments, or an unambiguous newly created native transcript.
+ Never select a different conversation merely because it shares the project.
+ Save the Harness ID, conversation ID, cwd, name, profile and launch settings
+ before removing the live row. An unbound snapshot of the same process cannot
+ overwrite a previously confirmed conversation.
2. End the old runtime. The saved record remains searchable in the user-facing
harness catalog; it has no user-facing Stopped badge or different action.
3. On Enter, either return a verified running instance of that conversation or
@@ -159,11 +164,32 @@ npm run test:resume
npm run test:resume-native
```
-`test:resume` runs 109 tests and enforces **100% lines, statements, branches and functions** for four production modules: `resumeAgentService.ts`, `resumeStoppedAgent.ts`, `stopAgentService.ts` and `stoppedAgents.ts`. This is measured coverage of those modules, not a claim of 100% coverage of the repository or every runtime environment. The complete CLI suite passed **3,757 tests, with 63 skipped**. TypeScript checking and the normal `build.mjs` build passed.
+`test:resume` runs 181 tests and enforces **100% lines, statements, branches and functions** for five production modules: `captureResumeIdentity.ts`, `resumeAgentService.ts`, `resumeStoppedAgent.ts`, `stopAgentService.ts` and `stoppedAgents.ts`. This is measured coverage of those modules, not a claim of 100% coverage of the repository or every runtime environment. The complete CLI suite passed **3,820 tests, with 63 skipped**. TypeScript checking and the normal `build.mjs` build passed.
-`test:resume-native` requires installed Claude Code, Codex and tmux. It launches the real vendor CLIs against synthetic saved conversations using the production BackendSocket, Stop/Resume handlers, registry/archive, launch arguments and native hook server. It verifies visible saved history, exact conversation IDs, live attach without process replacement, operation receipts, Stop persistence across a registry reload, new tmux runtimes on resume, and preservation of a surviving shell after engine exit. It uses a separate tmux socket, isolated data/config directories and unavailable loopback model endpoints, without real credentials or paid model calls. Only after restored Codex history is visible does the fixture submit a harmless test message to trigger its deferred native hook. No such message is submitted by production resume.
+`test:resume-native` requires installed Claude Code, Codex and tmux. It launches the real vendor CLIs against synthetic saved conversations using the production BackendSocket, Stop/Resume handlers, registry/archive, launch arguments and native hook server. It verifies visible saved history, exact conversation IDs, live attach without process replacement, operation receipts, Stop persistence across a registry reload, new tmux runtimes on resume, preservation of a surviving shell after engine exit, and recovery when the live row and archive have deliberately lost their conversation binding before Stop. It uses a separate tmux socket, isolated data/config directories and unavailable loopback model endpoints, without real credentials or paid model calls. Only after restored Codex history is visible does the fixture submit a harmless test message to trigger its deferred native hook. No such message is submitted by production resume.
-Desktop regression coverage includes Cmd-P/T selection of retained sessions, pending native terminals, receipt and identity races, creation placement, repeated Cmd-T, Escape from search and creation, occupied-tab preservation, and the last-tab onboarding exception. The final full desktop suite passed **2,671 tests, with 10 skipped**. The analyzer reported no errors or warnings, with 17 existing informational findings. The plain New Tab and onboarding layouts were visually reviewed with the real dock at 1280×800 and 960×640; a widget regression verifies the tagline stays centered in the visible area above search and creation docks.
+The native desktop acceptance test also passed using the production local WebSocket,
+terminal stream manager, tmux backend and installed CLIs. For **each** Claude/Codex
+session it stops and reopens through both Cmd-P and Cmd-T, verifies the original
+history in the desktop terminal buffer, checks the live registry and archive,
+confirms replacement PID/pane IDs after Stop and unchanged IDs for live attach,
+and keeps an unrelated tab open. Run it with the fixture isolated from real work:
+
+```sh
+# cli/ — prints its loopback URL; keep this process running
+npm run test:resume-native -- --serve
+# desktop/ — replace the port with the printed fixture port
+FLUTTER_TEST=1 flutter test -d macos --no-pub integration_test/native_resume_e2e_test.dart \
+ --dart-define=RESUME_FIXTURE_URL=http://127.0.0.1:PORT
+# Stop the disposable fixture after testing (or press Ctrl-C in its terminal)
+curl -X POST http://127.0.0.1:PORT/shutdown
+```
+
+This fixture build replaces the local debug app; rebuild the normal `lib/main.dart`
+review artifact afterward. Its injected keyboard events verify Flutter commands,
+not physical OS keyboard/IME delivery.
+
+Desktop regression coverage includes Cmd-P/T selection of retained sessions, pending native terminals, receipt and identity races, creation placement, repeated Cmd-T, Escape from search and creation, occupied-tab preservation, and the last-tab onboarding exception. The final full desktop suite passed **2,739 tests, with 10 skipped**. The analyzer reported no errors or warnings, with 17 existing informational findings. The plain New Tab and onboarding layouts were visually reviewed with the real dock at 1280×800 and 960×640; a widget regression verifies the tagline stays centered in the visible area above search and creation docks.
## Suggested manual acceptance checks
diff --git a/desktop/integration_test/native_resume_e2e_test.dart b/desktop/integration_test/native_resume_e2e_test.dart
new file mode 100644
index 000000000..071c38ef1
--- /dev/null
+++ b/desktop/integration_test/native_resume_e2e_test.dart
@@ -0,0 +1,165 @@
+// Start `node --import tsx scripts/resume-native-e2e.ts --serve` in cli first.
+// FLUTTER_TEST=1 flutter test -d macos --no-pub integration_test/native_resume_e2e_test.dart
+// --dart-define=RESUME_FIXTURE_URL=http://127.0.0.1:<fixture-port>
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:integration_test/integration_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/test_run.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import '../test/swarm_interactions_test.dart' show chord;
+import '../test/swarm_screen_test.dart' show mount;
+import '../test/swarm_state_test.dart' show createApp;
+
+void main() {
+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();
+ const endpoint = String.fromEnvironment('RESUME_FIXTURE_URL');
+ if (!kUnderTest || !endpoint.startsWith('http://127.0.0.1:')) {
+ throw StateError(
+ 'Requires FLUTTER_TEST=1 and the isolated resume fixture URL',
+ );
+ }
+ testWidgets(
+ 'real Claude/Codex stop, Cmd-P/T search, resume, registry and terminal history',
+ (tester) async {
+ final http = HttpClient();
+ addTearDown(() => http.close(force: true));
+ Future<Map<String, dynamic>> get(String path) async {
+ final response = await (await http.getUrl(Uri.parse('$endpoint$path')))
+ .close();
+ final body = jsonDecode(
+ await utf8.decoder.bind(response).join(),
+ ) as Map<String, dynamic>;
+ expect(response.statusCode, 200, reason: '$body');
+ return body;
+ }
+
+ Future<void> until(bool Function() condition, String label) async {
+ final deadline = DateTime.now().add(const Duration(seconds: 60));
+ while (!condition() && DateTime.now().isBefore(deadline)) {
+ await tester.pump(const Duration(milliseconds: 100));
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ }
+ expect(condition(), isTrue, reason: label);
+ }
+
+ final data = await get('/fixtures');
+ late AppNotifier app;
+ final connection = WsConn(
+ wsBaseUrl: '',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ transportKind: WsTransportKind.localPlaintext,
+ localWsUri: Uri.parse(
+ '${endpoint.replaceFirst('http:', 'ws:')}/api/local-ws',
+ ),
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (frame) => app.handleEventForTest('m', frame),
+ onStatus: (_) {},
+ );
+ app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ addTearDown(connection.close);
+ // The test injection supplies the same binary dispatch normally wired by the connection pool.
+ connection.onBinaryFrame = (raw) async {
+ final frame = decodeTerminalLocal(raw);
+ if (frame == null) return;
+ for (final pane in app.allPanes) {
+ if (pane.session?.streamId == frame.streamId) {
+ await pane.session!.handleBinary(frame);
+ }
+ }
+ };
+ await connection.connect();
+ await connection.waitUntilReady(timeout: const Duration(seconds: 10));
+ final inventory = await connection.request(
+ 'agents_list',
+ payload: {'includeStopped': true},
+ );
+ app.machineStates['m']!
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agents = (inventory['agents'] as List)
+ .map((a) => Agent.fromJson(Map<String, dynamic>.from(a)))
+ .toList();
+ await app.reloadMachineData('m');
+ expect(app.stateOf('m')!.terminalCapabilityAvailable, isTrue);
+ final anchorId = data['anchorId'] as String;
+ await app.addAgentToSwarm('m', anchorId);
+ final originalTab = app.activeSwarmId;
+ await mount(tester, app);
+
+ for (final raw in data['fixtures'] as List) {
+ final fixture = Map<String, dynamic>.from(raw);
+ final id = fixture['agentId'] as String;
+ final engine = fixture['engine'] as String;
+ final marker = fixture['marker'] as String;
+ Future<Map<String, dynamic>> open(LogicalKeyboardKey key) async {
+ await chord(tester, key);
+ await tester.pump();
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ 'Native $engine fixture',
+ );
+ await tester.pump();
+ expect(find.textContaining('Stopped'), findsNothing);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(find.byType(AlertDialog), findsNothing);
+ await until(
+ () => app.allPanes.any(
+ (p) =>
+ p.agentId == id &&
+ (p.session?.terminal.buffer.getText().contains(marker) ??
+ false),
+ ),
+ '$engine original history reaches the desktop terminal',
+ );
+ await until(
+ () => app
+ .stateOf('m')!
+ .agents
+ .any((a) => a.id == id && a.launchState == 'ready'),
+ '$engine native hook confirms resume',
+ );
+ expect(app.allPanes.any((p) => p.agentId == anchorId), isTrue);
+ expect(app.swarms.any((s) => s.id == originalTab), isTrue);
+ final verified = await get('/verify?id=$id');
+ expect(verified['sessionId'], fixture['sessionId']);
+ expect(verified['ready'], true);
+ return verified;
+ }
+
+ var previous = await open(LogicalKeyboardKey.keyP);
+ for (final key in [LogicalKeyboardKey.keyP, LogicalKeyboardKey.keyT]) {
+ expect(await app.deleteAgent('m', id), isNull);
+ await until(
+ () =>
+ app.stateOf('m')!.agents.any((a) => a.id == id && a.isStopped),
+ '$engine remains searchable after Stop',
+ );
+ expect((await get('/verify?id=$id'))['stopped'], true);
+ final resumed = await open(key);
+ expect(resumed['pane'], isNot(previous['pane']));
+ expect(resumed['pid'], isNot(previous['pid']));
+ previous = resumed;
+ }
+ // Opening an already-running harness must preserve its native process.
+ final attached = await open(LogicalKeyboardKey.keyP);
+ expect(attached['pid'], previous['pid']);
+ expect(attached['pane'], previous['pane']);
+ expect(await app.deleteAgent('m', id), isNull);
+ }
+ await tester.pumpWidget(const SizedBox());
+ },
+ timeout: const Timeout(Duration(minutes: 8)),
+ );
+}
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index 2f234ddbf..3ef3e4cdd 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -310,7 +310,11 @@ final harnessCommands = <HarnessCommand>[
nativeAction: 'cloneAgent',
keywords: ['duplicate', 'another', 'fresh'],
),
- const HarnessCommand('agent.restart', 'Restart Harness', ShortcutGroup.actions),
+ const HarnessCommand(
+ 'agent.restart',
+ 'Restart Harness',
+ ShortcutGroup.actions,
+ ),
const HarnessCommand(
'terminal.new',
'New Terminal',