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.

fix(cli): release shared Codex conversations before restarting (#1432)

Dee667e6a40d532
diff --git a/cli/e2e/engineNativeControl.e2e.ts b/cli/e2e/engineNativeControl.e2e.ts
index 8410f8453..ab47c76ac 100644
--- a/cli/e2e/engineNativeControl.e2e.ts
+++ b/cli/e2e/engineNativeControl.e2e.ts
@@ -91,6 +91,64 @@ describe('Codex\'s shared server, from the Codex worker', () => {
expect(d.coresStarted()).toBe(1)
})
+ it('restarts a failed shared conversation after a Codex update without leaving its writer locked', async () => {
+ const { d, c, s, agent, count } = await fresh()
+ // The old client shares its server; the installed update supports --no-daemon. The failed turn
+ // has no active goal, but its server still owns the thread, exactly as Codex 0.163.0 did.
+ s.state.failed = true
+ s.holdWriter()
+ writeFileSync(join(d.root, 'bin', 'codex'), `#!${process.execPath}\nimport(${JSON.stringify(pathToFileURL(join(CLI_ROOT, 'e2e/harness/fakeEngine.mjs')).href)}).then(m => m.run('codex', ${JSON.stringify(d.engineConfig)}))\n`, { mode: 0o755 })
+ const before = s.state.requests.length
+ const restarted = await c.request('agent_restart', { agentId: agent.id }, 90_000)
+ expect(restarted.error, JSON.stringify(restarted)).toBeUndefined()
+ expect(s.state.loaded, 'the old server must release the conversation before the replacement opens it').toBe(false)
+ expect(s.state.archived).toBe(false)
+ expect(count('thread/archive', before)).toBe(1)
+ expect(count('thread/unarchive', before)).toBe(1)
+ expect(count('turn/interrupt', before)).toBe(0)
+ expect(count('thread/goal/set', before)).toBe(0)
+ const screen = await d.tmux.run('capture-pane', '-p', '-t', agent.tmuxPane)
+ expect(screen).not.toContain('This conversation is open in another app')
+ const ended = c.next(frame => frame.type === 'turn_ended' && frame.agentId === agent.id, 30_000, 'a turn in the resumed conversation')
+ c.send('message', { agentId: agent.id, content: 'continue after the failed turn' })
+ await ended
+ const row = (await c.request('agents_list', {})).agents.find((row: Row) => row.id === agent.id)
+ expect(row.sessionId).toBe(agent.sessionId)
+ expect(d.coresStarted()).toBe(1)
+ })
+
+ it('keeps the original client when the Codex worker is lost while restart releases its shared conversation', async () => {
+ const { d, c, s, agent, count, pane } = await fresh()
+ const panePid = await pane()
+ s.state.hold = 'thread/turns/list'
+ const restarting = c.request('agent_restart', { agentId: agent.id }, 90_000)
+ await until('restart waiting on the server', () => count('thread/turns/list') > 0 || null, 30_000, 50)
+ process.kill(harnessdProcesses(d).get('engine-codex')!, 'SIGKILL')
+ const refused = await restarting
+ expect(refused.error, JSON.stringify(refused)).toBe('RESTART_FAILED')
+ expect(refused.detail).toContain('could not stop')
+ s.release()
+ expect(await pane()).toBe(panePid)
+ expect(s.state.loaded).toBe(true)
+ expect(count('thread/archive')).toBe(0)
+ expect(d.coresStarted()).toBe(1)
+ })
+
+ it('restarts a process-owned conversation without unloading an unrelated shared server', async () => {
+ const { d, c, s, agent, count } = await fresh({}, false)
+ const before = s.state.requests.length
+ const restarted = await c.request('agent_restart', { agentId: agent.id }, 90_000)
+ expect(restarted.error, JSON.stringify(restarted)).toBeUndefined()
+ expect(count('thread/read', before)).toBe(0)
+ expect(count('thread/archive', before)).toBe(0)
+ expect(s.state.loaded).toBe(true)
+ expect(s.state.archived).toBe(false)
+ const ended = c.next(frame => frame.type === 'turn_ended' && frame.agentId === agent.id, 30_000, 'a turn after process-owned restart')
+ c.send('message', { agentId: agent.id, content: 'continue in this terminal' })
+ await ended
+ expect(d.coresStarted()).toBe(1)
+ })
+
it('a worker killed while a stop waits on the server sends nothing more, leaves the pane, and a second close stops it once', async () => {
const { d, s, count, close, pane } = await fresh()
const core = d.corePid(), worker = harnessdProcesses(d).get('engine-codex')!, panePid = await pane()
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjs
index 019dede1e..97316a4ee 100644
--- a/cli/e2e/harness/fakeEngine.mjs
+++ b/cli/e2e/harness/fakeEngine.mjs
@@ -291,6 +291,23 @@ export async function run(engine, config = {}, { native = false } = {}) {
// refuses before its TUI is up (codex-rs app-server thread_processor.rs) until `codex unarchive <id>`
// moves it back under `sessions/`.
if (engine === 'codex' && resumed && !fork) {
+ // Codex 0.163.0 keeps a failed thread's writer in its shared app-server. A --no-daemon resume
+ // stays alive on this lock screen without opening the conversation or sending SessionStart
+ // (2026-10-19). A live terminal process alone therefore cannot prove that a restart succeeded.
+ const writer = join(codexHome, 'app-server-daemon', 'fake-writer.json')
+ const locked = () => args.includes('--no-daemon') && existsSync(writer)
+ && JSON.parse(readFileSync(writer, 'utf8')).threadId === resumed
+ if (locked()) {
+ process.stdout.write('This conversation is open in another app\r\nClose it there and press R to continue here.\r\n')
+ process.stdin.setRawMode?.(true)
+ process.stdin.resume()
+ await new Promise(resolve => {
+ const retry = data => {
+ if (/r/i.test(String(data)) && !locked()) { process.stdin.off('data', retry); resolve() }
+ }
+ process.stdin.on('data', retry)
+ })
+ }
const holds = (dir) => {
let names = []
try { names = readdirSync(dir, { withFileTypes: true }) } catch { return false }
diff --git a/cli/e2e/harness/sharedCodex.ts b/cli/e2e/harness/sharedCodex.ts
index 296e73157..09fd984b3 100644
--- a/cli/e2e/harness/sharedCodex.ts
+++ b/cli/e2e/harness/sharedCodex.ts
@@ -1,7 +1,7 @@
/** The local app-server protocol of an older shared Codex session, without a model or credentials.
* Its real loopback WebSocket is reached through the fake CLI's raw-byte `app-server proxy` command. */
import { execFileSync } from 'node:child_process'
-import { mkdirSync, writeFileSync } from 'node:fs'
+import { mkdirSync, rmSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { WebSocketServer } from 'ws'
@@ -17,7 +17,8 @@ export async function sharedCodex(home: string) {
// `open` counts the clients connected now. A request named in `hold` is answered only once `release()` is
// called: a test can stop whoever asked while the server still owes the answer.
// `archived`: a thread/archive with no thread/unarchive after it (the thread's history hidden from sessions).
- const state = { threadId: '', loaded: true, archived: false, open: 0, hold: null as string | null,
+ const writer = join(home, 'app-server-daemon', 'fake-writer.json')
+ const state = { threadId: '', loaded: true, failed: false, archived: false, open: 0, hold: null as string | null,
requests: [] as Array<{ method: string; params?: Record<string, unknown> }> }
const held: Array<() => void> = []
server.on('connection', socket => {
@@ -31,17 +32,18 @@ export async function sharedCodex(home: string) {
if (frame.method === 'initialize') result = { codexHome: home }
else if (frame.params?.threadId !== state.threadId) {
socket.send(JSON.stringify({ id: frame.id, error: { message: 'unknown fixture thread' } })); return
- } else if (frame.method === 'thread/read') result = { thread: { id: state.threadId, status: { type: state.loaded ? 'active' : 'notLoaded' } } }
- else if (frame.method === 'thread/goal/get') result = { goal: { status: 'active' } }
- else if (frame.method === 'thread/turns/list') result = { data: [{ id: 'held-turn', status: 'inProgress' }] }
- else if (frame.method === 'thread/archive') { state.loaded = false; state.archived = true }
+ } else if (frame.method === 'thread/read') result = { thread: { id: state.threadId, status: { type: state.loaded ? state.failed ? 'systemError' : 'active' : 'notLoaded' } } }
+ else if (frame.method === 'thread/goal/get') result = { goal: state.failed ? null : { status: 'active' } }
+ else if (frame.method === 'thread/turns/list') result = { data: [{ id: 'held-turn', status: state.failed ? 'failed' : 'inProgress' }] }
+ else if (frame.method === 'thread/archive') { state.loaded = false; state.archived = true; rmSync(writer, { force: true }) }
else if (frame.method === 'thread/unarchive') state.archived = false
const answer = () => { if (socket.readyState === socket.OPEN) socket.send(JSON.stringify({ id: frame.id, result })) }
if (frame.method === state.hold) held.push(answer)
else answer()
})
})
- return { state, release() { state.hold = null; for (const answer of held.splice(0)) answer() }, async close() {
+ return { state, holdWriter() { writeFileSync(writer, JSON.stringify({ threadId: state.threadId })) },
+ release() { state.hold = null; for (const answer of held.splice(0)) answer() }, async close() {
for (const socket of server.clients) socket.terminate()
await new Promise<void>(resolve => server.close(() => resolve()))
} }
diff --git a/cli/src/core/agents/swap.spec.ts b/cli/src/core/agents/swap.spec.ts
index 118dc7e48..73b7428b2 100644
--- a/cli/src/core/agents/swap.spec.ts
+++ b/cli/src/core/agents/swap.spec.ts
@@ -33,6 +33,7 @@ function setup(row: RegisteredSession | null = session()) {
tmuxBackend: tmuxBackend as unknown as PaneSwapDeps['tmuxBackend'],
prepareSessionResume: vi.fn(),
keepAbandonedConversation: vi.fn(),
+ stopNative: vi.fn(async () => {}),
}
return { deps, tmuxBackend, swap: createPaneSwap(deps) }
}
@@ -61,13 +62,17 @@ describe('the pane-process swap', () => {
it('passes revocable ownership into the final signal and tmux dispatch boundaries', async () => {
const { swap, tmuxBackend } = setup()
- const current = () => false
+ let allowed = true
+ const current = () => allowed
const prepared = swap.paneSwapDeps(session(), runtime, {}, null, current)
- expect(prepared.isCurrent?.()).toBe(false)
+ expect(prepared.isCurrent?.()).toBe(true)
await prepared.holdOpen()
expect(tmuxBackend.holdOpen).toHaveBeenCalledWith(runtime, current)
await prepared.terminate()
- expect(vi.mocked(terminateDeletedAgent).mock.lastCall?.[1].current).toBe(current)
+ const signalCurrent = vi.mocked(terminateDeletedAgent).mock.lastCall?.[1].current
+ expect(signalCurrent?.()).toBe(true)
+ allowed = false
+ expect(signalCurrent?.()).toBe(false)
await prepared.respawn(['fixture-engine'])
expect(tmuxBackend.respawn).toHaveBeenCalledWith(runtime, expect.objectContaining({ current }))
})
@@ -120,6 +125,53 @@ describe('the pane-process swap', () => {
expect(log).toHaveBeenCalledWith('stopping')
})
+ it('releases the conversation on its native server before signalling the terminal client', async () => {
+ const { deps, swap } = setup(session({ engine: 'codex' }))
+ let release!: () => void
+ vi.mocked(deps.stopNative).mockImplementationOnce(() => new Promise<void>(resolve => { release = resolve }))
+ const stopping = swap.paneSwapDeps(session({ engine: 'codex' }), runtime).terminate()
+ expect(deps.stopNative).toHaveBeenCalledWith(session({ engine: 'codex' }), expect.any(Function))
+ expect(terminateDeletedAgent).not.toHaveBeenCalled()
+ release()
+ await stopping
+ expect(terminateDeletedAgent).toHaveBeenCalledOnce()
+ })
+
+ it('leaves the terminal client running when its native server cannot release the conversation', async () => {
+ const { deps, swap } = setup()
+ vi.mocked(deps.stopNative).mockRejectedValueOnce(new Error('Could not confirm the conversation stopped'))
+ await expect(swap.paneSwapDeps(session(), runtime).terminate()).rejects.toThrow('Could not confirm')
+ expect(terminateDeletedAgent).not.toHaveBeenCalled()
+ })
+
+ it('does nothing when the swap was cancelled before releasing its conversation', async () => {
+ const { deps, swap } = setup()
+ expect(await swap.paneSwapDeps(session(), runtime, {}, null, () => false).terminate()).toBe('not-ours')
+ expect(deps.stopNative).not.toHaveBeenCalled()
+ expect(terminateDeletedAgent).not.toHaveBeenCalled()
+ })
+
+ it.each(['cancelled', 'conversation', 'profile', 'process', 'registration', 'removed'] as const)('revokes the native stop and the terminal signal when %s while the server answers', async change => {
+ const row = session({ engine: 'codex', processIdentity: { pid: 42, executable: 'codex', startMarker: 'before' } })
+ const { deps, swap } = setup(row)
+ let allowed = true
+ const prepared = swap.paneSwapDeps(row, runtime, {}, null, () => allowed)
+ vi.mocked(deps.stopNative).mockImplementationOnce(async (target, current) => {
+ expect(current()).toBe(true)
+ if (change === 'cancelled') allowed = false
+ if (change === 'conversation') row.sessionId = 'new-conversation'
+ if (change === 'profile') row.codexHome = '/new-profile'
+ if (change === 'process') row.processIdentity!.startMarker = 'replacement'
+ if (change === 'registration') row.registeredAt++
+ if (change === 'removed') vi.mocked(deps.byAgent).mockReturnValue(undefined)
+ expect(target.sessionId).toBe('s1')
+ expect(target.processIdentity!.startMarker).toBe('before')
+ expect(current()).toBe(false)
+ })
+ expect(await prepared.terminate()).toBe('not-ours')
+ expect(terminateDeletedAgent).not.toHaveBeenCalled()
+ })
+
it('waits for the new process with growing pauses, and gives up once eight seconds have passed', async () => {
vi.useFakeTimers()
const { swap } = setup()
diff --git a/cli/src/core/agents/swap.ts b/cli/src/core/agents/swap.ts
index 165c16175..feec96ac7 100644
--- a/cli/src/core/agents/swap.ts
+++ b/cli/src/core/agents/swap.ts
@@ -15,6 +15,8 @@ import type { TmuxRuntimeRef } from '../../lib/terminalTypes.js'
import { bypassPermissionActive, resolvePaneEngineProcess } from '../../lib/tmux.js'
import { sameProcessIdentity } from '../../lib/terminalRuntime.js'
import type { TmuxBackend } from '../../lib/tmuxBackend.js'
+import type { StopAgentServiceDeps } from '../../lib/stopAgentService.js'
+import { paneReadIdentity } from '../transcripts/readIdentity.js'
export interface PaneSwapDeps {
restartJobs?: AgentRestartCoordinator
@@ -24,12 +26,14 @@ export interface PaneSwapDeps {
prepareSessionResume: (session: RegisteredSession) => void
/** Keeps a conversation a swap had to leave for a new one as a stopped harness (lib/keepAbandonedConversation.ts). */
keepAbandonedConversation: (left: RegisteredSession) => void
+ /** Release the conversation on its engine's server before replacing the terminal client. */
+ stopNative: StopAgentServiceDeps['stopNative']
}
/** How long a relaunched engine must stay running before a restart counts it as come up (`waitForProcess`). */
export const SWAP_SETTLE_MS = 500
-export function createPaneSwap({ byAgent, tmuxBackend, prepareSessionResume, keepAbandonedConversation, restartJobs = new AgentRestartCoordinator() }: PaneSwapDeps) {
+export function createPaneSwap({ byAgent, tmuxBackend, prepareSessionResume, keepAbandonedConversation, stopNative, restartJobs = new AgentRestartCoordinator() }: PaneSwapDeps) {
/**
* The dependencies a pane-process swap needs, for both callers that do one.
*
@@ -53,81 +57,96 @@ export function createPaneSwap({ byAgent, tmuxBackend, prepareSessionResume, kee
* stopped taking its flag and the caller dropped it (`dropPermissionFlagIfUnsupported`). */
permissionMode: string | null = session.permissionMode ?? null,
current?: () => boolean,
- ): RestartAgentDeps => ({
- ...(current ? { isCurrent: current } : {}),
- prepareResume: () => prepareSessionResume(session),
- // The row as the swap found it: the conversation a fallback to a fresh start leaves behind.
- keepAbandoned: () => keepAbandonedConversation(session),
- respawnRefusal: () => tmuxBackend!.respawnRefusal(launch.env ? { env: launch.env } : {}),
- holdOpen: async () => {
- const result = await tmuxBackend!.holdOpen(runtime, current)
- return result.state === 'succeeded'
- ? { ok: true }
- : { ok: false, reason: 'reason' in result ? result.reason : 'could not re-arm remain-on-exit' }
- },
- terminate: (checkAfterMs) => terminateDeletedAgent(session, {
- checkRuntime: checkPidRuntime,
- kill: (pid, signal) => process.kill(pid, signal),
- sleep: (ms) => new Promise((resolve) => { const t = setTimeout(resolve, ms); t.unref?.() }),
- log: (message) => console.log(message),
- ...(current ? { current } : {}),
- }, checkAfterMs),
- respawn: async (argv) => {
- const result = await tmuxBackend!.respawn(runtime, {
- command: argv,
- ...(current ? { current } : {}),
- cwd: homedir(),
- ...(launch.env ? { env: launch.env } : {}),
- })
- return result.state === 'succeeded'
- ? { ok: true }
- : { ok: false, reason: 'reason' in result ? result.reason : 'tmux respawn-pane did not complete' }
- },
- waitForProcess: async () => {
- // Mirrors onCreateAgent's own discovery budget/backoff shape for the same reason: the engine's
- // interactive-login-shell startup, not the tmux call, is the slow half.
- const SWAP_DISCOVERY_BUDGET_MS = 8_000
- let delayMs = 150
- let waited = 0
- while (waited < SWAP_DISCOVERY_BUDGET_MS) {
- await new Promise((resolve) => setTimeout(resolve, delayMs))
- waited += delayMs
- const found = await resolvePaneEngineProcess(runtime.paneId, session.engine)
- if (found) {
- // Up means still up a moment later: a launch the engine refuses (`codex resume` after an update
- // dropped it) runs for an instant, and seen then, the restart said "resumed" and never fell back
- // to a fresh start (e2e/updates.e2e.ts on Linux, whose faster start put it in the first look).
- await new Promise((resolve) => setTimeout(resolve, SWAP_SETTLE_MS))
- waited += SWAP_SETTLE_MS
- const still = await resolvePaneEngineProcess(runtime.paneId, session.engine)
- if (sameProcessIdentity(still, found)) return found
+ ): RestartAgentDeps => {
+ const target = { ...session, processIdentity: session.processIdentity && { ...session.processIdentity } }
+ const identity = paneReadIdentity(target)
+ const ownsOriginal = () => current?.() !== false && sameRestartTarget(target)
+ && paneReadIdentity(byAgent(target.agentId)) === identity
+ return {
+ ...(current ? { isCurrent: current } : {}),
+ prepareResume: () => prepareSessionResume(session),
+ // The row as the swap found it: the conversation a fallback to a fresh start leaves behind.
+ keepAbandoned: () => keepAbandonedConversation(session),
+ respawnRefusal: () => tmuxBackend!.respawnRefusal(launch.env ? { env: launch.env } : {}),
+ holdOpen: async () => {
+ const result = await tmuxBackend!.holdOpen(runtime, current)
+ return result.state === 'succeeded'
+ ? { ok: true }
+ : { ok: false, reason: 'reason' in result ? result.reason : 'could not re-arm remain-on-exit' }
+ },
+ terminate: async (checkAfterMs) => {
+ if (!ownsOriginal()) return 'not-ours'
+ // Restart used to kill only Codex's terminal client. Its shared app-server kept the writer
+ // lock after a failed turn, so the replacement stayed alive on "open in another app" and
+ // was reported resumed (2026-10-19). Use Stop Harness's conversation cleanup before any
+ // signal, for restart and retarget alike. A refusal leaves the original client running.
+ await stopNative(target, ownsOriginal)
+ if (!ownsOriginal()) return 'not-ours'
+ return terminateDeletedAgent(target, {
+ checkRuntime: checkPidRuntime,
+ kill: (pid, signal) => process.kill(pid, signal),
+ sleep: (ms) => new Promise((resolve) => { const t = setTimeout(resolve, ms); t.unref?.() }),
+ log: (message) => console.log(message),
+ current: ownsOriginal,
+ }, checkAfterMs)
+ },
+ respawn: async (argv) => {
+ const result = await tmuxBackend!.respawn(runtime, {
+ command: argv,
+ ...(current ? { current } : {}),
+ cwd: homedir(),
+ ...(launch.env ? { env: launch.env } : {}),
+ })
+ return result.state === 'succeeded'
+ ? { ok: true }
+ : { ok: false, reason: 'reason' in result ? result.reason : 'tmux respawn-pane did not complete' }
+ },
+ waitForProcess: async () => {
+ // Mirrors onCreateAgent's own discovery budget/backoff shape for the same reason: the engine's
+ // interactive-login-shell startup, not the tmux call, is the slow half.
+ const SWAP_DISCOVERY_BUDGET_MS = 8_000
+ let delayMs = 150
+ let waited = 0
+ while (waited < SWAP_DISCOVERY_BUDGET_MS) {
+ await new Promise((resolve) => setTimeout(resolve, delayMs))
+ waited += delayMs
+ const found = await resolvePaneEngineProcess(runtime.paneId, session.engine)
+ if (found) {
+ // Up means still up a moment later: a launch the engine refuses (`codex resume` after an update
+ // dropped it) runs for an instant, and seen then, the restart said "resumed" and never fell back
+ // to a fresh start (e2e/updates.e2e.ts on Linux, whose faster start put it in the first look).
+ await new Promise((resolve) => setTimeout(resolve, SWAP_SETTLE_MS))
+ waited += SWAP_SETTLE_MS
+ const still = await resolvePaneEngineProcess(runtime.paneId, session.engine)
+ if (sameProcessIdentity(still, found)) return found
+ }
+ delayMs = Math.min(delayMs * 2, 750)
}
- delayMs = Math.min(delayMs * 2, 750)
- }
- return null
- },
- buildArgv: (opts) => buildEngineLaunchArgv(session.engine, {
- ...opts,
- ...(launch.native ? { native: launch.native } : {}),
- // The mode picked at create outranks what the live argv said: `bypassPermission` is a yes/no, and
- // Plan or Accept edits would come back as Ask without it.
- ...(permissionMode ? { permissionMode } : {}),
- ...(session.cwd ? { cwd: session.cwd } : {}),
- ...(launch.extraArgs?.length ? { extraArgs: launch.extraArgs } : {}),
- // A pane swap onto a grid has to clear the same vendor credentials a fresh create does, for the
- // same reason and against the same failure: an engine re-exec'd with the grid's variables still
- // sees whatever else the pane inherited, and picks its provider from all of it. This was the
- // gap — a create cleared them, then moving that agent onto a grid from the pane header put them
- // straight back, so the engine came up on Anthropic with a grid selected above it.
- //
- // Named by the caller (`buildLaunchOverrides` derives it from what the grid launch provides), so
- // a swap that sets no grid — back to the engine's own login, or a Codex profile's CODEX_HOME —
- // clears nothing. There the user's own variables are the point.
- ...(launch.clearEnv?.length ? { clearEnv: launch.clearEnv } : {}),
- ...(launch.env?.HARNESS_DSH ? { harnessNode: true } : {}),
- }),
- log: (message) => console.log(message),
- })
+ return null
+ },
+ buildArgv: (opts) => buildEngineLaunchArgv(session.engine, {
+ ...opts,
+ ...(launch.native ? { native: launch.native } : {}),
+ // The mode picked at create outranks what the live argv said: `bypassPermission` is a yes/no, and
+ // Plan or Accept edits would come back as Ask without it.
+ ...(permissionMode ? { permissionMode } : {}),
+ ...(session.cwd ? { cwd: session.cwd } : {}),
+ ...(launch.extraArgs?.length ? { extraArgs: launch.extraArgs } : {}),
+ // A pane swap onto a grid has to clear the same vendor credentials a fresh create does, for the
+ // same reason and against the same failure: an engine re-exec'd with the grid's variables still
+ // sees whatever else the pane inherited, and picks its provider from all of it. This was the
+ // gap — a create cleared them, then moving that agent onto a grid from the pane header put them
+ // straight back, so the engine came up on Anthropic with a grid selected above it.
+ //
+ // Named by the caller (`buildLaunchOverrides` derives it from what the grid launch provides), so
+ // a swap that sets no grid — back to the engine's own login, or a Codex profile's CODEX_HOME —
+ // clears nothing. There the user's own variables are the point.
+ ...(launch.clearEnv?.length ? { clearEnv: launch.clearEnv } : {}),
+ ...(launch.env?.HARNESS_DSH ? { harnessNode: true } : {}),
+ }),
+ log: (message) => console.log(message),
+ }
+ }
/** The bypass-permission flag the LIVE process was launched with. The fallback behind
* `bypassPermissionFor` for a row that recorded neither a mode nor the flag (written before either
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 3e8c7dae7..0e893d082 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -2546,6 +2546,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
tmuxBackend,
prepareSessionResume,
keepAbandonedConversation,
+ stopNative: (session, current) => nativeControls.stop(session, current),
})
// A message sent while an engine is being replaced waits for the new one instead of being refused.
terminals.whileChanging((agentId) => restorePanes.busy(agentId) || restartJobs.busy(agentId))
diff --git a/cli/src/lib/restartAgent.spec.ts b/cli/src/lib/restartAgent.spec.ts
index a4c476cdf..a34516433 100644
--- a/cli/src/lib/restartAgent.spec.ts
+++ b/cli/src/lib/restartAgent.spec.ts
@@ -104,6 +104,13 @@ describe('restartAgent', () => {
expect(d.calls).toEqual(['holdOpen', 'terminate'])
})
+ it.each([new Error('The conversation is still held on its server'), 'server unavailable'])('reports a refused native stop without respawning or falling back: %s', async error => {
+ const d = deps({ terminate: async () => { throw error } })
+ const outcome = await restartAgent({ engine: 'codex', sessionId: 's1' }, false, d)
+ expect(outcome).toEqual({ ok: false, detail: `could not stop the running codex session: ${error instanceof Error ? error.message : error}` })
+ expect(d.calls).toEqual(['holdOpen', 'terminate'])
+ })
+
it('treats "gone" (the process had already exited) as a confirmed kill, safe to respawn over', async () => {
const d = deps({ terminate: async () => 'gone' })
const outcome = await restartAgent({ engine: 'claude', sessionId: 's1' }, false, d)
diff --git a/cli/src/lib/restartAgent.ts b/cli/src/lib/restartAgent.ts
index ec58d473c..501f23d47 100644
--- a/cli/src/lib/restartAgent.ts
+++ b/cli/src/lib/restartAgent.ts
@@ -130,7 +130,11 @@ export async function restartAgent(
return { ok: false, detail: armed.reason ?? 'could not re-arm the pane before restart' }
}
- const outcome = await deps.terminate()
+ let outcome: TerminateOutcome
+ try { outcome = await deps.terminate() }
+ catch (error) {
+ return { ok: false, detail: `could not stop the running ${session.engine} session: ${error instanceof Error ? error.message : error}` }
+ }
if (!current()) return changed
if (!KILL_CONFIRMED.has(outcome)) {
return { ok: false, detail: `could not confirm the running ${session.engine} process was stopped (${outcome})` }
diff --git a/cli/src/lib/restoreAgents.spec.ts b/cli/src/lib/restoreAgents.spec.ts
index aced5a373..d5a71510d 100644
--- a/cli/src/lib/restoreAgents.spec.ts
+++ b/cli/src/lib/restoreAgents.spec.ts
@@ -314,7 +314,7 @@ describe('restore ownership across asynchronous work', () => {
h.deps.probeProcess = () => probe.promise
await restoreAgents(h.deps)
const swap = createPaneSwap({ restartJobs, byAgent: h.deps.registry.byAgent, tmuxBackend: null,
- prepareSessionResume: () => {}, keepAbandonedConversation: () => {} })
+ prepareSessionResume: () => {}, keepAbandonedConversation: () => {}, stopNative: async () => {} })
expect(swap.restartJobs).toBe(restartJobs)
probe.resolve(identity(8))
await settled(h, 1, 1)