Skip to content

Codex terminal cold restore may omit saved session resume; defensive candidate and isolated regression tests #26436

Open

Description

@roaki-w

Title: Cold restore of a Codex terminal pane can start a new Codex session instead of resuming the saved session id

Environment

  • Orca desktop 1.4.222, macOS arm64, build commit 9fdd90ffa7721e145f1353ad9fb9df2f70c31f43 (official signed build)
  • Codex CLI 0.161.0, local terminal panes (no SSH)

What we observed (causation not established)

Before an OS restart, the profile had a saved sleeping-agent record (session_id) for each of several Codex terminal panes in one tab. About five minutes after the restart, one of those panes was running a new Codex session (a new session file appeared), and the post-restart saved record showed the new session id. The previous session file was still on disk. We did not capture that process's command line. We did not establish whether Orca's cold restore or a manual launch started it. We did not reproduce it against an unpatched build.

What we found in the source at the commit above

Reading the cold-restore path, we could not find a step that guarantees a same-id resume when the restored pane's effective startup command is empty, or is a recognized codex command with no resume token. In that case the spawn can go ahead as a plain codex launch. This comes from reading the source, not from a failing test against the base commit.

Expected behavior

For a verified cold restore of a Codex pane that has a saved session_id:

  • If the effective command is empty, or is codex without a resume token, launch codex resume <saved id> exactly once.
  • If the command already ends with a resume of the same id, keep it and do not add a second one.
  • If the command resumes a different id, cannot be classified, or the saved rollout cannot be verified, stop before spawning with a clear message rather than silently starting a new session. Keep the saved record so the next attempt can still resume.
  • If a spawn fails, clear only the launch registration and keep the saved record. The next remount should rebuild the same resume.
  • Explicit new sessions, pasted commands, arbitrary user commands, and a live pre-adopted process stay as they are today.

A candidate change (attached, not merged anywhere)

candidate.diff (20 files, against the commit above) adds an explicit coldRestoreResume intent. Only the cold-restore connect sets it. The renderer passes it through IPC and runtime spawn, including remote create params. Main uses it to align the Codex command as described above. Telemetry request_kind is not used for the decision. Shell quoting follows the already-resolved shell override; if no shell can be determined, the spawn stops instead of guessing.

What was verified, and what was not

Verified in an isolated dev checkout with the candidate applied, with node-pty and the transport replaced by the existing test doubles:

  • tsc --noEmit for the node and web configs: exit 0.
  • vitest: 10 files, 117 tests pass. This includes 2 new test files from tests.diff, a required coldRestoreResume: true literal added to 2 existing test files, and 6 existing files run unchanged. No unhandled errors.
  • The new boundary tests go through the real pty:spawn handler, the runtime controller spawn, and startFreshSpawn. The new retry test mounts connectPanePty for a local pane (no SSH connection). The first spawn is rejected; the saved record is kept; a second mount rebuilds the same codex resume <id> with the cold-restore flag.
  • Two deliberate regressions are each caught by the retry test: clearing the saved record on spawn failure, and dropping the cold-restore flag.

Not verified:

  • A packaged or running app, an Electron launch, an actual OS restart, Windows, a real SSH remote, a real Codex process or account.
  • A failing reproduction against the unpatched base commit.

Out of scope

This covers the Codex provider only. Other agent CLIs restored the same way (for example the Cursor agent with conversation_id) are not changed by the candidate and were not tested.

Reproduction commands

Base

  • Repository: stablyai/orca
  • Commit: 9fdd90ffa7721e145f1353ad9fb9df2f70c31f43 (same commit as the installed 1.4.222 build)
  • Public tag v1.4.222 points to a different commit (4bb6f2072b07c1f0664b809551f77754700570e4); neither contains the candidate.

Apply

git checkout 9fdd90ffa7721e145f1353ad9fb9df2f70c31f43
git apply candidate.diff
git apply tests.diff

tests.diff adds two test files and a coldRestoreResume: true literal to two existing tests:

  • src/main/ipc/pty-spawn-cold-restore-boundaries.test.ts (new)
  • src/renderer/src/components/terminal-pane/pty-connection-cold-restore-retry-closure.test.ts (new)
  • src/renderer/src/components/terminal-pane/pty-connection/empty-reattach-retire-evidence.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler-park-reveal-verdict.test.ts

The fixtures use synthetic ids (for example 019f81b9-19a9-7651-a8d1-352d9420bd11) and a placeholder home /Users/example.

Run

pnpm run typecheck:node
pnpm run typecheck:web
pnpm exec vitest run --config config/vitest.config.ts \
  src/renderer/src/components/terminal-pane/pty-connection-cold-restore-retry-closure.test.ts \
  src/main/ipc/pty-spawn-cold-restore-boundaries.test.ts \
  src/renderer/src/components/terminal-pane/pty-connection/empty-reattach-retire-evidence.test.ts \
  src/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler-park-reveal-verdict.test.ts \
  src/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.test.ts \
  src/renderer/src/components/terminal-pane/pty-connection-cold-restore-agent-resume.test.ts \
  src/renderer/src/components/terminal-pane/pty-connection-agent-session-resume.test.ts \
  src/main/ipc/pty-spawn-env-codex-resume-provenance.test.ts \
  src/renderer/src/components/terminal-pane/terminal-pane-recovery.test.ts \
  src/renderer/src/components/terminal-pane/terminal-pane-recovery-unsettled-fallback.test.ts

Our result: both typechecks exit 0; 10 files / 117 tests pass; no unhandled errors. Dependencies were installed with --ignore-scripts (no Electron rebuild, no husky). No app build or launch.

Mutation check

Two regressions were each applied to src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts, one at a time, with the retry test run against each:

  • In the spawn failure .catch, call session.clearSleepingRecordAfterColdRestoreSpawn(coldRestoreOverride) → the test fails (saved record must be kept).
  • Remove ...(coldRestoreOverride ? { coldRestoreResume: true as const } : {}) → the test fails (connect options must carry the flag).

Scenario the candidate targets

  1. A local Codex pane has a saved sleeping-agent record (session_id, transcript under the Codex home) from the quit capture.
  2. The app (or OS) restarts and the tab cold-restores that pane.
  3. The effective startup command is empty, or is codex without a resume token.
  4. Expected: codex resume <saved id> exactly once. Without the candidate, from reading the source, a plain codex launch may start a new session. This step has not been reproduced on an unpatched packaged build.

Not covered

Real app, packaged build, OS restart, Windows, real SSH remote, real Codex process. The Cursor agent provider (conversation_id) is out of scope.

candidate.diff
--- a/src/main/ipc/pty/host-env/codex-resume.ts
+++ b/src/main/ipc/pty/host-env/codex-resume.ts
@@ -1,9 +1,18 @@
 import type { TuiAgent } from '../../../../shared/tui-agent'
 import {
+  getAgentResumeArgv,
   normalizeAgentProviderSession,
   type AgentProviderSessionMetadata
 } from '../../../../shared/agent-session-resume'
-import { SETUP_AGENT_SEQUENCE_STARTUP_COMMAND_ENV } from '../../../../shared/setup-agent-sequencing'
+import {
+  resolveSetupAgentSequenceLaunchCommand,
+  SETUP_AGENT_SEQUENCE_STARTUP_COMMAND_ENV
+} from '../../../../shared/setup-agent-sequencing'
+import { buildAgentResumeLaunchCommand } from '../../../../shared/agent-resume-launch-command'
+import { recognizeAgentProcessFromCommandLine } from '../../../../shared/agent-process-recognition'
+import { tokenizeCommandLine } from '../../../../shared/agent-command-line-entrypoint'
+import type { AgentStartupShell } from '../../../../shared/tui-agent-startup-shell'
+import { canonicalizeWindowsShellOverride } from '../../../../shared/windows-terminal-shell'
 import { dropAgentResumeArgvFromCommand } from '../../../../shared/agent-resume-argv-drop'
 import type { CodexAccountSelectionTarget } from '../../../codex-accounts/runtime-selection'
 import { dropUnverifiedCodexResumeArgv } from '../../../codex/codex-unverified-resume-launch'
