Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Verify saved-session resume and retain exited harnesses

dee507f96a150dc
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 417613a21..9ad730345 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -1536,7 +1536,7 @@ export class BackendSocket {
// 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))))
+ projects.push(...await Promise.all(stoppedAgents.available(registry.advertised()).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
@@ -2297,7 +2297,7 @@ export class BackendSocket {
if (result.ok) return { state: 'created', agentId: result.session.agentId, resumed: result.resumed }
// RESTART_FAILED can follow an unobserved relaunch. Never silently
// replace that process again when a caller checks this intent.
- if (result.error === 'RESTART_FAILED') return { state: 'unconfirmed' }
+ if (result.error === 'RESTART_FAILED' || result.error === 'RESUME_UNCONFIRMED') return { state: 'unconfirmed' }
return { state: 'failed', error: result.error, ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }
}).then(async (status) => {
reply(type, requestId, { creationId, ...await this.creationStatusPayload(status) })
@@ -2537,6 +2537,11 @@ export class BackendSocket {
return status
}
+ async publishStoppedAgent(s: RegisteredSession): Promise<void> {
+ this.send({ type: 'agent_synced', payload: { agent: await this.toStoppedProject(s) } })
+ this.sendCommander({ type: 'agent_deleted', payload: { agentId: s.agentId } })
+ }
+
private async toStoppedProject(s: RegisteredSession): Promise<AgentFrame> {
const frame = await agentFrame(s, { selectedModel: s.model, terminalAvailable: false, dsh: this.dshFrameProvider?.(s) ?? null })
return {
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index b444ab854..d552269e6 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -43,7 +43,7 @@ import { DaemonCableHost, cableEventFor, cableQuestionFor, cableQuestionCloseFor
import { MachineListCache, machineListCachePath, withStaleMarker } from './device/machineList.js'
import { DeviceLink } from './device/deviceLink.js'
import { DeviceFleet } from './device/deviceFleet.js'
-import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
+import { registry, projectDisplayName, validTranscriptPath, type RegisteredSession } from './lib/registry.js'
import { engineSessionTitle } from './lib/sessionTitle.js'
import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installGrokHooks, installAgyHooks, installCopilotHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'
import { PID_FILE, daemonPort, isAlive, isDaemonRunning, readPid } from './lib/daemonState.js'
@@ -85,7 +85,7 @@ 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 { resumeStoppedAgent, waitForResumedAgent, resumeChanged, resumeUnconfirmed } 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'
@@ -107,6 +107,7 @@ import {
permissionModeFromArgv,
clearPaneRemainOnExit,
resolvePaneEngineProcess,
+ checkSessionRuntime,
tmuxPaneState,
} from './lib/tmux.js'
import { HerdrBackend } from './lib/herdrBackend.js'
@@ -2368,8 +2369,8 @@ async function runForeground(session: AuthSession): Promise<void> {
// Recaps are STORED under the engine session id — that is what lets `--resume` bring the last recap
// back under a brand-new agent — but they are ASKED FOR by agent id, which is the only id the device
// and the voice router know. Resolve across the two, or every tile restores empty.
- backend.recentProvider = (id, n) => mirror.recent(registry.resolve(id)?.sessionId || id, n)
- backend.recentAsksProvider = (id, n) => mirror.recentAsks(registry.resolve(id)?.sessionId || id, n)
+ backend.recentProvider = (id, n) => mirror.recent(registry.resolve(id)?.sessionId || stoppedAgents.get(id)?.sessionId || id, n)
+ backend.recentAsksProvider = (id, n) => mirror.recentAsks(registry.resolve(id)?.sessionId || stoppedAgents.get(id)?.sessionId || id, n)
const runtimeController = new RuntimeProfileController({
manager: runtimeProfiles,
@@ -2589,6 +2590,20 @@ async function runForeground(session: AuthSession): Promise<void> {
}
+ /** Retain the conversation's identity; a surviving shell gets its own live identity. */
+ const retainExitedSession = (entry: RegisteredSession, paneAlive: boolean): void => {
+ stoppedAgents.save(entry)
+ const saved = stoppedAgents.get(entry.agentId)!
+ invalidateTerminalControl(entry.agentId)
+ input.forget(entry.agentId)
+ detachDsh(entry.agentId)
+ const terminal = paneAlive ? registry.releaseEngine(entry.agentId, true) : null
+ if (!paneAlive) registry.removeAgent(entry.agentId)
+ syncRecapPool()
+ void backend.publishStoppedAgent(saved).catch(error => console.warn('[resume] could not announce saved harness', error))
+ if (terminal) announceSession(terminal, { device: false })
+ }
+
type RegisteredMeta = {
isNew: boolean
evicted: string | null
@@ -2675,6 +2690,11 @@ async function runForeground(session: AuthSession): Promise<void> {
announceSession(entry)
return
}
+ const confirmed = registry.byAgent(entry.agentId)
+ if (confirmed?.sessionId === entry.sessionId) {
+ stoppedAgents.save(confirmed)
+ if (confirmed.resumeOnly) stoppedAgents.finishResume(confirmed.agentId)
+ }
syncRecapPool()
if (!meta.isNew) return
registry.inheritName(entry.agentId, entry.sessionId)
@@ -2702,6 +2722,7 @@ async function runForeground(session: AuthSession): Promise<void> {
//
// The switch leaves exactly one trace — the `inuse.<pid>.lock` Copilot takes on the new session
// directory. It writes nothing to the transcript and fires no hook until the next prompt.
+ if (agent.resumeOnly && agent.launch && agent.launch.state !== 'ready') return
if (agent.sessionId) {
if (observed.engine === 'copilot') {
const current = await copilotSessionForPid(env.COPILOT_HOME, observed.processIdentity.pid)
@@ -2906,7 +2927,7 @@ async function runForeground(session: AuthSession): Promise<void> {
if (observed.dsh && !current.dsh) registry.setDsh(current.agentId, observed.dsh)
const withDsh = registry.byAgent(current.agentId)
if (withDsh?.dsh) attachDsh(withDsh)
- if (wasLaunching) registry.setLaunch(current.agentId, { state: 'ready' })
+ if (wasLaunching && !current.resumeOnly) registry.setLaunch(current.agentId, { state: 'ready' })
await bindObservedAgent(observed)
if (wasDormant || wasLaunching || adopted) {
const active = registry.byAgent(current.agentId)
@@ -2929,7 +2950,7 @@ async function runForeground(session: AuthSession): Promise<void> {
const refreshed = registry.byAgent(current.agentId)
if (refreshed) announceSession(refreshed)
},
- onDormant: (agent, reason) => {
+ onDormant: async (agent, reason) => {
if (!agent.active) return
invalidateTerminalControl(agent.agentId)
input.forget(agent.agentId)
@@ -2937,24 +2958,19 @@ async function runForeground(session: AuthSession): Promise<void> {
questionWatcher.stop(agent.sessionId)
stopHeartbeat(agent.sessionId)
}
- // The engine has exited and its pane is a shell at its prompt (every launch runs the engine
- // inside the pane's shell — engineLaunch.ts `harness_engine` — and so does a terminal somebody
- // typed it into): the row becomes a terminal — live, not dormant — and the dial, which only
- // ever knew it as an agent, is told it is gone. The app gets the same row with its engine
- // now `terminal` and draws it as one. Not while the launch is still `starting`: a pane with
- // no engine process yet is an install in progress, not an exit, and releasing it would wipe
- // 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`.
+ // Preserve the conversation's public identity and give the surviving shell its own row.
+ // A starting install is not an exited engine; strict uncertain starts keep their reservation.
+ if (agent.resumeOnly && agent.launch?.state === 'failed') {
+ const pane = await tmuxPaneState(agent.tmuxPane)
+ // An unconfirmed install/startup can still be about to launch the engine. Do not
+ // turn its live shell into permission to start another one.
+ if (!pane || (!pane.dead && pane.engineExit == null)) return
+ }
if (agent.launch?.state !== 'starting') {
- stoppedAgents.save(agent)
- const released = registry.releaseEngine(agent.agentId)
- if (released) {
- syncRecapPool()
- console.log(`[discovery] ${sid(agent.agentId)} ${agent.engine} → terminal · ${reason}`)
- announceSession(released, { device: false })
- backendRef?.sendCommander({ type: 'agent_deleted', payload: { agentId: agent.agentId } })
- return
- }
+ retainExitedSession(agent, true)
+ if (agent.resumeOnly) stoppedAgents.finishResume(agent.agentId)
+ console.log(`[discovery] ${sid(agent.agentId)} retained · ${reason}`)
+ return
}
registry.setActive(agent.agentId, false)
console.log(`[discovery] ${sid(agent.agentId)} dormant · ${reason}`)
@@ -3931,9 +3947,14 @@ async function runForeground(session: AuthSession): Promise<void> {
// pass five seconds later would drop the agents for good. Pane creation is awaited so the first
// announce already shows every restored agent with a terminal; binding their engine processes
// continues in the background, the same way `agent_create` does it.
+ for (const entry of registry.list()) {
+ const saved = isTerminalEngine(entry.engine) ? stoppedAgents.get(entry.agentId) : null
+ if (saved && !isTerminalEngine(saved.engine)) retainExitedSession(entry, true)
+ }
if (tmuxBackend) {
const backend = tmuxBackend
const summary = await restoreAgents({
+ retainStopped: retainExitedSession,
registry,
// "Alive" means the pane still runs THIS row's engine — not merely that tmux knows the id.
// A new tmux server hands out `%N` from zero again, so a stale id can name someone's shell;
@@ -4187,9 +4208,14 @@ 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)
+ // A hook may have bound a conversation while this watcher was awaiting its probe.
+ // Archive the current row, not the pre-hook pending snapshot.
+ const row = registry.byAgent(pending.agentId)
+ if (row?.sessionId) retainExitedSession(row, true)
+ else {
+ 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`)
return
}
@@ -4496,7 +4522,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 resumeConversations = new Set<string>()
const sameRestartTarget = (session: RegisteredSession): boolean => {
const current = registry.byAgent(session.agentId)
return !!current && current.registeredAt === session.registeredAt
@@ -4668,6 +4694,7 @@ async function runForeground(session: AuthSession): Promise<void> {
if (!capture) return { ok: false, error: 'TMUX_FAILED' }
if (!inspectRuntimePane(session.engine, capture).idle) return { ok: false, error: 'AGENT_BUSY' }
// Nothing may type into the pane while it is being replaced.
+ if (restartJobs.busy(session.agentId)) return { ok: false, error: 'AGENT_BUSY' }
const release = acquireTerminalControl(session.agentId)
if (!release) return { ok: false, error: 'AGENT_BUSY' }
// The grid's env and argv, config directory written (keyed on the agent, so moving it between
@@ -4777,7 +4804,7 @@ async function runForeground(session: AuthSession): Promise<void> {
/**
* 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
+ * registry entry, and kills its containing tmux session. Exact PID/start-marker validation guards the engine's
* SIGTERM/SIGKILL fallback. Engine conversation files, recaps and the Harness name remain on disk.
*/
const stopJobs = new Map<string, Promise<void>>()
@@ -4786,7 +4813,6 @@ async function runForeground(session: AuthSession): Promise<void> {
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
@@ -4807,8 +4833,9 @@ async function runForeground(session: AuthSession): Promise<void> {
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])
+ const [paneOutcomes, outcome] = await Promise.all([paneStop, processStop])
if (outcome !== 'failed') {
+ if (paneOutcomes.every(result => result.state === 'succeeded')) stoppedAgents.finishResume(sessionId)
clearDeleted(sessionId)
if (s.sessionId) clearDeleted(s.sessionId)
}
@@ -4820,65 +4847,155 @@ async function runForeground(session: AuthSession): Promise<void> {
return job
}
+ const waitForResume = async (saved: RegisteredSession, current: () => boolean) => {
+ const result = await waitForResumedAgent(saved, {
+ current: () => current() && registry.byAgent(saved.agentId)?.tmuxPane === saved.tmuxPane,
+ session: () => registry.byAgent(saved.agentId),
+ process: () => resolvePaneEngineProcess(saved.tmuxPane, saved.engine),
+ pane: () => tmuxPaneState(saved.tmuxPane),
+ sleep: ms => new Promise(resolve => { const timer = setTimeout(resolve, ms); timer.unref?.() }),
+ })
+ if (!current()) return resumeChanged
+ if (result.ok) {
+ await clearPaneRemainOnExit(saved.tmuxPane)
+ if (!current()) return resumeChanged
+ stoppedAgents.finishResume(saved.agentId)
+ announceSession(result.session)
+ } else if (result.error !== 'AGENT_CHANGED') {
+ const row = registry.byAgent(saved.agentId)
+ if (row && row.tmuxPane === saved.tmuxPane) {
+ const failed = registry.setLaunch(row.agentId, { state: 'failed', error: result.error, detail: result.detail })
+ if (failed) announceSession(failed)
+ // A verified exit releases the reservation and keeps the shell/output. Unknown startup
+ // keeps both runtime and reservation; another Enter cannot launch a duplicate process.
+ if (result.error === 'RESUME_FAILED' && (await checkPidRuntime(row)).state === 'gone') {
+ if (!current()) return resumeChanged
+ const pane = await tmuxPaneState(saved.tmuxPane)
+ if (!current()) return resumeChanged
+ retainExitedSession(row, !!pane && !pane.dead)
+ stoppedAgents.finishResume(saved.agentId)
+ }
+ }
+ }
+ return result
+ }
+
const resumeStopped = (agentId: string, current: () => boolean) => resumeStoppedAgent({
live: () => registry.byAgent(agentId),
saved: () => stoppedAgents.get(agentId),
current,
+ checkLive: async entry => {
+ if (!entry.tmuxPane) return { state: 'unknown', reason: 'Only tmux resume is supported.' }
+ const inventory = await listTmuxPanes()
+ if (!inventory.ok) return { state: 'unknown', reason: 'Terminal inventory is unavailable.' }
+ const paneAlive = inventory.panes.some(pane => pane.tmuxPane === entry.tmuxPane)
+ if (isTerminalEngine(entry.engine)) return paneAlive ? { state: 'alive' } : { state: 'gone', reason: 'Shell pane is gone.' }
+ const process = await checkPidRuntime(entry)
+ if (process.state !== 'gone') {
+ if (!paneAlive || process.state === 'unknown') return { state: 'unknown', reason: 'The previous process is not available through its saved terminal.' }
+ return checkSessionRuntime(entry)
+ }
+ if (!entry.processIdentity && paneAlive) return { state: 'unknown', reason: 'The engine has not been identified yet.' }
+ return process
+ },
+ retain: async entry => {
+ const inventory = await listTmuxPanes()
+ if (!inventory.ok) throw new Error('Could not verify the previous terminal. Try again.')
+ if (!current()) return
+ retainExitedSession(entry, inventory.panes.some(pane => pane.tmuxPane === entry.tmuxPane))
+ },
+ waitForReady: saved => waitForResume(saved, current),
canLaunch: async saved => {
await stopJobs.get(agentId)
return !registry.bySession(saved.sessionId) && (await checkPidRuntime(saved)).state === 'gone'
},
launch: async (saved, resumeSessionId) => {
if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
- 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,
+ if (saved.grid && !saved.gridLaunch) return { ok: false, error: 'GRID_CREDENTIAL_REQUIRED', detail: 'The saved provider configuration is unavailable.' }
+ if (saved.dsh && !installedDsh(saved.dsh)) return { ok: false, error: 'INVALID_DSH', detail: 'Install this harness from the Harness Store before resuming it.' }
+ try {
+ if (!saved.cwd || !statSync(saved.cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND', detail: 'The saved project folder is no longer available.' }
+ } catch { return { ok: false, error: 'CWD_NOT_FOUND', detail: 'The saved project folder is no longer available.' } }
+ if (resumeSessionId && (!saved.transcriptPath || !validTranscriptPath(saved.engine, saved.transcriptPath, saved.codexHome ?? undefined))) {
+ return { ok: false, error: 'RESUME_UNAVAILABLE', detail: 'The saved conversation file is unavailable. Start a new conversation separately.' }
}
- // 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 {
+ // Match the registry's globally unique conversation index, including aliases/profiles.
+ const key = saved.sessionId || saved.agentId
+ if (resumeConversations.has(key)) return { ok: false, error: 'AGENT_BUSY' }
+ resumeConversations.add(key)
+ let token: string | null = null
+ let allocationAttempted = false
+ try {
+ // Reserve before preparing history or rewriting launch configuration: an unknown previous
+ // allocation may still have a writer using those files.
+ token = stoppedAgents.beginResume(agentId)
+ if (!token) return resumeUnconfirmed
+ const built = await relaunchOverrides(saved)
+ if (!built.ok) return { ok: false, error: built.error, detail: built.detail }
+ if (!current()) return resumeChanged
+ if (resumeSessionId) {
+ try { prepareSessionResume(saved) } catch {
+ return { ok: false, error: 'RESUME_PREPARATION_FAILED', detail: 'Could not prepare the saved conversation. Its history has been retained.' }
+ }
+ }
+ if (saved.sessionId && registry.bySession(saved.sessionId)) return { ok: false, error: 'AGENT_BUSY' }
+ const { env: launchEnv, extraArgs, clearEnv } = built.overrides
+ const options = {
+ resumeSessionId,
+ bypassPermission: saved.bypassPermission === true,
+ ...(saved.permissionMode ? { permissionMode: saved.permissionMode } : {}),
+ ...(saved.cwd ? { cwd: saved.cwd } : {}),
+ ...(extraArgs.length ? { extraArgs } : {}),
+ ...(clearEnv.length ? { clearEnv } : {}),
+ ...(launchEnv.HARNESS_DSH ? { harnessNode: true } : {}),
+ installIfMissing: enginePathOverride(saved.engine) ? undefined : engineInstallRecipe(saved.engine),
+ }
+ clearDeleted(agentId)
+ if (saved.sessionId) clearDeleted(saved.sessionId)
+ allocationAttempted = true
+ const result = await createAndRegisterPane({
+ tmuxBackend,
+ registry: { openPendingAgent: input => current() ? registry.resumePendingAgent(saved, input.runtimes) : null },
+ maxAttempts: 1,
+ engine: saved.engine,
+ sessionLabel: buildHarnessSessionLabel(saved.engine),
+ argv: buildEngineLaunchArgv(saved.engine, options),
+ ...(Object.keys(launchEnv).length ? { env: launchEnv } : {}),
+ })
+ if (!result.ok) {
+ if (result.error === 'TMUX_UNAVAILABLE') {
+ stoppedAgents.finishResume(agentId, token)
+ return { ok: false, error: result.error, detail: result.detail }
+ }
+ return resumeUnconfirmed
+ }
+ if (!current()) return resumeChanged
+ const { pending, spawned } = result
+ refreshGridWebSearch(pending.agentId, built.overrides)
+ announceSession(pending)
+ if (isTerminalEngine(saved.engine)) {
+ await clearPaneRemainOnExit(spawned.runtime.paneId)
+ if (!current()) return resumeChanged
+ const ready = registry.setLaunch(pending.agentId, { state: 'ready' })!
+ stoppedAgents.finishResume(agentId, token)
+ announceSession(ready)
+ return { ok: true, session: ready, resumed: true }
+ }
if (pending.dsh) attachDsh(pending)
- void watchNewPane(saved.engine, pending, spawned, buildEngineCommandArgv(saved.engine, options), installIfMissing)
+ return await waitForResume(pending, current)
+ } finally {
+ if (token && !allocationAttempted) stoppedAgents.finishResume(agentId, token)
+ resumeConversations.delete(key)
}
- announceSession(pending)
- return { ok: true, session: pending, resumed: true }
},
})
- backend.onResumeAgent = (agentId) => resumeJobs.run(agentId, current => resumeStopped(agentId, current))
+ backend.onResumeAgent = agentId => restartJobs.run(agentId, async current => {
+ await stopJobs.get(agentId)
+ if (!current()) return resumeChanged
+ if (pinnedControls.has(agentId)) return { ok: false, error: 'AGENT_BUSY' }
+ return resumeStopped(agentId, current)
+ }, 'resume')
/**
* Web or device restarted an agent (`agent_restart`): exit the live engine process and relaunch it in
@@ -4900,6 +5017,7 @@ async function runForeground(session: AuthSession): Promise<void> {
* from inside the engine's own terminal since launch).
*/
backend.onRestartAgent = (agentId) => restartJobs.run(registry.resolve(agentId)?.agentId ?? agentId, async (operationCurrent) => {
+ if (stopJobs.has(agentId) || pinnedControls.has(agentId)) return { ok: false, error: 'AGENT_BUSY' }
const session = registry.resolve(agentId)
if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }
if (!session.tmuxPane || !tmuxBackend) return { ok: false, error: 'RESTART_UNSUPPORTED_BACKEND' }
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index 91f94180c..78c1e8802 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -1497,7 +1497,7 @@ describe('registry across a reboot and pane loss', () => {
// 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',
+ engine: 'claude', sessionId: original.sessionId, transcriptPath, tmuxPane: '%22', cwd: '/tmp/demo', processIdentity: processIdentity(122),
})
expect(bound?.entry.agentId).toBe(original.agentId)
expect(bound?.entry.resumeOnly).toBe(true)
@@ -1508,6 +1508,22 @@ describe('registry across a reboot and pane loss', () => {
})
})
+ it('requires the exact resumed session hook; process discovery alone stays starting', async () => {
+ const transcriptPath = join(dataDir, 'resume-target.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ const { registry } = await loadRegistryModule()
+ const original = registerProcess(registry, { engine: 'claude', sessionId: 'resume-target', transcriptPath, tmuxPane: '%21' })!.entry
+ registry.removeAgent(original.agentId)
+ registry.resumePendingAgent(original, [{ backend: 'tmux', paneId: '%22' }])
+ registry.openProcessAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%22' }], processIdentity: processIdentity(122) })
+ expect(registry.byAgent(original.agentId)?.launch?.state).toBe('starting')
+ expect(registry.byAgent(original.agentId)?.lastHookAt).toBe(0)
+ expect(registry.register({ engine: 'claude', sessionId: 'unexpected-new-session', transcriptPath, tmuxPane: '%22', processIdentity: processIdentity(122) })).toBeNull()
+ expect(registry.byAgent(original.agentId)).toMatchObject({ sessionId: 'resume-target', launch: { state: 'failed', error: 'RESUME_SESSION_MISMATCH' } })
+ const confirmed = registry.register({ engine: 'claude', sessionId: 'resume-target', transcriptPath, tmuxPane: '%22', processIdentity: processIdentity(122) })
+ expect(confirmed?.entry).toMatchObject({ agentId: original.agentId, sessionId: 'resume-target', launch: { state: 'ready' } })
+ })
+
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 80055cf3f..7c835e5cc 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -1021,7 +1021,7 @@ class Registry {
existing.cwd = input.cwd ?? existing.cwd
existing.processIdentity = processIdentity
existing.active = true
- if (existing.launch) existing.launch = { state: 'ready' }
+ if (existing.launch && !existing.resumeOnly) existing.launch = { state: 'ready' }
// Only a successful read speaks: an undefined probe (ps failed, /proc unreadable) keeps whatever
// the last good one said rather than silently downgrading a gateway agent to a vendor one.
if (input.gateway !== undefined) existing.gateway = input.gateway
@@ -1176,6 +1176,8 @@ class Registry {
const entry: RegisteredSession = {
...saved,
resumeOnly: true,
+ boundAt: null,
+ lastHookAt: 0,
active: true,
launch: { state: 'starting' },
processIdentity: null,
@@ -1278,6 +1280,14 @@ 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) {
+ this.setLaunch(agentId, { state: 'failed', error: 'RESUME_SESSION_MISMATCH', detail: 'The agent reported a different conversation. The requested conversation is still saved.' })
+ return null
+ }
+ if (!validProcessIdentity(input.processIdentity)) return null
+ }
// `isNew` still means "this SESSION id was not bound here before" — a rotation counts as new, which is
// what makes the caller announce the newly bound session. The agent itself may be long-lived.
const isNew = !existing || existing.sessionId !== sessionId
@@ -1368,7 +1378,7 @@ class Registry {
agent: existing?.agent ?? null,
...(existing?.bypassPermission ? { bypassPermission: true } : {}),
...(existing?.permissionMode ? { permissionMode: existing.permissionMode } : {}),
- ...(existing?.resumeOnly ? { resumeOnly: true } : {}),
+ ...(existing?.resumeOnly ? { resumeOnly: true, launch: { state: 'ready' as const } } : {}),
...(existing?.terminalHost ? { terminalHost: true } : {}),
processIdentity: validProcessIdentity(input.processIdentity) ? input.processIdentity : existing?.processIdentity ?? null,
registeredAt: existing?.registeredAt ?? now,
@@ -1489,11 +1499,16 @@ class Registry {
* pane and its name stay: this is the opposite of dormant, the terminal is live. `terminalHost`
* is set from here on, since that is what the pane now is.
*/
- releaseEngine(agentId: string): RegisteredSession | null {
- const entry = this.agents.get(agentId)
- if (!entry || isTerminalEngine(entry.engine)) return null
- this.drop(entry)
+ releaseEngine(agentId: string, separateShell = false): RegisteredSession | null {
+ const original = this.agents.get(agentId)
+ if (!original || (isTerminalEngine(original.engine) && !separateShell)) return null
+ this.drop(original)
+ this.terminalAvailableAgents.delete(agentId)
+ // The archived conversation owns the original Harness ID. Preserve the physical shell under
+ // a new identity, without sending input, stopping processes or claiming its route twice.
+ const entry = separateShell ? { ...original, agentId: randomUUID(), dsh: null, agent: null, defaultName: this.automaticName('Terminal', new Date()) } : original
this.releaseBinding(entry)
+ delete entry.resumeOnly
entry.engine = 'terminal'
entry.terminalHost = true
entry.processIdentity = null
diff --git a/cli/src/lib/restartAgent.ts b/cli/src/lib/restartAgent.ts
index f7f994d63..9cda084e3 100644
--- a/cli/src/lib/restartAgent.ts
+++ b/cli/src/lib/restartAgent.ts
@@ -45,12 +45,13 @@ export type RestartAgentReply =
/** One process replacement per agent, even across clients and different receipt
* IDs. Stop cancels the work before its next process-changing step. */
export class AgentRestartCoordinator {
- private readonly jobs = new Map<string, { cancelled: boolean; result: Promise<RestartAgentReply> }>()
+ private readonly jobs = new Map<string, { operation: string; cancelled: boolean; result: Promise<RestartAgentReply> }>()
- run(agentId: string, restart: (current: () => boolean) => Promise<RestartAgentReply>): Promise<RestartAgentReply> {
+ run(agentId: string, restart: (current: () => boolean) => Promise<RestartAgentReply>, operation = 'restart'): Promise<RestartAgentReply> {
const existing = this.jobs.get(agentId)
- if (existing) return existing.result
- const job = { cancelled: false, result: null! as Promise<RestartAgentReply> }
+ if (existing) return existing.operation === operation ? existing.result
+ : Promise.resolve({ ok: false, error: 'AGENT_BUSY', detail: 'Another lifecycle operation is changing this harness.' })
+ const job = { operation, cancelled: false, result: null! as Promise<RestartAgentReply> }
const current = () => !job.cancelled && this.jobs.get(agentId) === job
job.result = Promise.resolve().then(async () => {
if (!current()) return { ok: false, error: 'AGENT_CHANGED' } as const
@@ -63,6 +64,8 @@ export class AgentRestartCoordinator {
return job.result
}
+ busy(agentId: string): boolean { return this.jobs.has(agentId) }
+
cancel(agentId: string): void {
const job = this.jobs.get(agentId)
if (job) job.cancelled = true
diff --git a/cli/src/lib/restoreAgents.spec.ts b/cli/src/lib/restoreAgents.spec.ts
index ebeebb665..c4e2a28c4 100644
--- a/cli/src/lib/restoreAgents.spec.ts
+++ b/cli/src/lib/restoreAgents.spec.ts
@@ -476,3 +476,25 @@ describe('restoreAgents — terminals', () => {
expect(h.rows.get('term-1')).toMatchObject({ engine: 'terminal', launch: { state: 'ready' } })
})
})
+
+
+it('retains a missing strict-resume pane for explicit Open after daemon restart', async () => {
+ const entry = row({ resumeOnly: true, launch: { state: 'starting' } })
+ const h = harness([entry])
+ h.deps.retainStopped = vi.fn((saved, _paneAlive) => { h.rows.delete(saved.agentId) })
+ const summary = await restoreAgents(h.deps)
+ expect(h.deps.retainStopped).toHaveBeenCalledWith(entry, false)
+ expect(summary.restored).toEqual([])
+ expect(h.paneCreates).toBe(0)
+ expect(h.respawns).toBe(0)
+})
+
+it('archives an engine that exited while the daemon was down without overwriting its shell', async () => {
+ const entry = row()
+ const h = harness([entry], { alivePanes: ['%3'] })
+ h.deps.retainStopped = vi.fn()
+ await restoreAgents(h.deps)
+ expect(h.deps.retainStopped).toHaveBeenCalledWith(entry, true)
+ expect(h.paneCreates).toBe(0)
+ expect(h.respawns).toBe(0)
+})
diff --git a/cli/src/lib/restoreAgents.ts b/cli/src/lib/restoreAgents.ts
index 2d495b032..c65c881d2 100644
--- a/cli/src/lib/restoreAgents.ts
+++ b/cli/src/lib/restoreAgents.ts
@@ -43,6 +43,8 @@ export type RestoreLaunchResult = RestoreLaunch | { error: string; detail: strin
export const GRID_CREDENTIAL_REQUIRED = 'GRID_CREDENTIAL_REQUIRED'
export interface RestoreAgentsDeps {
+ retainStopped?: (entry: RegisteredSession, paneAlive: boolean) => void
+
registry: {
list(): RegisteredSession[]
byAgent(agentId: string): RegisteredSession | undefined
@@ -155,11 +157,17 @@ export async function restoreAgents(deps: RestoreAgentsDeps): Promise<RestoreSum
// reconciler adopts it by process instead of treating it as an unbound route.
if (!entry.processIdentity) deps.registry.updateProcessIdentity(entry.agentId, engineLive)
} else if (!isTerminalEngine(entry.engine)) {
- deps.registry.releaseEngine(entry.agentId)
+ if (deps.retainStopped) deps.retainStopped(entry, true)
+ else deps.registry.releaseEngine(entry.agentId)
deps.log(`[restore] ${entry.engine} → terminal · agent ${entry.agentId} · its engine exited while the daemon was down`)
}
continue
}
+ if (entry.resumeOnly && deps.retainStopped) {
+ deps.retainStopped(entry, false)
+ summary.skipped.push({ agentId: entry.agentId, reason: 'saved conversation awaits explicit Open' })
+ continue
+ }
// A terminal whose pane is gone comes back as a terminal — never as the engine that was once
// typed into it: that engine's session went with the pane.
if (entry.terminalHost) {
diff --git a/cli/src/lib/resumeStoppedAgent.spec.ts b/cli/src/lib/resumeStoppedAgent.spec.ts
index 7aaef48d9..3d73f4b9e 100644
--- a/cli/src/lib/resumeStoppedAgent.spec.ts
+++ b/cli/src/lib/resumeStoppedAgent.spec.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
-import { resumeStoppedAgent } from './resumeStoppedAgent.js'
+import { resumeStoppedAgent, waitForResumedAgent } from './resumeStoppedAgent.js'
import { AgentRestartCoordinator } from './restartAgent.js'
+import type { RuntimeCheck } from './tmux.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
@@ -9,6 +10,9 @@ function fixture() {
live: vi.fn((): RegisteredSession | undefined => undefined),
saved: vi.fn(() => saved),
current: vi.fn(() => true),
+ checkLive: vi.fn(async (): Promise<RuntimeCheck> => ({ state: 'alive' })),
+ retain: vi.fn(async (_entry: RegisteredSession) => {}),
+ waitForReady: vi.fn(async () => ({ ok: true as const, session: saved, resumed: true })),
canLaunch: vi.fn(async () => true),
launch: vi.fn(async () => ({ ok: true as const, session: saved, resumed: true })),
}
@@ -69,3 +73,109 @@ describe('Enter resumes stopped work', () => {
expect(deps.launch).not.toHaveBeenCalled()
})
})
+
+
+describe('resume runtime verification', () => {
+ it.each(['unknown', 'gone'] as const)('never calls a %s registry row a successful attachment', async state => {
+ const deps = fixture()
+ deps.live.mockReturnValue(saved)
+ deps.checkLive.mockResolvedValue({ state, reason: 'fixture' })
+ deps.retain.mockImplementation(async () => { deps.live.mockReturnValue(undefined) })
+ const result = await resumeStoppedAgent(deps)
+ if (state === 'gone') {
+ expect(result.ok).toBe(true)
+ expect(deps.retain).toHaveBeenCalledWith(saved)
+ expect(deps.launch).toHaveBeenCalledTimes(1)
+ } else {
+ expect(result).toMatchObject({ ok: false, error: 'RESUME_UNCONFIRMED' })
+ expect(deps.retain).not.toHaveBeenCalled()
+ expect(deps.launch).not.toHaveBeenCalled()
+ }
+ })
+
+ it('preserves a same-ID shell separately and resumes the archived engine', async () => {
+ const deps = fixture()
+ const shell = { ...saved, engine: 'terminal' as const, sessionId: '' }
+ deps.live.mockReturnValue(shell)
+ deps.retain.mockImplementation(async () => { deps.live.mockReturnValue(undefined) })
+ await expect(resumeStoppedAgent(deps)).resolves.toMatchObject({ ok: true })
+ expect(deps.checkLive).not.toHaveBeenCalled()
+ expect(deps.retain).toHaveBeenCalledWith(shell)
+ expect(deps.launch).toHaveBeenCalledWith(saved, saved.sessionId)
+ })
+
+ it('waits for a pending native resume instead of calling pane allocation success', async () => {
+ const deps = fixture()
+ const pending = { ...saved, resumeOnly: true as const, launch: { state: 'starting' as const } }
+ deps.live.mockReturnValue(pending)
+ await resumeStoppedAgent(deps)
+ expect(deps.waitForReady).toHaveBeenCalledWith(pending)
+ expect(deps.launch).not.toHaveBeenCalled()
+ })
+
+ it('refuses a restart while another client is resuming the same agent', async () => {
+ const jobs = new AgentRestartCoordinator()
+ let finish!: (value: any) => void
+ const pending = jobs.run(saved.agentId, () => new Promise(resolve => { finish = resolve }), 'resume')
+ await Promise.resolve()
+ const restart = vi.fn()
+ await expect(jobs.run(saved.agentId, restart)).resolves.toMatchObject({ ok: false, error: 'AGENT_BUSY' })
+ expect(restart).not.toHaveBeenCalled()
+ jobs.cancel(saved.agentId)
+ finish({ ok: true, session: saved, resumed: true })
+ await expect(pending).resolves.toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ })
+})
+
+describe('exact conversation readiness', () => {
+ const process = { pid: 42, startMarker: 'new-process', executable: 'codex' }
+ function readiness() {
+ let now = 0
+ let row: RegisteredSession = { ...saved, processIdentity: process, lastHookAt: 0, launch: { state: 'starting' } }
+ return {
+ current: vi.fn(() => true),
+ session: () => row,
+ process: vi.fn(async () => process),
+ pane: vi.fn(async (): Promise<{ dead: boolean; engineExit?: number } | null> => ({ dead: false })),
+ sleep: vi.fn(async (ms: number) => { now += ms }),
+ now: () => now,
+ budgetMs: 1000,
+ set: (next: Partial<RegisteredSession>) => { row = { ...row, ...next } },
+ }
+ }
+ it('does not treat a visible process or saved session binding as readiness', async () => {
+ const deps = readiness()
+ await expect(waitForResumedAgent(saved, deps)).resolves.toMatchObject({ ok: false, error: 'RESUME_UNCONFIRMED' })
+ expect(deps.sleep).toHaveBeenCalled()
+ })
+ it('waits for the matching startup hook from the newly observed process', async () => {
+ const deps = readiness()
+ deps.sleep.mockImplementation(async () => { deps.set({ lastHookAt: 100, launch: { state: 'ready' } }) })
+ await expect(waitForResumedAgent(saved, deps)).resolves.toMatchObject({ ok: true, session: { sessionId: saved.sessionId } })
+ expect(deps.process).toHaveBeenCalledTimes(2)
+ })
+ 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)
+ await expect(waitForResumedAgent(saved, deps)).resolves.toMatchObject({ ok: false, error: 'RESUME_FAILED' })
+ })
+ it('does not accept a startup hook for another process or conversation', async () => {
+ const deps = readiness()
+ deps.set({ lastHookAt: 100, launch: { state: 'ready' }, processIdentity: { ...process, pid: 99 } })
+ await expect(waitForResumedAgent(saved, deps)).resolves.toMatchObject({ ok: false, error: 'RESUME_UNCONFIRMED' })
+ deps.set({ sessionId: 'fresh-conversation', processIdentity: process })
+ await expect(waitForResumedAgent(saved, deps)).resolves.toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ })
+ it('does not report success if the process exits between readiness probes', async () => {
+ const deps = readiness()
+ deps.set({ lastHookAt: 100, launch: { state: 'ready' } })
+ deps.pane.mockResolvedValue({ dead: false, engineExit: 1 })
+ await expect(waitForResumedAgent(saved, deps)).resolves.toMatchObject({ ok: false, error: 'RESUME_FAILED' })
+ })
+ it('checks Stop cancellation after async probes', async () => {
+ const deps = readiness()
+ deps.set({ lastHookAt: 100, launch: { state: 'ready' } })
+ deps.process.mockImplementation(async () => { deps.current.mockReturnValue(false); return process })
+ await expect(waitForResumedAgent(saved, deps)).resolves.toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ })
+})
diff --git a/cli/src/lib/resumeStoppedAgent.ts b/cli/src/lib/resumeStoppedAgent.ts
index 50bcac574..bdaa8aa9b 100644
--- a/cli/src/lib/resumeStoppedAgent.ts
+++ b/cli/src/lib/resumeStoppedAgent.ts
@@ -1,31 +1,92 @@
-import { LAUNCH_RESUME_FLAG } from './engineLaunch.js'
import { isTerminalEngine } from '../engines/types.js'
-import type { RegisteredSession } from './registry.js'
+import type { RegisteredSession, ProcessIdentity } from './registry.js'
import type { RestartAgentReply } from './restartAgent.js'
+import type { RuntimeCheck } from './tmux.js'
export interface ResumeStoppedDeps {
live: () => RegisteredSession | undefined
saved: () => RegisteredSession | null
current: () => boolean
+ checkLive: (session: RegisteredSession) => Promise<RuntimeCheck>
canLaunch: (saved: RegisteredSession) => Promise<boolean>
+ /** Only called after the engine is confirmed gone; never destroys the surviving shell. */
+ retain: (session: RegisteredSession) => Promise<void>
+ waitForReady: (session: RegisteredSession) => Promise<RestartAgentReply>
launch: (saved: RegisteredSession, resumeSessionId: string | undefined) => Promise<RestartAgentReply>
}
-/** Enter means attach or resume. There is deliberately no fresh-conversation fallback. */
+export const resumeChanged = { ok: false, error: 'AGENT_CHANGED', detail: 'The harness changed while opening. Select it again.' } as const
+export const resumeUnconfirmed = { ok: false, error: 'RESUME_UNCONFIRMED', detail: 'The saved conversation has not been confirmed yet. Check the terminal, then select the harness again to check its status.' } as const
+
+/** Enter means attach or exact resume. A route, shell or allocated pane alone is not success. */
export async function resumeStoppedAgent(deps: ResumeStoppedDeps): Promise<RestartAgentReply> {
+ if (!deps.current()) return resumeChanged
const existing = deps.live()
- if (existing) return { ok: true, session: existing, resumed: true }
- const saved = deps.saved()
+ let saved = deps.saved()
+ if (existing) {
+ // Compatibility with an archive written before surviving shells got a new identity.
+ if (isTerminalEngine(existing.engine) && saved && !isTerminalEngine(saved.engine)) {
+ await deps.retain(existing)
+ } else if (existing.resumeOnly && existing.launch?.state === 'starting') {
+ return deps.waitForReady(existing)
+ } else {
+ const runtime = await deps.checkLive(existing)
+ if (!deps.current() || deps.live() !== existing) return resumeChanged
+ if (runtime.state === 'unknown') return resumeUnconfirmed
+ if (runtime.state === 'alive') {
+ if (existing.resumeOnly && existing.launch?.state === 'failed') return resumeUnconfirmed
+ return { ok: true, session: existing, resumed: true }
+ }
+ saved = { ...existing }
+ await deps.retain(existing)
+ }
+ }
+ if (!deps.current()) return resumeChanged
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 (!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.' }
}
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.' }
+ 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 { 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 }
+ 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)
}
+
+export interface ResumeReadinessDeps {
+ current: () => boolean
+ session: () => RegisteredSession | undefined
+ process: () => Promise<ProcessIdentity | null>
+ pane: () => Promise<{ dead: boolean; engineExit?: number | null } | null>
+ sleep: (ms: number) => Promise<void>
+ now?: () => number
+ 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. */
+export async function waitForResumedAgent(saved: RegisteredSession, deps: ResumeReadinessDeps): Promise<RestartAgentReply> {
+ const now = deps.now ?? Date.now
+ const until = now() + (deps.budgetMs ?? 10 * 60_000)
+ while (now() < until) {
+ if (!deps.current()) return resumeChanged
+ const process = await deps.process()
+ const pane = await deps.pane()
+ if (!deps.current()) return resumeChanged
+ const row = deps.session()
+ if (!row) return { ok: false, error: 'RESUME_FAILED', detail: 'The resume runtime disappeared. The saved conversation is still retained.' }
+ if (row.sessionId !== saved.sessionId || row.engine !== saved.engine) return resumeChanged
+ if (row.launch?.state === 'failed') return { ok: false, error: row.launch.error, detail: row.launch.detail }
+ if (!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 }
+ }
+ await deps.sleep(250)
+ }
+ return resumeUnconfirmed
+}
diff --git a/cli/src/lib/stoppedAgents.spec.ts b/cli/src/lib/stoppedAgents.spec.ts
index 052eb3185..a4951034f 100644
--- a/cli/src/lib/stoppedAgents.spec.ts
+++ b/cli/src/lib/stoppedAgents.spec.ts
@@ -80,3 +80,32 @@ describe('stopped harness persistence', () => {
expect(() => store.get(saved.agentId)).toThrow()
})
})
+
+
+it('keeps the original identity searchable while preserving the surviving shell route', async () => {
+ const { registry, saved, store } = await fixture()
+ // Use the actual row, as the daemon does after registering its session.
+ Object.assign(registry.byAgent(saved.agentId)!, saved)
+ store.save(saved)
+ const shell = registry.releaseEngine(saved.agentId, true)!
+ expect(shell.agentId).not.toBe(saved.agentId)
+ expect(shell).toMatchObject({ engine: 'terminal', sessionId: '', tmuxPane: '%8', processIdentity: null })
+ expect(registry.byAgent(saved.agentId)).toBeUndefined()
+ expect(registry.bySession(saved.sessionId)).toBeUndefined()
+ expect(store.available(registry.list()).map(row => row.agentId)).toEqual([saved.agentId])
+ const resumed = registry.resumePendingAgent(store.get(saved.agentId)!, [{ backend: 'tmux', paneId: '%99' }])!
+ expect(resumed.agentId).toBe(saved.agentId)
+ expect(registry.byRuntimeTerminal({ backend: 'tmux', paneId: '%8' })?.agentId).toBe(shell.agentId)
+ expect(registry.list()).toHaveLength(2)
+})
+
+it('reserves allocation across daemon restarts and different receipt IDs', async () => {
+ const { store, StoppedAgentStore, saved } = await fixture()
+ const token = store.beginResume(saved.agentId)!
+ const restarted = new StoppedAgentStore(join(directory, 'stopped-agents'))
+ expect(restarted.beginResume(saved.agentId)).toBeNull()
+ restarted.finishResume(saved.agentId, 'someone-else')
+ expect(store.beginResume(saved.agentId)).toBeNull()
+ restarted.finishResume(saved.agentId, token)
+ expect(store.beginResume(saved.agentId)).not.toBeNull()
+})
diff --git a/cli/src/lib/stoppedAgents.ts b/cli/src/lib/stoppedAgents.ts
index 448d47132..afcfb7f5f 100644
--- a/cli/src/lib/stoppedAgents.ts
+++ b/cli/src/lib/stoppedAgents.ts
@@ -1,5 +1,6 @@
/** Stopped work is durable history, separate from the registry of live terminal routes. */
-import { readdirSync } from 'node:fs'
+import { closeSync, constants, fsyncSync, openSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'
+import { randomUUID } from 'node:crypto'
import { dirname, join } from 'node:path'
import { env } from '../config/env.js'
import { isTerminalEngine } from '../engines/types.js'
@@ -61,6 +62,40 @@ export class StoppedAgentStore {
atomicWriteJson(join(this.directory, `${session.agentId}.json`), { version: 1, session: snapshot })
}
+ /** Reserve before tmux allocation. A crash between allocation and registry persistence
+ * must not permit a second process under a new request/receipt ID. */
+ beginResume(agentId: string): string | null {
+ if (!SAFE_ID.test(agentId)) throw new Error('Invalid saved harness identity.')
+ secureStateDirectory(dirname(this.directory))
+ secureStateDirectory(this.directory)
+ const file = join(this.directory, `${agentId}.resume`)
+ let fd: number
+ try { fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600) }
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'EEXIST') return null; throw error }
+ const token = randomUUID()
+ try { writeFileSync(fd, JSON.stringify({ token })); fsyncSync(fd) } finally { closeSync(fd) }
+ this.syncDirectory()
+ return token
+ }
+
+ /** Clear only a verified outcome. Unknown allocation/readiness keeps its reservation. */
+ finishResume(agentId: string, token?: string): void {
+ if (!SAFE_ID.test(agentId)) return
+ const file = join(this.directory, `${agentId}.resume`)
+ try {
+ secureStateDirectory(this.directory, false)
+ const marker = JSON.parse(readPrivateStateFile(file, 1024))
+ if (token !== undefined && marker.token !== token) return
+ unlinkSync(file)
+ this.syncDirectory()
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error }
+ }
+
+ private syncDirectory(): void {
+ const fd = openSync(this.directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)
+ try { fsyncSync(fd) } finally { closeSync(fd) }
+ }
+
/** Suppress archives whose identity or conversation is already running. */
available(live: readonly RegisteredSession[]): RegisteredSession[] {
const ids = new Set(live.map(session => session.agentId))
diff --git a/desktop/design/agent-lifecycle-map.md b/desktop/design/agent-lifecycle-map.md
index 70f2e71dd..c2da27b8b 100644
--- a/desktop/design/agent-lifecycle-map.md
+++ b/desktop/design/agent-lifecycle-map.md
@@ -1,13 +1,9 @@
# 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.
+Implementation review: `worktree-agent-resume`, [WIP PR #168](https://github.com/autonomous-ai/openharness/pull/168).
+The original proposal and pre-change mapping are preserved in [issue #167](https://github.com/autonomous-ai/openharness/issues/167).
+The command dock and welcome screen were merged separately in #165. This branch adds CLI/daemon lifecycle behavior and remains unmerged for team review.
+Commands below omit existing profile, permissions, provider, installer and shell-wrapper arguments.
## Three identities
@@ -30,18 +26,18 @@ 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_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. Save a durable archive **before removal**; a storage failure refuses the explicit stop before mutation. |
| `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. |
+| `agents_list` | No mutation | None | Reads `registry.advertised()` (verified available terminal routes). `includeStopped: true` 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_recent` | No mutation | None | Resolves Harness ID to engine `sessionId` and reads stored recaps/recent user asks. Providers resolve through the live registry or the archive, so recaps and recent asks work before Open. |
| `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. |
+| `agent_resume` **(this PR)** | Keep a verified running runtime; otherwise allocate a new session and pane for saved work | `claude --resume <savedSessionId>` / `codex resume <savedSessionId>`; no fresh fallback | Return a verified running engine. Otherwise reserve the operation, restore the **same Harness ID and conversation ID** on a new route with no stale PID and `launch: starting`, and await the exact conversation hook from the new process. Keep the saved record on failure. No fresh fallback. |
Harness normally creates one tmux session per harness, initially with one
@@ -73,11 +69,11 @@ In-process model changes are in
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
+This PR 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:
+The stop/resume transition is:
1. Save the Harness ID, engine conversation ID, cwd, name, profile and launch
settings before removing the live row.
@@ -88,13 +84,7 @@ The proposed stop/resume transition is:
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.
+When an engine exits into a surviving shell, its conversation is archived under the original Harness ID. `releaseEngine(agentId, true)` removes its process, route and conversation indexes, then preserves that physical shell under a new Terminal ID. No input is sent and no shell process is replaced. The saved conversation remains searchable under the original ID; Open creates a new runtime for it. Archives written by the early prototype behind a same-ID Terminal are separated on startup or Open.
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
@@ -113,7 +103,7 @@ the app tab, Harness ID or tmux route.
| 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. |
+| Engine process exits while its shell survives | Archive the conversation under its original ID; preserve the shell under a new Terminal ID. Send a retained-session snapshot and a separate terminal snapshot. |
| Terminal route disappears | Reconciliation removes the live row. The new archive retains its saved resume information. |
Evidence: [`notify.mjs`](../../cli/hook/notify.mjs),
@@ -124,58 +114,44 @@ Evidence: [`notify.mjs`](../../cli/hook/notify.mjs),
| 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_deleted` | Remove the row/view from the receiving client's live inventory. The `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.
+Natural engine exit sends `agent_synced` with `status: stopped` and no terminal route for the original identity. The separate shell is announced as a Terminal. Devices receive a deletion for the engine because they list live agents. Explicit Stop still sends `agent_deleted` with `retained: true`, so desktop closes its live views and refreshes the saved catalog.
+
+## Cmd-P/T contract
+
+- All retained harnesses use the same row, Enter glyph and **Open** action. No Stopped badge, separate Resume action or confirmation dialog.
+- Running sessions keep their existing process and conversation; opening multiple app views was already supported.
+- Stopped Claude Code and Codex sessions use native resume with the exact saved conversation. Required cwd, Codex profile, permission mode, DSH and provider configuration are preserved. Missing history, project, DSH or provider credentials produce explicit errors.
+- Pane allocation publishes `launch: starting`. Process discovery alone does not mark strict resume ready. A verified native hook must bind the requested conversation and the readiness poll must observe that same process. A different session ID fails instead of rebinding to a new conversation.
+- Resume does not submit a prompt, restore process memory or promise to continue an interrupted tool call.
+- An explicit **Start New Conversation** action remains available after failure; it is never invoked automatically.
+
+## Concurrency and recovery
+
+- Resume and Restart share an agent coordinator. Repeated requests for the same operation join; conflicting operations return `AGENT_BUSY`. Stop cancels a pending operation before its next mutation. Retarget checks this coordinator and its terminal control lease.
+- Conversation reservations match the registry's conversation uniqueness constraint, including requests through different retained Harness IDs.
+- `creationId` uses the existing durable receipt protocol and `agent_create_status`. A retry of the same intent returns its recorded result or uncertainty, never a new process.
+- A private, fsynced per-agent `.resume` reservation is written **before** history preparation and tmux allocation. It protects the gap between starting tmux and persisting a new registry row, including requests with a different receipt ID after daemon restart.
+- Confirmed native binding, verified completion or a confirmed stop clears the reservation. Unknown allocation/readiness keeps it; startup failure keeps history and preserves the shell/output when available.
+- On daemon restart, a strict-resume row whose pane disappeared is archived for explicit Open. It never enters restore's fresh fallback. A surviving engine is re-observed, and a surviving shell is separated from the saved conversation.
+
+## Scope and review limits
+
+- Conversation resume supports **Claude Code and Codex on tmux**. A retained Terminal can open a new shell; shell process memory is not restored. Other engines' saved rows remain discoverable and return an explicit unsupported-history error on Open.
+- The catalog contains histories retained by this daemon, not vendor conversations that Harness never recorded. Previously deleted histories are not imported.
+- `agent_recent` works from the archive. Other file/model/edit RPCs still use a live row; open the harness before using them.
+- Unknown tmux allocation is intentionally conservative. If the daemon died before any runtime was registered and no native hook later confirms it, the reservation remains blocked for operator investigation. There is no automatic force-clear, destructive retry or terminal takeover in this PR.
+- Unit, protocol, persistence and desktop tests use isolated fixture state. Native Claude/Codex login, trust prompts, and resume hooks across installed vendor versions still need team acceptance testing before merge. The running user daemon is not replaced by verification.
+
+## Suggested manual acceptance checks
+
+1. Open a running Claude Code/Codex harness in a second app pane; its process and conversation should be unchanged.
+2. Stop a disposable harness, find the same name in Cmd-T/P, and press Enter. Check the same conversation, folder and permissions; no confirmation or fresh conversation.
+3. Exit the engine into its shell, start harmless shell work there, then Open the retained conversation. The shell must remain untouched; the resumed engine gets another pane under its original Harness ID.
+4. Press Enter repeatedly or from two clients. Confirm one runtime and identical receipt outcomes.
+5. Make a disposable history unavailable, or make its native resume command fail. Check the explicit error, retained saved row and separate Start New Conversation action.
+6. Restart the daemon during startup and repeat the same receipt. Check confirmed recovery or explicit uncertainty, with no duplicate engine or fresh fallback.
+
+`agent_pause` is outside this PR. Turn completion/cancellation is separate from process stop and conversation resume.
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index c7967a25f..f3662ff64 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -6928,7 +6928,9 @@ class AppNotifier extends ChangeNotifier {
return unknown;
}
attempt._awaitingConfirmation = false;
- return RestartAgentResult(error: _restartFailure(code, result['detail']));
+ return RestartAgentResult(
+ error: _restartFailure(code, result['detail'], resuming: resuming),
+ );
}
switch (result['state']) {
case 'pending':
@@ -6951,7 +6953,11 @@ class AppNotifier extends ChangeNotifier {
if (failure is! Map || failure['code'] is! String) return unknown;
attempt._awaitingConfirmation = false;
return RestartAgentResult(
- error: _restartFailure(failure['code'] as String, failure['detail']),
+ error: _restartFailure(
+ failure['code'] as String,
+ failure['detail'],
+ resuming: resuming,
+ ),
);
case 'created':
case null:
@@ -6965,6 +6971,13 @@ class AppNotifier extends ChangeNotifier {
if (raw is! Map || raw['id'] != agentId) return unknown;
try {
var updated = Agent.fromJson(Map<String, dynamic>.from(raw));
+ if (resuming &&
+ (result['resumed'] == false ||
+ updated.sessionId != attempt.agent!.sessionId ||
+ updated.launchState == 'starting' ||
+ updated.launchState == 'failed')) {
+ return unknown;
+ }
final current = machine.agents
.where((agent) => agent.id == agentId)
.first;
@@ -6987,7 +7000,7 @@ class AppNotifier extends ChangeNotifier {
} catch (_) {
return unknown;
}
- } else if (!result.containsKey('resumed')) {
+ } else if (resuming || !result.containsKey('resumed')) {
return unknown;
}
machine._agentRestartRevisions[agentId] = ++machine._agentRevision;
@@ -7000,14 +7013,22 @@ class AppNotifier extends ChangeNotifier {
);
}
- String _restartFailure(String code, Object? detail) =>
- detail is String && detail.isNotEmpty
+ String _restartFailure(
+ String code,
+ Object? detail, {
+ bool resuming = false,
+ }) => detail is String && detail.isNotEmpty
? detail
: switch (code) {
'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>
- 'Update the harness CLI on this machine to restart an agent.',
+ resuming
+ ? '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.',
- _ => 'Restart failed: $code',
+ _ =>
+ resuming
+ ? 'Could not open this harness: $code'
+ : 'Restart failed: $code',
};
bool _forkSourceCurrent(AgentForkAttempt attempt) {
diff --git a/desktop/test/stopped_harness_test.dart b/desktop/test/stopped_harness_test.dart
index 544dbb6c2..aa31776e0 100644
--- a/desktop/test/stopped_harness_test.dart
+++ b/desktop/test/stopped_harness_test.dart
@@ -157,6 +157,71 @@ void main() {
},
);
+ test(
+ 'repeated Enter joins one request; a lost reply checks its receipt',
+ () async {
+ final first = app.resumeAgent('m', 'saved');
+ final second = app.resumeAgent('m', 'saved');
+ expect(identical(first, second), isTrue);
+ expect(connection.types, ['agent_resume']);
+ final creationId = connection.requests.single['creationId'];
+ connection.restartReplies.single.completeError(
+ Exception('lost response'),
+ );
+ expect((await first).error, isNotNull);
+ final checking = app.resumeAgent('m', 'saved');
+ expect(connection.types, ['agent_resume']);
+ expect(connection.checks, hasLength(1));
+ expect(connection.checks.single['creationId'], creationId);
+ connection.checkReplies.single.complete(
+ restartReceipt(
+ creationId as String,
+ agentId: 'saved',
+ sessionId: 'original-conversation',
+ ),
+ );
+ expect((await checking).error, isNull);
+ },
+ );
+
+ test('never accepts a fresh conversation as a successful resume', () async {
+ final opening = app.resumeAgent('m', 'saved');
+ connection.restartReplies.single.complete(
+ restartReceipt(
+ connection.requests.single['creationId'] as String,
+ agentId: 'saved',
+ sessionId: 'unexpected-conversation',
+ ),
+ );
+ expect((await opening).error, isNotNull);
+ expect(
+ app.stateOf('m')!.agents.firstWhere((a) => a.id == 'saved').sessionId,
+ 'original-conversation',
+ );
+ expect(app.allPanes, isEmpty);
+ });
+
+ test(
+ 'retained-session pushes preserve existing pane intent and searchability',
+ () async {
+ await app.handleEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {
+ 'agent': {
+ 'id': 'saved',
+ 'name': 'Saved work',
+ 'engine': 'codex',
+ 'sessionId': 'original-conversation',
+ 'status': 'stopped',
+ 'terminal': {'available': false},
+ },
+ },
+ });
+ expect(row().agentId, 'saved');
+ expect(connection.requests, isEmpty);
+ },
+ );
+
testWidgets('Enter submits resume immediately with no confirmation dialog', (
tester,
) async {