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(codex): a move between a grid and the own login continues the conversation in a fork (#2318)

lingrd6470ba96fb48
diff --git a/cli/src/core/agents/retarget.spec.ts b/cli/src/core/agents/retarget.spec.ts
index 70c6be645..894b0a004 100644
--- a/cli/src/core/agents/retarget.spec.ts
+++ b/cli/src/core/agents/retarget.spec.ts
@@ -338,6 +338,30 @@ describe('retargeting an agent', () => {
})
describe('a move that goes ahead', () => {
+ // Codex 0.166 refuses to resume a conversation on another provider (thread/resume → ModelProviderMismatch);
+ // a move between a grid and its own login changes provider, so the conversation goes on in a fork of it.
+ it.each([
+ ['its own login onto a grid', agent({ engine: 'codex' }), grid, true],
+ ['a grid back to its own login', agent({ engine: 'codex', gridLaunch: grid }), null, true],
+ ['one grid to another (the same provider)', agent({ engine: 'codex', gridLaunch: grid }), { ...grid, networkId: 'g2' }, false],
+ ] as const)('continues a Codex conversation moved from %s in a fork only when its provider changes', async (_how, row, to, forks) => {
+ const run = setup(row)
+ expect(await run.retarget({ agentId: 'a1', grid: to })).toEqual({ ok: true })
+ expect(vi.mocked(restartAgent).mock.calls[0][0]).toEqual({ engine: 'codex', sessionId: 's1', ...(forks ? { continueInFork: true } : {}) })
+ })
+
+ it('resumes an engine whose conversations follow any provider (Claude Code) on every move', async () => {
+ const run = setup(agent())
+ expect(await run.retarget({ agentId: 'a1', grid })).toEqual({ ok: true })
+ expect(vi.mocked(restartAgent).mock.calls[0][0]).toEqual({ engine: 'claude', sessionId: 's1' })
+ })
+
+ it('starts fresh rather than forking a Codex agent with no conversation yet', async () => {
+ const run = setup(agent({ engine: 'codex', sessionId: '' }))
+ expect(await run.retarget({ agentId: 'a1', grid })).toEqual({ ok: true })
+ expect(vi.mocked(restartAgent).mock.calls[0][0]).toEqual({ engine: 'codex', sessionId: '' })
+ })
+
it('keeps its route until a slow replacement is confirmed, even past the default hold timer', async () => {
vi.useFakeTimers()
const onDiscovered = vi.fn()
diff --git a/cli/src/core/agents/retarget.ts b/cli/src/core/agents/retarget.ts
index 9adc9eaba..56579c789 100644
--- a/cli/src/core/agents/retarget.ts
+++ b/cli/src/core/agents/retarget.ts
@@ -25,6 +25,7 @@ import type { RuntimeProfileManager } from '../../lib/runtimeProfile.js'
import { parseRuntimeProfile } from '../../lib/runtimeProfileWire.js'
import type { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'
import { canRestart, restartTargetOf } from '../../lib/terminalBackend.js'
+import { launchContract } from '../../engines/launches.js'
import type { TerminalBackendCoordinator } from '../../lib/terminalBackendCoordinator.js'
import { terminalRouteKey } from '../../lib/terminalRuntime.js'
import { workspaceMissing } from '../../lib/workspaceCheck.js'
@@ -282,8 +283,13 @@ export function createAgentRetargeter({
const retargetPermission = await downgradedPermission(session, bypassPermission, 'retarget', native)
if (retargetPermission.nativeHold || native?.current() === false) return failed('NATIVE_LAUNCH_HELD', retargetPermission.nativeHold ?? 'Waiting for fresh executable and hook evidence.')
if (!current()) return changed()
+ // A Codex conversation is bound to its provider (`providerBoundConversations`): moved between a grid and the
+ // own login it goes on in a fork, its whole history with it; grid to grid is one provider and resumes.
+ const movesProvider = !!launchContract(session.engine)?.providerBoundConversations
+ && !!session.sessionId && !!(session.gridLaunch || session.grid) !== !!grid
const outcome = await restartAgent(
- { engine: session.engine, sessionId: session.sessionId, ...(session.resumeOnly ? { resumeOnly: true as const } : {}) },
+ { engine: session.engine, sessionId: session.sessionId, ...(session.resumeOnly ? { resumeOnly: true as const } : {}),
+ ...(movesProvider ? { continueInFork: true as const } : {}) },
retargetPermission.bypassPermission === true,
{ ...paneSwapDeps(session, place, !grid && !backend.clearEnv ? { ...built.overrides, clearPaneEnv: gridEnvVarNames(session.engine) } : built.overrides,
retargetPermission.permissionMode ?? null, dispatchCurrent), isCurrent: dispatchCurrent },
@@ -313,7 +319,7 @@ export function createAgentRetargeter({
// The app decides whether to still offer a move from what it is told here, so a silent success
// would leave the banner up over an agent that had already been moved.
if (refreshed) { announceSession(refreshed); refreshGridAssignment(refreshed) }
- const how = outcome.resumed ? 'resumed' : 'fresh session'
+ const how = outcome.resumed ? (movesProvider ? 'continued in a fork' : 'resumed') : 'fresh session'
const record = built.overrides.gridLaunchRecord
const where = record
? describeGridLaunch(session.engine, record.override, record.webSearch)
diff --git a/cli/src/core/agents/swap.ts b/cli/src/core/agents/swap.ts
index 7924b5cd5..804076689 100644
--- a/cli/src/core/agents/swap.ts
+++ b/cli/src/core/agents/swap.ts
@@ -14,7 +14,7 @@ import { windowsLaunchRefusal } from '../../lib/windows/launch.js'
import { isWindowsHeldPane, windowsPaneLaunch } from '../../lib/windows/engineStart.js'
import { mergedLaunchEnv } from './launchEnv.js'
import type { RegisteredSession } from '../../lib/registry.js'
-import { AgentRestartCoordinator, type RestartAgentDeps } from '../../lib/restartAgent.js'
+import { AgentRestartCoordinator, type RelaunchArgvOptions, type RestartAgentDeps } from '../../lib/restartAgent.js'
import { processRows } from '../../lib/terminalAgentDiscovery.js'
import type { RestartTarget } from '../../lib/terminalBackend.js'
import { resolvePaneEngineProcess } from '../../lib/paneEngineProcess.js'
@@ -70,7 +70,7 @@ export function createPaneSwap({ byAgent, prepareSessionResume, keepAbandonedCon
const identity = paneReadIdentity(target)
const ownsOriginal = () => current?.() !== false && sameRestartTarget(target)
&& paneReadIdentity(byAgent(target.agentId)) === identity
- const relaunchOptions = (opts: { bypassPermission: boolean; resumeSessionId?: string }) => ({
+ const relaunchOptions = (opts: RelaunchArgvOptions) => ({
...opts,
...(launch.native ? { native: launch.native } : {}),
// The mode picked at create outranks what the live argv said: `bypassPermission` is a yes/no, and
diff --git a/cli/src/engines/codex/launch.ts b/cli/src/engines/codex/launch.ts
index c49bf18af..8d301e013 100644
--- a/cli/src/engines/codex/launch.ts
+++ b/cli/src/engines/codex/launch.ts
@@ -60,6 +60,15 @@ export const launch: EngineLaunch = {
* every launch, and OpenCode's is a file this daemon writes, so only Codex declares this.
*/
ownProvider: { home: 'CODEX_HOME', file: 'config.toml', key: 'model_provider', fallback: 'openai', args: ['-c', 'model_provider="{value}"'] },
+ /**
+ * From codex-cli 0.166.0 that argv no longer outranks the stored row: `thread/resume` checks the thread's saved
+ * provider against the one it is given and refuses a difference (app-server config_manager.rs `load_for_resume`,
+ * ModelProviderMismatch: "This chat uses openai, but your current provider is grid"), and the restart fell back to a
+ * new conversation without its history. No app-server method changes a thread's provider (`thread/metadata/update`
+ * and `thread/settings/update` carry none); `thread/fork` builds its config as a new thread's, so a move between a
+ * grid and the own login continues the conversation in a fork, history included, on every version.
+ */
+ providerBoundConversations: true,
/**
* Codex keeps its folder trust in `<CODEX_HOME>/config.toml` as a `[projects."<path>"]` table with
* `trust_level = "trusted"`, read from the agent's own profile or a CODEX_HOME the person moved, exact
diff --git a/cli/src/engines/facets/launch.ts b/cli/src/engines/facets/launch.ts
index 972d67a1d..7037f9465 100644
--- a/cli/src/engines/facets/launch.ts
+++ b/cli/src/engines/facets/launch.ts
@@ -284,6 +284,9 @@ export interface EngineLaunch {
envArgs?: EnvArgsTemplate
sharedServer?: SharedServerContract
ownProvider?: OwnProviderContract
+ /** A conversation stays on the provider it was started on: the engine refuses to resume it on another, so a move
+ * between a grid and the engine's own login continues it in a fork (`forkArgs`) instead (core/agents/retarget.ts). */
+ providerBoundConversations?: true
startup?: StartupContract
/** The screen the engine's TUI runs on, where Harness chooses it; applied to every launch (kit/launchScreen.ts). */
screen?: ScreenContract
diff --git a/cli/src/lib/restartAgent.spec.ts b/cli/src/lib/restartAgent.spec.ts
index 08bc8fcf0..edb34fa86 100644
--- a/cli/src/lib/restartAgent.spec.ts
+++ b/cli/src/lib/restartAgent.spec.ts
@@ -164,6 +164,37 @@ describe('restartAgent', () => {
expect(d.calls).not.toContain('keepAbandoned')
})
+ it('continues in a fork of the conversation when asked to, with its history prepared, and leaves nothing behind', async () => {
+ const argvCalls: Array<{ bypassPermission: boolean; resumeSessionId?: string; forkSessionId?: string }> = []
+ const d = deps({ buildArgv: (opts) => { argvCalls.push(opts); return ['codex'] }, prepareResume: () => {} })
+ const outcome = await restartAgent({ engine: 'codex', sessionId: 'sess-42', continueInFork: true }, false, d)
+ expect(argvCalls).toEqual([{ bypassPermission: false, forkSessionId: 'sess-42' }])
+ expect(outcome).toEqual({ ok: true, processIdentity: IDENTITY, resumed: true })
+ expect(d.calls).toContain('prepareResume')
+ // The fork carries the whole conversation: no stopped harness is kept for the one it came from.
+ expect(d.calls).not.toContain('keepAbandoned')
+ })
+
+ it('asks whether the fork it would launch is refused, before anything is stopped', async () => {
+ const asked: Array<{ bypassPermission: boolean; resumeSessionId?: string; forkSessionId?: string }> = []
+ const d = { ...deps(), launchRefusal: (opts: { bypassPermission: boolean; resumeSessionId?: string; forkSessionId?: string }) => { asked.push(opts); return null } }
+ await restartAgent({ engine: 'codex', sessionId: 'sess-42', continueInFork: true }, false, d)
+ expect(asked).toEqual([{ bypassPermission: false, forkSessionId: 'sess-42' }])
+ })
+
+ it('falls back to a fresh relaunch when the fork never comes up, keeping the conversation it could not continue', async () => {
+ let attempt = 0
+ const argvCalls: Array<{ bypassPermission: boolean; resumeSessionId?: string; forkSessionId?: string }> = []
+ const d = deps({
+ buildArgv: (opts) => { argvCalls.push(opts); return ['codex'] },
+ waitForProcess: async () => { attempt += 1; return attempt === 1 ? null : IDENTITY },
+ })
+ const outcome = await restartAgent({ engine: 'codex', sessionId: 'sess-42', continueInFork: true }, false, d)
+ expect(argvCalls).toEqual([{ bypassPermission: false, forkSessionId: 'sess-42' }, { bypassPermission: false }])
+ expect(outcome).toEqual({ ok: true, processIdentity: IDENTITY, resumed: false })
+ expect(d.calls.at(-1)).toBe('keepAbandoned')
+ })
+
it('launches fresh (no resumeSessionId) when the session has none', async () => {
const argvCalls: Array<{ bypassPermission: boolean; resumeSessionId?: string }> = []
const d = deps({ buildArgv: (opts) => { argvCalls.push(opts); return ['claude'] } })
diff --git a/cli/src/lib/restartAgent.ts b/cli/src/lib/restartAgent.ts
index d5e7d0486..f35f22b2d 100644
--- a/cli/src/lib/restartAgent.ts
+++ b/cli/src/lib/restartAgent.ts
@@ -83,6 +83,9 @@ export class AgentRestartCoordinator {
}
}
+/** How the relaunch reopens the conversation: resumed, continued in a fork of it, or neither (a fresh one). */
+export interface RelaunchArgvOptions { bypassPermission: boolean; resumeSessionId?: string; forkSessionId?: string }
+
export interface RestartAgentDeps {
/** False after Stop, replacement, or removal. Checked across every await. */
isCurrent?: () => boolean
@@ -110,10 +113,10 @@ export interface RestartAgentDeps {
* ordering only, never allowed to fail the restart; implementations swallow their own errors.
*/
stopConflictingJob?: () => Promise<void>
- buildArgv: (opts: { bypassPermission: boolean; resumeSessionId?: string }) => string[]
+ buildArgv: (opts: RelaunchArgvOptions) => string[]
/** Why the relaunch [buildArgv] would build is refused on this platform (a Windows batch-file engine whose arguments
* cmd.exe would read, lib/windows/launch.ts), asked before anything is stopped; null when it is not. */
- launchRefusal?: (opts: { bypassPermission: boolean; resumeSessionId?: string }) => string | null
+ launchRefusal?: (opts: RelaunchArgvOptions) => string | null
log: (message: string) => void
/** Keeps the conversation the fresh fallback left as a stopped harness (keepAbandonedConversation.ts). */
keepAbandoned?: () => void
@@ -124,8 +127,14 @@ export interface RestartAgentDeps {
* respawn over a target the kill sequence could not confirm. */
export const KILL_CONFIRMED: ReadonlySet<TerminateOutcome> = new Set(['gone', 'terminated', 'killed'])
+/**
+ * [session.continueInFork]: the conversation goes on in a fork of it (`codex fork <id>`) instead of being resumed — the
+ * relaunch moves it to a provider it cannot be resumed on (`EngineLaunch.providerBoundConversations`). The fork is the
+ * whole conversation, so nothing is kept for the one it came from; the agent follows the fork's id when it binds
+ * (bind.ts, as a rebound).
+ */
export async function restartAgent(
- session: { engine: AgentEngine; sessionId: string; resumeOnly?: true },
+ session: { engine: AgentEngine; sessionId: string; resumeOnly?: true; continueInFork?: true },
bypassPermission: boolean,
deps: RestartAgentDeps,
): Promise<RestartOutcome> {
@@ -135,8 +144,9 @@ export async function restartAgent(
// Before anything is stopped: refused after the kill, the agent was left with no engine at all.
const refused = await deps.respawnRefusal?.()
if (refused) return { ok: false, detail: `${refused} Nothing was stopped.` }
+ const reopen = (id: string | undefined) => !id ? {} : session.continueInFork ? { forkSessionId: id } : { resumeSessionId: id }
// The resume relaunch has every argument the fresh fallback has, and more: refused, neither would start.
- const launchRefused = deps.launchRefusal?.({ bypassPermission, ...(session.sessionId ? { resumeSessionId: session.sessionId } : {}) })
+ const launchRefused = deps.launchRefusal?.({ bypassPermission, ...reopen(session.sessionId) })
if (launchRefused) return { ok: false, error: 'ENGINE_LAUNCH_REFUSED', detail: `${launchRefused} Nothing was stopped.` }
if (!current()) return changed
const armed = await deps.holdOpen()
@@ -166,10 +176,7 @@ export async function restartAgent(
if (!current()) return changed
const spawnAndWait = async (withResume: boolean): Promise<ProcessIdentity | null> => {
if (!current()) return null
- const argv = deps.buildArgv({
- bypassPermission,
- ...(withResume && resumeSessionId ? { resumeSessionId } : {}),
- })
+ const argv = deps.buildArgv({ bypassPermission, ...(withResume ? reopen(resumeSessionId) : {}) })
const spawned = await deps.respawn(argv)
if (!current()) return null
if (!spawned.ok) {