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.

Keep restarted harnesses in their existing panes (#1589)

Dee78305cce0534
diff --git a/cli/e2e/restartIdentity.e2e.ts b/cli/e2e/restartIdentity.e2e.ts
new file mode 100644
index 000000000..5c5aff5c8
--- /dev/null
+++ b/cli/e2e/restartIdentity.e2e.ts
@@ -0,0 +1,52 @@
+/** Restart keeps the pane's identity; legacy default-profile archives hand their views to its live owner. */
+import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, expect, it, onTestFailed } from 'vitest'
+import { LocalClient } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+let daemon: IsolatedDaemon | undefined
+afterEach(async () => { await daemon?.close(); daemon = undefined })
+
+it('keeps a named Codex harness through restart and hides an archive of its explicit default profile', async () => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => console.log(d.log().split('\n').slice(-100).join('\n')))
+ await d.start()
+ const client = await LocalClient.connect(d)
+ const cwd = join(d.projectsDir, 'builder-3')
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine: 'codex', cwd, name: 'Builder 3', bypassPermission: true }, 60_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const id = created.agent.id
+ const rows = async () => (await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true })).agents
+ const before = await until('Builder 3 to bind', async () => (await rows()).find(a => a.id === id && a.sessionId && a.status === 'active') || null, 45_000, 250)
+ const restarted = await client.request('agent_restart', { agentId: id }, 90_000)
+ expect(restarted.error, JSON.stringify(restarted)).toBeUndefined()
+ expect(restarted.agent).toMatchObject({ id, name: 'Builder 3', sessionId: before.sessionId, tmuxPane: before.tmuxPane })
+ expect((await client.request('agent_resume', { agentId: id }, 60_000)).error).toBeUndefined()
+ expect((await rows()).filter(a => a.sessionId === before.sessionId)).toHaveLength(1)
+
+ // The observed incident: the old archive named ~/.codex explicitly; the replacement used the default.
+ // Seed only the disposable daemon's archive, using its real registered row and private engine home.
+ const live = JSON.parse(readFileSync(join(d.dataDir, 'registry.json'), 'utf8')).find((a: Record<string, any>) => a.agentId === id)
+ expect(live).toBeDefined()
+ const staleId = 'old-builder-3'
+ const archive = join(d.dataDir, 'stopped-agents')
+ mkdirSync(archive, { recursive: true, mode: 0o700 })
+ writeFileSync(join(archive, `${staleId}.json`), JSON.stringify({ version: 1,
+ session: { ...live, agentId: staleId, active: false, codexHome: live.codexHome ? null : d.engineConfig.codexHome },
+ }), { mode: 0o600 })
+ expect((await rows()).filter(a => a.sessionId === before.sessionId).map(a => a.id)).toEqual([id])
+ await d.restart()
+ client.close()
+ const again = await LocalClient.connect(d)
+ await until('the stale profile archive to be set aside for the running owner', async () =>
+ existsSync(join(archive, 'superseded', `${staleId}.json`)) || null, 45_000, 250)
+ const back = await again.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true })
+ expect(back.agents.filter(a => a.sessionId === before.sessionId).map(a => a.id)).toEqual([id])
+ const ended = again.next(f => f.type === 'turn_ended' && f.agentId === id, 30_000, 'Builder 3 next turn')
+ again.send('message', { agentId: id, content: 'continue after reopening the same conversation' })
+ await ended
+ again.close()
+})
diff --git a/cli/package.json b/cli/package.json
index 9d44f71ca..f6595e1cf 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -28,7 +28,7 @@
"test:cursor-e2e": "RUN_CURSOR_E2E=1 vitest run src/engines/cursor/localE2e.spec.ts",
"test:tmux-real": "RUN_REAL_TMUX_DISCOVERY=1 vitest run src/lib/tmuxAgentDiscovery.real.spec.ts src/lib/engineShellStartup.spec.ts src/lib/codexUpdateRestart.real.spec.ts src/lib/restartDiscovery.real.spec.ts src/lib/terminalClose.real.spec.ts src/lib/engineStop.real.spec.ts --reporter=verbose",
"test:guest-real": "RUN_REAL_GUEST_PARITY=1 vitest run src/lib/guestParity.real.spec.ts --reporter=verbose",
- "test:resume": "vitest run src/lib/controlTranscript.spec.ts src/lib/sessionRepair.spec.ts src/lib/captureResumeIdentity.spec.ts src/lib/resumeStoppedAgent.spec.ts src/lib/resumeAgentService.spec.ts src/lib/stoppedAgents.spec.ts src/lib/stopAgentService.spec.ts --coverage --coverage.include=src/lib/captureResumeIdentity.ts --coverage.include=src/lib/resumeStoppedAgent.ts --coverage.include=src/lib/resumeAgentService.ts --coverage.include=src/lib/stoppedAgents.ts --coverage.include=src/lib/stopAgentService.ts --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.branches=100 --coverage.thresholds.functions=100 --coverage.reporter=text --coverage.reporter=json --coverage.reportsDirectory=coverage/resume",
+ "test:resume": "vitest run src/lib/controlTranscript.spec.ts src/lib/sessionRepair.spec.ts src/lib/captureResumeIdentity.spec.ts src/lib/resumeStoppedAgent.spec.ts src/lib/resumeAgentService.spec.ts src/lib/stoppedAgents.spec.ts src/lib/stopAgentService.spec.ts --coverage --coverage.include=src/lib/conversationIdentity.ts --coverage.include=src/lib/captureResumeIdentity.ts --coverage.include=src/lib/resumeStoppedAgent.ts --coverage.include=src/lib/resumeAgentService.ts --coverage.include=src/lib/stoppedAgents.ts --coverage.include=src/lib/stopAgentService.ts --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.branches=100 --coverage.thresholds.functions=100 --coverage.reporter=text --coverage.reporter=json --coverage.reportsDirectory=coverage/resume",
"test:resume-native": "tsc -p tsconfig.resume-native.json && tsx scripts/resume-native-e2e.ts",
"test:portability": "vitest run --config vitest.portability.config.ts"
},
diff --git a/cli/src/core/agents/conversationOwners.spec.ts b/cli/src/core/agents/conversationOwners.spec.ts
index 8b6c0cb3f..bab73ffe0 100644
--- a/cli/src/core/agents/conversationOwners.spec.ts
+++ b/cli/src/core/agents/conversationOwners.spec.ts
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { RegisteredSession } from '../../lib/registry.js'
import { conversationKey, createConversationOwners, type ConversationOwnersDeps } from './conversationOwners.js'
+import { env } from '../../config/env.js'
const row = (agentId: string, sessionId: string, extra: Partial<RegisteredSession> = {}): RegisteredSession => ({
agentId, sessionId, engine: 'claude', codexHome: null, hermesHome: null, boundAt: 1000, registeredAt: 500, touchedAt: 2000,
@@ -48,6 +49,15 @@ describe('one owner per conversation, stopped harnesses included', () => {
expect(commander).toContainEqual({ type: 'agent_deleted', payload: { agentId: 'old' } })
})
+ it.each([true, false])('hands over a Codex conversation across explicit and implicit default profiles, archived explicit=%s', explicit => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const saved = row('builder-3', 'conversation', { engine: 'codex', codexHome: explicit ? env.CODEX_HOME : null })
+ const running = row('replacement', 'conversation', { engine: 'codex', codexHome: explicit ? null : env.CODEX_HOME })
+ const { owners, sent } = setup([saved], [running])
+ expect(owners.settle()).toEqual(['builder-3'])
+ expect(sent).toContainEqual({ type: 'agent_deleted', payload: { agentId: 'builder-3', retained: false, successor: 'replacement' } })
+ })
+
it('among stopped records the newest binding wins, then the newest record, then the id', () => {
vi.spyOn(console, 'log').mockImplementation(() => {})
const bound = setup([row('a', 'c1', { boundAt: 3000 }), row('b', 'c1', { boundAt: 5000 }), row('c', 'c1', { boundAt: null })])
diff --git a/cli/src/core/agents/conversationOwners.ts b/cli/src/core/agents/conversationOwners.ts
index 98f55dd51..e463f7fef 100644
--- a/cli/src/core/agents/conversationOwners.ts
+++ b/cli/src/core/agents/conversationOwners.ts
@@ -16,7 +16,7 @@
* conversation (names are kept by session id, `registry.rename`). A harness that is running is never set
* aside (its record follows it), nor one whose resume is in flight.
*/
-import { isTerminalEngine } from '../../engines/types.js'
+import { conversationKey } from '../../lib/conversationIdentity.js'
import { sid } from '../../lib/log.js'
import type { RegisteredSession } from '../../lib/registry.js'
import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'
@@ -34,16 +34,7 @@ export interface ConversationOwnersDeps {
now?: () => number
}
-type Owned = Pick<RegisteredSession, 'engine' | 'sessionId' | 'codexHome' | 'hermesHome'>
-
-/**
- * A conversation, or null for a record that holds none. The same id under another Codex profile or Hermes
- * home is another conversation; a terminal holds none of its own.
- */
-export function conversationKey(row: Owned): string | null {
- if (!row.sessionId || isTerminalEngine(row.engine)) return null
- return [row.engine, row.codexHome ?? '', row.hermesHome ?? '', row.sessionId].join('\u0000')
-}
+export { conversationKey } from '../../lib/conversationIdentity.js'
/** Newest binding first; then the newest record, then the id, so every daemon picks the same one. */
const newestFirst = (a: RegisteredSession, b: RegisteredSession): number =>
diff --git a/cli/src/core/agents/restart.spec.ts b/cli/src/core/agents/restart.spec.ts
index 527d976e4..7ad4e6f22 100644
--- a/cli/src/core/agents/restart.spec.ts
+++ b/cli/src/core/agents/restart.spec.ts
@@ -13,6 +13,7 @@ import { createAgentRestarter, type RestartDeps } from './restart.js'
import { createLaunchAuthority } from './launchAuthority.js'
import { createSwarmSkillAdoption } from './swarmSkills.js'
import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'
+import { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'
vi.mock('../../lib/engineBin.js', async (real) => ({ ...await real<object>(), enginePathOverride: vi.fn(() => undefined) }))
vi.mock('../../lib/engineLaunch.js', async (real) => ({
@@ -60,7 +61,7 @@ function setup(row: RegisteredSession | null = agent(), over: Partial<RestartDep
pinnedControls: new Set(),
terminals: { backendFor: vi.fn((runtime: { backend: string }) => runtime.backend === 'tmux' ? tmuxBackend : undefined) } as unknown as RestartDeps['terminals'],
sameRestartTarget: vi.fn(() => true),
- agentReconciler: { holdRoute: vi.fn(), releaseRoute: vi.fn() },
+ agentReconciler: { holdRoute: vi.fn((key: string) => () => deps.agentReconciler.releaseRoute(key)), releaseRoute: vi.fn() },
terminalHintMachineName: () => 'studio',
announceSession: vi.fn(),
refreshGridAssignment: vi.fn(),
@@ -81,6 +82,64 @@ describe('restarting an agent', () => {
beforeEach(() => { vi.spyOn(console, 'log').mockImplementation(() => {}) })
afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })
+ it.each(['terminal', 'claude'] as const)('keeps a slow %s restart hidden from discovery until publication', async engine => {
+ vi.useFakeTimers()
+ const onDiscovered = vi.fn()
+ const reconciler = new TerminalAgentReconciler({ current: () => [], backends: [], backendOrder: ['tmux'],
+ onDiscovered, onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),
+ probe: async () => ({ processTableAvailable: true, ambiguousPlacements: new Set(),
+ targets: [{ instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime, rootPid: 1, cwd: '/work' }] } }],
+ agents: [{ engine: 'claude', cwd: '/work', processIdentity: newProcess,
+ args: 'claude', resumeSessionId: null, runtimes: [runtime], primaryRuntimeKey: routeKey }],
+ }),
+ })
+ let finish!: () => void
+ const run = setup(engine === 'terminal' ? terminal() : agent(), { agentReconciler: reconciler })
+ if (engine === 'terminal') run.tmuxBackend.respawn.mockImplementationOnce(() => new Promise(done => {
+ finish = () => done({ state: 'succeeded' })
+ }))
+ else vi.mocked(restartAgent).mockImplementationOnce(() => new Promise(done => {
+ finish = () => done({ ok: true, resumed: true, processIdentity: newProcess })
+ }))
+ const pending = run.restart('a1')
+ try {
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'))
+ await vi.advanceTimersByTimeAsync(30_001)
+ await reconciler.trigger()
+ expect(onDiscovered).not.toHaveBeenCalled()
+ finish()
+ expect(await pending).toMatchObject({ ok: true })
+ expect(run.deps.announceSession).toHaveBeenCalled()
+ await reconciler.trigger()
+ expect(onDiscovered).toHaveBeenCalledOnce()
+ } finally { finish?.(); await pending; vi.useRealTimers() }
+ })
+
+ it.each(['terminal', 'claude'] as const)('a cancelled %s restart cannot release a newer Stop hold', async engine => {
+ const onDiscovered = vi.fn()
+ const reconciler = new TerminalAgentReconciler({ current: () => [], backends: [], backendOrder: ['tmux'],
+ onDiscovered, onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),
+ probe: async () => ({ processTableAvailable: true, ambiguousPlacements: new Set(),
+ targets: [{ instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime, rootPid: 1, cwd: '/work' }] } }],
+ agents: [{ engine: 'claude', cwd: '/work', processIdentity: newProcess,
+ args: 'claude', resumeSessionId: null, runtimes: [runtime], primaryRuntimeKey: routeKey }],
+ }),
+ })
+ const run = setup(engine === 'terminal' ? terminal() : agent(), { agentReconciler: reconciler })
+ let releaseStop!: () => void
+ const stop = () => { run.state.live = false; releaseStop = reconciler.holdRoute(routeKey) }
+ if (engine === 'terminal') run.tmuxBackend.respawn.mockImplementationOnce(async () => { stop(); return { state: 'succeeded' } })
+ else vi.mocked(restartAgent).mockImplementationOnce(async () => { stop(); return { ok: false, detail: 'cancelled' } })
+ try {
+ expect(await run.restart('a1')).toMatchObject({ error: 'AGENT_CHANGED' })
+ await reconciler.trigger()
+ expect(onDiscovered).not.toHaveBeenCalled()
+ releaseStop()
+ await reconciler.trigger()
+ expect(onDiscovered).toHaveBeenCalledOnce()
+ } finally { releaseStop?.() }
+ })
+
it('adopts an old role before native inspection and relaunch', async () => {
const skill = { role: 'lead' as const, key: 'a1' }
const run = setup(agent(), { adoptSwarmSkill: async row => ({ ...row, swarmSkill: skill }) })
@@ -325,7 +384,7 @@ describe('restarting an agent', () => {
expect(backend.releaseHold).toHaveBeenCalledWith(pty)
expect(run.tmuxBackend.respawn).not.toHaveBeenCalled()
expect(releaseHold).not.toHaveBeenCalled()
- expect(run.deps.agentReconciler.holdRoute).toHaveBeenCalledWith(terminalRouteKey(pty))
+ expect(run.deps.agentReconciler.holdRoute).toHaveBeenCalledWith(terminalRouteKey(pty), null)
})
it('swaps an engine in that pane and hands it back to that backend', async () => {
@@ -346,7 +405,7 @@ describe('restarting an agent', () => {
const run = setup(terminal({ runtimes: [{ backend: 'ptyhost', instance: 'p1', paneId: '%4' }, tmux5] }))
expect(await run.restart('a1')).toMatchObject({ ok: true })
expect(run.tmuxBackend.respawn).toHaveBeenCalledExactlyOnceWith(tmux5, expect.anything())
- expect(run.deps.agentReconciler.holdRoute).toHaveBeenCalledWith(terminalRouteKey(tmux5))
+ expect(run.deps.agentReconciler.holdRoute).toHaveBeenCalledWith(terminalRouteKey(tmux5), null)
})
it('restarts as a fresh shell in the same pane, opened like a new terminal tile', async () => {
@@ -358,7 +417,7 @@ describe('restarting an agent', () => {
expect(run.deps.registry.setActive).toHaveBeenCalledWith('a1', true)
expect(run.deps.announceSession).toHaveBeenCalledWith(terminal())
expect(console.log).toHaveBeenCalledWith('[restart] a1 terminal · fresh shell')
- expect(run.deps.agentReconciler.holdRoute).toHaveBeenCalledWith(routeKey)
+ expect(run.deps.agentReconciler.holdRoute).toHaveBeenCalledWith(routeKey, null)
expect(run.deps.agentReconciler.releaseRoute).toHaveBeenCalledWith(routeKey)
expect(run.deps.relaunchOverrides).not.toHaveBeenCalled()
})
@@ -428,7 +487,7 @@ describe('restarting an agent', () => {
expect(run.deps.announceSession).toHaveBeenCalledWith(agent())
expect(run.deps.refreshGridAssignment).toHaveBeenCalledWith(agent())
expect(console.log).toHaveBeenCalledWith('[restart] a1 claude · resumed')
- expect(run.deps.agentReconciler.holdRoute).toHaveBeenCalledWith(routeKey)
+ expect(run.deps.agentReconciler.holdRoute).toHaveBeenCalledWith(routeKey, null)
expect(run.deps.agentReconciler.releaseRoute).toHaveBeenCalledWith(routeKey)
})
diff --git a/cli/src/core/agents/restart.ts b/cli/src/core/agents/restart.ts
index d8f52a6b0..4750025c0 100644
--- a/cli/src/core/agents/restart.ts
+++ b/cli/src/core/agents/restart.ts
@@ -171,7 +171,7 @@ export function createAgentRestarter({
// process-swap choreography below applies. A terminal that ADOPTED an engine restarts the
// engine, like any agent: the tile said Restart about the engine it shows.
if (isTerminalEngine(engine)) {
- agentReconciler.holdRoute(routeKey)
+ const releaseRoute = agentReconciler.holdRoute(routeKey, null)
try {
// The same opening a fresh terminal tile prints (`onCreateAgent`'s `terminalHint`): a
// restarted tile is a fresh shell too, and should look like one.
@@ -192,7 +192,7 @@ export function createAgentRestarter({
console.log(`[restart] ${sid(session.agentId)} terminal · fresh shell`)
return { ok: true, session: refreshed, resumed: false }
} finally {
- agentReconciler.releaseRoute(routeKey)
+ releaseRoute()
}
}
if (!session.processIdentity) return { ok: false, error: 'NO_ACTIVE_PROCESS' }
@@ -227,7 +227,9 @@ export function createAgentRestarter({
if (!current()) return changed
if (!built.ok) return built
- agentReconciler.holdRoute(routeKey)
+ // Shell startup and native checks can outlast the reconciler's default 30-second hold.
+ // Keep this route through publication, and release only this operation's own reservation.
+ const releaseRoute = agentReconciler.holdRoute(routeKey, null)
try {
const restartPermission = await downgradedPermission(session,
await bypassPermissionFor(session, () => liveBypassPermission(session)), 'restart', built.overrides.native)
@@ -254,7 +256,7 @@ export function createAgentRestarter({
+ (session.gridLaunch ? ` · grid ${session.gridLaunch.networkName}` : ''))
return { ok: true, session: refreshed, resumed: outcome.resumed }
} finally {
- agentReconciler.releaseRoute(routeKey)
+ releaseRoute()
}
})
return restartAgentHandler
diff --git a/cli/src/lib/conversationIdentity.ts b/cli/src/lib/conversationIdentity.ts
new file mode 100644
index 000000000..f7af8868f
--- /dev/null
+++ b/cli/src/lib/conversationIdentity.ts
@@ -0,0 +1,15 @@
+import { resolve } from 'node:path'
+import { env } from '../config/env.js'
+import { isTerminalEngine } from '../engines/types.js'
+import type { RegisteredSession } from './registry.js'
+
+type Conversation = Pick<RegisteredSession, 'engine' | 'sessionId' | 'codexHome' | 'hermesHome'>
+
+/** The same conversation, whether its default Codex home was recorded explicitly or left implicit. */
+export function conversationKey(row: Conversation): string | null {
+ if (!row.sessionId || isTerminalEngine(row.engine)) return null
+ // Builder 3's restart was discovered with a null profile while its archive named ~/.codex.
+ // Treating those as separate conversations left the stale picker entry refusing every Open.
+ const profile = row.codexHome && resolve(row.codexHome) !== resolve(env.CODEX_HOME) ? row.codexHome : ''
+ return [row.engine, profile, row.hermesHome ?? '', row.sessionId].join('\u0000')
+}
diff --git a/cli/src/lib/stopAgentService.spec.ts b/cli/src/lib/stopAgentService.spec.ts
index 767e680e1..2789b67cc 100644
--- a/cli/src/lib/stopAgentService.spec.ts
+++ b/cli/src/lib/stopAgentService.spec.ts
@@ -130,6 +130,27 @@ it('keeps a guest harness whose process is still running after its pane closed',
expect(deps.forgetSession).not.toHaveBeenCalled()
expect(registry.byAgent(row.agentId)).toBe(row)
})
+it('checks the saved guest process after its pane removes the registry row, without claiming the changed stop completed', async () => {
+ vi.useFakeTimers()
+ Object.assign(row, { guest: '[email protected]' })
+ const identity = { ...row.processIdentity! }
+ tmuxKill.mockImplementationOnce(async () => {
+ registry.removeAgent(row.agentId)
+ return { state: 'succeeded', dispatch: 'executed' }
+ })
+ vi.mocked(checkPidRuntime).mockResolvedValueOnce({ state: 'alive' })
+ .mockResolvedValue({ state: 'gone', reason: 'guest exited after its pane closed' })
+ try {
+ const result = expect(createStopAgentService(deps)(row.agentId)).rejects.toThrow('The harness changed while pausing')
+ await vi.advanceTimersByTimeAsync(250)
+ await result
+ expect(checkPidRuntime).toHaveBeenCalledTimes(2)
+ for (const [session] of vi.mocked(checkPidRuntime).mock.calls) expect(session.processIdentity).toEqual(identity)
+ expect(deps.forgetSession).not.toHaveBeenCalled()
+ expect(terminateDeletedAgent).not.toHaveBeenCalled()
+ expect(stoppedAgents.get(row.agentId)?.sessionId).toBe('saved')
+ } finally { vi.useRealTimers() }
+})
it('waits for the process a starting guest harness gained while it was saved', async () => {
// Stopped before its engine was seen, which the pane's watcher binds while the screen is saved: an older copy of the
// row has no process, which reads as gone at once.
diff --git a/cli/src/lib/stoppedAgents.spec.ts b/cli/src/lib/stoppedAgents.spec.ts
index 878d39876..3784f918e 100644
--- a/cli/src/lib/stoppedAgents.spec.ts
+++ b/cli/src/lib/stoppedAgents.spec.ts
@@ -297,6 +297,17 @@ describe('stopped harness persistence', () => {
expect(store.available([])).toHaveLength(1)
})
+ it.each([true, false])('hides a live Codex conversation across explicit and implicit default profiles, archived explicit=%s', async explicit => {
+ const { saved, store } = await fixture()
+ const { env } = await import('../config/env.js')
+ const defaultHome = join(env.CODEX_HOME, '.')
+ store.save({ ...saved, engine: 'codex', codexHome: explicit ? defaultHome : null })
+ const running = { ...saved, engine: 'codex' as const, agentId: 'replacement', codexHome: explicit ? null : defaultHome }
+ expect(store.available([running])).toEqual([])
+ expect(store.get(saved.agentId)?.sessionId).toBe(saved.sessionId)
+ expect(store.available([{ ...running, codexHome: '/another/codex-profile' }])).toHaveLength(1)
+ })
+
it('stopping the shell left by an exited engine preserves its conversation', async () => {
const { saved, store } = await fixture()
store.save(saved)
diff --git a/cli/src/lib/stoppedAgents.ts b/cli/src/lib/stoppedAgents.ts
index 3c4929d87..649512228 100644
--- a/cli/src/lib/stoppedAgents.ts
+++ b/cli/src/lib/stoppedAgents.ts
@@ -7,6 +7,7 @@ import { isTerminalEngine } from '../engines/types.js'
import { atomicWriteJson, projectDisplayName, strictPersistedRow, type RegisteredSession } from './registry.js'
import { readPrivateStateFile, secureStateDirectory, syncStateDirectory } from './secureState.js'
import { sameProcessIdentity } from './terminalRuntime.js'
+import { conversationKey } from './conversationIdentity.js'
const SAFE_ID = /^[a-zA-Z0-9_-]{1,128}$/
const CATALOG_CACHE_RECORDS = 2048
@@ -256,10 +257,11 @@ export class StoppedAgentStore {
/** 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}`)))
+ const conversations = new Set(live.map(conversationKey))
+ return this.list().filter(session => {
+ const key = conversationKey(session)
+ return !ids.has(session.agentId) && (key === null || !conversations.has(key))
+ })
}
}
diff --git a/cli/src/lib/windows/dataFolderClaim.spec.ts b/cli/src/lib/windows/dataFolderClaim.spec.ts
index 937a69cf6..baa397271 100644
--- a/cli/src/lib/windows/dataFolderClaim.spec.ts
+++ b/cli/src/lib/windows/dataFolderClaim.spec.ts
@@ -127,10 +127,19 @@ describe.skipIf(process.platform === 'win32')('the data folder claim, a Unix soc
})
it('waits for the core of a master that is gone, then claims the folder once it leaves', async () => {
- const { dataDir, deps } = folder({ alive: () => false, pollMs: 20 })
+ let orphanObserved!: () => void
+ const waiting = new Promise<void>((resolve) => { orphanObserved = resolve })
+ const { dataDir, deps } = folder({ alive: () => false, pollMs: 20, log: (line) => {
+ lines.push(line)
+ orphanObserved()
+ } })
const orphan = await claimDataFolder(dataDir, TOKEN, { ...deps, holder: { pid: 41, corePid: 42 } })
- setTimeout(() => orphan.release(), 150)
- expect((await take(dataDir, TOKEN, deps)).held).toBe(true)
+ const claiming = take(dataDir, TOKEN, deps)
+ // A timed close could cut the holder's proof in half under CI load and test the unrelated
+ // "not Harness" path. Release only after the claimant has proved and observed the orphan.
+ await waiting
+ orphan.release()
+ expect((await claiming).held).toBe(true)
expect(lines).toContain(`[cli] this data folder is still claimed by the core (pid 42) of a master that is gone (pid 41) — waiting for it to leave`)
})