@@ -17,6 +26,21 @@
   notifyResumeUnavailable: boolean
   droppedResumeArgv: boolean
   providerSession: AgentProviderSessionMetadata | null
+  /** Set only when the eval'd sequenced command, not the PTY command, must change. */
+  sequencedStartupCommand?: string
+}
+
+export const AUTOMATIC_CODEX_RESUME_STOPPED =
+  'Orca stopped this saved Codex resume instead of starting a new chat.'
+
+export type CodexResumeLaunchContext = {
+  env?: { readonly [key: string]: string | undefined }
+  /** Set only by a cold-restore connect. */
+  coldRestoreResume?: boolean
+  /** `terminalRuntimeOptions.shellOverride` for this spawn, after the caller's own resolution. */
+  shellOverride?: string | null
+  platform?: NodeJS.Platform
+  connectionId?: string | null
 }
 
 export type PreparedCodexResumeHome = {
@@ -67,14 +91,20 @@
   }
 }
 
-/** The command a Codex launch actually runs: unchanged when provenance is verified,
- *  stripped of `resume <id>` when it is not. */
+/** Verified automatic resume aligns the command that actually runs. Other launches stay. */
 export function resolveCodexResumeLaunch(
   command: string | undefined,
-  preparation: PreparedCodexResumeHome
+  preparation: PreparedCodexResumeHome,
+  context?: CodexResumeLaunchContext
 ): Promise<CodexResumeLaunch> {
   return preparation.preparation.then((prepared) => {
     const providerSession = preparation.providerSession
+    if (prepared?.outcome === 'resume') {
+      return alignVerifiedAutomaticResume({ command, providerSession, prepared, context })
+    }
+    if (prepared?.outcome === 'fresh' && context?.coldRestoreResume === true) {
+      throw new Error(AUTOMATIC_CODEX_RESUME_STOPPED)
+    }
     if (prepared?.outcome !== 'fresh') {
       return {
         codexResumeHome: prepared ?? null,
@@ -119,10 +149,132 @@
 
 /** Why: buildPtyHostEnv prefers ORCA_SEQUENCED_STARTUP_COMMAND over the launch command
  *  and the sequenced wrapper `eval`s it, so a dropped resume argv has to go there too. */
+function classifySavedCodexResume(
+  command: string,
+  argv: readonly string[]
+): 'same' | 'missing' | 'other' {
+  const resume = argv[1]
+  const id = argv.at(-1)
+  if (!resume || !id) {
+    return 'other'
+  }
+  const tokens = tokenizeCommandLine(command)
+  const indexes = tokens.flatMap((token, index) => (token === resume ? [index] : []))
+  if (indexes.length === 0) {
+    return 'missing'
+  }
+  const index = indexes[0]
+  if (
+    indexes.length === 1 &&
+    tokens[index + 1] === id &&
+    index === tokens.length - 2 &&
+    recognizeAgentProcessFromCommandLine(command)?.agent === 'codex'
+  ) {
+    return 'same'
+  }
+  return 'other'
+}
+
+const POSIX_STARTUP_SHELL_NAMES = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'fish'])
+
+/** Maps the spawn's resolved shell override onto the existing quote family.
+ *  An accepted Windows name uses canonicalizeWindowsShellOverride. A local
+ *  non-Windows basename uses the posix set already named by the quote helper.
+ *  Anything else is unsupported and returns null; callers must not guess. */
+function agentStartupShellForOverride(args: {
+  shellOverride: string | null | undefined
+  platform: NodeJS.Platform
+  connectionId?: string | null
+}): AgentStartupShell | null {
+  const trimmed = args.shellOverride?.trim() ?? ''
+  if (!trimmed) {
+    if (args.connectionId || args.platform === 'win32') {
+      return null
+    }
+    return 'posix'
+  }
+  const base = trimmed.replaceAll('\\', '/').split('/').pop() ?? trimmed
+  const canonical =
+    canonicalizeWindowsShellOverride(trimmed) ?? canonicalizeWindowsShellOverride(base)
+  if (canonical === 'powershell.exe' || canonical === 'pwsh.exe') {
+    return 'powershell'
+  }
+  if (canonical === 'cmd.exe') {
+    return 'cmd'
+  }
+  if (canonical === 'wsl.exe' || canonical === 'bash.exe' || canonical === 'git-bash') {
+    return 'posix'
+  }
+  if (
+    !args.connectionId &&
+    args.platform !== 'win32' &&
+    POSIX_STARTUP_SHELL_NAMES.has(base.toLowerCase())
+  ) {
+    return 'posix'
+  }
+  return null
+}
+
+function alignVerifiedAutomaticResume(args: {
+  command: string | undefined
+  providerSession: AgentProviderSessionMetadata
+  prepared: Extract<CodexSessionResumePreparation, { outcome: 'resume' }>
+  context?: CodexResumeLaunchContext
+}): CodexResumeLaunch {
+  const keep = (
+    command: string | undefined,
+    sequencedStartupCommand?: string
+  ): CodexResumeLaunch => ({
+    codexResumeHome: args.prepared,
+    command,
+    notifyResumeUnavailable: false,
+    droppedResumeArgv: false,
+    providerSession: args.providerSession,
+    ...(sequencedStartupCommand ? { sequencedStartupCommand } : {})
+  })
+  if (args.context?.coldRestoreResume !== true) {
+    return keep(args.command)
+  }
+  const argv = getAgentResumeArgv('codex', args.providerSession)
+  if (!argv?.[0]) {
+    throw new Error(AUTOMATIC_CODEX_RESUME_STOPPED)
+  }
+  const env = args.context.env ?? {}
+  const sequenced = env[SETUP_AGENT_SEQUENCE_STARTUP_COMMAND_ENV]?.trim()
+  const effective = resolveSetupAgentSequenceLaunchCommand(env, args.command)
+  const quoteShell = (): AgentStartupShell => {
+    const shell = agentStartupShellForOverride({
+      shellOverride: args.context?.shellOverride,
+      platform: args.context?.platform ?? process.platform,
+      connectionId: args.context?.connectionId
+    })
+    if (!shell) {
+      throw new Error(AUTOMATIC_CODEX_RESUME_STOPPED)
+    }
+    return shell
+  }
+  const write = (next: string): CodexResumeLaunch =>
+    sequenced ? keep(args.command, next) : keep(next)
+  if (!effective?.trim()) {
+    return write(buildAgentResumeLaunchCommand('codex', argv[0], argv, quoteShell()))
+  }
+  const kind = classifySavedCodexResume(effective, argv)
+  if (kind === 'same') {
+    return keep(args.command)
+  }
+  if (kind === 'missing' && recognizeAgentProcessFromCommandLine(effective)?.agent === 'codex') {
+    return write(buildAgentResumeLaunchCommand('codex', effective, argv, quoteShell()))
+  }
+  throw new Error(AUTOMATIC_CODEX_RESUME_STOPPED)
+}
+
 export function stripSequencedStartupResumeArgv<T extends Record<string, string> | undefined>(
   env: T,
   launch: CodexResumeLaunch
 ): T {
+  if (env && launch.sequencedStartupCommand) {
+    return { ...env, [SETUP_AGENT_SEQUENCE_STARTUP_COMMAND_ENV]: launch.sequencedStartupCommand }
+  }
   const sequenced = env?.[SETUP_AGENT_SEQUENCE_STARTUP_COMMAND_ENV]
   if (!env || !sequenced || !launch.droppedResumeArgv || !launch.providerSession) {
     return env
--- a/src/main/ipc/pty/ipc/spawn-env-codex.ts
+++ b/src/main/ipc/pty/ipc/spawn-env-codex.ts
@@ -43,7 +43,13 @@
         ...(args.replacesPtyId ? { useSelectedAccount: true } : {})
       })
   ctx.codexResumeLaunch = codexResumePreparation
-    ? await ctx.deps.resolveCodexResumeLaunch(args.command, codexResumePreparation)
+    ? await ctx.deps.resolveCodexResumeLaunch(args.command, codexResumePreparation, {
+        env: ctx.baseEnv,
+        coldRestoreResume: args.coldRestoreResume === true,
+        shellOverride: ctx.terminalRuntimeOptions.shellOverride,
+        platform: process.platform,
+        connectionId: args.connectionId
+      })
     : ctx.deps.noCodexResumeLaunch(ctx.preAdoptedStablePane ? undefined : args.command)
   // Why: these three phases have unrelated costs (session provenance + hook
   // repair, account/auth resolution, then the synchronous env build). One
--- a/src/main/ipc/pty/ipc/spawn-types.ts
+++ b/src/main/ipc/pty/ipc/spawn-types.ts
@@ -18,7 +18,11 @@
   PrepareClaudeAuth,
   PrepareCodexSessionResume
 } from '../host-env/types'
-import type { CodexResumeLaunch, PreparedCodexResumeHome } from '../host-env/codex-resume'
+import type {
+  CodexResumeLaunch,
+  CodexResumeLaunchContext,
+  PreparedCodexResumeHome
+} from '../host-env/codex-resume'
 import type { StablePaneOwner } from '../pane/stable-owner'
 
 export type PtySpawnIpcArgs = {
@@ -33,6 +37,8 @@
   commandDelivery?: 'renderer' | 'provider'
   launchConfig?: SleepingAgentLaunchConfig
   resumeProviderSession?: AgentProviderSessionMetadata
+  /** Set only by a cold-restore connect. */
+  coldRestoreResume?: true
   launchToken?: unknown
   launchAgent?: TuiAgent
   startupCommandDelivery?: StartupCommandDelivery
@@ -109,7 +115,8 @@
   noCodexResumeLaunch: (command: string | undefined) => CodexResumeLaunch
   resolveCodexResumeLaunch: (
     command: string | undefined,
-    prepared: PreparedCodexResumeHome
+    prepared: PreparedCodexResumeHome,
+    context?: CodexResumeLaunchContext
   ) => Promise<CodexResumeLaunch>
   reconcileSharedRuntimeResumeHome: (
     resumeHome: Extract<CodexSessionResumePreparation, { outcome: 'resume' }>,
--- a/src/main/ipc/pty/runtime/controller-deps.ts
+++ b/src/main/ipc/pty/runtime/controller-deps.ts
@@ -14,7 +14,11 @@
   PrepareClaudeAuth,
   PrepareCodexSessionResume
 } from '../host-env/types'
-import type { CodexResumeLaunch, PreparedCodexResumeHome } from '../host-env/codex-resume'
+import type {
+  CodexResumeLaunch,
+  CodexResumeLaunchContext,
+  PreparedCodexResumeHome
+} from '../host-env/codex-resume'
 import type { StablePaneOwner } from '../pane/stable-owner'
 import type { AdoptStablePaneArgs, AdoptStablePaneResult } from '../ipc/spawn-types'
 import type { finishPtyShutdown } from '../provider/liveness'
@@ -34,7 +38,8 @@
   }) => PreparedCodexResumeHome | null
   resolveCodexResumeLaunch: (
     command: string | undefined,
-    prepared: PreparedCodexResumeHome
+    prepared: PreparedCodexResumeHome,
+    context?: CodexResumeLaunchContext
   ) => Promise<CodexResumeLaunch>
   noCodexResumeLaunch: (command: string | undefined) => CodexResumeLaunch
   reconcileSharedRuntimeResumeHome: (
--- a/src/main/ipc/pty/runtime/spawn-preflight.ts
+++ b/src/main/ipc/pty/runtime/spawn-preflight.ts
@@ -138,13 +138,6 @@
         target: ctx.codexSelectionTarget,
         launchEnv: args.env
       })
