The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: Harness Monitor pauses and resumes every engine, not two (#263)
0xken157ac2945238e4
diff --git a/cli/scripts/pause-resume-e2e.mts b/cli/scripts/pause-resume-e2e.mtsnew file mode 100644index 000000000..4d6edf1ee--- /dev/null+++ b/cli/scripts/pause-resume-e2e.mts@@ -0,0 +1,135 @@+// End-to-end check of Harness Monitor's Pause/Resume against a RUNNING daemon, over its loopback WS+// — the same transport the desktop app uses — for this machine or one it relays to (a docker box).+//+// npx tsx scripts/pause-resume-e2e.mts <machineId> [label] [engine]+//+// Pause is `agent_delete` (stop, conversation saved first) and Resume is `agent_resume`, exactly as+// the desktop sends them. The engine defaults to `terminal`, which every machine has; pass another+// (`opencode`, `claude`, …) to exercise a real conversation. What this proves:+//+// * `agents_list` carries `resumeMode` for the engine — the capability the desktop words its+// button from, and the thing that used to be an allow-list copied into the client.+// * Pause archives the row: it comes back in the list as `status: stopped`, still carrying+// `resumeMode`, so the paused row can still offer Resume.+// * Resume brings it back on the same pane/folder, and says whether it reopened the conversation+// (`resumed`) rather than failing when it could not.+//+// A relayed machine runs every frame through the daemon's E2EE envelope, so passing against a+// docker box is what proves the remote half. Leaves nothing behind on a pass.+import WebSocket from 'ws'+import { randomUUID } from 'node:crypto'++const machineId = process.argv[2]+const label = process.argv[3] ?? machineId?.slice(0, 8)+const engine = process.argv[4] ?? 'terminal'+if (!machineId) throw new Error('machineId required')+const log = (m: string) => console.log(`[${label}] ${new Date().toISOString().slice(11, 19)} ${m}`)+const fail = (m: string): never => { console.error(`[${label}] FAIL ${m}`); process.exit(1) }++const ws = new WebSocket('ws://127.0.0.1:18473/api/local-ws')+const frames: Array<Record<string, any>> = []+const waiters: Array<{ test: (f: Record<string, any>) => boolean; resolve: (f: Record<string, any>) => void }> = []+ws.on('close', (code, reason) => log(`ws closed ${code} ${reason.toString()}`))+ws.on('message', (raw, isBinary) => {+ if (isBinary) return+ const f = JSON.parse(raw.toString()) as Record<string, any>+ frames.push(f)+ for (const w of [...waiters]) if (w.test(f)) { waiters.splice(waiters.indexOf(w), 1); w.resolve(f) }+})+const send = (type: string, payload: Record<string, unknown>) => ws.send(JSON.stringify({ type, payload }))+const waitFor = (test: (f: Record<string, any>) => boolean, ms = 20_000, what = 'frame'): Promise<Record<string, any>> =>+ new Promise((resolve, reject) => {+ const hit = frames.find(test)+ if (hit) return resolve(hit)+ const t = setTimeout(() => reject(new Error(`timeout waiting for ${what}`)), ms)+ waiters.push({ test, resolve: (f) => { clearTimeout(t); resolve(f) } })+ })+const rpc = async (type: string, payload: Record<string, unknown>, ms = 60_000) => {+ const requestId = randomUUID()+ send(type, { requestId, ...payload })+ const r = await waitFor((f) => f.type === `${type}_result` && f.payload?.requestId === requestId, ms, `${type}_result`)+ return r.payload as Record<string, any>+}+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))+const rowOf = async (agentId: string): Promise<Record<string, any> | undefined> => {+ const list = await rpc('agents_list', { includeStopped: true })+ return (list.agents as any[]).find((a) => a.id === agentId)+}+/** The list is refreshed by the daemon's own scans; a state change is not instant. */+const pollRow = async (agentId: string, want: (row: Record<string, any> | undefined) => boolean, ms: number, what: string) => {+ const until = Date.now() + ms+ let last: Record<string, any> | undefined+ while (Date.now() < until) {+ last = await rowOf(agentId)+ if (want(last)) return last+ await sleep(1000)+ }+ return fail(`${what} did not happen within ${ms}ms · last row: ${JSON.stringify(last)}`)+}++await new Promise<void>((resolve) => ws.on('open', () => resolve()))+send('machine_select', { machineId, localProtocolVersion: 1 })+await waitFor((f) => f.type === 'connected', 20_000, 'connected')+log(`connected · engine=${engine}`)++const cwd = process.env.E2E_CWD ?? '/tmp'+// A first prompt, because an engine that has not been spoken to has no conversation to archive —+// and then the pause/resume under test is only ever the fresh path. `E2E_PROMPT=` (empty) skips it.+const prompt = engine === 'terminal' ? undefined : (process.env.E2E_PROMPT ?? 'reply with the single word: ok')+const created = await rpc('agent_create', { engine, cwd, bypassPermission: true, ...(prompt ? { prompt } : {}) }, 60_000)+if (created.error) fail(`agent_create → ${created.error} ${created.detail ?? ''}`)+const agentId: string = created.agent.id+log(`created ${engine} ${agentId.slice(0, 8)} · resumeMode=${created.agent.resumeMode}`)+if (!created.agent.resumeMode) fail('agent_create result carries no resumeMode — the daemon is older than this check')++let live = await pollRow(agentId, (r) => !!r && r.status !== 'stopped', 45_000, 'agent appears live')+// Give the engine a moment to bind a conversation, so the pause has one to archive and the resume+// takes the exact-conversation path rather than the fresh one. Not fatal if it never does: pausing+// an engine that never bound is a case in its own right, and the resume says `resumed: false`.+if (engine !== 'terminal') {+ const until = Date.now() + Number(process.env.E2E_BIND_MS ?? 45_000)+ while (Date.now() < until && !(live?.sessionId)) {+ await sleep(2000)+ live = await rowOf(agentId)+ }+ if (!live?.sessionId) log('no conversation bound yet — this run exercises the fresh-resume path')+}+log(`live · status=${live!.status} resumeMode=${live!.resumeMode} sessionId=${(live!.sessionId ?? '').slice(0, 8) || '-'}`)+if (live!.resumeMode !== created.agent.resumeMode) fail(`resumeMode changed between create and list: ${created.agent.resumeMode} → ${live!.resumeMode}`)+const wantedConversation = !!live!.sessionId && live!.resumeMode === 'conversation'++// ── Pause ────────────────────────────────────────────────────────────────────+const stopped = await rpc('agent_delete', { agentId }, 60_000)+if (stopped.error) fail(`agent_delete (pause) → ${stopped.error} ${stopped.detail ?? ''}`)+log('paused')+const archived = await pollRow(agentId, (r) => r?.status === 'stopped', 45_000, 'row archives as stopped')+log(`archived · resumeMode=${archived!.resumeMode} sessionId=${(archived!.sessionId ?? '').slice(0, 8) || '-'}`)+if (!archived!.resumeMode) fail('the paused row lost resumeMode — the desktop would grey out Resume')++// ── Resume ───────────────────────────────────────────────────────────────────+const creationId = randomUUID()+let resumed = await rpc('agent_resume', { agentId, creationId }, 120_000)+// A resume that outlives its reply is checked the way the desktop checks it.+for (let i = 0; resumed.state === 'unconfirmed' && i < 20; i++) {+ await sleep(3000)+ resumed = await rpc('agent_create_status', { creationId }, 60_000)+}+if (resumed.error) fail(`agent_resume → ${resumed.error} ${resumed.detail ?? ''}`)+log(`resumed · state=${resumed.state} resumed=${resumed.resumed} sessionId=${(resumed.agent?.sessionId ?? '').slice(0, 8) || '-'}`)+// The promise the button makes. A shell is exempt from the second half: `resumed` there means the+// pane came back, which is the whole of what a shell resume is (`resumeAgentService`'s terminal+// branch), and `resumeMode: 'shell'` is what already tells a client there is no conversation.+if (wantedConversation && resumed.resumed !== true) fail(`a recorded conversation was not reopened (resumed=${resumed.resumed})`)+if (!wantedConversation && live!.resumeMode !== 'shell' && resumed.resumed === true) {+ fail('claimed to reopen a conversation that was never recorded')+}+const back = await pollRow(agentId, (r) => !!r && r.status !== 'stopped', 60_000, 'row comes back live')+if (back!.cwd && live!.cwd && back!.cwd !== live!.cwd) fail(`came back in another folder: ${live!.cwd} → ${back!.cwd}`)+log(`back · status=${back!.status} cwd=${back!.cwd} resumeMode=${back!.resumeMode}`)++// ── Clean up ─────────────────────────────────────────────────────────────────+const removed = await rpc('agent_delete', { agentId }, 60_000)+if (removed.error) log(`cleanup agent_delete → ${removed.error} (left behind: ${agentId})`)+log('PASS')+ws.close()+process.exit(0)diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.tsindex edc60e61b..41019d85b 100644--- a/cli/src/lib/agentFrame.ts+++ b/cli/src/lib/agentFrame.ts@@ -26,6 +26,7 @@ import type { GridAssignment } from './gridAssignment.js'import type { GridWebSearchStatus } from './gridLaunch.js'import { projectDisplayName, sessionDisplayTitle, type RegisteredSession } from './registry.js'import { engineCanFork } from './forkAgent.js'+import { resumeMode, type ResumeMode } from './resumeCapability.js'import type { DshVerdict } from '../dsh/verdict.js'/**@@ -83,6 +84,14 @@ export type AgentFrame = {/** Whether `agent_fork` can do anything for this engine (lib/forkAgent.ts) — natively, or by a* handoff. A client hides the Fork action on a false rather than offering a button that refuses. */forkable: boolean+ /**+ * How much a Pause of this harness can promise to bring back (lib/resumeCapability.ts):+ * `'shell'` (a terminal — a fresh shell in the same tile), `'conversation'` (this engine reopens+ * the one it was in) or `'fresh'` (it comes back, as a new conversation). Every value is+ * pausable; a client words the button from this rather than keeping its own copy of the engine+ * table, which is how the two drifted before.+ */+ resumeMode: ResumeMode/*** The launch choices a client needs to open ANOTHER agent like this one — the desktop's Clone* (`agent_create` with the same `permissionMode`, `bypassPermission` and `agent`). Read off the@@ -182,6 +191,7 @@ export async function agentFrame(verdict: dsh?.verdict ?? null,forkedFrom: s.forkedFrom ? { agentId: s.forkedFrom.agentId, name: s.forkedFrom.name } : null,forkable: engineCanFork(s.engine),+ resumeMode: resumeMode(s.engine),permissionMode: s.permissionMode ?? null,bypassPermission: s.bypassPermission ?? null,namedAgent: s.agent ?? null,diff --git a/cli/src/lib/captureResumeIdentity.spec.ts b/cli/src/lib/captureResumeIdentity.spec.tsindex a6c6e1a0f..f4ded10cf 100644--- a/cli/src/lib/captureResumeIdentity.spec.ts+++ b/cli/src/lib/captureResumeIdentity.spec.ts@@ -1,9 +1,9 @@import { beforeEach, expect, it, vi } from 'vitest'import { captureResumeIdentity } from './captureResumeIdentity.js'-import { validTranscriptPath, type RegisteredSession } from './registry.js'+import { engineKeepsTranscriptFile, 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('./registry.js', () => ({ validTranscriptPath: vi.fn(() => true), engineKeepsTranscriptFile: 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@@ -13,16 +13,33 @@ beforeEach(() => {processIdentity: { pid: 77, executable: '/bin/claude', startMarker: 'Mon Sep 21 01:00:00 2026' } } as RegisteredSessionvi.mocked(processRows).mockResolvedValue([{ ...row.processIdentity!, args: 'claude', parentPid: 1 }])vi.mocked(validTranscriptPath).mockReturnValue(true)+ vi.mocked(engineKeepsTranscriptFile).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 () => {+it('leaves a shell and a complete binding 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('takes a database-backed engine on its recorded id, with no transcript to check', async () => {+ // opencode/kilo/hermes/devin keep the conversation in SQLite: there is no file, and demanding one+ // is what used to leave their resume with nothing to reopen.+ vi.mocked(engineKeepsTranscriptFile).mockReturnValue(false)+ Object.assign(row, { engine: 'opencode', sessionId: 'known' })+ expect(await captureResumeIdentity(row)).toBe(row)+ expect(findResumedTranscript).not.toHaveBeenCalled()+})++it('captures a database-backed engine id read off the live process', async () => {+ vi.mocked(engineKeepsTranscriptFile).mockReturnValue(false)+ row.engine = 'opencode'+ vi.mocked(findLiveSession).mockResolvedValue({ sessionId: 'live' })+ expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: 'live', source: 'stop-repair' })+})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')diff --git a/cli/src/lib/captureResumeIdentity.ts b/cli/src/lib/captureResumeIdentity.tsindex 468100f42..8d70e1cd3 100644--- a/cli/src/lib/captureResumeIdentity.ts+++ b/cli/src/lib/captureResumeIdentity.ts@@ -1,12 +1,25 @@-/** Save an exact conversation identity while its native process still exists. */-import { validTranscriptPath, type RegisteredSession } from './registry.js'+/**+ * Save an exact conversation identity while its native process still exists.+ *+ * Pause kills the engine, and afterwards there is nothing left to ask: the id the resume will need+ * has to be read out now. This runs for EVERY engine — it used to be claude and codex only, which is+ * why every other engine's pause archived whatever the registry happened to hold and its resume then+ * had nothing to reopen. `findLiveSession` already knows how to find a live session for all of them,+ * including the four that keep theirs in a database rather than a file.+ */+import { engineKeepsTranscriptFile, validTranscriptPath, type RegisteredSession } from './registry.js'import { claudeProcessSession, findLiveSession, findResumedTranscript } from './sessionRepair.js'import { processRows, resumeSessionId } from './tmux.js'+import { isTerminalEngine } from '../engines/types.js'export async function captureResumeIdentity(session: RegisteredSession): Promise<RegisteredSession> {- if (session.engine !== 'claude' && session.engine !== 'codex') return session+ // A shell holds no conversation; there is nothing here to capture for it.+ if (isTerminalEngine(session.engine)) return sessionconst options = { codexHome: session.codexHome ?? undefined }+ const keepsFile = engineKeepsTranscriptFile(session.engine)if (session.sessionId) {+ // A database-backed engine has the whole record already: the id IS the conversation.+ if (!keepsFile) return sessionif (session.transcriptPath && validTranscriptPath(session.engine, session.transcriptPath, options.codexHome)) return sessionconst transcriptPath = await findResumedTranscript(session.engine, session.sessionId, options)return transcriptPath && validTranscriptPath(session.engine, transcriptPath, options.codexHome)@@ -25,6 +38,15 @@ export async function captureResumeIdentity(session: RegisteredSession): Promise: 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() }+ if (!found?.sessionId) return session+ // A file-backed engine still has to produce a transcript this daemon can point a resume at; a+ // database-backed one has nothing to check and is taken on its id alone.+ if (keepsFile && (!found.transcriptPath || !validTranscriptPath(session.engine, found.transcriptPath, options.codexHome))) return session+ return {+ ...session,+ sessionId: found.sessionId,+ ...(found.transcriptPath ? { transcriptPath: found.transcriptPath } : {}),+ source: 'stop-repair',+ boundAt: Date.now(),+ }}diff --git a/cli/src/lib/e2ee/relayLink.spec.ts b/cli/src/lib/e2ee/relayLink.spec.tsindex 7b1857a26..41ed781de 100644--- a/cli/src/lib/e2ee/relayLink.spec.ts+++ b/cli/src/lib/e2ee/relayLink.spec.ts@@ -159,6 +159,19 @@ describe('remote-password link + relay session crypto (interop with the real E2eexpect(resumeReply.payload).not.toHaveProperty('agent')expect(crypto.unwrapIncoming(resumeReply)?.payload).toEqual(resumed)+ // Pause takes the same route, and is the half that was never covered: a relayed harness is+ // paused by `agent_delete`, and the relay must see neither the agent id nor the reply's+ // confirmation. Without this the whole Pause/Resume round trip over a remote machine had one+ // end tested and the other assumed.+ const stop = { requestId: 'stop-1', agentId: 'saved-work' }+ const stopRequest = crypto.wrapOutgoing({ type: 'agent_delete', payload: stop })+ expect(stopRequest.payload).not.toHaveProperty('agentId')+ expect(manager.unwrapDown('session-conn', stopRequest)?.payload).toEqual(stop)+ const stopped = { ...stop, deleted: true }+ const stopReply = manager.wrapTarget('session-conn', 'agent_delete_result', stopped)!+ expect(stopReply.payload).not.toHaveProperty('deleted')+ expect(crypto.unwrapIncoming(stopReply)?.payload).toEqual(stopped)+const lowerDown = crypto.wrapOutgoing({ type: 'terminal_resize', payload: { streamId: 's', cols: 80 } })const higherDown = crypto.wrapOutgoing({ type: 'terminal_resize', payload: { streamId: 's', cols: 120 } })expect((manager.unwrapDown('session-conn', higherDown)?.payload as Record<string, unknown>).cols).toBe(120)diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.tsindex b301b7f08..c5d13df01 100644--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@ -321,6 +321,12 @@ export const LAUNCH_FORK_FLAG: Readonly<Partial<Record<AgentEngine, { lead: stricodex: { lead: ['fork'] },}+/** Whether a relaunch can reopen this engine's previous conversation — see [LAUNCH_RESUME_FLAG].+ * `lib/resumeCapability.ts` turns this into what Pause/Resume may promise a person. */+export function supportsLaunchResume(engine: AgentEngine): boolean {+ return LAUNCH_RESUME_FLAG[engine] !== undefined+}+export function supportsNativeFork(engine: AgentEngine): boolean {return LAUNCH_FORK_FLAG[engine] !== undefined}diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 5800132e9..a843bd46a 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -15,6 +15,7 @@import { DSH_ID_RE } from '../dsh/manifest.js'import { AGENT_NAME_RE } from './engineLaunch.js'+import { resumesConversation } from './resumeCapability.js'import { namingTitle } from './sessionTitle.js'import { claudeProjectMatches, claudeTranscriptCwd, isClaudeProjectTranscript } from './claudeProject.js'import { automaticAgentName, engineLabel, isAutomaticName } from './agentNames.js'@@ -614,33 +615,49 @@ function isWithin(root: string, file: string): boolean {return rel === '' || (!rel.startsWith('..') && !rel.startsWith(`/`) && !rel.startsWith(`\\`))}+/**+ * Where each engine's conversation file lives, or **null for an engine that keeps no file at all**.+ *+ * The null entries are not gaps: opencode, kilo, hermes and devin keep their conversations in a+ * SQLite database (`sessionRepair.ts`'s `dbEngineSession` reads an id out and has no path to+ * return), and a terminal has no conversation. Written as a table rather than the nested ternary it+ * replaces so "this engine has no transcript" is a fact a caller can ASK for — Pause and Resume both+ * need it, and both used to demand a file every engine was assumed to have.+ */+const TRANSCRIPT_ROOT: Readonly<Record<AgentEngine, ((codexHome?: string) => string) | null>> = {+ // Amp's root is OURS, not Amp's: the transcript is written by the adapter's own plugin because Amp+ // keeps no conversation on disk (see installAmpPlugin).+ amp: () => env.AMP_SESSIONS_DIR,+ muse: () => join(env.MUSE_HOME, 'sessions'),+ // The specific agent's own CODEX_HOME profile, when it has one — see RegisteredSession.codexHome.+ codex: codexHome => join(codexHome || env.CODEX_HOME, 'sessions'),+ grok: () => join(env.GROK_HOME, 'sessions'),+ agy: () => join(env.AGY_HOME, 'brain'),+ copilot: () => join(env.COPILOT_HOME, 'session-state'),+ cursor: () => join(env.CURSOR_HOME, 'projects'),+ pi: () => join(env.PI_HOME, 'agent', 'sessions'),+ commandcode: () => join(env.COMMANDCODE_HOME, 'projects'),+ claude: () => env.CLAUDE_PROJECTS_DIR,+ opencode: null,+ kilo: null,+ hermes: null,+ devin: null,+ terminal: null,+}++/** Whether this engine's conversation is a FILE the daemon can point a resume at. False for the+ * database-backed engines and the shell — for them a recorded session id is the whole record, and+ * demanding a transcript would refuse a resume that works. */+export function engineKeepsTranscriptFile(engine: AgentEngine): boolean {+ return TRANSCRIPT_ROOT[engine] !== null+}+export function validTranscriptPath(engine: AgentEngine, filePath: string, codexHome?: string): boolean {+ const rootFor = TRANSCRIPT_ROOT[engine]+ if (!rootFor) return falsetry {const actual = realpathSync(filePath)- const root = realpathSync(- // Amp's root is OURS, not Amp's: the transcript is written by the adapter's own plugin because Amp- // keeps no conversation on disk (see installAmpPlugin).- engine === 'amp'- ? env.AMP_SESSIONS_DIR- : engine === 'muse'- ? join(env.MUSE_HOME, 'sessions')- : engine === 'codex'- // The specific agent's own CODEX_HOME profile, when it has one — see RegisteredSession.codexHome.- ? join(codexHome || env.CODEX_HOME, 'sessions')- : engine === 'grok'- ? join(env.GROK_HOME, 'sessions')- : engine === 'agy'- ? join(env.AGY_HOME, 'brain')- : engine === 'copilot'- ? join(env.COPILOT_HOME, 'session-state')- : engine === 'cursor'- ? join(env.CURSOR_HOME, 'projects')- : engine === 'pi'- ? join(env.PI_HOME, 'agent', 'sessions')- : engine === 'commandcode'- ? join(env.COMMANDCODE_HOME, 'projects')- : env.CLAUDE_PROJECTS_DIR,- )+ const root = realpathSync(rootFor(codexHome))const st = statSync(actual)if (!st.isFile() || !isWithin(root, actual)) return falseif (engine === 'cursor') {@@ -1311,8 +1328,11 @@ class Registry {const now = Date.now()const existing = this.agents.get(agentId)if (existing?.resumeOnly && existing.launch && existing.launch.state !== 'ready') {- // A native startup hook, carrying the verified process, must confirm this exact history.- if (sessionId !== existing.sessionId) {+ // A native startup hook, carrying the verified process, must confirm this exact history —+ // but only where an exact history was asked for. A resume that opened a NEW conversation (an+ // engine with no resume argv, or a row with no id to reopen) reports a different id BECAUSE+ // it did what it was told; failing it there would refuse the resume the caller requested.+ if (sessionId !== existing.sessionId && resumesConversation(engine, existing.sessionId)) {this.setLaunch(agentId, { state: 'failed', error: 'RESUME_SESSION_MISMATCH', detail: 'The agent reported a different conversation. The requested conversation is still saved.' })return null}diff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.tsindex bf924c237..a28b3933f 100644--- a/cli/src/lib/resumeAgentService.spec.ts+++ b/cli/src/lib/resumeAgentService.spec.ts@@ -17,7 +17,11 @@ 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']) }))+// `resumeCapability` reads the real flag table through this module; only the argv builder is faked.+vi.mock('./engineLaunch.js', async importOriginal => ({+ ...(await importOriginal<typeof import('./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() }))@@ -90,6 +94,21 @@ describe('production resume handler', () => {expect(JSON.stringify(disk)).toContain(saved.sessionId)expect(JSON.stringify(disk)).toContain('resumeOnly')})+ it('resumes a database-backed engine on its id alone, with no transcript to demand', async () => {+ // opencode/kilo/hermes/devin keep the conversation in SQLite; requiring a transcript file here+ // refused a resume that works, and refused it AFTER the harness had been paused.+ rewrite({ engine: 'opencode', transcriptPath: '' })+ expect(await start()).toMatchObject({ ok: true, resumed: true, session: { launch: { state: 'ready' } } })+ expect(buildEngineLaunchArgv).toHaveBeenCalledWith('opencode', expect.objectContaining({ resumeSessionId: saved.sessionId }))+ })++ it('marks an engine with no startup hook ready off its own process', async () => {+ // muse never hooks, so nothing else would ever leave this row `starting` — it would read as+ // "Starting" for ever and keep discovery out of the pane.+ rewrite({ engine: 'muse' })+ expect(await start()).toMatchObject({ ok: true, session: { launch: { state: 'ready' } } })+ })+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' } } })diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.tsindex 09c6ea247..b5a07ecca 100644--- a/cli/src/lib/resumeAgentService.ts+++ b/cli/src/lib/resumeAgentService.ts@@ -1,9 +1,10 @@/** Exact-resume lifecycle shared by the daemon and its isolated acceptance tests. */import { isTerminalEngine } from '../engines/types.js'import { installedDsh } from '../dsh/installed.js'-import { registry as liveRegistry, validTranscriptPath, type RegisteredSession } from './registry.js'+import { engineKeepsTranscriptFile, registry as liveRegistry, validTranscriptPath, type RegisteredSession } from './registry.js'import type { StoppedAgentStore } from './stoppedAgents.js'import { resumeStoppedAgent, waitForResumedAgent, resumeChanged, resumeUnconfirmed } from './resumeStoppedAgent.js'+import { confirmsResumeByHook, resumesConversation } from './resumeCapability.js'import { checkPidRuntime } from './deleteAgentFallback.js'import { checkSessionRuntime, clearPaneRemainOnExit, resolvePaneEngineProcess, tmuxPaneState } from './tmux.js'import { listTmuxPanes } from './tmuxAgentDiscovery.js'@@ -60,7 +61,16 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {await clearPaneRemainOnExit(saved.tmuxPane)if (!ownsRoute()) return resumeChangedstoppedAgents.finishResume(saved.agentId)- announceSession(result.session)+ // A resume confirmed by its process rather than by a startup hook has nothing else coming to+ // mark the row ready, and a row left `starting` reads as "Starting" for ever and keeps+ // discovery out of it (see cli.ts's resumeOnly guard). Same condition as the proof itself in+ // `waitForResumedAgent`: only a resume that ASKED for a conversation, on an engine that hooks+ // at launch, is marked ready by `register` instead.+ const byHook = resumesConversation(saved.engine, saved.sessionId) && confirmsResumeByHook(saved.engine)+ const ready = byHook+ ? result.session+ : registry.setLaunch(saved.agentId, { state: 'ready' }) ?? result.session+ announceSession(ready)} 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 })@@ -114,7 +124,11 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {if (!saved.cwd) return { ok: false, error: 'CWD_NOT_FOUND', detail: 'The saved project folder is no longer available.' }const missing = workspaceMissing(saved.cwd)if (missing) return missing- if (resumeSessionId && (!saved.transcriptPath || !validTranscriptPath(saved.engine, saved.transcriptPath, saved.codexHome ?? undefined))) {+ // Only for an engine whose conversation IS a file. opencode, kilo, hermes and devin keep+ // theirs in a database, so they have no transcript to point at and demanding one here refused+ // a resume that works — after the harness had already been paused.+ if (resumeSessionId && engineKeepsTranscriptFile(saved.engine)+ && (!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.diff --git a/cli/src/lib/resumeCapability.spec.ts b/cli/src/lib/resumeCapability.spec.tsnew file mode 100644index 000000000..976c527f0--- /dev/null+++ b/cli/src/lib/resumeCapability.spec.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from 'vitest'+import { ENGINES, type AgentEngine } from '../engines/types.js'+import { LAUNCH_RESUME_FLAG } from './engineLaunch.js'+import { confirmsResumeByHook, resumeMode, resumesConversation } from './resumeCapability.js'++describe('what a paused harness can promise, per engine', () => {+ it('gives every engine exactly one mode, from the launch table itself', () => {+ for (const engine of ENGINES) {+ const mode = resumeMode(engine)+ expect(['shell', 'conversation', 'fresh']).toContain(mode)+ if (engine === 'terminal') expect(mode).toBe('shell')+ else expect(mode).toBe(LAUNCH_RESUME_FLAG[engine] ? 'conversation' : 'fresh')+ }+ })++ it('names the shell and the one engine with no resume argv', () => {+ expect(resumeMode('terminal')).toBe('shell')+ // devin is deliberately absent from LAUNCH_RESUME_FLAG — no confirmed flag exists.+ expect(resumeMode('devin')).toBe('fresh')+ expect(resumeMode('claude')).toBe('conversation')+ expect(resumeMode('opencode')).toBe('conversation')+ })++ it('asks for a conversation only when there is one to ask for', () => {+ expect(resumesConversation('claude', 'abc')).toBe(true)+ expect(resumesConversation('claude', '')).toBe(false)+ expect(resumesConversation('claude', null)).toBe(false)+ // A recorded id cannot help an engine that has no way to reopen it.+ expect(resumesConversation('devin', 'abc')).toBe(false)+ expect(resumesConversation('terminal', 'abc')).toBe(false)+ })++ it('trusts a startup hook to confirm a resume only where one is sent on a resume', () => {+ expect(confirmsResumeByHook('claude')).toBe(true)+ expect(confirmsResumeByHook('codex')).toBe(true)+ // OpenCode re-attaches its session silently on `--session <id>` and posts nothing; copilot, pi+ // and amp hook on a turn; muse never hooks. Waiting for one only hangs the resume.+ for (const engine of ['opencode', 'kilo', 'copilot', 'pi', 'amp', 'muse', 'cursor', 'hermes', 'commandcode', 'devin', 'grok', 'agy', 'terminal'] as AgentEngine[]) {+ expect(confirmsResumeByHook(engine)).toBe(false)+ }+ })++ it('covers the whole roster, so a new engine cannot be forgotten', () => {+ // A new engine gets the weaker proof by default, never a ten-minute wait.+ const strict = ENGINES.filter(engine => confirmsResumeByHook(engine))+ expect(strict).toEqual(['claude', 'codex'])+ expect(ENGINES.length).toBe(15)+ })+})diff --git a/cli/src/lib/resumeCapability.ts b/cli/src/lib/resumeCapability.tsnew file mode 100644index 000000000..5a762a4ed--- /dev/null+++ b/cli/src/lib/resumeCapability.ts@@ -0,0 +1,59 @@+/**+ * How much of a paused harness can be brought back, per engine, and what counts as proof that it+ * came back.+ *+ * Pause/Resume used to be offered for claude and codex alone. Every other engine was refused at+ * `resumeStoppedAgent`, which is stricter than the rest of the daemon already is: `agent_restart`+ * and the post-reboot restore relaunch EVERY engine with its own resume argv and fall back to a+ * fresh session when that fails (`restartAgent.ts`, `restoreAgents.ts`). This module is the one+ * place that says what each engine can promise, so Pause, the wire frame and the desktop's wording+ * all read the same answer instead of three copies of an engine list.+ */++import { isTerminalEngine, type AgentEngine } from '../engines/types.js'+import { supportsLaunchResume } from './engineLaunch.js'++/**+ * - `shell` — a terminal. There is no conversation; relaunching the login shell in the same pane IS+ * the resume, and what is lost (the scrollback, whatever was running) is what Stop Terminal+ * already says is lost.+ * - `conversation` — the engine has a documented resume argv (`LAUNCH_RESUME_FLAG`), so a paused+ * harness with a recorded session id comes back where it left off.+ * - `fresh` — no resume argv exists for this engine (today: `devin`). Pausing still works and the+ * harness still comes back — same pane, same folder, same name — but as a NEW conversation, and+ * every surface says so rather than refusing a person the pause.+ */+export type ResumeMode = 'shell' | 'conversation' | 'fresh'++export function resumeMode(engine: AgentEngine): ResumeMode {+ if (isTerminalEngine(engine)) return 'shell'+ return supportsLaunchResume(engine) ? 'conversation' : 'fresh'+}++/** Whether THIS resume is bringing a conversation back, for the row it is resuming. An engine that+ * could resume one but never recorded an id is in the same position as one with no resume argv. */+export function resumesConversation(engine: AgentEngine, sessionId: string | null | undefined): boolean {+ return resumeMode(engine) === 'conversation' && !!sessionId+}++/**+ * Whether this engine's startup hook fires on a RESUMED launch, so `SessionStart` carrying the new+ * pid is proof that it reopened the requested conversation.+ *+ * Measured, not assumed — and the measurement is narrower than "has a startup hook". OpenCode's+ * plugin posts on `session.created`, which a resume does not emit: relaunched with `--session <id>`+ * it re-attaches the conversation it already has, sends nothing, and a resume waiting for that hook+ * sat there until its ten-minute budget ran out (measured 2026-09-23, `scripts/pause-resume-e2e.mts`+ * against a bound opencode session). Copilot's `sessionStart` fires after the first prompt; pi's and+ * amp's plugins post on a turn; muse has no hooks at all (`sessionRepair.ts`: its store scan is "the+ * ONLY way a muse pane is ever bound").+ *+ * That leaves claude and codex, the two the strict path was written for and has always been proven+ * with. For every other engine the live engine process in its own pane is the proof — exactly the+ * bar `agent_restart` clears for all of them today (`restartAgent.ts` waits for the process and+ * nothing else). A new engine defaults to the weaker proof, which fails towards "answers in a+ * second" rather than "hangs for ten minutes".+ */+export function confirmsResumeByHook(engine: AgentEngine): boolean {+ return engine === 'claude' || engine === 'codex'+}diff --git a/cli/src/lib/resumeStoppedAgent.spec.ts b/cli/src/lib/resumeStoppedAgent.spec.tsindex 9e86a94fa..a4322f996 100644--- a/cli/src/lib/resumeStoppedAgent.spec.ts+++ b/cli/src/lib/resumeStoppedAgent.spec.ts@@ -33,11 +33,24 @@ describe('Enter resumes stopped work', () => {expect(deps.launch).toHaveBeenCalledExactlyOnceWith(saved, 'original-conversation')})- it.each([{ ...saved, sessionId: '' }, { ...saved, engine: 'devin' as const }])('refuses unavailable resume without opening a fresh conversation', async entry => {+ it.each([+ // No id recorded to reopen, and an engine with no resume argv at all: both still come back —+ // same pane, same folder — as a new conversation, launched without a resume id.+ { ...saved, sessionId: '' },+ { ...saved, engine: 'devin' as const },+ ])('resumes without a conversation rather than refusing the harness', async entry => {const deps = fixture()deps.saved.mockReturnValue(entry)- await expect(resumeStoppedAgent(deps)).resolves.toMatchObject({ ok: false, error: 'RESUME_UNAVAILABLE' })- expect(deps.launch).not.toHaveBeenCalled()+ await expect(resumeStoppedAgent(deps)).resolves.toMatchObject({ ok: true })+ expect(deps.launch).toHaveBeenCalledExactlyOnceWith(entry, undefined)+ })++ it('reopens the conversation of an engine that keeps one, whatever its vendor', async () => {+ const deps = fixture()+ const entry = { ...saved, engine: 'opencode' as const }+ deps.saved.mockReturnValue(entry)+ await expect(resumeStoppedAgent(deps)).resolves.toMatchObject({ ok: true })+ expect(deps.launch).toHaveBeenCalledExactlyOnceWith(entry, 'original-conversation')})it('does not launch while the old process is still alive or unverified', async () => {@@ -129,9 +142,9 @@ describe('resume runtime verification', () => {describe('exact conversation readiness', () => {const process = { pid: 42, startMarker: 'new-process', executable: 'codex' }- function readiness() {+ function readiness(engine: RegisteredSession['engine'] = saved.engine) {let now = 0- let row: RegisteredSession = { ...saved, processIdentity: process, lastHookAt: 0, launch: { state: 'starting' } }+ let row: RegisteredSession = { ...saved, engine, processIdentity: process, lastHookAt: 0, launch: { state: 'starting' } }return {current: vi.fn(() => true),session: () => row,@@ -154,6 +167,35 @@ describe('exact conversation readiness', () => {await expect(waitForResumedAgent(saved, deps)).resolves.toMatchObject({ ok: true, session: { sessionId: saved.sessionId } })expect(deps.process).toHaveBeenCalledTimes(2)})+ it('accepts a live process for an engine that has no startup hook to send', async () => {+ // muse never hooks; copilot/pi/amp hook on the first turn. Waiting for one only converts a+ // working resume into the whole budget of "Starting", then RESUME_UNCONFIRMED.+ const deps = readiness('muse')+ const hookless = { ...saved, engine: 'muse' as const }+ await expect(waitForResumedAgent(hookless, deps)).resolves.toMatchObject({+ ok: true,+ resumed: true,+ session: { sessionId: saved.sessionId },+ })+ expect(deps.sleep).not.toHaveBeenCalled()+ })++ it('still reports a hookless engine whose pane died', async () => {+ const deps = readiness('muse')+ deps.pane.mockResolvedValue({ dead: true })+ await expect(waitForResumedAgent({ ...saved, engine: 'muse' as const }, deps))+ .resolves.toMatchObject({ ok: false, error: 'RESUME_FAILED' })+ })++ it('says a resume with no conversation to reopen is a fresh one', async () => {+ // devin hooks at launch like the rest, so it is confirmed the strict way — but it has no resume+ // argv, so what came back is a new conversation and `resumed` says so rather than lying.+ const deps = readiness('devin')+ deps.set({ lastHookAt: 100, launch: { state: 'ready' } })+ await expect(waitForResumedAgent({ ...saved, engine: 'devin' as const }, deps))+ .resolves.toMatchObject({ ok: true, resumed: false })+ })+it.each([null, { dead: true }, { dead: false, engineExit: 1 }])('reports early exit without a fresh fallback: %s', async pane => {const deps = readiness()deps.pane.mockResolvedValue(pane)diff --git a/cli/src/lib/resumeStoppedAgent.ts b/cli/src/lib/resumeStoppedAgent.tsindex 5d963f2e4..08b956174 100644--- a/cli/src/lib/resumeStoppedAgent.ts+++ b/cli/src/lib/resumeStoppedAgent.ts@@ -1,5 +1,6 @@import { isTerminalEngine } from '../engines/types.js'import type { RegisteredSession, ProcessIdentity } from './registry.js'+import { confirmsResumeByHook, resumesConversation } from './resumeCapability.js'import type { RestartAgentReply } from './restartAgent.js'import type { RuntimeCheck } from './tmux.js'@@ -47,16 +48,18 @@ export async function resumeStoppedAgent(deps: ResumeStoppedDeps): Promise<Resta}if (!deps.current()) return resumeChangedif (!saved) return { ok: false, error: 'AGENT_NOT_FOUND', detail: 'The saved harness is no longer available.' }- if (!isTerminalEngine(saved.engine) && (!saved.sessionId || !['claude', 'codex'].includes(saved.engine))) {- return { ok: false, error: 'RESUME_UNAVAILABLE', detail: 'This harness has no supported saved conversation to resume. Start a new conversation separately.' }- }+ // No engine is refused here any more. An engine with a resume argv and a recorded id comes back+ // where it left off; one with neither still comes back — same pane, same folder, same name — as a+ // new conversation, which `resumed: false` and the client's wording say out loud. Refusing the+ // pause instead was the stricter rule: `agent_restart` has relaunched every engine this way for as+ // long as it has existed (`restartAgent.ts`).if (!await deps.canLaunch(saved)) {return { ok: false, error: 'AGENT_BUSY', detail: 'The previous process is still running or could not be checked. Wait for it to stop, then retry.' }}if (!deps.current()) return resumeChanged// Discovery won the race. Recheck it through the same verified attach path.if (deps.live()) return resumeStoppedAgent(deps)- return deps.launch(saved, isTerminalEngine(saved.engine) ? undefined : saved.sessionId)+ return deps.launch(saved, resumesConversation(saved.engine, saved.sessionId) ? saved.sessionId : undefined)}export interface ResumeReadinessDeps {@@ -69,8 +72,15 @@ export interface ResumeReadinessDeps {budgetMs?: number}-/** SessionStart from the new process must confirm the requested vendor conversation.- * Process discovery and a resume argument alone do not prove that it loaded. */+/**+ * Wait for the replacement process to prove it came back.+ *+ * For an engine that hooks at LAUNCH, the proof is its `SessionStart` carrying the new pid: process+ * discovery and a resume argument alone do not prove the conversation loaded. An engine that hooks+ * later — or not at all — cannot produce that, and waiting for it turns a working resume into ten+ * minutes of "Starting"; there the live engine process in its own pane is the proof, which is the+ * bar `agent_restart` clears for every engine today. See `resumeCapability.ts`.+ */export async function waitForResumedAgent(saved: RegisteredSession, deps: ResumeReadinessDeps): Promise<RestartAgentReply> {const now = deps.now ?? Date.nowconst until = now() + (deps.budgetMs ?? 10 * 60_000)@@ -86,9 +96,22 @@ export async function waitForResumedAgent(saved: RegisteredSession, deps: Resumeif (!pane || pane.dead || pane.engineExit != null) {return { ok: false, error: 'RESUME_FAILED', detail: 'The agent exited before confirming the saved conversation. Its terminal output and conversation have been retained.' }}- if (process && row.lastHookAt > 0 && row.launch?.state !== 'starting'- && row.processIdentity?.pid === process.pid && row.processIdentity.startMarker === process.startMarker) {- return { ok: true, session: row, resumed: true }+ // Two things decide what proof is available. A conversation was only REQUESTED when the engine+ // can reopen one and a row recorded one — otherwise there is nothing for a hook to confirm and+ // the id it eventually reports is a new one by design. And only some engines hook at launch at+ // all. Where both hold, the hook carrying the new pid is the proof; everywhere else the engine+ // process alive in its own pane is, which is the bar `agent_restart` clears for every engine.+ const resumed = resumesConversation(saved.engine, saved.sessionId)+ if (process && resumed && confirmsResumeByHook(saved.engine)) {+ if (row.lastHookAt > 0 && row.launch?.state !== 'starting'+ && row.processIdentity?.pid === process.pid && row.processIdentity.startMarker === process.startMarker) {+ return { ok: true, session: row, resumed }+ }+ } else if (process) {+ // The row's own `processIdentity` stays null until a hook binds it (`resumePendingAgent`), so+ // the evidence here is the pane's engine process itself, checked against a pane confirmed+ // alive above.+ return { ok: true, session: row, resumed }}await deps.sleep(250)}diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dartindex 9e6dafd85..55eb3cccc 100644--- a/desktop/lib/core/models.dart+++ b/desktop/lib/core/models.dart@@ -331,6 +331,12 @@ class Agent {/// decides (see [canFork]).final bool? forkable;+ /// How much a Pause of this harness can promise to bring back, as the daemon+ /// reports it (`lib/resumeCapability.ts`): `shell`, `conversation` or+ /// `fresh`. Null from a daemon that predates the field — see+ /// [canPauseAndResume] for what this build assumes then.+ final String? resumeMode;+/// The permission mode this agent was launched in (`plan`, `readOnly`, …),/// as the daemon recorded it; null from a daemon that predates the field, a/// row from before the choice existed, or an agent Harness did not launch.@@ -376,6 +382,7 @@ class Agent {this.verdict,this.forkedFrom,this.forkable,+ this.resumeMode,this.permissionMode,this.bypassPermission,this.namedAgent,@@ -388,6 +395,31 @@ class Agent {(engine == 'claude' || engine == 'codex') &&sessionId?.isNotEmpty == true;+ /// Whether Harness Monitor may pause this harness and bring it back.+ ///+ /// Every engine can, and the daemon says so per engine through [resumeMode]+ /// — a client that kept its own allow-list is how the two drifted, with+ /// engines the daemon would happily resume greyed out here for a year.+ /// What DIFFERS per engine is how much comes back, which+ /// [resumesFreshConversation] answers and the button's wording says.+ ///+ /// The fallback is for a daemon that predates the field: the old rule, so an+ /// older machine is never offered a Pause its CLI will refuse. `'terminal'`+ /// is `kTerminalEngine` (`widgets/engine_identity.dart`), spelled out for the+ /// same reason `'claude'`/`'codex'` are above: this is the model layer and+ /// does not reach into the widgets.+ bool get canPauseAndResume =>+ resumeMode != null || engine == 'terminal' || canResumeConversation;++ /// Whether resuming this harness opens a NEW conversation rather than the one+ /// it was paused in — either because the engine has no resume argv (`fresh`),+ /// or because nothing recorded a conversation to reopen. The button says so+ /// before it is pressed, and a resume that reports it is a success, not a+ /// failure.+ bool get resumesFreshConversation =>+ resumeMode == 'fresh' ||+ (resumeMode == 'conversation' && (sessionId?.isEmpty ?? true));+/// Explicit names win. An automatic CLI label gives way to its session title.String get displayName => _automaticHarnessName.hasMatch(name)? (title?.trim().isNotEmpty == true ? title!.trim() : kUntitledPane)@@ -484,6 +516,7 @@ class Agent {verdict: AgentVerdict.fromJson(j['verdict']),forkedFrom: ForkedFrom.fromJson(j['forkedFrom']),forkable: j['forkable'] is bool ? j['forkable'] as bool : null,+ resumeMode: _safeResumeMode(j['resumeMode']),permissionMode: _safePermissionMode(j['permissionMode']),bypassPermission: j['bypassPermission'] is bool? j['bypassPermission'] as bool@@ -524,6 +557,7 @@ class Agent {verdict: verdict,forkedFrom: forkedFrom,forkable: forkable,+ resumeMode: resumeMode,permissionMode: permissionMode,bypassPermission: bypassPermission,namedAgent: namedAgent,@@ -533,6 +567,14 @@ class Agent {/// one word. Not checked against this build's own list — the daemon that/// launched the agent is the authority, and it is the one that will read the/// id back on a clone.+ /// One of the daemon's three resume modes, or null for anything else — an+ /// older daemon that does not send it, or a newer one that grew a fourth+ /// this build has no wording for.+ static String? _safeResumeMode(Object? raw) =>+ raw is String && const {'shell', 'conversation', 'fresh'}.contains(raw)+ ? raw+ : null;+static String? _safePermissionMode(Object? raw) =>raw is String && RegExp(r'^[A-Za-z]{1,32}$').hasMatch(raw) ? raw : null;diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex db0aaf30c..8b36d004b 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -6997,7 +6997,7 @@ class AppNotifier extends ChangeNotifier {if (_agentPauses[key] case final pending?) return pending;final machine = stateOf(machineId);final agent = machine?.agents.where((a) => a.id == agentId).firstOrNull;- if (machine == null || agent == null || !agent.canResumeConversation) {+ if (machine == null || agent == null || !agent.canPauseAndResume) {return Future.value('This harness has no supported saved conversation to resume.',);@@ -7005,29 +7005,35 @@ class AppNotifier extends ChangeNotifier {if (agent.isStopped) return Future.value(null);final revision = _authRevision;late final Future<String?> pause;- pause = (() async {- final error = await deleteAgent(machineId, agentId);- if (!_machineWorkCurrent(machine, revision)) return error;- final current = machine.agents.where((a) => a.id == agentId).firstOrNull;- if (error == null && current == null) {- _upsertAgent(- machine,- agent.copyWith(status: 'stopped', terminalAvailable: false),- );- notifyListeners();- }- await reloadMachineData(machineId);- if (!_machineWorkCurrent(machine, revision)) return error;- final observed = machine.agents.where((a) => a.id == agentId).firstOrNull;- // A lost reply is resolved by authoritative inventory, never by resending Stop.- if (observed?.isStopped == true && observed?.sessionId == agent.sessionId) {- return null;- }- return error;- })().whenComplete(() {- if (identical(_agentPauses[key], pause)) _agentPauses.remove(key);- if (_authWorkCurrent(revision)) notifyListeners();- });+ pause =+ (() async {+ final error = await deleteAgent(machineId, agentId);+ if (!_machineWorkCurrent(machine, revision)) return error;+ final current = machine.agents+ .where((a) => a.id == agentId)+ .firstOrNull;+ if (error == null && current == null) {+ _upsertAgent(+ machine,+ agent.copyWith(status: 'stopped', terminalAvailable: false),+ );+ notifyListeners();+ }+ await reloadMachineData(machineId);+ if (!_machineWorkCurrent(machine, revision)) return error;+ final observed = machine.agents+ .where((a) => a.id == agentId)+ .firstOrNull;+ // A lost reply is resolved by authoritative inventory, never by resending Stop.+ if (observed?.isStopped == true &&+ observed?.sessionId == agent.sessionId) {+ return null;+ }+ return error;+ })().whenComplete(() {+ if (identical(_agentPauses[key], pause)) _agentPauses.remove(key);+ if (_authWorkCurrent(revision)) notifyListeners();+ });_agentPauses[key] = pause;return pause;}@@ -7187,9 +7193,11 @@ class AppNotifier extends ChangeNotifier {/// Attach to a running harness or resume its saved conversation immediately.Future<RestartAgentResult> resumeAgent(String machineId, String agentId) {if (pendingAgentPause(machineId, agentId) != null) {- return Future.value(const RestartAgentResult(- error: 'The harness is still pausing. Try again in a moment.',- ));+ return Future.value(+ const RestartAgentResult(+ error: 'The harness is still pausing. Try again in a moment.',+ ),+ );}final agent = stateOf(machineId)?.agents.where((agent) => agent.id == agentId)@@ -7358,9 +7366,18 @@ class AppNotifier extends ChangeNotifier {if (raw is! Map || raw['id'] != agentId) return unknown;try {var updated = Agent.fromJson(Map<String, dynamic>.from(raw));+ // A resume that says it opened a NEW conversation is only a surprise+ // where an old one was promised. An engine with no resume argv, or a+ // harness paused before anything recorded a conversation, comes back as+ // a new one BECAUSE that is what it was asked for — and the button said+ // so beforehand — so the receipt is honoured rather than read as a+ // failure that leaves the row stuck.+ final fresh =+ attempt.agent!.resumesFreshConversation ||+ updated.resumesFreshConversation;if (resuming &&- (result['resumed'] == false ||- updated.sessionId != attempt.agent!.sessionId ||+ ((result['resumed'] == false && !fresh) ||+ (updated.sessionId != attempt.agent!.sessionId && !fresh) ||updated.launchState == 'starting' ||updated.launchState == 'failed')) {return unknown;@@ -7412,6 +7429,9 @@ class AppNotifier extends ChangeNotifier {? 'Update the harness CLI on this machine to open saved harnesses.': 'Update the harness CLI on this machine to restart an agent.','AGENT_BUSY' => 'Another operation is changing this agent. Wait for it to finish, then retry.',+ 'RESUME_UNAVAILABLE' => 'The saved conversation is unavailable. The harness can still be started fresh.',+ 'RESUME_SESSION_MISMATCH' => 'The harness came back on a different conversation. The saved one is still kept.',+ 'RESUME_FAILED' => 'The harness did not come back. Its output and conversation are kept.',_ =>resuming? 'Could not open this harness: $code'@@ -8108,11 +8128,15 @@ class AppNotifier extends ChangeNotifier {if (_disposed || machine == null || !await _awaitAgent(machine, agentId)) {return false;}- if (_disposed || revision != _authRevision || !identical(machineStates[machineId], machine)) {+ if (_disposed ||+ revision != _authRevision ||+ !identical(machineStates[machineId], machine)) {return false;}await openAgentFromDial(machineId, agentId);- if (_disposed || revision != _authRevision || !identical(machineStates[machineId], machine) ||+ if (_disposed ||+ revision != _authRevision ||+ !identical(machineStates[machineId], machine) ||!allPanes.any((p) => p.machineId == machineId && p.agentId == agentId,)) {diff --git a/desktop/lib/state/harness_sessions.dart b/desktop/lib/state/harness_sessions.dartindex 277c7d6f5..45d9ac9dd 100644--- a/desktop/lib/state/harness_sessions.dart+++ b/desktop/lib/state/harness_sessions.dart@@ -48,12 +48,12 @@ class HarnessSession {(online &&(agent.terminalAvailable ||(agent.isStopped &&- agent.canResumeConversation &&+ agent.canPauseAndResume &&!machine.machine.isShared)));bool get canControl =>online &&!machine.machine.isShared &&- agent.canResumeConversation &&+ agent.canPauseAndResume &&(agent.isStopped || agent.terminalAvailable) &&agent.launchState != 'starting';String get status => !online@@ -61,7 +61,7 @@ class HarnessSession {: machine.machine.isShared? 'View only': agent.isStopped- ? (agent.canResumeConversation ? 'Paused' : 'Resume unavailable')+ ? (agent.canPauseAndResume ? 'Paused' : 'Resume unavailable'): agent.launchState == 'failed'? 'Start failed': agent.launchState == 'starting'@@ -77,10 +77,12 @@ class HarnessSession {? 'Reconnect ${machine.machine.displayName} to control this harness.': machine.machine.isShared? 'Shared harnesses are view-only.'- : !agent.canResumeConversation+ // Only reachable against a daemon too old to report what its engines can+ // resume; a current one offers Pause for every harness it runs.+ : !agent.canPauseAndResume? (agent.engine == 'claude' || agent.engine == 'codex'? 'Waiting for a saved conversation before enabling pause and resume.'- : 'Pause and resume are not available for this engine yet.')+ : 'Update the harness CLI on this machine to pause and resume this engine.'): !canControl? agent.launchDetail ??agent.terminalUnavailableReason ??diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dartindex d062cbd3b..7325d41ed 100644--- a/desktop/lib/state/swarm_navigation.dart+++ b/desktop/lib/state/swarm_navigation.dart@@ -365,8 +365,16 @@ Future<void> _resumeStoppedDestination(// This opens a view of the allocated terminal, not a claim that history// has loaded. The native CLI may need login or hook review before it can// confirm the conversation; the receipt keeps verifying in the background.+ //+ // The conversation has to be the one asked for — unless none was: a resume+ // that was always going to open a new one (an engine with no resume argv, a+ // harness paused with nothing recorded) reports a different id because it+ // did as it was told, and the tile it opened is still this harness's.+ final fresh =+ agent?.resumesFreshConversation == true ||+ current?.resumesFreshConversation == true;if (current?.terminalAvailable == true &&- current?.sessionId == agent!.sessionId &&+ (fresh || current?.sessionId == agent!.sessionId) &¤t?.launchState != 'failed' &¤t?.isStopped == false) {terminalReady.complete();diff --git a/desktop/lib/widgets/harness_session_manager.dart b/desktop/lib/widgets/harness_session_manager.dartindex 390397636..3fd95bd6e 100644--- a/desktop/lib/widgets/harness_session_manager.dart+++ b/desktop/lib/widgets/harness_session_manager.dart@@ -269,7 +269,10 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {child: Row(children: [Expanded(- child: Text('Harness Monitor', style: AppType.heading()),+ child: Text(+ 'Harness Monitor',+ style: AppType.heading(),+ ),),IconButton(tooltip: 'Close Harness Monitor',@@ -793,12 +796,13 @@ class _SessionRow extends StatelessWidget {),),Tooltip(+ // Every harness pauses; what differs is how much comes+ // back, and the button says which before it is pressed —+ // a shell loses what was running in it, and an engine with+ // no way to reopen its conversation returns to a new one.message: busy? pendingLabel- : row.controlUnavailable ??- (row.agent.isStopped- ? 'Resume harness'- : 'Pause harness'),+ : row.controlUnavailable ?? _toggleLabel(row),child: SizedBox(width: 40,height: 40,@@ -939,3 +943,20 @@ class _MonitorStats extends StatelessWidget {);}}++/// What the Pause/Resume button promises for this row. Three answers, because+/// three things can come back: the same shell, the same conversation, or the+/// harness with a new one (`resumeMode` on the agent frame).+String _toggleLabel(HarnessSession row) {+ if (isTerminalEngine(row.agent.engine)) {+ return row.agent.isStopped+ ? 'Open a fresh shell here'+ : 'Pause terminal — ends this shell and anything running in it';+ }+ if (row.agent.resumesFreshConversation) {+ return row.agent.isStopped+ ? 'Resume as a new conversation'+ : 'Pause harness — it comes back as a new conversation';+ }+ return row.agent.isStopped ? 'Resume harness' : 'Pause harness';+}diff --git a/desktop/test/agent_model_test.dart b/desktop/test/agent_model_test.dartindex e7a9a5fd1..ab9e530e8 100644--- a/desktop/test/agent_model_test.dart+++ b/desktop/test/agent_model_test.dart@@ -373,4 +373,52 @@ void _cloneTests() {);expect(Agent.fromJson({'id': 'agent-1', 'name': 'a'}).canClone, isFalse);});++ group('what a pause can promise', () {+ Agent parse(Map<String, dynamic> extra) => Agent.fromJson({+ 'id': 'a0',+ 'name': 'Row',+ 'engine': 'opencode',+ ...extra,+ });++ test('reads the daemon\'s mode, and only a word it knows', () {+ expect(parse({'resumeMode': 'conversation'}).resumeMode, 'conversation');+ expect(parse({'resumeMode': 'fresh'}).resumeMode, 'fresh');+ expect(parse({'resumeMode': 'shell'}).resumeMode, 'shell');+ // A fourth word this build has no wording for, or an older daemon.+ expect(parse({'resumeMode': 'someday'}).resumeMode, isNull);+ expect(parse({}).resumeMode, isNull);+ });++ test('offers pause for any engine the daemon reports on', () {+ expect(parse({'resumeMode': 'conversation'}).canPauseAndResume, isTrue);+ expect(parse({'resumeMode': 'fresh'}).canPauseAndResume, isTrue);+ // No word: the old rule, so an older CLI is never offered a pause it refuses.+ expect(parse({}).canPauseAndResume, isFalse);+ expect(parse({'engine': 'terminal'}).canPauseAndResume, isTrue);+ expect(+ parse({'engine': 'claude', 'sessionId': 'abc'}).canPauseAndResume,+ isTrue,+ );+ });++ test('says when coming back means a new conversation', () {+ expect(+ parse({'resumeMode': 'fresh', 'sessionId': 'abc'})+ .resumesFreshConversation,+ isTrue,+ );+ expect(+ parse({'resumeMode': 'conversation'}).resumesFreshConversation,+ isTrue,+ reason: 'nothing recorded to reopen',+ );+ expect(+ parse({'resumeMode': 'conversation', 'sessionId': 'abc'})+ .resumesFreshConversation,+ isFalse,+ );+ });+ });}diff --git a/desktop/test/agent_pause_state_test.dart b/desktop/test/agent_pause_state_test.dartindex b0a27f9b3..10e492752 100644--- a/desktop/test/agent_pause_state_test.dart+++ b/desktop/test/agent_pause_state_test.dart@@ -138,7 +138,9 @@ void main() {},);- test('pause never sends a command for an unsupported or missing saved conversation', () async {+ test('pause is refused only where the daemon could not carry it out', () async {+ // No `resumeMode` on the frame: an older CLI, whose resume refuses anything+ // but claude/codex with a recorded conversation.app.stateOf('m')!.agents = [const Agent(id: 'a0',@@ -160,4 +162,123 @@ void main() {expect(await app.pauseAgent('m', 'a0'), isNotNull);expect(connection.stops, isEmpty);});++ test(+ 'any engine a current daemon reports pauses, whatever it can restore',+ () async {+ for (final mode in ['conversation', 'fresh']) {+ app.stateOf('m')!.agents = [+ Agent(+ id: 'a0',+ name: 'Other engine',+ engine: 'opencode',+ sessionId: mode == 'conversation' ? 'saved' : null,+ resumeMode: mode,+ terminalAvailable: true,+ ),+ ];+ connection.stops.clear();+ connection.inventory = Completer<Map<String, dynamic>>()+ ..complete({+ 'agents': [+ {+ 'id': 'a0',+ 'name': 'Other engine',+ 'engine': 'opencode',+ 'resumeMode': mode,+ 'status': 'stopped',+ 'terminal': {'available': false},+ },+ ],+ });+ final pause = app.pauseAgent('m', 'a0');+ connection.stopReplies.last.complete({'deleted': true});+ expect(await pause, isNull, reason: mode);+ expect(connection.stops, ['a0'], reason: mode);+ expect(app.stateOf('m')!.agents.single.isStopped, isTrue, reason: mode);+ }+ },+ );++ test(+ 'a resume that opens a new conversation is a success, not a surprise',+ () async {+ // devin has no resume argv: the daemon says `fresh`, answers `resumed:false`+ // and hands back a different session id — all three as promised.+ app.stateOf('m')!.agents = [+ const Agent(+ id: 'a0',+ name: 'No resume flag',+ engine: 'devin',+ sessionId: 'archived',+ resumeMode: 'fresh',+ status: 'stopped',+ ),+ ];+ final resume = app.resumeAgent('m', 'a0');+ connection.restartReplies.single.complete({+ 'creationId': connection.requests.single['creationId'],+ 'state': 'created',+ 'resumed': false,+ 'agent': {+ 'id': 'a0',+ 'name': 'No resume flag',+ 'engine': 'devin',+ 'resumeMode': 'fresh',+ 'sessionId': 'brand-new',+ 'terminal': {'available': true},+ },+ });+ final result = await resume;+ expect(result.error, isNull);+ // `resumed: false` is reported as the truth it is, not a failed resume.+ expect(result.resumed, isFalse);+ expect(app.stateOf('m')!.agents.single.sessionId, 'brand-new');+ expect(app.stateOf('m')!.agents.single.isStopped, isFalse);+ },+ );++ test(+ 'a terminal pauses without a saved conversation, and comes back',+ () async {+ // The daemon relaunches a shell with no sessionId (`resumeStoppedAgent.ts`),+ // so nothing here has a conversation to wait for.+ app.stateOf('m')!.agents = [+ const Agent(+ id: 'shell',+ name: 'Untitled Pane',+ engine: 'terminal',+ terminalAvailable: true,+ ),+ ];+ connection.inventory = Completer<Map<String, dynamic>>()+ ..complete({+ 'agents': [+ {+ 'id': 'shell',+ 'name': 'Untitled Pane',+ 'engine': 'terminal',+ 'status': 'stopped',+ 'terminal': {'available': false},+ },+ ],+ });+ final pause = app.pauseAgent('m', 'shell');+ connection.stopReplies.single.complete({'deleted': true});+ expect(await pause, isNull);+ expect(connection.stops, ['shell']);+ expect(app.stateOf('m')!.agents.single.isStopped, isTrue);++ final resume = app.resumeAgent('m', 'shell');+ connection.restartReplies.single.complete(+ restartReceipt(+ connection.requests.single['creationId'] as String,+ agentId: 'shell',+ name: 'Untitled Pane',+ ),+ );+ expect((await resume).error, isNull);+ expect(app.stateOf('m')!.agents.single.isStopped, isFalse);+ },+ );}diff --git a/desktop/test/harness_session_manager_test.dart b/desktop/test/harness_session_manager_test.dartindex 282d72168..c5883ca19 100644--- a/desktop/test/harness_session_manager_test.dart+++ b/desktop/test/harness_session_manager_test.dart@@ -73,6 +73,22 @@ void main() {await tester.pumpAndSettle();}+ /// A row past the fold is not built, and a fixture with a few harnesses in it+ /// reaches that fold — the rows carry their token and edit figures now.+ Future<Finder> reveal(WidgetTester tester, Finder target) async {+ if (target.evaluate().isEmpty) {+ await tester.scrollUntilVisible(+ target,+ 120,+ scrollable: find.byType(Scrollable).last,+ );+ await tester.pumpAndSettle();+ }+ await tester.ensureVisible(target);+ await tester.pumpAndSettle();+ return target;+ }+PendingQuestion question(String id, {String request = 'question'}) =>PendingQuestion(machineId: 'm',@@ -512,8 +528,128 @@ void main() {);testWidgets(- 'unsupported engines stay openable without a misleading pause control',+ 'a terminal pauses and comes back as a fresh shell in the same tile',+ (tester) async {+ // A shell holds no conversation, so the saved-conversation rule the+ // engines live under has nothing to protect here — the daemon has always+ // relaunched one (`resumeStoppedAgent.ts` exempts it).+ app+ .stateOf('m')!+ .agents+ .add(+ const Agent(+ id: 'shell',+ name: 'Untitled Pane',+ engine: 'terminal',+ terminalAvailable: true,+ project: _project,+ ),+ );+ app.rememberOpenedHarness('m', 'shell');+ await open(tester);+ await reveal(tester, toggle('shell'));+ expect(tester.widget<IconButton>(toggle('shell')).onPressed, isNotNull);+ expect(+ find.byTooltip(+ 'Pause terminal — ends this shell and anything running in it',+ ),+ findsOneWidget,+ );++ connection.inventory = Completer<Map<String, dynamic>>();+ await tester.tap(toggle('shell'));+ await tester.pump();+ expect(connection.stops, ['shell']);+ connection.stopReplies.single.complete({'deleted': true});+ await tester.pump();+ connection.inventory!.complete({+ 'agents': [+ {+ 'id': 'shell',+ 'name': 'Untitled Pane',+ 'engine': 'terminal',+ 'status': 'stopped',+ 'terminal': {'available': false},+ },+ ],+ });+ await tester.pumpAndSettle();+ expect(app.stateOf('m')!.agents.single.isStopped, isTrue);+ // Paused, not "Resume unavailable": it can come back.+ expect(harnessSessions(app).single.status, 'Paused');+ expect(find.text('Paused 1'), findsOneWidget);+ expect(+ tester.widget<IconButton>(toggle('shell')).onPressed,+ isNotNull,+ reason: 'the paused shell offers resume',+ );+ expect(find.byTooltip('Open a fresh shell here'), findsOneWidget);++ await tester.tap(toggle('shell'));+ await tester.pump();+ expect(connection.types, ['agent_resume']);+ connection.restartReplies.single.complete(+ restartReceipt(+ connection.requests.single['creationId'] as String,+ agentId: 'shell',+ name: 'Untitled Pane',+ ),+ );+ await tester.pumpAndSettle();+ expect(app.stateOf('m')!.agents.single.isStopped, isFalse);+ },+ );++ testWidgets('every engine the daemon reports is pausable, in its own words', (+ tester,+ ) async {+ // The daemon says per engine how much a resume brings back (`resumeMode`).+ // An engine that reopens its conversation and one that cannot both pause;+ // only the sentence differs.+ app.stateOf('m')!.agents.addAll(const [+ Agent(+ id: 'keeps',+ name: 'Keeps its conversation',+ engine: 'opencode',+ sessionId: 'history',+ resumeMode: 'conversation',+ terminalAvailable: true,+ ),+ Agent(+ id: 'fresh',+ name: 'No resume flag',+ engine: 'devin',+ sessionId: 'history',+ resumeMode: 'fresh',+ terminalAvailable: true,+ ),+ ]);+ // The Monitor lists the harnesses this app has opened.+ app.rememberOpenedHarness('m', 'keeps');+ app.rememberOpenedHarness('m', 'fresh');+ await open(tester);+ await reveal(tester, toggle('keeps'));+ expect(tester.widget<IconButton>(toggle('keeps')).onPressed, isNotNull);+ expect(+ find.ancestor(+ of: toggle('keeps'),+ matching: find.byTooltip('Pause harness'),+ ),+ findsOneWidget,+ );+ await reveal(tester, toggle('fresh'));+ expect(tester.widget<IconButton>(toggle('fresh')).onPressed, isNotNull);+ expect(+ find.byTooltip('Pause harness — it comes back as a new conversation'),+ findsOneWidget,+ );+ });++ testWidgets(+ 'an engine a pre-resumeMode daemon cannot pause keeps its explanation',(tester) async {+ // No `resumeMode` on the frame: an older CLI, whose resume would refuse+ // anything but claude/codex. Offering the button would only fail.app.stateOf('m')!.agents@@ -528,13 +664,14 @@ void main() {);app.rememberOpenedHarness('m', 'unsupported');await open(tester);+ await reveal(tester, toggle('unsupported'));expect(tester.widget<IconButton>(toggle('unsupported')).onPressed,isNull,);expect(find.byTooltip(- 'Pause and resume are not available for this engine yet.',+ 'Update the harness CLI on this machine to pause and resume this engine.',),findsOneWidget,);