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.

Draft saved-session catalog and agent_resume protocol

dee7908ee37b814
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 96db264c7..5a1540131 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -8,6 +8,7 @@ import { WS_IDLE_DEADLINE_MS as IDLE_DEADLINE_MS } from './lib/wsLiveness.js'
import type { TerminalStreamManager } from './lib/terminalStreamManager.js'
import { decodeTerminalLocal, TerminalBinaryKind } from './lib/terminalBinary.js'
import { registry, type RegisteredSession } from './lib/registry.js'
+import { stoppedAgents } from './lib/stoppedAgents.js'
import * as mediaPreview from './lib/mediaPreview.js'
import * as projectFolder from './lib/projectFolder.js'
import * as projectPreview from './lib/projectPreview.js'
@@ -1418,6 +1419,38 @@ describe('agent_restart RPC', () => {
return { socket, frames }
}
+ it('lists stopped work only on request, without exposing old routes or launch credentials', async () => {
+ const { socket, frames } = localSocket()
+ const saved = { ...BASE_SESSION, gridLaunch: { apiKey: 'fixture-private-key' } } as RegisteredSession
+ vi.spyOn(registry, 'advertised').mockReturnValue([])
+ vi.spyOn(registry, 'list').mockReturnValue([])
+ vi.spyOn(stoppedAgents, 'available').mockReturnValue([saved])
+ socket.handleLocalFrame('local:restart', { type: 'agents_list', payload: { requestId: 'live' } })
+ socket.handleLocalFrame('local:restart', { type: 'agents_list', payload: { requestId: 'all', includeStopped: true } })
+ await vi.waitFor(() => expect(frames.filter(frame => frame.type === 'agents_list_result')).toHaveLength(2))
+ const response = (id: string) => frames.find(frame => (frame.payload as any).requestId === id)?.payload as any
+ expect(response('live').agents).toEqual([])
+ expect(response('all').agents).toEqual([expect.objectContaining({ id: 'agent-1', status: 'stopped', sessionId: 'session-1', terminal: { available: false, primary: '', runtimes: [] }, tmuxPane: null, forkable: false })])
+ expect(JSON.stringify(response('all'))).not.toContain('fixture-private-key')
+ await socket.unregisterLocalClient('local:restart')
+ await socket.stop()
+ })
+
+ it('delegates a resume-only intent and retains its original receipt', async () => {
+ const { socket, frames } = localSocket()
+ const creationId = `resume-${randomUUID()}`
+ const handler = vi.fn(async () => ({ ok: true as const, session: BASE_SESSION, resumed: true }))
+ socket.onResumeAgent = handler
+ vi.spyOn(registry, 'byAgent').mockReturnValue(BASE_SESSION)
+ for (const requestId of ['first', 'again']) {
+ socket.handleLocalFrame('local:restart', { type: 'agent_resume', payload: { requestId, agentId: 'agent-1', creationId } })
+ await vi.waitFor(() => expect(frames.some(frame => (frame.payload as any).requestId === requestId)).toBe(true))
+ }
+ expect(handler).toHaveBeenCalledExactlyOnceWith('agent-1')
+ await socket.unregisterLocalClient('local:restart')
+ await socket.stop()
+ })
+
it('replies MISSING_AGENT_ID when no agentId is given', async () => {
const { socket, frames } = localSocket()
socket.handleLocalFrame('local:restart', { type: 'agent_restart', payload: { requestId: 'r1' } })
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index a92660618..417613a21 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -57,6 +57,7 @@ import { dshInstallReply, dshInstallRequest, dshInstallStatus, dshListRows, dshR
import { terminalHandoffRequest } from './lib/terminalHandoff.js'
import { routeVoiceTask } from './lib/voiceRouter.js'
import { tailFile } from './lib/sessions.js'
+import { stoppedAgents } from './lib/stoppedAgents.js'
import { messagesToEvents, windowRawLines, subagentStatsFromRawLines, type SessionEvent } from './lib/normalize.js'
import { listFileTree, readProjectFile } from './lib/files.js'
import { MediaPreviewError, readMediaPreviewChunk } from './lib/mediaPreview.js'
@@ -400,7 +401,7 @@ export class BackendSocket {
onCancel: ((sessionId: string) => void) | null = null
/** Called when the web deletes an agent (`agent_delete`) — cli.ts signals only the validated engine
* process and forgets the session. Keeps recap + agent name. */
- onDeleteAgent: ((sessionId: string) => void) | null = null
+ onDeleteAgent: ((sessionId: string) => void | Promise<void>) | null = null
/** Called on `agent_create` — cli.ts spawns a fresh tmux session running the requested engine in the
* requested folder and returns its process-agent. Session metadata may bind later through hooks. */
onCreateAgent: ((input: {
@@ -517,6 +518,9 @@ export class BackendSocket {
{ ok: true; session: RegisteredSession; resumed: boolean }
| { ok: false; error: string; detail?: string }
>) | null = null
+ /** Resume stopped work directly, or attach if it is already running. Never replaces a live
+ * process and never falls back to a fresh conversation. */
+ onResumeAgent: BackendSocket['onRestartAgent'] = null
/** Called on `agent_fork` — cli.ts opens a NEW agent that starts with `agentId`'s whole history
* (lib/forkAgent.ts) and returns its process-agent, exactly as `agent_create` does. `level` says
* what the new agent actually got: the engine's own fork, or a handoff message. */
@@ -1529,6 +1533,11 @@ export class BackendSocket {
case 'agents_list': {
const projects = await Promise.all(registry.advertised().map((s) => this.toProject(s)))
+ // Older clients/devices keep their live-only contract. The desktop picker
+ // explicitly asks for stopped work and receives no stale terminal routes.
+ if (payload.includeStopped === true && this.e2ee.sessionRole(connId) !== 'device') {
+ projects.push(...await Promise.all(stoppedAgents.available(registry.list()).map(s => this.toStoppedProject(s))))
+ }
// Ordered by creation time, oldest → newest — a stable tab order that doesn't reshuffle as
// sessions become active (createdAt = the session's registeredAt). The id breaks a tie so the
// order is TOTAL: without it two agents registered in the same millisecond fall through to array
@@ -2265,23 +2274,25 @@ export class BackendSocket {
case 'agent_delete': {
const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)
if (!target) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }
- this.onDeleteAgent?.(target)
+ await this.onDeleteAgent?.(target)
reply(type, requestId, { deleted: true })
return
}
- // Restart an agent: exit its live engine process and relaunch it in the SAME tmux pane, keeping
- // the SAME agentId. Follows agent_create/agent_delete's exact validate → delegate → reply shape.
+ // Resume attaches or restores a saved conversation; restart replaces a live process in its
+ // existing pane. Both keep the agentId and use the same durable operation receipt protocol.
+ case 'agent_resume':
case 'agent_restart': {
const target = payload.agentId as string | undefined
if (!target) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }
- if (!this.onRestartAgent) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }
+ const operation = type === 'agent_resume' ? 'resume' : 'restart'
+ const restart = operation === 'resume' ? this.onResumeAgent : this.onRestartAgent
+ if (!restart) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }
const creationId = payload.creationId
if (creationId !== undefined) {
if (!validCreationId(creationId)) { reply(type, requestId, { error: 'INVALID_CREATION_ID' }); return }
- const restart = this.onRestartAgent
try {
- void this.agentCreations.run(creationId, creationFingerprint({ operation: 'restart', agentId: target }), async () => {
+ void this.agentCreations.run(creationId, creationFingerprint({ operation, agentId: target }), async () => {
const result = await restart(target)
if (result.ok) return { state: 'created', agentId: result.session.agentId, resumed: result.resumed }
// RESTART_FAILED can follow an unobserved relaunch. Never silently
@@ -2296,7 +2307,7 @@ export class BackendSocket {
}
return
}
- const result = await this.onRestartAgent(target)
+ const result = await restart(target)
if (!result.ok) {
reply(type, requestId, result.detail ? { error: result.error, detail: result.detail } : { error: result.error })
return
@@ -2526,6 +2537,18 @@ export class BackendSocket {
return status
}
+ private async toStoppedProject(s: RegisteredSession): Promise<AgentFrame> {
+ const frame = await agentFrame(s, { selectedModel: s.model, terminalAvailable: false, dsh: this.dshFrameProvider?.(s) ?? null })
+ return {
+ ...frame,
+ status: 'stopped',
+ tmuxPane: null,
+ terminal: { available: false, primary: '', runtimes: [] },
+ viewerUrl: null,
+ forkable: false,
+ }
+ }
+
/** Map a registered tmux session onto the web's Project shape (tabs in ProjectTabs). */
private toProject(s: RegisteredSession): Promise<AgentFrame> {
return agentFrame(s, {
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 975346af3..b444ab854 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -84,6 +84,8 @@ import { DEFAULT_HOST_THEME, loadHostTheme, saveHostTheme, type HostTheme } from
import { createAndRegisterPane } from './lib/createAgentPane.js'
import { forkName, planFork } from './lib/forkAgent.js'
import { restoreAgents } from './lib/restoreAgents.js'
+import { stoppedAgents } from './lib/stoppedAgents.js'
+import { resumeStoppedAgent } from './lib/resumeStoppedAgent.js'
import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from './lib/launchOverrides.js'
import { prepareCodexResume } from './engines/codex/portableHistory.js'
import { buildHarnessSessionLabel } from './lib/harnessSessionLabel.js'
@@ -2542,6 +2544,7 @@ async function runForeground(session: AuthSession): Promise<void> {
? `[agent] ${sid(announceId)} released session ${sid(sessionId)}`
: `[agent] ${sid(announceId)} forgotten`)
+ if (!opts.keepAgent && doomed) stoppedAgents.save(doomed)
if (opts.keepAgent) registry.unbindSession(sessionId)
else if (doomed) registry.removeAgent(doomed.agentId)
else registry.remove(sessionId)
@@ -2581,7 +2584,7 @@ async function runForeground(session: AuthSession): Promise<void> {
if (!opts.keepAgent) detachDsh(announceId)
mirror.forget(sessionId) // aborts any in-flight recap + clears busy; KEEPS the persisted summary
if (opts.keepAgent) return
- backend.send({ type: 'agent_deleted', payload: { agentId: announceId } }) // web tab
+ backend.send({ type: 'agent_deleted', payload: { agentId: announceId, retained: !!doomed } }) // web tab
backend.sendCommander({ type: 'agent_deleted', payload: { agentId: announceId } })
}
@@ -2943,6 +2946,7 @@ async function runForeground(session: AuthSession): Promise<void> {
// the grid/profile/DSH the launch is about to use. Not for a pane that is dead either — that
// one is on its way to `onRemoved`.
if (agent.launch?.state !== 'starting') {
+ stoppedAgents.save(agent)
const released = registry.releaseEngine(agent.agentId)
if (released) {
syncRecapPool()
@@ -4183,6 +4187,7 @@ async function runForeground(session: AuthSession): Promise<void> {
// "Start failed" tile they cannot type into.
if (paneState.engineExit !== null) {
await clearPaneRemainOnExit(spawned.runtime.paneId)
+ stoppedAgents.save(pending)
const released = registry.releaseEngine(pending.agentId)
if (released) announceSession(released)
console.warn(`[agent] create · ${engine} exited (${paneState.engineExit}) before ready · agent ${pending.agentId} kept as a terminal`)
@@ -4491,6 +4496,7 @@ async function runForeground(session: AuthSession): Promise<void> {
* half that drifts is the half nobody ran today.
*/
const restartJobs = new AgentRestartCoordinator()
+ const resumeJobs = new AgentRestartCoordinator()
const sameRestartTarget = (session: RegisteredSession): boolean => {
const current = registry.byAgent(session.agentId)
return !!current && current.registeredAt === session.registeredAt
@@ -4770,56 +4776,110 @@ async function runForeground(session: AuthSession): Promise<void> {
}
/**
- * Web or device deleted an agent (`agent_delete`): end the AGENT, not the user's window.
- *
- * This used to `tmux kill-pane`, which took the pane down — and with it the window, and the session if
- * that pane was the last one. The pane is the user's; only the exact discovered engine process is
- * signalled. Its PID and start marker are re-validated before SIGTERM/SIGKILL.
- *
- * `registry.remove` + `mirror.forget` keep the recap AND the agent-name override for a later resume.
+ * Stop Harness (`agent_delete`) archives its conversation and launch settings, removes the live
+ * registry entry, and closes its tmux pane. Exact PID/start-marker validation guards the engine's
+ * SIGTERM/SIGKILL fallback. Engine conversation files, recaps and the Harness name remain on disk.
*/
- backend.onDeleteAgent = (sessionId) => {
- restartJobs.cancel(registry.resolve(sessionId)?.agentId ?? sessionId)
- const s = registry.resolve(sessionId) // BEFORE forgetSession — that removes it from the registry
- // The engine outlives this call by a second or two now, and its catch hook fires on every turn
- // boundary. Without the tombstone that hook re-registers the session and the tile comes straight back.
- markDeleted(sessionId)
- if (s?.processIdentity) {
- agentReconciler.suppress(s)
- }
- forgetSession(sessionId, { force: true })
- if (!s) return
- // Stopping is closing the pane. Every pane is a shell with the engine inside it now, so signalling
- // the engine alone would leave a shell running in a pane nobody can see any more — a leak, and
- // for a bare terminal there is no engine pid to signal at all. The engine's own termination
- // below stays as the belt to this: a pane kill that does not land must not leave a live engine
- // the UI already calls gone.
- if (tmuxBackend) {
- const runtimes = s.runtimes.filter((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')
- void Promise.all(runtimes.map((runtime) => tmuxBackend.kill(runtime))).then(() => {
- console.log(`[delete] ${sid(sessionId)} ${s.engine} · pane closed`)
- if (isTerminalEngine(s.engine)) clearDeleted(sessionId)
- void agentReconciler.trigger()
- }).catch((err) => {
- console.error('[delete] terminal pane close failed:', err instanceof Error ? err.message : err)
- })
- if (isTerminalEngine(s.engine)) return
- }
- void terminateDeletedAgent(s, {
- checkRuntime: checkPidRuntime,
- kill: (pid, signal) => process.kill(pid, signal),
- sleep: (ms) => new Promise((resolve) => { const t = setTimeout(resolve, ms); t.unref?.() }),
- log: (message) => console.log(message),
- }, 0).then((outcome) => {
- console.log(`[delete] ${sid(sessionId)} ${s.engine} · ${outcome}`)
- // Provably gone ⇒ nothing left that could re-register, so stop blocking the id early.
- if (outcome !== 'failed') clearDeleted(sessionId)
+ const stopJobs = new Map<string, Promise<void>>()
+ backend.onDeleteAgent = (target) => {
+ const sessionId = registry.resolve(target)?.agentId ?? target
+ const existing = stopJobs.get(sessionId)
+ if (existing) return existing
+ restartJobs.cancel(sessionId)
+ resumeJobs.cancel(sessionId)
+ const job = Promise.resolve().then(async () => {
+ const s = registry.resolve(sessionId)
+ if (!s) return
+ // Saving precedes every mutation. A storage failure leaves the live agent alone.
+ stoppedAgents.save(s)
+ markDeleted(sessionId)
+ if (s.sessionId) markDeleted(s.sessionId)
+ if (s.processIdentity) agentReconciler.suppress(s)
+ forgetSession(sessionId, { force: true })
+ const paneStop = tmuxBackend
+ ? Promise.all(s.runtimes.filter((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')
+ .map(runtime => tmuxBackend!.kill(runtime)))
+ : Promise.resolve([])
+ const processStop = isTerminalEngine(s.engine) ? Promise.resolve('gone' as const)
+ : terminateDeletedAgent(s, {
+ checkRuntime: checkPidRuntime,
+ kill: (pid, signal) => process.kill(pid, signal),
+ sleep: ms => new Promise(resolve => { const timer = setTimeout(resolve, ms); timer.unref?.() }),
+ log: message => console.log(message),
+ }, 0)
+ const [, outcome] = await Promise.all([paneStop, processStop])
+ if (outcome !== 'failed') {
+ clearDeleted(sessionId)
+ if (s.sessionId) clearDeleted(s.sessionId)
+ }
void agentReconciler.trigger()
- }).catch((err) => {
- console.error('[delete] process termination failed:', err instanceof Error ? err.message : err)
+ }).finally(() => {
+ if (stopJobs.get(sessionId) === job) stopJobs.delete(sessionId)
})
+ stopJobs.set(sessionId, job)
+ return job
}
+ const resumeStopped = (agentId: string, current: () => boolean) => resumeStoppedAgent({
+ live: () => registry.byAgent(agentId),
+ saved: () => stoppedAgents.get(agentId),
+ current,
+ canLaunch: async saved => {
+ await stopJobs.get(agentId)
+ return !registry.bySession(saved.sessionId) && (await checkPidRuntime(saved)).state === 'gone'
+ },
+ launch: async (saved, resumeSessionId) => {
+ if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
+ const built = await relaunchOverrides(saved)
+ if (!built.ok) return { ok: false, error: built.error, detail: built.detail }
+ if (resumeSessionId) {
+ try { prepareSessionResume(saved) } catch {
+ return { ok: false, error: 'RESUME_PREPARATION_FAILED', detail: 'Could not prepare the saved conversation. Start a new conversation separately if needed.' }
+ }
+ }
+ if (!current()) return { ok: false, error: 'AGENT_CHANGED' }
+ if (saved.sessionId && registry.bySession(saved.sessionId)) return { ok: false, error: 'AGENT_BUSY', detail: 'This conversation is already running. Select its running harness in search.' }
+ const { env: launchEnv, extraArgs, clearEnv } = built.overrides
+ const installIfMissing = enginePathOverride(saved.engine) ? undefined : engineInstallRecipe(saved.engine)
+ const options = {
+ resumeSessionId,
+ bypassPermission: saved.bypassPermission === true,
+ ...(saved.permissionMode ? { permissionMode: saved.permissionMode } : {}),
+ ...(saved.cwd ? { cwd: saved.cwd } : {}),
+ ...(extraArgs.length ? { extraArgs } : {}),
+ ...(clearEnv.length ? { clearEnv } : {}),
+ ...(launchEnv.HARNESS_DSH ? { harnessNode: true } : {}),
+ installIfMissing,
+ }
+ // The saved id is passed exactly once. This path never invokes restart's
+ // best-effort fallback to a fresh conversation.
+ clearDeleted(agentId)
+ const result = await createAndRegisterPane({
+ tmuxBackend,
+ registry: { openPendingAgent: input => current() ? registry.resumePendingAgent(saved, input.runtimes) : null },
+ maxAttempts: 1,
+ engine: saved.engine,
+ sessionLabel: buildHarnessSessionLabel(saved.engine),
+ argv: buildEngineLaunchArgv(saved.engine, options),
+ ...(Object.keys(launchEnv).length ? { env: launchEnv } : {}),
+ })
+ if (!result.ok) return { ok: false, error: result.error, detail: result.detail }
+ const { pending, spawned } = result
+ refreshGridWebSearch(pending.agentId, built.overrides)
+ if (isTerminalEngine(saved.engine)) {
+ await clearPaneRemainOnExit(spawned.runtime.paneId)
+ registry.setLaunch(pending.agentId, { state: 'ready' })
+ } else {
+ if (pending.dsh) attachDsh(pending)
+ void watchNewPane(saved.engine, pending, spawned, buildEngineCommandArgv(saved.engine, options), installIfMissing)
+ }
+ announceSession(pending)
+ return { ok: true, session: pending, resumed: true }
+ },
+ })
+
+ backend.onResumeAgent = (agentId) => resumeJobs.run(agentId, current => resumeStopped(agentId, current))
+
/**
* Web or device restarted an agent (`agent_restart`): exit the live engine process and relaunch it in
* the SAME tmux pane, keeping the SAME agentId/session — restart must never look like delete+create to
diff --git a/cli/src/lib/e2ee/core.test.ts b/cli/src/lib/e2ee/core.test.ts
index 4ee61eaf8..9b6feaf1c 100644
--- a/cli/src/lib/e2ee/core.test.ts
+++ b/cli/src/lib/e2ee/core.test.ts
@@ -210,6 +210,6 @@ describe('e2ee core — interop keystone', () => {
it('core.ts still hashes to the pinned value shared with the other implementations', () => {
const here = dirname(fileURLToPath(import.meta.url))
const actual = createHash('sha256').update(readFileSync(join(here, 'core.ts'))).digest('hex')
- expect(actual).toBe('87c9a1b87a4428bd529b111899ef636b337ba3ac3fedad6d3cc7dfb4bcf7badc')
+ expect(actual).toBe('3b5b79f18c6f6346b7d87da26d424402f81b9d1608a2c26dee62eb3287c9ca36')
})
})
diff --git a/cli/src/lib/e2ee/core.ts b/cli/src/lib/e2ee/core.ts
index 640f644c7..46e8c9fa3 100644
--- a/cli/src/lib/e2ee/core.ts
+++ b/cli/src/lib/e2ee/core.ts
@@ -349,7 +349,7 @@ export const ENCRYPTED_RPC_RESULT_TYPES = new Set<string>([
'e2ee_pairings_unpair_all_result', 'e2ee_browser_link_create_result',
// Device RPC replies that carry adapter content (recap headline/body, new agent name). Must be
// ciphertext so the backend relay can't read them — device↔adapter E2EE parity with web.
- 'agent_recent_result', 'agent_create_result', 'agent_create_status_result', 'agent_restart_result',
+ 'agent_recent_result', 'agent_create_result', 'agent_create_status_result', 'agent_restart_result', 'agent_resume_result',
// A fork's reply names the new agent, exactly like agent_create's.
'agent_fork_result',
// A remote-machine directory listing (New Agent folder browser) — leaks filesystem layout if plaintext.
@@ -373,7 +373,7 @@ export const ENCRYPTED_DOWN_TYPES = new Set<string>([
// as "no session/answers", the pane dialog was never keyed, and the CLI waited on question 1 forever.
'question_response',
'agents_list', 'sessions_list', 'session_get', 'models_list',
- 'agent_create', 'agent_create_status', 'agent_delete', 'agent_restart', 'agent_recent', 'agent_update', 'agent_files', 'agent_read_file',
+ 'agent_create', 'agent_create_status', 'agent_delete', 'agent_restart', 'agent_resume', 'agent_recent', 'agent_update', 'agent_files', 'agent_read_file',
// Carries the fork's name and first task — what the person typed — like agent_create's prompt.
'agent_fork',
'fs_list_dir', 'project_preview', 'codex_profiles_list', 'codex_profile_link',
diff --git a/cli/src/lib/e2ee/relayLink.spec.ts b/cli/src/lib/e2ee/relayLink.spec.ts
index 190377af3..7b1857a26 100644
--- a/cli/src/lib/e2ee/relayLink.spec.ts
+++ b/cli/src/lib/e2ee/relayLink.spec.ts
@@ -150,6 +150,15 @@ describe('remote-password link + relay session crypto (interop with the real E2e
expect(statusReply.payload).not.toHaveProperty('agent')
expect(crypto.unwrapIncoming(statusReply)?.payload).toEqual(status)
+ const resume = { requestId: 'resume-1', agentId: 'saved-work', creationId: 'resume-fixture-001' }
+ const resumeRequest = crypto.wrapOutgoing({ type: 'agent_resume', payload: resume })
+ expect(resumeRequest.payload).not.toHaveProperty('agentId')
+ expect(manager.unwrapDown('session-conn', resumeRequest)?.payload).toEqual(resume)
+ const resumed = { ...resume, state: 'created', agent: { id: 'saved-work', cwd: '/private/work' } }
+ const resumeReply = manager.wrapTarget('session-conn', 'agent_resume_result', resumed)!
+ expect(resumeReply.payload).not.toHaveProperty('agent')
+ expect(crypto.unwrapIncoming(resumeReply)?.payload).toEqual(resumed)
+
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/registry.spec.ts b/cli/src/lib/registry.spec.ts
index fa3a92757..91f94180c 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -1483,6 +1483,31 @@ describe('registry across a reboot and pane loss', () => {
expect(bound?.entry.subscriptionModel).toBe('opus')
})
+ it('keeps strict conversation resume after the engine binds and the daemon reloads', async () => {
+ const transcriptPath = join(dataDir, 'session-resumed.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const original = registerProcess(registry, {
+ engine: 'claude', sessionId: 'session-resumed', transcriptPath, tmuxPane: '%21', cwd: '/tmp/demo',
+ })!.entry
+ registry.removeAgent(original.agentId)
+ registry.resumePendingAgent(original, [{ backend: 'tmux', paneId: '%22' }])
+
+ // SessionStart rebuilds the row. It must retain the policy that prevents a
+ // later daemon restore from silently replacing this saved conversation.
+ const bound = registry.register({
+ engine: 'claude', sessionId: original.sessionId, transcriptPath, tmuxPane: '%22', cwd: '/tmp/demo',
+ })
+ expect(bound?.entry.agentId).toBe(original.agentId)
+ expect(bound?.entry.resumeOnly).toBe(true)
+ const { registry: reloaded } = await loadRegistryModule()
+ reloaded.load()
+ expect(reloaded.byAgent(original.agentId)).toMatchObject({
+ sessionId: original.sessionId, tmuxPane: '%22', resumeOnly: true,
+ })
+ })
+
it('drops any launch state on the hook that proves the engine is up', async () => {
const transcriptPath = join(dataDir, 'session-f.jsonl')
writeFileSync(transcriptPath, '{}\n')
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 176916250..80055cf3f 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -73,6 +73,8 @@ export interface RegisteredSession {
active: boolean
/** Harness-created panes can be rendered before their engine process exists. Absent on legacy rows. */
launch?: AgentLaunch
+ /** Enter on stopped work must never become a fresh conversation, including after a daemon restart. */
+ resumeOnly?: true
/**
* THE AGENT. Public identity: this is what web tabs, device tiles and every inbound frame address.
*
@@ -387,7 +389,7 @@ function rowFingerprint(row: unknown): string {
return JSON.stringify(row)
}
-function atomicWriteJson(file: string, value: unknown, exclusive = false): void {
+export function atomicWriteJson(file: string, value: unknown, exclusive = false): void {
const exists = hardenPrivateStateFileIfPresent(file)
if (exclusive && exists) return
const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`
@@ -441,7 +443,7 @@ function persistedRow(entry: RegisteredSession): RegisteredSession | Omit<Regist
return { ...row, runtimes: row.runtimes.map((runtime) => ({ ...runtime })) }
}
-function strictPersistedRow(value: unknown): RegisteredSession | null {
+export function strictPersistedRow(value: unknown): RegisteredSession | null {
if (!value || typeof value !== 'object') return null
const row = value as Partial<RegisteredSession>
const runtimes = normalizedRuntimes(row.runtimes, row.tmuxPane)
@@ -860,6 +862,7 @@ class Registry {
schemaVersion: 2,
active,
...(launch ? { launch } : {}),
+ ...(raw.resumeOnly === true ? { resumeOnly: true } : {}),
agentId,
boundAt: bound ? (typeof raw.boundAt === 'number' ? raw.boundAt : (raw.registeredAt ?? now)) : null,
engine,
@@ -1163,6 +1166,30 @@ class Registry {
return entry
}
+ /** A stopped agent gets a new terminal route while keeping its saved conversation and identity.
+ * Archived routes/processes are evidence only: none of them may be indexed or signalled here. */
+ resumePendingAgent(saved: RegisteredSession, runtimes: TerminalRuntimeRef[]): RegisteredSession | null {
+ if (this.writeBlocked || this.agents.has(saved.agentId)
+ || (saved.sessionId && this.bySession(saved.sessionId))) return null
+ const routes = normalizedRuntimes(runtimes)
+ if (!routes.length || routes.some(route => this.runtimeIndex.has(terminalRouteKey(route)))) return null
+ const entry: RegisteredSession = {
+ ...saved,
+ resumeOnly: true,
+ active: true,
+ launch: { state: 'starting' },
+ processIdentity: null,
+ runtimes: routes,
+ primaryRuntimeKey: selectedRuntimeKey(routes, ''),
+ tmuxPane: tmuxProjection(routes),
+ updatedAt: Date.now(),
+ }
+ this.index(entry)
+ this.terminalAvailableAgents.add(entry.agentId)
+ this.save()
+ return entry
+ }
+
/** Every name an agent on this machine answers to: default names, project names, renames. */
agentNamesInUse(): string[] {
return [
@@ -1341,6 +1368,7 @@ class Registry {
agent: existing?.agent ?? null,
...(existing?.bypassPermission ? { bypassPermission: true } : {}),
...(existing?.permissionMode ? { permissionMode: existing.permissionMode } : {}),
+ ...(existing?.resumeOnly ? { resumeOnly: true } : {}),
...(existing?.terminalHost ? { terminalHost: true } : {}),
processIdentity: validProcessIdentity(input.processIdentity) ? input.processIdentity : existing?.processIdentity ?? null,
registeredAt: existing?.registeredAt ?? now,
diff --git a/cli/src/lib/restoreAgents.spec.ts b/cli/src/lib/restoreAgents.spec.ts
index 840c1d6c8..ebeebb665 100644
--- a/cli/src/lib/restoreAgents.spec.ts
+++ b/cli/src/lib/restoreAgents.spec.ts
@@ -288,6 +288,25 @@ describe('restoreAgents — which agents get a pane back', () => {
})
describe('restoreAgents — waiting for the engine', () => {
+ it('keeps an explicit resume failure instead of silently starting fresh after a daemon restart', async () => {
+ const h = harness([row({ resumeOnly: true })])
+ h.probes.set('%0', [null, null])
+ h.states.set('%0', [{ dead: true }])
+ await restoreAgents(h.deps)
+ await settled(h, 1)
+ expect(h.respawns).toBe(0)
+ expect(h.launches).toEqual([{ agentId: 'agent-a', resumeSessionId: 'session-a' }])
+ expect(h.rows.get('agent-a')?.launch).toMatchObject({ state: 'failed', error: 'RESUME_FAILED' })
+ expect(h.calls).not.toContain('unbind:session-a')
+ })
+
+ it('does not create a fresh conversation if a resume-only binding is missing', async () => {
+ const h = harness([row({ resumeOnly: true, sessionId: '' })])
+ await restoreAgents(h.deps)
+ expect(h.launches).toEqual([])
+ expect(h.rows.get('agent-a')?.launch).toMatchObject({ state: 'failed', error: 'RESUME_UNAVAILABLE' })
+ })
+
it('falls back to a fresh launch once when the resumed engine dies, and unbinds the stale session', async () => {
const h = harness([row()])
h.probes.set('%0', [null, null, identity(9)])
diff --git a/cli/src/lib/restoreAgents.ts b/cli/src/lib/restoreAgents.ts
index 1ce28bafd..2d495b032 100644
--- a/cli/src/lib/restoreAgents.ts
+++ b/cli/src/lib/restoreAgents.ts
@@ -203,6 +203,12 @@ export async function restoreAgents(deps: RestoreAgentsDeps): Promise<RestoreSum
// into this agent (route adoption requires either no identity or a matching pid).
deps.registry.clearProcessIdentity(entry.agentId)
const resumeSessionId = entry.sessionId || undefined
+ if (entry.resumeOnly && !resumeSessionId && !isTerminalEngine(entry.engine)) {
+ const reason = 'The saved conversation is no longer available. Start a new conversation separately.'
+ summary.failed.push({ agentId: entry.agentId, reason })
+ deps.registry.setLaunch(entry.agentId, { state: 'failed', error: 'RESUME_UNAVAILABLE', detail: reason })
+ continue
+ }
const launch = await deps.buildLaunch(entry, resumeSessionId ? { resumeSessionId } : {})
if ('error' in launch) {
summary.failed.push({ agentId: entry.agentId, reason: launch.detail })
@@ -260,6 +266,10 @@ async function watchRestoredPane(
let mayRetryFresh = resuming
/** The pane's engine is gone. True when a fresh relaunch is now under way, false when this is the end. */
const relaunchFresh = async (): Promise<boolean> => {
+ if (entry.resumeOnly) {
+ fail('RESUME_FAILED', `${engine} could not resume the saved conversation. See the terminal output, or start a new conversation separately.`)
+ return false
+ }
if (!mayRetryFresh) {
fail('ENGINE_DID_NOT_START', `${engine} exited before its engine process became ready. See the terminal output for details.`)
return false
diff --git a/cli/src/lib/resumeStoppedAgent.spec.ts b/cli/src/lib/resumeStoppedAgent.spec.ts
new file mode 100644
index 000000000..7aaef48d9
--- /dev/null
+++ b/cli/src/lib/resumeStoppedAgent.spec.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it, vi } from 'vitest'
+import { resumeStoppedAgent } from './resumeStoppedAgent.js'
+import { AgentRestartCoordinator } from './restartAgent.js'
+import type { RegisteredSession } from './registry.js'
+
+const saved = { agentId: 'saved-agent', sessionId: 'original-conversation', engine: 'codex', cwd: '/work', codexHome: '/profile', permissionMode: 'plan' } as RegisteredSession
+function fixture() {
+ return {
+ live: vi.fn((): RegisteredSession | undefined => undefined),
+ saved: vi.fn(() => saved),
+ current: vi.fn(() => true),
+ canLaunch: vi.fn(async () => true),
+ launch: vi.fn(async () => ({ ok: true as const, session: saved, resumed: true })),
+ }
+}
+
+describe('Enter resumes stopped work', () => {
+ it('attaches an already live harness without launching or stopping it', async () => {
+ const deps = fixture()
+ deps.live.mockReturnValue(saved)
+ await expect(resumeStoppedAgent(deps)).resolves.toMatchObject({ ok: true, session: saved })
+ expect(deps.launch).not.toHaveBeenCalled()
+ expect(deps.canLaunch).not.toHaveBeenCalled()
+ })
+
+ it('passes the original conversation and complete launch profile directly to launch', async () => {
+ const deps = fixture()
+ await expect(resumeStoppedAgent(deps)).resolves.toMatchObject({ ok: true, resumed: true })
+ 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 => {
+ const deps = fixture()
+ deps.saved.mockReturnValue(entry)
+ await expect(resumeStoppedAgent(deps)).resolves.toMatchObject({ ok: false, error: 'RESUME_UNAVAILABLE' })
+ expect(deps.launch).not.toHaveBeenCalled()
+ })
+
+ it('does not launch while the old process is still alive or unverified', async () => {
+ const deps = fixture()
+ deps.canLaunch.mockResolvedValue(false)
+ await expect(resumeStoppedAgent(deps)).resolves.toMatchObject({ ok: false, error: 'AGENT_BUSY' })
+ expect(deps.launch).not.toHaveBeenCalled()
+ })
+
+ it('does not launch after Stop cancels a pending resume', async () => {
+ const deps = fixture()
+ deps.current.mockReturnValue(false)
+ await expect(resumeStoppedAgent(deps)).resolves.toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ expect(deps.launch).not.toHaveBeenCalled()
+ })
+
+ it('joins repeated Enter requests and never falls back after a launch failure', async () => {
+ const deps = fixture()
+ const launch = vi.fn(async () => ({ ok: false as const, error: 'RESUME_FAILED' }))
+ const coordinator = new AgentRestartCoordinator()
+ const run = () => coordinator.run(saved.agentId, current => resumeStoppedAgent({ ...deps, current, launch }))
+ const first = run()
+ expect(run()).toBe(first)
+ await expect(first).resolves.toEqual({ ok: false, error: 'RESUME_FAILED' })
+ expect(launch).toHaveBeenCalledTimes(1)
+ expect(launch).toHaveBeenCalledWith(saved, 'original-conversation')
+ })
+
+ it('reattaches if another client resumes while the old process is being checked', async () => {
+ const deps = fixture()
+ deps.canLaunch.mockImplementation(async () => { deps.live.mockReturnValue(saved); return true })
+ await expect(resumeStoppedAgent(deps)).resolves.toMatchObject({ ok: true, session: saved })
+ expect(deps.launch).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/lib/resumeStoppedAgent.ts b/cli/src/lib/resumeStoppedAgent.ts
new file mode 100644
index 000000000..50bcac574
--- /dev/null
+++ b/cli/src/lib/resumeStoppedAgent.ts
@@ -0,0 +1,31 @@
+import { LAUNCH_RESUME_FLAG } from './engineLaunch.js'
+import { isTerminalEngine } from '../engines/types.js'
+import type { RegisteredSession } from './registry.js'
+import type { RestartAgentReply } from './restartAgent.js'
+
+export interface ResumeStoppedDeps {
+ live: () => RegisteredSession | undefined
+ saved: () => RegisteredSession | null
+ current: () => boolean
+ canLaunch: (saved: RegisteredSession) => Promise<boolean>
+ launch: (saved: RegisteredSession, resumeSessionId: string | undefined) => Promise<RestartAgentReply>
+}
+
+/** Enter means attach or resume. There is deliberately no fresh-conversation fallback. */
+export async function resumeStoppedAgent(deps: ResumeStoppedDeps): Promise<RestartAgentReply> {
+ const existing = deps.live()
+ if (existing) return { ok: true, session: existing, resumed: true }
+ const saved = deps.saved()
+ if (!saved) return { ok: false, error: 'AGENT_NOT_FOUND', detail: 'The saved harness is no longer available.' }
+ if (!isTerminalEngine(saved.engine) && (!saved.sessionId || !LAUNCH_RESUME_FLAG[saved.engine])) {
+ return { ok: false, error: 'RESUME_UNAVAILABLE', detail: 'This harness has no resumable conversation. You can start a new conversation separately.' }
+ }
+ if (!await deps.canLaunch(saved)) {
+ return { ok: false, error: 'AGENT_BUSY', detail: 'The previous process has not stopped yet. Try again when it has finished.' }
+ }
+ if (!deps.current()) return { ok: false, error: 'AGENT_CHANGED' }
+ // Another client or discovery may have restored it while the process was checked.
+ const attached = deps.live()
+ if (attached) return { ok: true, session: attached, resumed: true }
+ return deps.launch(saved, isTerminalEngine(saved.engine) ? undefined : saved.sessionId)
+}
diff --git a/cli/src/lib/stoppedAgents.spec.ts b/cli/src/lib/stoppedAgents.spec.ts
new file mode 100644
index 000000000..052eb3185
--- /dev/null
+++ b/cli/src/lib/stoppedAgents.spec.ts
@@ -0,0 +1,82 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import type { RegisteredSession } from './registry.js'
+
+let directory = ''
+beforeEach(() => {
+ vi.resetModules()
+ directory = mkdtempSync(join(tmpdir(), 'harness-stopped-'))
+ vi.stubEnv('ADAPTER_DATA_DIR', directory)
+})
+afterEach(() => {
+ vi.unstubAllEnvs()
+ rmSync(directory, { recursive: true, force: true })
+})
+
+async function fixture() {
+ const { registry } = await import('./registry.js')
+ const { StoppedAgentStore } = await import('./stoppedAgents.js')
+ const entry = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%8' }], cwd: '/tmp/work', defaultName: 'My work', codexHome: '/tmp/profile', dsh: 'autonomous/fixture', permissionMode: 'plan' })!
+ const saved: RegisteredSession = { ...entry, sessionId: 'conversation-123', title: 'Continue my work', processIdentity: { pid: 98765, executable: 'codex', startMarker: 'old-process' } }
+ const store = new StoppedAgentStore(join(directory, 'stopped-agents'))
+ return { registry, StoppedAgentStore, saved, store }
+}
+
+describe('stopped harness persistence', () => {
+ it('retains the conversation and launch profile after removal and store reload', async () => {
+ const { registry, StoppedAgentStore, saved, store } = await fixture()
+ store.save(saved)
+ registry.removeAgent(saved.agentId)
+ const restored = new StoppedAgentStore(join(directory, 'stopped-agents')).get(saved.agentId)!
+ expect(restored).toMatchObject({ agentId: saved.agentId, sessionId: 'conversation-123', engine: 'codex', cwd: '/tmp/work', codexHome: '/tmp/profile', dsh: 'autonomous/fixture', permissionMode: 'plan', active: false })
+ expect(registry.list()).toHaveLength(0)
+ expect(registry.advertised()).toHaveLength(0)
+ expect(store.available([])).toHaveLength(1)
+ expect(statSync(join(directory, 'stopped-agents', `${saved.agentId}.json`)).mode & 0o777).toBe(0o600)
+ })
+
+ it('hides a running identity or conversation, without discarding its archive', async () => {
+ const { saved, store } = await fixture()
+ store.save(saved)
+ expect(store.available([saved])).toEqual([])
+ expect(store.available([{ ...saved, agentId: 'another-agent' }])).toEqual([])
+ expect(store.available([{ ...saved, agentId: 'another-agent', codexHome: '/other/profile' }])).toHaveLength(1)
+ expect(store.available([])).toHaveLength(1)
+ })
+
+ it('stopping the shell left by an exited engine preserves its conversation', async () => {
+ const { saved, store } = await fixture()
+ store.save(saved)
+ store.save({ ...saved, engine: 'terminal', sessionId: '', codexHome: null, dsh: null })
+ expect(store.get(saved.agentId)).toMatchObject({ engine: 'codex', sessionId: 'conversation-123', codexHome: '/tmp/profile' })
+ })
+
+ it('resumes on a new route with the same identity and refuses a duplicate claim', async () => {
+ const { registry, saved, store } = await fixture()
+ store.save(saved)
+ registry.removeAgent(saved.agentId)
+ const resumed = registry.resumePendingAgent(store.get(saved.agentId)!, [{ backend: 'tmux', paneId: '%99' }])!
+ expect(resumed).toMatchObject({ agentId: saved.agentId, sessionId: saved.sessionId, tmuxPane: '%99', processIdentity: null, launch: { state: 'starting' }, permissionMode: 'plan', codexHome: '/tmp/profile' })
+ expect(registry.resumePendingAgent(saved, [{ backend: 'tmux', paneId: '%100' }])).toBeNull()
+ expect(registry.advertised()).toHaveLength(1)
+ })
+
+ it('does not follow a planted archive symlink or overwrite unsafe state', async () => {
+ const { saved, store } = await fixture()
+ store.save(saved)
+ const file = join(directory, 'stopped-agents', `${saved.agentId}.json`)
+ const other = join(directory, 'other.json')
+ writeFileSync(other, 'untouched', { mode: 0o600 })
+ rmSync(file)
+ symlinkSync(other, file)
+ expect(() => store.get(saved.agentId)).toThrow()
+ expect(() => store.save(saved)).toThrow()
+ expect(readFileSync(other, 'utf8')).toBe('untouched')
+ rmSync(file)
+ store.save(saved)
+ chmodSync(file, 0o666)
+ expect(() => store.get(saved.agentId)).toThrow()
+ })
+})
diff --git a/cli/src/lib/stoppedAgents.ts b/cli/src/lib/stoppedAgents.ts
new file mode 100644
index 000000000..448d47132
--- /dev/null
+++ b/cli/src/lib/stoppedAgents.ts
@@ -0,0 +1,74 @@
+/** Stopped work is durable history, separate from the registry of live terminal routes. */
+import { readdirSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { env } from '../config/env.js'
+import { isTerminalEngine } from '../engines/types.js'
+import { atomicWriteJson, projectDisplayName, strictPersistedRow, type RegisteredSession } from './registry.js'
+import { readPrivateStateFile, secureStateDirectory } from './secureState.js'
+
+const SAFE_ID = /^[a-zA-Z0-9_-]{1,128}$/
+export class StoppedAgentStore {
+ constructor(private readonly directory = join(env.ADAPTER_DATA_DIR, 'stopped-agents')) {}
+
+ get(agentId: string): RegisteredSession | null {
+ if (!SAFE_ID.test(agentId)) return null
+ try {
+ secureStateDirectory(this.directory, false)
+ const raw = JSON.parse(readPrivateStateFile(join(this.directory, `${agentId}.json`), 1024 * 1024))
+ if (raw.version !== 1) return null
+ const session = strictPersistedRow(raw.session)
+ return session?.agentId === agentId ? session : null
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
+ throw new Error('Could not read the saved stopped harness.')
+ }
+ }
+
+ list(): RegisteredSession[] {
+ try {
+ secureStateDirectory(this.directory, false)
+ return readdirSync(this.directory).filter(name => name.endsWith('.json')).flatMap(name => {
+ try {
+ const saved = this.get(name.slice(0, -5))
+ return saved ? [saved] : []
+ } catch {
+ // One unreadable record must not hide the other saved harnesses.
+ return []
+ }
+ })
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []
+ throw error
+ }
+ }
+
+ save(session: RegisteredSession): void {
+ 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
+ secureStateDirectory(dirname(this.directory))
+ secureStateDirectory(this.directory)
+ const snapshot = {
+ ...session,
+ active: false,
+ launch: { state: 'ready' },
+ defaultName: projectDisplayName(session),
+ updatedAt: Date.now(),
+ }
+ // Herdr-only snapshots omit the legacy alias just like registry persistence.
+ if (!snapshot.tmuxPane) delete (snapshot as Partial<RegisteredSession>).tmuxPane
+ atomicWriteJson(join(this.directory, `${session.agentId}.json`), { version: 1, session: snapshot })
+ }
+
+ /** Suppress archives whose identity or conversation is already running. */
+ available(live: readonly RegisteredSession[]): RegisteredSession[] {
+ const ids = new Set(live.map(session => session.agentId))
+ const conversations = new Set(live.filter(session => session.sessionId).map(session =>
+ `${session.engine}\0${session.codexHome ?? ''}\0${session.sessionId}`))
+ return this.list().filter(session => !ids.has(session.agentId)
+ && (!session.sessionId || !conversations.has(`${session.engine}\0${session.codexHome ?? ''}\0${session.sessionId}`)))
+ }
+}
+
+export const stoppedAgents = new StoppedAgentStore()
diff --git a/desktop/design/agent-lifecycle-map.md b/desktop/design/agent-lifecycle-map.md
new file mode 100644
index 000000000..70f2e71dd
--- /dev/null
+++ b/desktop/design/agent-lifecycle-map.md
@@ -0,0 +1,181 @@
+# Harness requests and Claude Code / Codex actions
+
+Source review: 2026-09-20, `worktree-command-box`. This describes the current
+working tree. `agent_resume`, the stopped-harness archive, and
+`agents_list.includeStopped` are local changes under review, not existing
+released protocol guarantees. Commands below omit profile, permissions,
+provider, installation and shell-wrapper arguments. A partial resume draft was
+already loaded into the local review build during the earlier work. The user
+has now requested this review before further resume implementation; this
+review changes documentation only.
+
+## Three identities
+
+- `agentId` identifies the Harness row that clients address.
+- `sessionId` identifies the Claude Code or Codex conversation. A session
+ rotation can change it without changing the Harness row or tab.
+- The process identity and terminal route identify the running CLI and its
+ pane. Restart replaces the process; resuming a stopped harness allocates a
+ new pane while retaining the Harness and conversation IDs.
+
+The registry has separate process, route and conversation indexes. A running
+CLI can be idle, working, or waiting for input; these are turn states, not
+evidence that the process is stopped.
+
+## Request mapping
+
+These are client-to-daemon requests, answered with `<request>_result`. The
+three pushes discussed below run in the opposite direction.
+
+| Request | tmux action | Claude Code / Codex action | Registry and persisted state |
+| --- | --- | --- | --- |
+| `agent_create` | `new-session -d`: new session and initial pane | Launch `claude [prompt]` / `codex [prompt]`; install a missing executable through the existing launch wrapper | `openPendingAgent` creates a new Harness ID with the new route, saved launch settings, `launch: starting`, and no engine conversation yet. Hooks/discovery bind `sessionId` and the process identity. |
+| `agent_delete` | **`kill-session` for the session containing the registered pane** | In parallel, validate the engine PID identity; SIGTERM if still alive, then SIGKILL after the grace period if needed | Remove the live row and its route/process/conversation indexes through `removeAgent`; clear runtime tracking. Vendor history, recaps and name overrides remain. The local resume draft additionally saves a durable archive **before removal**. |
+| `agent_restart` | Enable `remain-on-exit`; terminate the engine; `respawn-pane -k` in the existing pane | `claude --resume ID` / `codex resume ID` when known; existing fallback can launch fresh | Retain Harness ID and route. Hold reconciliation during replacement; update process identity and provider observations, then persist. A fresh fallback's new conversation is bound by a later hook. No missing-pane recreation. |
+| `agent_fork` | New session and pane; source untouched | `claude --resume ID --fork-session` / `codex fork ID` | New pending row and Harness ID, initially carrying `forkedFrom`; bind the newly forked engine conversation later. Source row remains. |
+| `agent_retarget` | Existing pane, same process-swap mechanism as restart | Relaunch with changed provider/grid configuration and native resume arguments | Retain Harness ID and route; replace process identity, save the new grid launch configuration and any remembered subscription model. Inherits restart's possible fresh fallback. |
+| `agent_update` with `name` | `select-pane -T` changes the pane title | No native conversation rename command | `registry.rename` persists a name override keyed by engine `sessionId`, or `agentId` before a session is bound. Does not replace the row, process or conversation. |
+| `agent_update` with `selectedModel` | Send terminal input in the existing pane | Claude `/model <model>` and `/effort <effort>`; Codex `/model` menus | Keep registry identity, route and process. Runtime profile state/observations are updated and announced; no lifecycle row replacement. |
+| `agents_list` | No mutation | None | Reads `registry.advertised()` (verified available terminal routes). The draft's `includeStopped` merges eligible archive records into the response without adding stale routes back to the live registry. |
+| `agent_create_status` | No mutation | None | Reads a separate durable operation receipt, optionally resolving its resulting live row. Does not launch or recreate a registry entry. |
+| `agent_recent` | No mutation | None | Resolves Harness ID to engine `sessionId` and reads stored recaps/recent user asks. Current provider uses the live registry; the draft still needs archive lookup for sessions with no live row. |
+| `agent_files` | No mutation | None | Reads the live row's `cwd`, then lists project files. No registry change. |
+| `agent_read_file` | No mutation | None | Reads the live row's `cwd`, then a bounded project file/media chunk. No registry change. |
+| `agent_resume` **(proposed contract; partial local draft)** | Keep a verified running runtime; otherwise allocate a new session and pane for saved work | `claude --resume <savedSessionId>` / `codex resume <savedSessionId>`; no fresh fallback | If running, return the existing row. Otherwise restore the **same Harness ID and conversation ID** into the live registry using a new route, cleared old process identity and `launch: starting`; bind the new process when observed. Keep the durable saved record available for failures and future resumes. |
+
+
+Harness normally creates one tmux session per harness, initially with one
+pane. The app's multi-pane layout displays these runtimes; selecting an
+existing harness adds or focuses a view rather than starting another CLI.
+The implementation of `kill` still targets the **whole tmux session**. Any
+additional windows/panes in that session would close too. This corrects the
+earlier description of `agent_delete` as killing only one pane; the exact
+command is in [`tmuxBackend.ts`](../../cli/src/lib/tmuxBackend.ts).
+
+For restart, a removed registry row yields `AGENT_NOT_FOUND`. If the stale
+row still has a missing pane, the `remain-on-exit` step fails and restart
+returns a failure before signalling the saved engine. If the pane disappears
+later, respawn also fails. Restart never calls `agent_delete` and never
+allocates a replacement tmux session.
+
+`agent_pause` is not implemented. No native pause operation is wired here.
+
+Request dispatch lives in [`backendSocket.ts`](../../cli/src/backendSocket.ts).
+The daemon callbacks live in [`cli.ts`](../../cli/src/cli.ts). Exact resume and
+fork argv are in [`engineLaunch.ts`](../../cli/src/lib/engineLaunch.ts).
+Process replacement and fallback are in
+[`restartAgent.ts`](../../cli/src/lib/restartAgent.ts); strict stopped resume is
+in [`resumeStoppedAgent.ts`](../../cli/src/lib/resumeStoppedAgent.ts).
+In-process model changes are in
+[`runtimeProfileController.ts`](../../cli/src/lib/runtimeProfileController.ts).
+
+## Registry design to review
+
+The live registry is persisted, but it is an index of runtimes and their
+current conversation bindings, not a complete history of every conversation.
+The resume draft adds a separate durable saved-session store. Old pane IDs and
+PIDs can be retained there as historical evidence, but must not be reinserted
+as live routes/processes when resuming.
+
+The proposed stop/resume transition is:
+
+1. Save the Harness ID, engine conversation ID, cwd, name, profile and launch
+ settings before removing the live row.
+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
+ create a new runtime and associate it with the same saved identity.
+4. Confirm startup separately from pane allocation. Failure retains the saved
+ session and reports an error, without silently starting fresh.
+
+There is a related existing transition to resolve: when the engine exits but
+its shell survives, `releaseEngine` retains the row/route as a Terminal and
+clears its conversation binding, PID and observed model/provider fields.
+The draft archives before this conversion, but currently hides that archive
+because a live row has the same Harness ID. The finished design must preserve
+access to the original conversation while distinguishing the surviving shell
+from the running engine. This is still under review.
+
+A rename uses the separate name-override file, so it outlives removal from the
+live registry. A new conversation created through `/clear` or `/new` rebinds
+the existing Harness row to a different engine `sessionId`; it need not change
+the app tab, Harness ID or tmux route.
+
+## Turn actions and events are separate
+
+| Action or event | What this code does |
+| --- | --- |
+| `message` | Types the prompt into the existing terminal and submits Enter. Transcript/hook events report the resulting turn. |
+| `cancel` | Sends Ctrl-C through the input queue and closes Harness's busy bookkeeping. Intended to interrupt the turn, not implement process pause/resume. |
+| Terminal attach/detach | Connects or disconnects a terminal viewer. Detaching is separate from stopping the CLI. |
+| Claude `SessionStart` / catch hooks | Bind the engine conversation and transcript to a discovered or pending Harness row. |
+| Claude `Stop` / `StopFailure` | Close the turn, with an error indication for failure. They do not mean the CLI process exited. |
+| Claude `SessionEnd` | Requests reconciliation. Process discovery decides whether the engine actually exited; this hook alone does not remove the Harness. |
+| Codex `task_started` / user-message events | Feed turn tracking. In the normalizer, `task_started` marks a pending task and the user-message event opens `turn_started`. |
+| Codex `task_complete` / `turn_aborted` | Close the open turn as `turn_ended`. They do not imply process death. |
+| Engine process exits while its shell survives | `onDormant` calls `releaseEngine`: the existing row becomes a live **Terminal**, clearing its current engine-session binding. The new archive captures the conversation before that conversion. |
+| Terminal route disappears | Reconciliation removes the live row. The new archive retains its saved resume information. |
+
+Evidence: [`notify.mjs`](../../cli/hook/notify.mjs),
+[`codex/normalizer.ts`](../../cli/src/engines/codex/normalizer.ts),
+[`sessionInput.ts`](../../cli/src/lib/sessionInput.ts), and
+[`registry.ts`](../../cli/src/lib/registry.ts).
+
+| Daemon push | Meaning for clients | tmux / engine action caused by the push |
+| --- | --- | --- |
+| `agent_synced` | Upsert the current Harness row, including identity, launch state and terminal availability. Used for newly observed and updated agents. | None; reports a change already observed or performed. |
+| `agent_deleted` | Remove the row/view from the receiving client's live inventory. The draft's `retained` flag tells desktop to reload the stopped catalog. | None. It is not itself a kill command or proof that the engine exited; terminal unavailability can also produce it. |
+| `agent_renamed` | Update the Harness display name. | None; name/title mutation happened separately. |
+
+For example, `agent_synced` can report an engine becoming a live Terminal in
+desktop, while the device receives `agent_deleted` because it does not list
+bare terminals.
+
+## Consequences for Cmd-P/T
+
+1. All saved harness sessions use the same row presentation, enter symbol and
+ Open action. Running/stopped is backend state, with no Stopped badge or
+ special Resume action. Enter on a verified running engine attaches to it.
+2. Enter on a retained stopped conversation should use `agent_resume` directly.
+ `agent_restart` is unsuitable because its existing contract permits fresh
+ fallback. Restoring history does not continue an interrupted tool call or
+ automatically send another prompt.
+3. A CLI that exited into its surviving shell still appears as **Terminal**.
+ The archive currently hides entries with the same live Harness ID, so this
+ case is not yet presented as a stopped Claude/Codex row.
+4. Historical vendor conversations that were never retained by Harness are not
+ populated by `agents_list`. Supporting that requires a separate history
+ import/index rather than merely adding a lifecycle verb.
+5. The current recent-summary providers resolve conversation IDs through the
+ live registry. They also need the archive mapping if stopped rows are to
+ show their saved recaps before being resumed.
+6. Launch allocation and confirmed conversation readiness are distinct. The
+ new resume path still uses the generic asynchronous new-pane watcher;
+ an early engine exit becomes a Terminal. A dedicated failed-resume state
+ would make that case clearer than treating allocation as full success.
+7. The draft currently treats any row returned by `registry.byAgent` as
+ attachable. The final resume contract must verify the engine/conversation
+ and runtime, rather than mistake a surviving shell or stale row for the
+ original running agent.
+
+## Resume contract to finish after this review
+
+- A confirmed running instance of the requested conversation: return that
+ runtime for attachment, without restarting it.
+- A retained stopped conversation whose old process is confirmed gone:
+ allocate a new tmux session/pane and run the engine's native resume command.
+ Preserve Harness ID, conversation ID, cwd, profile and launch settings.
+- Repeated requests and lost replies: share one operation receipt and one
+ per-agent launch, rather than create another process.
+- Missing history, an unconfirmed old process, or failed startup: report the
+ specific state. Never silently start a new conversation or overwrite a
+ live terminal. Enter needs no confirmation.
+- A surviving shell remains a separate design case: it must not be reported
+ as successful attachment to the original engine. The existing row-to-
+ terminal conversion and archive visibility need to be resolved together.
+- Publish progress through `agent_synced`; creating a pane alone does not
+ prove that the engine resumed the requested conversation.
+
+If a Pause action is added, its product contract should distinguish stopping
+the CLI while retaining the conversation from interrupting a turn. Neither
+turn completion nor an idle CLI should automatically be labelled paused.
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index 27e4edcc7..61633643b 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -326,6 +326,8 @@ class Agent {
this.namedAgent,
});
+ bool get isStopped => status == 'stopped';
+
/// 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)
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index cb9f99701..78d386421 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -1879,14 +1879,44 @@ class _SwarmScreenState extends State<SwarmScreen> {
return;
}
_preparePaneFocus();
- final opened = await activateSwarmSearchSelection(
- app,
- selected,
- destinationSwarmId: target,
- projects: _projects.projects,
- split: split,
- placement: placement,
- );
+ bool opened;
+ try {
+ opened = await activateSwarmSearchSelection(
+ app,
+ selected,
+ destinationSwarmId: target,
+ projects: _projects.projects,
+ split: split,
+ placement: placement,
+ );
+ } on SwarmResumeFailure catch (failure) {
+ if (!mounted) return;
+ final row = failure.destination;
+ final agent = app
+ .stateOf(row.machineId!)
+ ?.agents
+ .where((agent) => agent.id == row.agentId)
+ .firstOrNull;
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(
+ content: Text(failure.message),
+ action: SnackBarAction(
+ label: 'Start New Conversation',
+ onPressed: () => _openNewHarness(
+ machineId: row.machineId!,
+ engine: agent?.dsh ?? agent?.engine,
+ folder: agent?.project?.cwd,
+ swarmId: app.swarms.any((tab) => tab.id == target)
+ ? target
+ : app.activeSwarmId,
+ placement: placement,
+ task: '',
+ ),
+ ),
+ ),
+ );
+ return;
+ }
if (!opened && mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 7599dd39b..c7967a25f 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -3883,6 +3883,7 @@ class AppNotifier extends ChangeNotifier {
try {
final response = await connection.request(
'agents_list',
+ payload: const {'includeStopped': true},
timeout: const Duration(seconds: 10),
);
if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) {
@@ -4473,7 +4474,7 @@ class AppNotifier extends ChangeNotifier {
payload: {
'agentId': agentId,
'gridModel': modelId,
- if (gridName != null) 'gridName': gridName,
+ 'gridName': ?gridName,
},
timeout: const Duration(seconds: 30),
);
@@ -4807,6 +4808,7 @@ class AppNotifier extends ChangeNotifier {
);
final response = await connection.request(
'agents_list',
+ payload: const {'includeStopped': true},
timeout: remaining,
);
if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) {
@@ -6800,6 +6802,27 @@ class AppNotifier extends ChangeNotifier {
return true;
}
+ /// Attach to a running harness or resume its saved conversation immediately.
+ Future<RestartAgentResult> resumeAgent(String machineId, String agentId) {
+ final agent = stateOf(machineId)?.agents
+ .where((agent) => agent.id == agentId)
+ .firstOrNull;
+ if (agent?.terminalAvailable == true) {
+ return Future.value(const RestartAgentResult());
+ }
+ if (agent?.isStopped != true) {
+ return Future.value(
+ const RestartAgentResult(
+ error: 'The saved harness is no longer available. Search again.',
+ retryable: false,
+ ),
+ );
+ }
+ // Resume shares the receipt coordinator, while sending its own lifecycle
+ // command. Repeated Enter checks the existing intent instead of relaunching.
+ return restartAgent(machineId, agentId);
+ }
+
/// Restart keeps the agent, every view and the current focus. Only explicit
/// new intent can repeat a request whose outcome is still unknown.
Future<RestartAgentResult> restartAgent(
@@ -6864,13 +6887,20 @@ class AppNotifier extends ChangeNotifier {
attempt._startedRevision = machine._agentRevision;
}
attempt._awaitingConfirmation = true;
- const unknown = RestartAgentResult(
- error: 'The restart is not confirmed yet. Check status, or close this prompt to inspect the terminal before restarting again.',
+ final resuming = attempt.agent?.isStopped == true;
+ final unknown = RestartAgentResult(
+ error: resuming
+ ? 'Still waiting for the resume response. Select the harness again to check status.'
+ : 'The restart is not confirmed yet. Check status, or close this prompt to inspect the terminal before restarting again.',
);
Map<String, dynamic> result;
try {
result = await _conn(machineId).request(
- checking ? 'agent_create_status' : 'agent_restart',
+ checking
+ ? 'agent_create_status'
+ : resuming
+ ? 'agent_resume'
+ : 'agent_restart',
payload: {'creationId': attempt._id, if (!checking) 'agentId': agentId},
);
} catch (_) {
@@ -6902,8 +6932,10 @@ class AppNotifier extends ChangeNotifier {
}
switch (result['state']) {
case 'pending':
- return const RestartAgentResult(
- error: 'The machine is still restarting the agent. Check again in a moment.',
+ return RestartAgentResult(
+ error: resuming
+ ? 'The machine is still resuming the harness. Select it again in a moment.'
+ : 'The machine is still restarting the agent. Check again in a moment.',
);
case 'missing':
case 'unconfirmed':
@@ -8917,7 +8949,11 @@ class AppNotifier extends ChangeNotifier {
final agentId = _eventAgentId(machine, event, payload);
if (agentId != null) {
await _removeAgent(machine, agentId);
- } else {
+ }
+ // Only a daemon that retained this stop asks us to refresh history.
+ // A legacy deletion must not race a newly reused identity with an
+ // unnecessary inventory request.
+ if (agentId == null || payload['retained'] == true) {
unawaited(_loadMachineData(machine, force: true));
}
break;
diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dart
index 1fe61c063..94ff2030b 100644
--- a/desktop/lib/state/swarm_navigation.dart
+++ b/desktop/lib/state/swarm_navigation.dart
@@ -330,6 +330,31 @@ class SwarmDestination {
enum SwarmSearchAction { open, addHere }
+class SwarmResumeFailure implements Exception {
+ const SwarmResumeFailure(this.destination, this.message);
+ final SwarmDestination destination;
+ final String message;
+}
+
+Future<void> _resumeStoppedDestination(
+ AppNotifier app,
+ SwarmDestination destination,
+) async {
+ final machineId = destination.machineId;
+ final agentId = destination.agentId;
+ if (machineId == null || agentId == null) return;
+ final agent = app
+ .stateOf(machineId)
+ ?.agents
+ .where((agent) => agent.id == agentId)
+ .firstOrNull;
+ if (agent?.isStopped != true) return;
+ final result = await app.resumeAgent(machineId, agentId);
+ if (result.error case final error?) {
+ throw SwarmResumeFailure(destination, error);
+ }
+}
+
({String text, String terminalText, int? branchOffset}) _harnessDetail(
String? type,
AgentProject? project,
@@ -678,7 +703,10 @@ Future<bool> activateSwarmSearchSelection(
final hasView = app.allPanes.any(
(pane) => pane.machineId == machineId && pane.agentId == agentId,
);
- if (agent == null || (!agent.terminalAvailable && !hasView)) return false;
+ if (agent == null ||
+ (!agent.terminalAvailable && !agent.isStopped && !hasView)) {
+ return false;
+ }
var target = app.swarms
.where((tab) => tab.id == destinationSwarmId)
.firstOrNull;
@@ -692,9 +720,20 @@ Future<bool> activateSwarmSearchSelection(
if (!existing && target.panes.length >= AppNotifier.maxPanes) {
return false;
}
+ }
+ await _resumeStoppedDestination(app, destination);
+ if (placement == HarnessPlacement.currentTab) {
+ if (!app.swarms.contains(target) ||
+ (target!.panes.length >= AppNotifier.maxPanes &&
+ !target.panes.any(
+ (pane) =>
+ pane.machineId == machineId && pane.agentId == agentId,
+ ))) {
+ return false;
+ }
} else {
- // Validation precedes allocation, and allocation precedes the first
- // network wait. A stale row cannot leave an empty tab behind.
+ // Validate and resume before allocation, so a stale row or a failed
+ // resume cannot leave an empty tab behind.
app.newSwarm();
target = app.activeSwarm;
}
@@ -744,6 +783,10 @@ Future<bool> activateSwarmSearchSelection(
}
// Validate the complete selection before recording any membership. Every
// add records its destination synchronously, before attachment can wait.
+ for (final row in members) {
+ await _resumeStoppedDestination(app, row);
+ }
+ if (!app.swarms.contains(target)) return false;
await Future.wait([
for (final row in members)
app.addAgentToSwarm(row.machineId!, row.agentId!, swarmId: target.id),
@@ -803,6 +846,10 @@ Future<bool> activateSwarmSearchSelection(
}
// Every membership is recorded before awaiting any attachment. A slow
// machine cannot retarget the add or hold up the other agents.
+ for (final row in members) {
+ await _resumeStoppedDestination(app, row);
+ }
+ if (!app.swarms.contains(target)) return false;
await Future.wait([
for (final row in members)
app.addAgentToSwarm(row.machineId!, row.agentId!, swarmId: target.id),
@@ -825,6 +872,11 @@ Future<bool> activateSwarmSearchSelection(
.where((e) => e.id == destination.id)
.firstOrNull;
if (live == null) return false;
+ await _resumeStoppedDestination(app, live);
+ if (!app.swarms.any((s) => s.id == destinationSwarmId) ||
+ (split != null && !app.isPaneSplitCurrent(split))) {
+ return false;
+ }
await app.assignAgentToPane(
null,
destination.machineId!,
@@ -1061,7 +1113,11 @@ List<SwarmDestination> swarmDestinations(
for (final id in {...owners.keys, if (!openOnly) ...agents.keys}) {
final memberships = owners[id] ?? const <Swarm>[];
final row = agents[id];
- if (memberships.isEmpty && row?.$2.terminalAvailable != true) continue;
+ if (memberships.isEmpty &&
+ row?.$2.terminalAvailable != true &&
+ row?.$2.isStopped != true) {
+ continue;
+ }
Swarm? owner;
var ownerRank = 1000;
for (final candidate in memberships) {
@@ -1289,10 +1345,12 @@ Future<bool> activateSwarmDestination(
final agent = app.machineStates[destination.machineId]?.agents
.where((a) => a.id == destination.agentId)
.firstOrNull;
- if (agent?.terminalAvailable != true ||
+ if ((agent?.terminalAvailable != true && agent?.isStopped != true) ||
!app.swarms.any((s) => s.id == destinationSwarmId)) {
return false;
}
+ await _resumeStoppedDestination(app, destination);
+ if (!app.swarms.any((s) => s.id == destinationSwarmId)) return false;
await app.addAgentToSwarm(
destination.machineId!,
destination.agentId!,
diff --git a/desktop/test/stopped_harness_test.dart b/desktop/test/stopped_harness_test.dart
new file mode 100644
index 000000000..544dbb6c2
--- /dev/null
+++ b/desktop/test/stopped_harness_test.dart
@@ -0,0 +1,189 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/state/swarm_search.dart';
+
+import 'support/restart_connection.dart';
+import 'swarm_interactions_test.dart' show chord;
+import 'swarm_screen_test.dart' show mount;
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late AppNotifier app;
+ late RestartConnection connection;
+ const stopped = Agent(
+ id: 'saved',
+ name: 'Saved work',
+ engine: 'codex',
+ sessionId: 'original-conversation',
+ status: 'stopped',
+ project: AgentProject(name: 'Project', cwd: '/work/project'),
+ );
+ setUp(() {
+ connection = RestartConnection();
+ app = createApp(connectionForTest: (_) => connection);
+ app.machineStates['m']!.agents.add(stopped);
+ });
+ tearDown(() => app.dispose());
+
+ SwarmDestination row() =>
+ swarmDestinations(app).firstWhere((row) => row.agentId == stopped.id);
+
+ test('stopped harnesses remain searchable alongside live ones', () {
+ final rows = swarmDestinations(app);
+ expect(rows.any((row) => row.agentId == 'a0'), isTrue);
+ expect(row().detail, isNot(contains('Stopped')));
+ expect(row().terminalDetail, isNot(contains('Stopped')));
+ expect(row().promptContext?.leading, isNot('Stopped'));
+ expect(SwarmSearchController.action(row()), 'Open Harness');
+ final picker = SwarmSearchController(app, const [], adding: true);
+ addTearDown(picker.dispose);
+ expect(
+ picker.actionLabel(row()),
+ picker.actionLabel(rows.firstWhere((row) => row.agentId == 'a0')),
+ );
+ expect(rankSwarmDestinations(rows, 'saved').single.agentId, 'saved');
+ expect(app.allPanes, isEmpty);
+ expect(connection.requests, isEmpty);
+ });
+
+ test(
+ 'a retained stop refreshes the saved row after closing its live view',
+ () async {
+ connection.inventory = Completer<Map<String, dynamic>>();
+ await app.handleEventForTest('m', {
+ 'type': 'agent_deleted',
+ 'payload': {'agentId': 'a0', 'retained': true},
+ });
+ connection.inventory!.complete({
+ 'agents': [
+ {
+ 'id': 'a0',
+ 'name': 'Stopped now',
+ 'engine': 'codex',
+ 'sessionId': 'original-conversation',
+ 'status': 'stopped',
+ 'terminal': {'available': false},
+ },
+ ],
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(app.stateOf('m')!.agents.single.isStopped, isTrue);
+ expect(swarmDestinations(app).any((row) => row.agentId == 'a0'), isTrue);
+ expect(app.allPanes, isEmpty);
+ },
+ );
+
+ for (final placement in HarnessPlacement.values) {
+ test('Enter resumes directly before opening ${placement.name}', () async {
+ final target = app.activeSwarmId;
+ final opening = activateSwarmSearchSelection(
+ app,
+ SwarmSearchSelection(row()),
+ destinationSwarmId: target,
+ placement: placement,
+ );
+ expect(connection.requests, hasLength(1));
+ final request = connection.requests.single;
+ expect(connection.types, ['agent_resume']);
+ expect(request['agentId'], 'saved');
+ expect(app.allPanes, isEmpty);
+ connection.restartReplies.single.complete(
+ restartReceipt(
+ request['creationId'] as String,
+ agentId: 'saved',
+ sessionId: 'original-conversation',
+ ),
+ );
+ expect(await opening, isTrue);
+ expect(app.allPanes.single.agentId, 'saved');
+ expect(
+ app.stateOf('m')!.agents.firstWhere((a) => a.id == 'saved').isStopped,
+ isFalse,
+ );
+ });
+ }
+
+ test(
+ 'a failed resume retains saved work and allocates no empty tab',
+ () async {
+ final tabs = app.swarms.length;
+ final opening = activateSwarmSearchSelection(
+ app,
+ SwarmSearchSelection(row()),
+ destinationSwarmId: app.activeSwarmId,
+ placement: HarnessPlacement.newTab,
+ );
+ final refusal = expectLater(opening, throwsA(isA<SwarmResumeFailure>()));
+ connection.restartReplies.single.complete({
+ 'creationId': connection.requests.single['creationId'],
+ 'state': 'failed',
+ 'failure': {
+ 'code': 'RESUME_UNAVAILABLE',
+ 'detail': 'Conversation missing',
+ },
+ });
+ await refusal;
+ expect(app.swarms, hasLength(tabs));
+ expect(app.allPanes, isEmpty);
+ expect(row().agentId, 'saved');
+ expect(connection.requests, hasLength(1));
+ },
+ );
+
+ test(
+ 'Enter on a running harness attaches without a restart request',
+ () async {
+ final active = swarmDestinations(app)
+ .firstWhere((row) => row.agentId == 'a0');
+ expect(
+ await activateSwarmSearchSelection(
+ app,
+ SwarmSearchSelection(active),
+ destinationSwarmId: app.activeSwarmId,
+ placement: HarnessPlacement.currentTab,
+ ),
+ isTrue,
+ );
+ expect(app.allPanes.single.agentId, 'a0');
+ expect(connection.requests, isEmpty);
+ },
+ );
+
+ testWidgets('Enter submits resume immediately with no confirmation dialog', (
+ tester,
+ ) async {
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyT);
+ await tester.pump();
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ 'Saved work',
+ );
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(connection.types, ['agent_resume']);
+ expect(find.byType(AlertDialog), findsNothing);
+ connection.restartReplies.single.complete({
+ 'creationId': connection.requests.single['creationId'],
+ 'state': 'failed',
+ 'failure': {
+ 'code': 'RESUME_UNAVAILABLE',
+ 'detail': 'Conversation missing',
+ },
+ });
+ await tester.pump();
+ expect(find.text('Conversation missing'), findsOneWidget);
+ expect(find.text('Start New Conversation'), findsOneWidget);
+ expect(app.allPanes, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ });
+}
diff --git a/desktop/test/support/restart_connection.dart b/desktop/test/support/restart_connection.dart
index 8f6786868..560edf058 100644
--- a/desktop/test/support/restart_connection.dart
+++ b/desktop/test/support/restart_connection.dart
@@ -5,6 +5,7 @@ import 'stop_connection.dart';
/// Controlled receipts only; never opens a connection or starts a process.
class RestartConnection extends StopConnection {
final requests = <Map<String, dynamic>>[];
+ final types = <String>[];
final restartReplies = <Completer<Map<String, dynamic>>>[];
final checks = <Map<String, dynamic>>[];
final checkReplies = <Completer<Map<String, dynamic>>>[];
@@ -15,9 +16,12 @@ class RestartConnection extends StopConnection {
Map<String, dynamic> payload = const {},
Duration timeout = const Duration(seconds: 20),
}) {
- if (type == 'agent_restart' || type == 'agent_create_status') {
+ if (type == 'agent_restart' ||
+ type == 'agent_resume' ||
+ type == 'agent_create_status') {
final reply = Completer<Map<String, dynamic>>();
- if (type == 'agent_restart') {
+ if (type == 'agent_restart' || type == 'agent_resume') {
+ types.add(type);
requests.add(Map.of(payload));
restartReplies.add(reply);
} else {