-  const codexResumeLaunch = codexResumePreparation
-    ? await ctx.deps.resolveCodexResumeLaunch(args.command, codexResumePreparation)
-    : ctx.deps.noCodexResumeLaunch(ctx.preAdoptedStablePane ? undefined : args.command)
-  const codexResumeHome = codexResumeLaunch.codexResumeHome
-  // Why: the drop still applies here, but this controller's result has no field for
-  // notifyResumeUnavailable — runtime/relay panes start fresh without the notice.
-  ctx.launchCommand = codexResumeLaunch.command
   ctx.claudeAuth =
     ctx.isClaudeLaunch && ctx.deps.prepareClaudeAuth
       ? await ctx.deps.prepareClaudeAuth(ctx.codexSelectionTarget)
@@ -178,6 +171,19 @@
   }
   const sshScopedEnv = stripRemotePaneEnvWhenHooksDisabled(args.connectionId, args.env)
   ctx.env = ctx.claudeAuth ? { ...sshScopedEnv, ...ctx.claudeAuth.envPatch } : sshScopedEnv
+  const codexResumeLaunch = codexResumePreparation
+    ? await ctx.deps.resolveCodexResumeLaunch(args.command, codexResumePreparation, {
+        env: ctx.env,
+        coldRestoreResume: args.coldRestoreResume === true,
+        shellOverride: ctx.terminalRuntimeOptions.shellOverride,
+        platform: process.platform,
+        connectionId: args.connectionId
+      })
+    : ctx.deps.noCodexResumeLaunch(ctx.preAdoptedStablePane ? undefined : args.command)
+  const codexResumeHome = codexResumeLaunch.codexResumeHome
+  // Why: the drop still applies here, but this controller's result has no field for
+  // notifyResumeUnavailable — runtime/relay panes start fresh without the notice.
+  ctx.launchCommand = codexResumeLaunch.command
   ctx.requestedAgentTeamsPath = ctx.env?.ORCA_AGENT_TEAMS_TEAM_ID
     ? ctx.env[resolvePathEnvKey(ctx.env, process.platform)]
     : undefined
--- a/src/main/ipc/pty/runtime/spawn-state.ts
+++ b/src/main/ipc/pty/runtime/spawn-state.ts
@@ -97,6 +97,8 @@
   env?: Record<string, string>
   envToDelete?: string[]
   resumeProviderSession?: AgentProviderSessionMetadata
+  /** Set only by a cold-restore connect. */
+  coldRestoreResume?: true
   connectionId?: string | null
   worktreeId?: string
   preAllocatedHandle?: string
--- a/src/main/runtime/orca-runtime-create-terminal.ts
+++ b/src/main/runtime/orca-runtime-create-terminal.ts
@@ -139,6 +139,7 @@
               agentTeamsPlan?.envToDelete
             ),
             resumeProviderSession: launchOpts.resumeProviderSession,
+            ...(launchOpts.coldRestoreResume === true ? { coldRestoreResume: true as const } : {}),
             telemetry: launchOpts.telemetry,
             connectionId: workspace.connectionId,
             worktreeId: workspace.id,
--- a/src/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods.ts
+++ b/src/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods.ts
@@ -61,6 +61,7 @@
               ...(params.resumeProviderSession
                 ? { resumeProviderSession: params.resumeProviderSession }
                 : {}),
+              ...(params.coldRestoreResume === true ? { coldRestoreResume: true as const } : {}),
               ...(params.launchToken ? { launchToken: params.launchToken } : {}),
               ...(params.launchAgent ? { launchAgent: params.launchAgent } : {}),
               ...(params.terminalKittyKeyboardProtocol === true
--- a/src/main/runtime/runtime-terminal-contracts.ts
+++ b/src/main/runtime/runtime-terminal-contracts.ts
@@ -41,6 +41,8 @@
   envToDelete?: string[]
   launchConfig?: WorktreeStartupLaunch['launchConfig']
   resumeProviderSession?: AgentProviderSessionMetadata
+  /** Set only by a cold-restore connect. */
+  coldRestoreResume?: true
   launchToken?: string
   launchAgent?: TuiAgent
   startupAgent?: TuiAgent
--- a/src/preload/api/pty-api.ts
+++ b/src/preload/api/pty-api.ts
@@ -32,6 +32,8 @@
     commandDelivery?: 'renderer' | 'provider'
     launchConfig?: SleepingAgentLaunchConfig
     resumeProviderSession?: AgentProviderSessionMetadata
+    /** Set only by a cold-restore connect. */
+    coldRestoreResume?: true
     launchToken?: string
     launchAgent?: TuiAgent
     startupCommandDelivery?: StartupCommandDelivery
--- a/src/renderer/src/components/terminal-pane/ipc-pty-spawn-request.ts
+++ b/src/renderer/src/components/terminal-pane/ipc-pty-spawn-request.ts
@@ -114,6 +114,7 @@
     ...((connectOptions.resumeProviderSession ?? resumeProviderSession)
       ? { resumeProviderSession: connectOptions.resumeProviderSession ?? resumeProviderSession }
       : {}),
+    ...(connectOptions.coldRestoreResume === true ? { coldRestoreResume: true as const } : {}),
     ...((connectOptions.launchToken ?? launchToken)
       ? { launchToken: connectOptions.launchToken ?? launchToken }
       : {}),
--- a/src/renderer/src/components/terminal-pane/pty-connection/cold-restore-resume-startup.ts
+++ b/src/renderer/src/components/terminal-pane/pty-connection/cold-restore-resume-startup.ts
@@ -113,6 +113,7 @@
         ORCA_AGENT_LAUNCH_TOKEN: coldRestoreLaunchToken
       },
       launchConfig: startupPlan.launchConfig,
+      coldRestoreResume: true,
       resumeProviderSession: providerSession,
       launchToken: coldRestoreLaunchToken,
       useLiveEntry: Boolean(useLiveEntry),
--- a/src/renderer/src/components/terminal-pane/pty-connection/deferred-session-attach.ts
+++ b/src/renderer/src/components/terminal-pane/pty-connection/deferred-session-attach.ts
@@ -175,6 +175,7 @@
             ...(coldRestoreStartup?.resumeProviderSession
               ? { resumeProviderSession: coldRestoreStartup.resumeProviderSession }
               : {}),
+            ...(coldRestoreStartup ? { coldRestoreResume: true as const } : {}),
             ...(coldRestoreStartup?.launchToken
               ? { launchToken: coldRestoreStartup.launchToken }
               : {}),
--- a/src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-connect.ts
+++ b/src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-connect.ts
@@ -99,6 +99,7 @@
     ...(coldRestoreStartup?.resumeProviderSession
       ? { resumeProviderSession: coldRestoreStartup.resumeProviderSession }
       : {}),
+    ...(coldRestoreStartup ? { coldRestoreResume: true as const } : {}),
     ...(coldRestoreStartup?.launchToken ? { launchToken: coldRestoreStartup.launchToken } : {}),
     ...(coldRestoreStartup?.agent ? { launchAgent: coldRestoreStartup.agent } : {}),
     ...(session.shouldDeclareHiddenAtSpawn() ? { initiallyHidden: true } : {}),
--- a/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts
+++ b/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts
@@ -111,6 +111,7 @@
       ...(coldRestoreOverride
         ? { resumeProviderSession: coldRestoreOverride.resumeProviderSession }
         : {}),
+      ...(coldRestoreOverride ? { coldRestoreResume: true as const } : {}),
       ...(coldRestoreOverride ? { launchToken: coldRestoreOverride.launchToken } : {}),
       ...(coldRestoreOverride ? { launchAgent: coldRestoreOverride.agent } : {}),
       ...(session.shouldDeclareHiddenAtSpawn() ? { initiallyHidden: true } : {}),
--- a/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-types.ts
+++ b/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-types.ts
@@ -16,6 +16,7 @@
 
 export type ColdRestoreAgentResumeStartup = PendingStartupCommand & {
   agent: ResumableTuiAgent
+  coldRestoreResume: true
   resumeProviderSession: AgentProviderSessionMetadata
   launchConfig: NonNullable<ReturnType<typeof buildAgentResumeStartupPlan>>['launchConfig']
   launchToken: string
--- a/src/renderer/src/components/terminal-pane/pty-transport-types.ts
+++ b/src/renderer/src/components/terminal-pane/pty-transport-types.ts
@@ -169,6 +169,8 @@
     envToDelete?: string[]
     launchConfig?: SleepingAgentLaunchConfig
     resumeProviderSession?: AgentProviderSessionMetadata
+    /** Set only by a cold-restore connect. */
+    coldRestoreResume?: true
     launchToken?: string
     launchAgent?: TuiAgent
     startupCommandDelivery?: StartupCommandDelivery
--- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
+++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
@@ -2252,6 +2252,7 @@
           ...(resumeProviderSessionToSend !== undefined
             ? { resumeProviderSession: resumeProviderSessionToSend }
             : {}),
+          ...(options.coldRestoreResume === true ? { coldRestoreResume: true as const } : {}),
           ...(launchTokenToSend !== undefined ? { launchToken: launchTokenToSend } : {}),
           ...(launchAgentToSend !== undefined ? { launchAgent: launchAgentToSend } : {}),
           ...(terminalColorQueryReplies ? { terminalColorQueryReplies } : {}),
--- a/src/shared/rpc-contract/terminal-unary-params.ts
+++ b/src/shared/rpc-contract/terminal-unary-params.ts
@@ -182,6 +182,7 @@
       transcriptPath: z.string().min(1).max(32_768).optional()
     })
     .optional(),
+  coldRestoreResume: z.literal(true).optional(),
   launchToken: OptionalString,
   launchAgent: z.string().refine(isTuiAgent).optional(),
   terminalKittyKeyboardProtocol: z.boolean().optional(),
--- a/src/shared/runtime-terminal-contracts.ts
+++ b/src/shared/runtime-terminal-contracts.ts
@@ -236,6 +236,8 @@
   envToDelete?: string[]
   launchConfig?: SleepingAgentLaunchConfig
   resumeProviderSession?: AgentProviderSessionMetadata
+  /** Set only by a cold-restore connect. */
+  coldRestoreResume?: true
   launchToken?: string
   launchAgent?: TuiAgent
   viewMode?: 'terminal' | 'chat'
tests.diff
diff --git a/src/renderer/src/components/terminal-pane/pty-connection/empty-reattach-retire-evidence.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/empty-reattach-retire-evidence.test.ts
index 086cfb82..68aa59a2 100644
--- a/src/renderer/src/components/terminal-pane/pty-connection/empty-reattach-retire-evidence.test.ts
+++ b/src/renderer/src/components/terminal-pane/pty-connection/empty-reattach-retire-evidence.test.ts
@@ -26,6 +26,7 @@ function resumeStartup(
 ): ColdRestoreAgentResumeStartup {
   return {
     command: 'codex resume conv-1',
+    coldRestoreResume: true,
     agent: 'codex',
     resumeProviderSession: { key: 'session_id', id: 'conv-1' },
     launchConfig: { agentArgs: '', agentEnv: {} },
diff --git a/src/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler-park-reveal-verdict.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler-park-reveal-verdict.test.ts
index addf17ba..6d94a8d1 100644
--- a/src/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler-park-reveal-verdict.test.ts
+++ b/src/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler-park-reveal-verdict.test.ts
@@ -351,6 +351,7 @@ describe('handleReattachResult empty reattach under a hibernation note', () => {
   } as const
   const startup: ColdRestoreAgentResumeStartup = {
     command: 'codex resume conv-1',
+    coldRestoreResume: true,
     agent: 'codex',
     resumeProviderSession: record.providerSession,
     launchConfig: { agentArgs: '', agentEnv: {} },
diff --git a/src/main/ipc/pty-spawn-cold-restore-boundaries.test.ts b/src/main/ipc/pty-spawn-cold-restore-boundaries.test.ts
new file mode 100644
index 00000000..9a354fef
--- /dev/null
+++ b/src/main/ipc/pty-spawn-cold-restore-boundaries.test.ts
@@ -0,0 +1,447 @@
+import { describe, expect, it, vi } from 'vitest'
+import { join } from 'node:path'
+import { spawnMock } from './pty-ipc-mock-registry'
+import { TEST_MANAGED_ROOT } from './pty-ipc-test-constants'
+import { setupPtyIpcSuite } from './pty-ipc-test-harness'
+import { prepareCodexSessionResume } from '../codex/codex-session-resume-preparation'
+import { registerPtyHandlers, setLocalPtyProvider, type PrepareCodexSessionResume } from './pty'
+import { registerSshPtyProvider, unregisterSshPtyProvider } from './pty/provider/registry'
+import {
+  AUTOMATIC_CODEX_RESUME_STOPPED,
+  noCodexResumeLaunch,
+  prepareCodexResumeHome,
+  reconcileSharedRuntimeResumeHome,
+  resolveCodexResumeLaunch,
+  stripSequencedStartupResumeArgv
+} from './pty/host-env/codex-resume'
+import { assemblePtyIpcSpawnCodexEnv } from './pty/ipc/spawn-env-codex'
+import { createPtyIpcSpawnState } from './pty/ipc/spawn-state'
+import type { PtySpawnIpcArgs, PtySpawnIpcDeps } from './pty/ipc/spawn-types'
+
+vi.mock('electron', () => import('./pty-ipc-mock-registry').then((m) => m.electronModuleMock()))
+vi.mock('fs', () => import('./pty-ipc-mock-registry').then((m) => m.fsModuleMock()))
+vi.mock('node-pty', () => import('./pty-ipc-mock-registry').then((m) => m.nodePtyModuleMock()))
+vi.mock('node:child_process', async (importOriginal) =>
+  (await import('./pty-ipc-mock-registry')).childProcessModuleMock(await importOriginal())
+)
+vi.mock('../opencode/hook-service', () =>
+  import('./pty-ipc-mock-registry').then((m) => m.openCodeHookServiceModuleMock())
+)
+vi.mock('../mimo/hook-service', () =>
+  import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock())
+)
+vi.mock('../agent-hooks/server', () =>
+  import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock())
+)
+vi.mock('../pi/titlebar-extension-service', () =>
+  import('./pty-ipc-mock-registry').then((m) => m.piTitlebarExtensionModuleMock())
+)
+vi.mock('../pwsh', () => import('./pty-ipc-mock-registry').then((m) => m.pwshModuleMock()))
+vi.mock('../wsl', async (importOriginal) =>
+  (await import('./pty-ipc-mock-registry')).wslModuleMock(await importOriginal())
+)
+vi.mock('../telemetry/client', () =>
+  import('./pty-ipc-mock-registry').then((m) => m.telemetryClientModuleMock())
+)
+vi.mock('../telemetry/classify-error', () =>
+  import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock())
+)
+vi.mock('../cli/linux-terminal-orca-cli-shim', () =>
+  import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock())
+)
+vi.mock('../memory/pty-registry', () =>
+  import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock())
+)
+vi.mock('../agent-hooks/migration-unsupported-pty-state', () =>
+  import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock())
+)
+vi.mock('../codex/codex-pane-account-registry', () =>
+  import('./pty-ipc-mock-registry').then((m) => m.codexPaneAccountRegistryModuleMock())
+)
+vi.mock('../codex/codex-state-db-backfill-recovery', () =>
+  import('./pty-ipc-mock-registry').then((m) => m.codexBackfillRecoveryModuleMock())
+)
+
+const SAVED_ID = '019f81b9-19a9-7651-a8d1-352d9420bd11'
+const OTHER_ID = '019f81b9-19a9-7651-a8d1-352d9420bd22'
+const QUOTE_ID = "a'b"
+const ORIGIN_HOME = join(TEST_MANAGED_ROOT, 'origin', 'home')
+const ORIGIN_ROLLOUT = join(
+  ORIGIN_HOME,
+  'sessions',
+  '2026',
+  '07',
+  '20',
+  `rollout-2026-07-20T12-00-00-${SAVED_ID}.jsonl`
+)
+const SEQUENCED = 'ORCA_SEQUENCED_STARTUP_COMMAND'
+const GATE = `bash -lc 'eval "$ORCA_SEQUENCED_STARTUP_SCRIPT"'`
+
+describe('cold restore resume boundaries through pty:spawn and the runtime controller', () => {
+  const { handlers, mainWindow } = setupPtyIpcSuite()
+
+  const prepareVerified: PrepareCodexSessionResume = ({ providerSession }) =>
+    prepareCodexSessionResume({
+      sessionId: providerSession.id,
+      transcriptPath: providerSession.transcriptPath,
+      trustedCodexHomes: [ORIGIN_HOME],
+      getSelectedAccountCodexHome: () => null,
+      systemCodexHomePath: null,
+      sharedRuntimeCodexHomePath: null,
+      fileIsRegular: () => true,
+      resolveVerifiedResumeHome: async (source) => source.homePath
+    })
+
+  function registerVerified() {
+    registerPtyHandlers(
+      mainWindow as never,
+      undefined,
+      vi.fn(() => ORIGIN_HOME),
+      undefined,
+      undefined,
+      undefined,
+      { prepareCodexSessionResume: prepareVerified }
+    )
+  }
+
+  function daemonProvider() {
+    const daemonSpawn = vi.fn(async (options: { command?: string; env: Record<string, string> }) => {
+      void options
+      return { id: 'daemon-pty' }
+    })
+    setLocalPtyProvider({
+      spawn: daemonSpawn,
+      supportsGitCredentialGuardHost: () => true,
+      supportsAgentSessionClaims: () => true,
+      supportsAgentSessionCreateOperations: () => true,
+      write: vi.fn(),
+      resize: vi.fn(),
+      kill: vi.fn(),
+      shutdown: vi.fn(),
+      onData: vi.fn(() => vi.fn()),
+      onExit: vi.fn(() => vi.fn()),
+      listProcesses: vi.fn(async () => []),
+      getForegroundProcess: vi.fn(async () => null)
+    } as never)
+    return daemonSpawn
+  }
+
+  function runtimeController() {
+    const runtime = {
+      setPtyController: vi.fn(),
+      registerPty: vi.fn(),
+      noteTerminalSpawnCommand: vi.fn(),
+      onPtySpawned: vi.fn(),
+      onPtyExit: vi.fn(),
+      onPtyData: vi.fn()
+    }
+    handlers.clear()
+    registerPtyHandlers(
+      mainWindow as never,
+      runtime as never,
+      vi.fn(() => ORIGIN_HOME),
+      undefined,
+      undefined,
+      undefined,
+      { prepareCodexSessionResume: prepareVerified }
+    )
+    return runtime.setPtyController.mock.calls[0]?.[0] as {
+      spawn(args: Record<string, unknown>): Promise<{ id: string }>
+    }
+  }
+
+  async function spawn(args: Record<string, unknown>) {
+    return handlers.get('pty:spawn')!(null, {
+      cols: 80,
+      rows: 24,
+      cwd: '/tmp',
+      launchAgent: 'codex',
+      resumeProviderSession: {
+        key: 'session_id',
+        id: SAVED_ID,
+        transcriptPath: ORIGIN_ROLLOUT
+      },
+      ...args
+    })
+  }
+
+  it('composes one resume for an empty cold restore and does not append it again', async () => {
+    const daemonSpawn = daemonProvider()
+    registerVerified()
+    await spawn({ command: '', coldRestoreResume: true })
+    const first = daemonSpawn.mock.calls.at(-1)![0].command as string
+    expect(first).toBe(`codex 'resume' '${SAVED_ID}'`)
+    expect(first.match(/resume/g)).toHaveLength(1)
+
+    await spawn({ command: first, coldRestoreResume: true })
+    expect(daemonSpawn.mock.calls.at(-1)![0].command).toBe(first)
+  })
+
+  it('appends one resume onto a codex command that has none, including the sequenced env', async () => {
+    const daemonSpawn = daemonProvider()
+    registerVerified()
+    await spawn({
+      command: GATE,
+      coldRestoreResume: true,
+      env: { [SEQUENCED]: 'codex --no-daemon' }
+    })
+    const options = daemonSpawn.mock.calls.at(-1)![0]
+    expect(options.command).toBe(GATE)
+    expect(options.env[SEQUENCED]).toBe(`codex --no-daemon 'resume' '${SAVED_ID}'`)
+    expect(options.env[SEQUENCED].match(/resume/g)).toHaveLength(1)
+  })
+
+  it('keeps a sequenced command that already ends with this id', async () => {
+    const daemonSpawn = daemonProvider()
+    registerVerified()
+    const sequenced = `codex 'resume' '${SAVED_ID}'`
+    await spawn({
+      command: GATE,
+      coldRestoreResume: true,
+      env: { [SEQUENCED]: sequenced }
+    })
+    const options = daemonSpawn.mock.calls.at(-1)![0]
+    expect(options.command).toBe(GATE)
+    expect(options.env[SEQUENCED]).toBe(sequenced)
+  })
+
+  it('stops a different id, an unverified resume, and a non-codex command before spawn', async () => {
+    const daemonSpawn = daemonProvider()
+    registerVerified()
+    await expect(
+      spawn({ command: `codex 'resume' '${OTHER_ID}'`, coldRestoreResume: true })
+    ).rejects.toThrow(AUTOMATIC_CODEX_RESUME_STOPPED)
+    await expect(
+      spawn({ command: 'echo hello', coldRestoreResume: true })
+    ).rejects.toThrow(AUTOMATIC_CODEX_RESUME_STOPPED)
+    handlers.clear()
+    registerPtyHandlers(
+      mainWindow as never,
+      undefined,
+      vi.fn(() => join(TEST_MANAGED_ROOT, 'other', 'home')),
+      undefined,
+      undefined,
+      undefined,
+      {
+        prepareCodexSessionResume: ({ providerSession }) =>
+          prepareCodexSessionResume({
+            sessionId: providerSession.id,
+            transcriptPath: providerSession.transcriptPath,
+            trustedCodexHomes: [join(TEST_MANAGED_ROOT, 'other', 'home')],
+            getSelectedAccountCodexHome: () => null,
+            systemCodexHomePath: null,
+            sharedRuntimeCodexHomePath: null,
+            fileIsRegular: () => true,
+            resolveVerifiedResumeHome: async (source) => source.homePath
+          })
+      }
+    )
+    await expect(
+      spawn({ command: `codex 'resume' '${SAVED_ID}'`, coldRestoreResume: true })
+    ).rejects.toThrow(AUTOMATIC_CODEX_RESUME_STOPPED)
+    expect(daemonSpawn).not.toHaveBeenCalled()
+    expect(spawnMock).not.toHaveBeenCalled()
+  })
+
+  it('leaves explicit new, paste, and an arbitrary command outside the cold-restore intent', async () => {
+    const daemonSpawn = daemonProvider()
+    registerVerified()
+    await spawn({
+      command: 'echo hello',
+      telemetry: { request_kind: 'resume' }
+    })
+    expect(daemonSpawn.mock.calls.at(-1)![0].command).toBe('echo hello')
+
+    await spawn({
+      command: `codex 'resume' '${SAVED_ID}'`,
+      telemetry: { request_kind: 'new' }
+    })
+    expect(daemonSpawn.mock.calls.at(-1)![0].command).toBe(`codex 'resume' '${SAVED_ID}'`)
+
+    await spawn({ command: '' })
+    expect(daemonSpawn.mock.calls.at(-1)![0].command).toBe('')
+  })
+
+  it('quotes from the resolved shell override and refuses an unsupported shell', async () => {
+    const daemonSpawn = daemonProvider()
+    registerVerified()
+    await spawn({
+      command: '',
+      coldRestoreResume: true,
+      shellOverride: '/bin/zsh',
+      resumeProviderSession: {
+        key: 'session_id',
+        id: QUOTE_ID,
+        transcriptPath: ORIGIN_ROLLOUT
+      }
+    })
+    expect(daemonSpawn.mock.calls.at(-1)![0].command).toBe(`codex 'resume' 'a'"'"'b'`)
+
+    await spawn({
+      command: '',
+      coldRestoreResume: true,
+      shellOverride: 'powershell.exe',
+      resumeProviderSession: {
+        key: 'session_id',
+        id: QUOTE_ID,
+        transcriptPath: ORIGIN_ROLLOUT
+      }
+    })
+    expect(daemonSpawn.mock.calls.at(-1)![0].command).toBe(`codex 'resume' 'a''b'`)
+
+    await spawn({
+      command: '',
+      coldRestoreResume: true,
+      shellOverride: '/bin/fish'
+    })
+    expect(daemonSpawn.mock.calls.at(-1)![0].command).toBe(`codex 'resume' '${SAVED_ID}'`)
+
+    await expect(
+      spawn({ command: '', coldRestoreResume: true, shellOverride: '/opt/nu' })
+    ).rejects.toThrow(AUTOMATIC_CODEX_RESUME_STOPPED)
+  })
+
+  it('returns the live pre-adopted pane from the runtime controller without a new spawn', async () => {
+    const daemonSpawn = daemonProvider()
+    const controller = runtimeController()
+    const result = await controller.spawn({
+      cols: 80,
+      rows: 24,
+      command: `codex 'resume' '${OTHER_ID}'`,
+      coldRestoreResume: true,
+      launchAgent: 'codex',
+      resumeProviderSession: {
+        key: 'session_id',
+        id: SAVED_ID,
+        transcriptPath: ORIGIN_ROLLOUT
+      },
+      adoptedStablePane: {
+        materialized: true,
+        result: { id: 'live-pty' },
+        owner: { handle: 'live-handle', tabId: 'tab', leafId: 'leaf' }
+      }
+    })
+    expect(result.id).toBe('live-pty')
+    expect(daemonSpawn).not.toHaveBeenCalled()
+  })
+
+  it('keeps a remote command because connectionId makes resume preparation null', async () => {
+    const remoteSpawn = vi.fn(async (options: { command?: string }) => ({
+      id: 'remote-pty',
+      command: options.command
+    }))
+    registerSshPtyProvider('ssh-1', {
+      spawn: remoteSpawn,
+      supportsGitCredentialGuardHost: () => false,
+      write: vi.fn(),
+      resize: vi.fn(),
+      kill: vi.fn(),
+      shutdown: vi.fn(),
+      onData: vi.fn(() => vi.fn()),
+      onExit: vi.fn(() => vi.fn()),
+      listProcesses: vi.fn(async () => []),
+      getForegroundProcess: vi.fn(async () => null)
+    } as never)
+    try {
+      const controller = runtimeController()
+      await controller.spawn({
+        cols: 80,
+        rows: 24,
+        cwd: '/tmp',
+        command: 'echo hello',
+        coldRestoreResume: true,
+        connectionId: 'ssh-1',
+        launchAgent: 'codex',
+        sessionId: 'remote-session',
+        resumeProviderSession: {
+          key: 'session_id',
+          id: SAVED_ID,
+          transcriptPath: ORIGIN_ROLLOUT
+        }
+      })
+      expect(remoteSpawn.mock.calls.at(-1)![0].command).toBe('echo hello')
+    } finally {
+      unregisterSshPtyProvider('ssh-1')
+    }
+  })
+
+  it('assemblePtyIpcSpawnCodexEnv keeps the command for remote and drops it for a live pane', async () => {
+    const deps = {
+      getLocalPtyStartupPromise: () => undefined,
+      adoptStablePane: async () => null,
+      assertFolderWorkspacePtyPathUsable: () => undefined,
+      resolvePtySpawnStartupCwd: (_worktreeId: string | undefined, cwd: string | undefined) => cwd,
+      localStartupCwdDirectoryExists: () => true,
+      prepareCodexResumeHome: (
+        args: Parameters<PtySpawnIpcDeps['prepareCodexResumeHome']>[0]
+      ) =>
+        prepareCodexResumeHome(
+          (prepareArgs) =>
+            prepareCodexSessionResume({
+              sessionId: prepareArgs.providerSession.id,
+              transcriptPath: prepareArgs.providerSession.transcriptPath,
+              trustedCodexHomes: [ORIGIN_HOME],
+              getSelectedAccountCodexHome: () => null,
+              systemCodexHomePath: null,
+              sharedRuntimeCodexHomePath: null,
+              fileIsRegular: () => true,
+              resolveVerifiedResumeHome: async (source) => source.homePath
+            }),
+          args
+        ),
+      noCodexResumeLaunch,
+      resolveCodexResumeLaunch,
+      reconcileSharedRuntimeResumeHome,
+      stripSequencedStartupResumeArgv,
+      getSettings: () => undefined,
+      transitionSpawnHiddenRendererPtyDeliveryState: () => undefined,
+      trustedTerminalHandleEnv: new Set<string>(),
+      sendPtySpawnedToRenderer: () => undefined,
+      syncPtyBackgroundedDelivery: () => undefined,
+      stopReplacedPty: async () => undefined
+    } as unknown as PtySpawnIpcDeps
+
+    const remote = createPtyIpcSpawnState(deps, {
+      cols: 80,
+      rows: 24,
+      command: 'echo hello',
+      coldRestoreResume: true,
+      connectionId: 'ssh-1',
+      launchAgent: 'codex',
+      sessionId: 'remote-session',
+      resumeProviderSession: {
+        key: 'session_id',
+        id: SAVED_ID,
+        transcriptPath: ORIGIN_ROLLOUT
+      }
+    } as PtySpawnIpcArgs)
+    remote.baseEnv = {}
+    remote.isDaemonHostSpawn = false
+    await assemblePtyIpcSpawnCodexEnv(remote)
+    expect(remote.launchCommand).toBe('echo hello')
+    expect(remote.codexResumeLaunch.codexResumeHome).toBeNull()
+
+    const live = createPtyIpcSpawnState(deps, {
+      cols: 80,
+      rows: 24,
+      command: `codex 'resume' '${OTHER_ID}'`,
+      coldRestoreResume: true,
+      launchAgent: 'codex',
+      sessionId: 'live-session',
+      resumeProviderSession: {
+        key: 'session_id',
+        id: SAVED_ID,
+        transcriptPath: ORIGIN_ROLLOUT
+      }
+    } as PtySpawnIpcArgs)
+    live.preAdoptedStablePane = {
+      result: { id: 'live-pty' },
+      owner: { handle: 'live-handle', tabId: 'tab', leafId: 'leaf', ptyId: 'live-pty' }
+    }
+    live.baseEnv = {}
+    live.isDaemonHostSpawn = false
+    await assemblePtyIpcSpawnCodexEnv(live)
+    expect(live.launchCommand).toBeUndefined()
+    expect(live.codexResumeLaunch.droppedResumeArgv).toBe(false)
+  })
+})
diff --git a/src/renderer/src/components/terminal-pane/pty-connection-cold-restore-retry-closure.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-cold-restore-retry-closure.test.ts
new file mode 100644
index 00000000..1939ce8a
--- /dev/null
+++ b/src/renderer/src/components/terminal-pane/pty-connection-cold-restore-retry-closure.test.ts
@@ -0,0 +1,259 @@
+import type * as React from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { makePaneKey } from '../../../../shared/stable-pane-id'
+import { flushAsyncTicks } from './pty-connection-test-async'
+import { LEAF_1, createMockTransport, createPane, createManager } from './pty-connection-test-pane-fixtures'
+import { buildPaneConnectionDeps } from './pty-connection-test-deps'
+import { createInitialStoreState } from './pty-connection-test-store-fixtures'
+import type { StoreState } from './pty-connection-test-store-state'
+import type { MockTransport } from './pty-connection-test-pane-fixtures'
+import {
+  installTerminalTestGlobals,
+  restoreTerminalTestGlobals
+} from './pty-connection-test-environment'
+import {
+  createRemountTerminalTabForRecovery,
+  createSettleTerminalTabRecovery
+} from '@/store/slices/worktrees/session/worktree-slice-lookups'
+
+const { scheduleRuntimeGraphSync, toastInfo, notifyCodexPaneBoundForStaleSweep } = vi.hoisted(
+  () => ({
+    scheduleRuntimeGraphSync: vi.fn(),
+    toastInfo: vi.fn(),
+    notifyCodexPaneBoundForStaleSweep: vi.fn()
+  })
+)
+
+let mockStoreState: StoreState
+let transportFactoryQueue: MockTransport[] = []
+let storeSubscribers: ((state: StoreState) => void)[] = []
+
+vi.mock('@/runtime/sync-runtime-graph', () => ({
+  scheduleRuntimeGraphSync
+}))
+
+vi.mock('@/store', () => ({
+  useAppStore: {
+    getState: () => mockStoreState,
+    subscribe: (listener: (state: StoreState) => void) => {
+      storeSubscribers.push(listener)
+      return () => {
+        storeSubscribers = storeSubscribers.filter((candidate) => candidate !== listener)
+      }
+    }
+  }
+}))
+
+vi.mock('@/lib/agent-status', async (importOriginal) => {
+  const { buildAgentStatusModuleMock } = await import('./pty-connection-test-environment')
+  return buildAgentStatusModuleMock(await importOriginal<Record<string, unknown>>())
+})
+
+vi.mock('sonner', () => ({
+  toast: {
+    info: toastInfo
+  }
+}))
+
+vi.mock('@/lib/codex-stale-pane-sweep', () => ({
+  notifyCodexPaneBoundForStaleSweep
+}))
+
+vi.mock('react', async (importOriginal) => {
+  const actual = await importOriginal<typeof React>()
+  return {
+    ...actual,
+    useCallback: <T extends (...args: unknown[]) => unknown>(fn: T): T => fn
+  }
+})
+
+vi.mock('./pty-transport', () => ({
+  createIpcPtyTransport: vi.fn(() => {
+    const nextTransport = transportFactoryQueue.shift()
+    if (!nextTransport) {
+      throw new Error('No mock transport queued')
+    }
+    return nextTransport
+  })
+}))
+
+vi.mock('./pty-dispatcher', async (importOriginal) => {
+  const actual = await importOriginal<Record<string, unknown>>()
+  return {
+    ...actual,
+    getEagerPtyBufferHandle: vi.fn(() => undefined)
+  }
+})
+
+const SAVED_ID = '019f81b9-19a9-7651-a8d1-352d9420bd11'
+const TRANSCRIPT = `/Users/example/.codex/sessions/2026/07/20/rollout-2026-07-20T12-00-00-${SAVED_ID}.jsonl`
+const STOPPED = 'Orca stopped this saved Codex resume instead of starting a new chat.'
+
+type StorePatch = Partial<StoreState> | ((state: StoreState) => Partial<StoreState> | StoreState)
+
+function applyStorePatch(patch: StorePatch): void {
+  const next = typeof patch === 'function' ? patch(mockStoreState) : patch
+  if (next === mockStoreState) {
+    return
+  }
+  mockStoreState = { ...mockStoreState, ...next } as StoreState
+  for (const listener of storeSubscribers) {
+    listener(mockStoreState)
+  }
+}
+
+function seedRestartedLocalPane(): string {
+  const paneKey = makePaneKey('tab-1', LEAF_1)
+  const getState = (): StoreState => mockStoreState
+  mockStoreState = {
+    ...mockStoreState,
+    tabsByWorktree: {
+      'wt-1': [{ id: 'tab-1', ptyId: null, generation: 0 }]
+    },
+    ptyIdsByTabId: { 'tab-1': [] },
+    terminalLayoutsByTabId: {
+      'tab-1': {
+        root: { type: 'leaf', leafId: LEAF_1 },
+        activeLeafId: LEAF_1,
+        expandedLeafId: null,
+        ptyIdsByLeafId: {}
+      }
+    },
+    pendingStartupByTabId: {},
+    settings: {
+      ...mockStoreState.settings,
+      agentCmdOverrides: {}
+    },
+    agentStatusByPaneKey: {},
+    sleepingAgentSessionsByPaneKey: {
+      [paneKey]: {
+        paneKey,
+        tabId: 'tab-1',
+        worktreeId: 'wt-1',
+        agent: 'codex',
+        providerSession: { key: 'session_id', id: SAVED_ID, transcriptPath: TRANSCRIPT },
+        prompt: 'finish the task',
+        state: 'working',
+        capturedAt: 1,
+        updatedAt: 1
+      }
+    },
+    remountTerminalTabForRecovery: createRemountTerminalTabForRecovery(
+      applyStorePatch as never,
+      getState as never
+    ),
+    settleTerminalTabRecovery: createSettleTerminalTabRecovery(
+      applyStorePatch as never,
+      getState as never
+    )
+  } as StoreState
+  return paneKey
+}
+
+function tab(): { generation?: number; recovery?: { outcome: string; reason: string } } {
+  return mockStoreState.tabsByWorktree['wt-1'][0] as never
+}
+
+async function settle(): Promise<void> {
+  await flushAsyncTicks(20)
+  await new Promise((resolve) => setTimeout(resolve, 300))
+  await flushAsyncTicks(20)
+}
+
+describe('local cold-restore spawn failure and the remounted retry', () => {
+  beforeEach(async () => {
+    vi.resetModules()
+    vi.clearAllMocks()
+    transportFactoryQueue = []
+    storeSubscribers = []
+    mockStoreState = createInitialStoreState(() => mockStoreState)
+    await installTerminalTestGlobals()
+    const { _resetTerminalPaneRecoveryForTests } = await import('./terminal-pane-recovery')
+    _resetTerminalPaneRecoveryForTests()
+  })
+
+  afterEach(async () => {
+    await restoreTerminalTestGlobals()
+  })
+
+  it('keeps the saved session after a stopped spawn and rebuilds the same resume on remount', async () => {
+    const { connectPanePty } = await import('./pty-connection')
+    const paneKey = seedRestartedLocalPane()
+    const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+    const failing = createMockTransport(null)
+    failing.connect.mockImplementation(async () => {
+      throw new Error(STOPPED)
+    })
+    transportFactoryQueue.push(failing)
+    const firstDeps = buildPaneConnectionDeps(() => mockStoreState)
+    const first = connectPanePty(createPane(1) as never, createManager(1) as never, firstDeps as never)
+    await settle()
+
+    expect(failing.connect).toHaveBeenCalledOnce()
+    const firstOptions = failing.connect.mock.calls[0][0] as Record<string, unknown>
+    expect(firstOptions.sessionId).toBeUndefined()
+    expect(firstOptions).toMatchObject({
+      coldRestoreResume: true,
+      launchAgent: 'codex',
+      resumeProviderSession: { key: 'session_id', id: SAVED_ID, transcriptPath: TRANSCRIPT }
+    })
+    expect(firstOptions.command).toBe(
+      `codex '--dangerously-bypass-approvals-and-sandbox' 'resume' '${SAVED_ID}'`
+    )
+    expect(mockStoreState.registerAgentLaunchConfig).toHaveBeenCalledWith(
+      paneKey,
+      expect.anything(),
+      expect.objectContaining({ agentType: 'codex', tabId: 'tab-1', leafId: LEAF_1 })
+    )
+    expect(mockStoreState.clearAgentLaunchConfig).toHaveBeenCalledWith(paneKey)
+    expect(mockStoreState.clearSleepingAgentSession).not.toHaveBeenCalled()
+    expect(mockStoreState.sleepingAgentSessionsByPaneKey[paneKey]).toMatchObject({
+      providerSession: { key: 'session_id', id: SAVED_ID }
+    })
+    expect(warn).toHaveBeenCalledWith(
+      '[terminal-lifecycle] fresh spawn left the pane unbound',
+      expect.objectContaining({ tabId: 'tab-1', leafId: LEAF_1, paneId: 1, ptyId: null })
+    )
+    expect(tab().generation).toBe(1)
+    expect(tab().recovery).toMatchObject({ outcome: 'pending', reason: 'spawn-left-pane-unbound' })
+
+    first.dispose()
+
+    const retry = createMockTransport(null)
+    retry.connect.mockImplementation(async () => 'retry-pty')
+    transportFactoryQueue.push(retry)
+    const secondDeps = buildPaneConnectionDeps(() => mockStoreState)
+    const second = connectPanePty(
+      createPane(1) as never,
+      createManager(1) as never,
+      secondDeps as never
+    )
+    await settle()
+
+    expect(retry.connect).toHaveBeenCalledOnce()
+    const retryOptions = retry.connect.mock.calls[0][0] as Record<string, unknown>
+    expect(retryOptions.sessionId).toBeUndefined()
+    expect(retryOptions).toMatchObject({
+      coldRestoreResume: true,
+      launchAgent: 'codex',
+      resumeProviderSession: { key: 'session_id', id: SAVED_ID, transcriptPath: TRANSCRIPT }
+    })
+    expect(retryOptions.command).toBe(firstOptions.command)
+    expect(retryOptions.launchToken).not.toBe(firstOptions.launchToken)
+
+    for (const options of [firstOptions, retryOptions]) {
+      expect(String(options.command).match(/'resume'/g)).toHaveLength(1)
+      expect(options.command).toContain(`'${SAVED_ID}'`)
+    }
+    expect(mockStoreState.clearSleepingAgentSession).toHaveBeenCalledExactlyOnceWith(paneKey)
+    expect(mockStoreState.sleepingAgentSessionsByPaneKey[paneKey]).toBeUndefined()
+    expect(tab().generation).toBe(1)
+    expect(tab().recovery).toMatchObject({ outcome: 'success' })
+    expect(secondDeps.onShowSessionRestoredBanner).toHaveBeenCalledWith(1, 'restored')
+    expect(firstDeps.onShowSessionRestoredBanner).not.toHaveBeenCalled()
+
+    second.dispose()
+    warn.mockRestore()
+  })
+})

Activity

  1. AmethystLiang commented on Oct 8, 2026

    @AmethystLiang
    Contributor

    Thanks for reporting. Looking into it

  2. megamorphg commented on Oct 10, 2026

    @megamorphg

    This happens especially when using an alternative codex home + wrapper. For example:
    Image

    In this case, putting the tab to sleep and waking it up just gives an empty terminal window.

    Doing a codex-naw resume works fine but yeah it seems like Orca needs to update the main Command during resume.

  3. nwparker commented on Oct 24, 2026

    @nwparker
    Contributor

    Thanks for the report! Please retest on 1.4.239+. If cold restore still starts a new Codex session, share: Orca version, macOS version, Codex CLI version, whether you use a custom CODEX_HOME and wrapper (describe, no secrets), and sleeping-agent records plus startup-command-delivery log lines (redacted). Please redact anything private before sharing; screenshots or log excerpts are fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions