Repository navigation
fix(codex): drop the resume argv when session provenance is unverifiable - #10805
Conversation
An unverifiable Codex rollout used to fail the spawn with a red per-pane toast. The throw existed because returning null only declined to override CODEX_HOME — the renderer had already baked `codex resume <id>` into the command, so a fall-through would resume the session under whichever account is selected now. Drop the resume argv instead. Main decides provenance and now rewrites the launch command to plain `codex`, so there is nothing left to resume and the cross-account invariant holds by construction rather than by refusing to spawn. Verified resumes are unchanged: CODEX_HOME still pins to the originating home. The pane says so — SessionRestoredBanner gains a `resume-unavailable` variant, gated on claimsCodexRolloutLayout so stale cross-agent metadata stays silent. Closes #10793
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughThe change adds Codex resume provenance resolution with structured resume and fresh outcomes. Unverifiable Codex resume commands can have their resume arguments removed, with PTY spawning reporting when a fresh session replaces a resume. Preload and transport contracts propagate this status to the renderer. Restored-session banner state now stores per-pane reasons, allowing separate text for restored sessions and sessions started fresh after unavailable resume provenance. Tests cover provenance resolution, command rewriting, PTY propagation, and banner state and rendering. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/ipc/pty.ts (1)
3153-3230: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winMirror
agentResumeUnavailablein the runtime-controller spawn response.
resolveCodexResumeLaunch()already computes this and the paired IPC path surfaces it asagentResumeUnavailable: true, but the genericruntime.setPtyController({ spawn })final response only spreads result fields and dropsnotifyResumeUnavailable. Include the same conditional field for non-reattach spawns so callers of this PTY API see the same resume-unavailable signal.🛠️ Proposed fix: mirror the IPC handler's response field
const response = { id: result.id, ...(result.incarnationId ? { incarnationId: result.incarnationId } : {}), - ...(result.agentSessionEnsure ? { agentSessionEnsure: result.agentSessionEnsure } : {}) + ...(result.agentSessionEnsure ? { agentSessionEnsure: result.agentSessionEnsure } : {}), + ...(codexResumeLaunch.notifyResumeUnavailable && !result.isReattach + ? { agentResumeUnavailable: true as const } + : {}) }
🧹 Nitpick comments (2)
src/main/ipc/pty.test.ts (1)
1849-1978: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider adding a spawn-level test for the "unrecognized" fail-safe path.
This suite covers 'fresh' outcomes (dropped/silent) and verified 'resume', but not the case where
dropAgentResumeArgvFromCommandreturns'unrecognized'anddropUnverifiedCodexResumeArgvthrows — the PR description states "Unrecognized resume commands still fail safely," but nothing here assertspty:spawnactually rejects/fails for such a command at this integration level (only unit-tested inagent-resume-argv-drop.test.ts).src/renderer/src/components/terminal-pane/pty-connection.ts (1)
4853-4863: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider consolidating the duplicated banner-reason resolution logic.
Both the fresh-spawn path and the reattach/cold-restore path independently implement the same "resume-unavailable wins, else fall back to hasSleepingRecord" decision. Since this exact class of logic (deciding whether to show/how to label the restored-session banner) was the root cause of the bug this PR fixes, extracting it into one shared helper would reduce the risk of the two call sites drifting apart in a future change.
♻️ Proposed helper extraction
+ const resolveAndShowRestoredSessionBanner = ( + agentResumeUnavailable: boolean | undefined, + hasSleepingRecord: boolean | undefined + ): void => { + if (agentResumeUnavailable) { + showSessionRestoredBanner('resume-unavailable') + } else if (hasSleepingRecord) { + showSessionRestoredBanner() + } + }Then at each call site:
- if ( - spawnedPtyId && - typeof spawnedPtyId === 'object' && - spawnedPtyId.agentResumeUnavailable - ) { - showSessionRestoredBanner('resume-unavailable') - } else if (coldRestoreOverride?.hasSleepingRecord) { - showSessionRestoredBanner() - } + resolveAndShowRestoredSessionBanner( + spawnedPtyId && typeof spawnedPtyId === 'object' + ? spawnedPtyId.agentResumeUnavailable + : undefined, + coldRestoreOverride?.hasSleepingRecord + )- if (didPrepareResume) { - if (connectResult.agentResumeUnavailable) { - showSessionRestoredBanner('resume-unavailable') - } else if (preparedStartup?.hasSleepingRecord) { - showSessionRestoredBanner() - } + if (didPrepareResume) { + resolveAndShowRestoredSessionBanner( + connectResult.agentResumeUnavailable, + preparedStartup?.hasSleepingRecord + ) clearSleepingRecordAfterColdRestoreSpawn(preparedStartup) }Also applies to: 7452-7463
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 8cee54b1-6c43-4685-be13-8df495df10d0
📒 Files selected for processing (22)
src/main/codex/codex-session-resume-home.test.tssrc/main/codex/codex-session-resume-home.tssrc/main/codex/codex-unverified-resume-launch.tssrc/main/index.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/components/terminal-pane/SessionRestoredBanner.tsxsrc/renderer/src/components/terminal-pane/SessionRestoredBannerPortals.tsxsrc/renderer/src/components/terminal-pane/TerminalPane.tsxsrc/renderer/src/components/terminal-pane/pty-connection-types.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/pty-transport-types.tssrc/renderer/src/components/terminal-pane/pty-transport.test.tssrc/renderer/src/components/terminal-pane/pty-transport.tssrc/renderer/src/components/terminal-pane/session-restored-banner-pane-state.test.tsxsrc/renderer/src/components/terminal-pane/session-restored-banner-pane-state.tssrc/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.tssrc/shared/agent-resume-argv-drop.test.tssrc/shared/agent-resume-argv-drop.ts
Review follow-ups on the resume-argv drop (#10793): - Notify for resumes with no transcriptPath. The drop is not gated on claimedCodexProvenance, so legacy sleeping-agent and relay records that persist only a session id were stripped to an empty pane with no notice. Suppression now covers only the mislabeled-pane case (a real ~/.claude transcriptPath), not the no-metadata case. - Stop turning `unrecognized` into a hard spawn failure for metadata that never claimed Codex layout. Base returned null there and launched normally; routing it through dropUnverifiedCodexResumeArgv made `pty:spawn` reject. The throw is now gated on claimedCodexProvenance. - Apply the same drop to ORCA_SEQUENCED_STARTUP_COMMAND on both spawn paths. buildPtyHostEnv prefers that env var over the launch command and the sequenced wrapper evals it, so rewriting only spawnOptions.command left a hole in the never-resume-under-the-wrong-account invariant. - Let 'resume-unavailable' through the renderer banner latch once, so an earlier plain 'restored' banner cannot leave a fresh pane claiming its session came back. - Constrain .session-restored-banner width; the new string is roughly twice as long and would wrap out of the 24px title strip onto the terminal grid. - Drop the dead ompResumeFilePath parameter and an unreachable length check. Extracts prepareCodexSessionResume so index.ts's provenance-to-preparation wiring is exercised by tests instead of restated by them. Tests: runtime-controller spawn path (command, sequenced env and noteTerminalSpawnCommand all strip the argv), the index.ts outcome wiring, both `unrecognized` branches, the isReattach notice guard, trimEnd and the locator re-check, the no-transcriptPath notice, the renderer fresh-spawn branch serving the primary #10757 path, the banner reason upgrade, and the latch. Every new test was mutation-proved against the hunk it covers.
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/main/index.ts (1)
857-871: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCapture
codexRuntimeHomelikesettingsStoreinstead of asserting inside the closure.Line 850 already snapshots
storeto keep the narrowing; the callback then re-assertscodexRuntimeHome!even though it was narrowed at line 841. Snapshotting it the same way removes the assertion and keeps the closure from observing a later reassignment.♻️ Proposed consistency tweak
const settingsStore = store + const runtimeHome = codexRuntimeHome // Why: a `fresh` outcome must skip migration, trust and hook repair entirely — there is // no verified origin home to prepare, so the PTY layer drops the resume argv (`#10793`). @@ { - isHostSystemDefaultRealHome: () => codexRuntimeHome!.isHostSystemDefaultRealHome(), + isHostSystemDefaultRealHome: () => runtimeHome.isHostSystemDefaultRealHome(), systemCodexHomePath: systemHomePath }src/main/ipc/pty.test.ts (1)
1906-1916: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
void optionsis dead —optionsis already read on the next line.♻️ Proposed cleanup
}) => { - void options return { id: options.sessionId ?? 'daemon-pty', ...spawnResult } }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d9d250d8-a557-47ae-8a49-7855f36758ce
📒 Files selected for processing (12)
src/main/codex/codex-session-resume-preparation.test.tssrc/main/codex/codex-session-resume-preparation.tssrc/main/codex/codex-unverified-resume-launch.tssrc/main/index.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/renderer/src/assets/terminal.csssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/session-restored-banner-pane-state.test.tsxsrc/shared/agent-resume-argv-drop.test.tssrc/shared/agent-resume-argv-drop.ts
🚧 Files skipped from review as they are similar to previous changes (6)
- src/main/codex/codex-unverified-resume-launch.ts
- src/shared/agent-resume-argv-drop.ts
- src/renderer/src/components/terminal-pane/pty-connection.ts
- src/shared/agent-resume-argv-drop.test.ts
- src/renderer/src/components/terminal-pane/session-restored-banner-pane-state.test.tsx
- src/main/ipc/pty.ts
The `pty:spawn` handler bound `env` to `baseEnv` before the sequenced-env strip ran. `stripSequencedStartupResumeArgv` returns a new object rather than mutating, so rebinding `baseEnv` left `env` pointing at the pre-strip object. Only the `isDaemonHostSpawn` branch re-derived `env` from `baseEnv`, so every local-provider spawn (LocalPtyProvider, or a provider that routes fresh spawns there) reached the PTY with ORCA_SEQUENCED_STARTUP_COMMAND still carrying `resume <id>`. buildPtyHostEnv prefers that env var over the launch command and the sequenced wrapper evals it, so the pane resumed under whichever account was selected — the exact invariant this change exists to protect — while the renderer showed "started fresh". Declaring `env` after the strip removes the two-variable asymmetry: there is no longer a point in the handler where the pre-strip value is reachable. The runtime-controller path was already correct (it rebinds `env` itself). The gap survived review because every sequenced assertion ran against the daemon provider, which re-derives its env. Adds local-provider coverage for both the stripped and the verified-provenance cases.
Composes #10801's rescan ranking with this branch's unverifiable-resume argv drop. Both conflicts were additive at the same insertion point, so both sides survive: - codex-session-resume-home.ts keeps rankTrustedCodexHomesForRescan and the three required inputs on findTrustedCodexSessionResume alongside the new resolveCodexSessionResumeProvenance. - index.ts keeps the ranking inputs it already passed while the hard-fail throw stays deleted; the migration/trust/hook work moved into the resolveVerifiedResumeHome callback, so it still runs only for a verified resume. Why the wrapper signatures grew instead of defaulting: resolveCodexSessionResume- Provenance and prepareCodexSessionResume now sit between index.ts and the ranking, so they take all three inputs as required and forward them. Nulling any one compiles and silently degrades the rescan to pure path order — the accident #10801 landed to remove. The selection stays a thunk so a provenance-present resume never stats the ownership marker. Adds two tests for that seam: nothing in the committed suite covered it. The full codex/codex-accounts/pty suites passed 1234/1234 with the forwarding deliberately nulled, because #10801's per-tier tests call the rescan directly and never traverse the wrapper. The new ranking test fails under that mutation.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/codex/codex-session-resume-home.ts (1)
109-112: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winKeep the ranking rationale brief.
These comments are substantially more detailed than necessary; reduce them to a concise statement of the precedence rule and its account-selection purpose. As per coding guidelines, “Comments must be concise, limited to non-obvious information, and preferably one line.”
Also applies to: 132-158
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 9a338698-056b-467e-b79c-12ebc35b632c
📒 Files selected for processing (8)
src/main/codex/codex-session-resume-home.test.tssrc/main/codex/codex-session-resume-home.tssrc/main/codex/codex-session-resume-preparation.test.tssrc/main/codex/codex-session-resume-preparation.tssrc/main/index.tssrc/main/ipc/pty.test.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- src/renderer/src/components/terminal-pane/pty-connection.ts
- src/main/codex/codex-session-resume-home.test.ts
- src/renderer/src/components/terminal-pane/pty-connection.test.ts
- src/main/ipc/pty.test.ts
- src/main/index.ts
… result #10770 added four pty.test.ts mocks returning a bare { codexHomePath }, while this branch changed PrepareCodexSessionResume to a discriminated result that requires an `outcome`. The merge was textually clean and the suite still passed — vitest does not typecheck — so this only surfaced under tsc.
…ble (stablyai#10805) Closes stablyai#10793. When Orca could not verify the originating Codex session file it either threw — a red per-pane toast and a failed spawn, reported as constant spam on stablyai#10757 — or returned null. Returning null did NOT start a fresh session: the renderer had already baked ['codex','resume',<id>] into the command and pty.ts never rewrote it, so CODEX_HOME simply fell through to whichever account was selected. The resume argv is now dropped so a plain `codex` launches, with a banner telling the user. The invariant — never run `codex resume <id>` under an account that does not own that rollout — is now satisfied by construction rather than by refusing to spawn. A verified resume is unchanged and still pins CODEX_HOME to the originating home. Reviewed over two adversarial rounds; seven defects found and fixed, including a HIGH where local-provider (non-daemon) spawns still carried ORCA_SEQUENCED_STARTUP_COMMAND with `resume <id>` — the wrong account behind a banner claiming it started fresh. `env` is now declared after the strip so no point in the handler can reach the pre-strip value. Live-validated in a real Orca dev build: all five cases proven on the SPAWNED PROCESS, including a real rollout under an untrusted home (the only shape that discriminates) and the local-provider path forced by stopping the daemon. An earlier CI failure on multi-client-navigation-isolation.integration.test.ts was investigated and is a PRE-EXISTING flake — a ~4ms race in the session-tabs notify coalescer that fails 5-8/24 on clean main, more often than on this branch. Fixed separately in stablyai#11022. Not verified: no Windows execution — its POSIX-only tests skip there and the stablyai#10757 reporter is on Windows. SSH is partial: no spurious banner or drop observed against a real target, but headless spawn does not deliver startup commands so the remote argv could not be read. The relay/mobile notice channel deliberately has no banner; the argv drop does happen there, so the invariant holds.
Closes #10793.
Root cause
prepareCodexSessionResumeForLaunch(src/main/index.ts) decides Codex resume provenance. When it could not verify which account owns a rollout it had exactly two outcomes, and neither started a fresh session:claimsCodexRolloutLayout, added in fix(codex): treat non-Codex transcript as stale resume metadata #10538). That surfaces as a red per-pane toast and the spawn fails outright. A user on [Bug] CHAT HISTORY LOST AFTER ACCOUNT SWITCH !!!! #10757 reports it as constant spam.null— which only declines to overrideCODEX_HOME. It does not start fresh: the renderer has already baked['codex','resume',<id>]into the command (getAgentResumeArgv,src/shared/agent-session-resume.ts), andsrc/main/ipc/pty.tsnever rewroteargs.command. So the pane runscodex resume <id>under whichever account is currently selected.That fall-through is harmless only while Codex cannot find the id under the selected account (
thread/resume failed: no rollout found for thread id, verified against codex-cli 0.145.0). PR #10770 adds a session bridge that hardlinks every rollout into every managed home preserving the session-id filename — after it lands, Codex can find it and the fall-through becomes a silent successful cross-account resume.The invariant: never run
codex resume <id>under an account that does not own that rollout.The fix
Drop the resume argv when provenance is not verified, so the pane launches plain
codex. With nothing to resume, cross-account resume is impossible by construction rather than by refusing to spawn — which is why the throw can go away safely.Main decides provenance but the renderer builds argv, so the channel is: main owns the final command. It already receives both
commandandresumeProviderSessionatpty:spawn.src/shared/agent-resume-argv-drop.ts(new) —dropAgentResumeArgvFromCommandreconstructs the exact suffixbuildAgentResumeStartupPlanappended (getAgentResumeArgv(...).slice(1)quoted for posix/powershell/cmd, plus the unquoted legacy form) and strips it from the tail. Structural, not a regex over an arbitrary string. Returnsdropped/absent(command never carried the locator) /unrecognized.src/main/codex/codex-unverified-resume-launch.ts(new) — onunrecognizedit still throws. If the locator is present but not strippable, launching could still cross accounts, so refusing is the correct outcome. This is unreachable for anything the shared builder produced.src/main/codex/codex-session-resume-home.ts—resolveCodexSessionResumeProvenanceextracts the decision into a testable pure function returning{outcome:'resume'}or{outcome:'fresh', claimedCodexProvenance}.src/main/index.ts— the throw is replaced by returning thatfreshresult.src/main/ipc/pty.ts— both spawn sites resolve an effectivelaunchCommandand thread it throughspawnOptions.command,buildPtyHostEnv({launchCommand}), andnoteTerminalSpawnCommand.Out of scope, deliberately
CODEX_HOMEstill pins to the originating home exactly as today.null. Treating it asfreshwould break WSL Codex resume entirely.agentandproviderSessionout of sync #10792 (keepingagentandproviderSessionin sync on pane reclassification).User-visible signal
Silently not resuming is its own bug — the user thinks their session came back.
SessionRestoredBannergains aresume-unavailablevariant (--- previous session unavailable, started fresh ---); the pane-idSetbecomes aMap<paneId, reason>. Main reports it on thepty:spawnresponse asagentResumeUnavailable, alongside the existingstartupCwdFallback— same shape, same path, no new IPC channel. Wired for both the fresh-spawn and daemon cold-restore paths inpty-connection.ts.Gated on
claimsCodexRolloutLayout: a path that claimed real Codex provenance and could not be found is worth reporting; stale cross-agent metadata (a ClaudetranscriptPathon a pane relabeledagent: "codex") is silent.Acceptance
codex, no resume argv, no toast, no bannercodex, no toast, bannercodex, no toast, nocodex resume <id>under the selected accountCODEX_HOMEpinned to the originating homeMutation proof
Every new test was mutation-proved by reverting the production hunk and confirming the test fails. This bar exists because on sibling PR #10538 a reviewer reverted the entire production hunk and all 567 tests still passed.
pty.tskeepsargs.commandonfresh(the old fall-through)launches plain codex when a REAL rollout sits under a home Orca no longer trusts,reports the dropped resume…claimedCodexProvenancehardcodedfalseresolveCodexSessionResumeProvenancerequires a whitespace boundary…includesinverted)SessionRestoredBannerignoresreasonnames a fresh session when the requested resume could not be verifiedpty-transport.tspass-through removedpty-connection.tsbanner-variant branches removedThe discriminating case. Missing-file cases pass with or without a correct fix, so the test that proves the delta is a rollout that is really present under an untrusted home — the same shape that proved #10538. Two layers:
codex-session-resume-home.test.tswrites a real rollout on disk under a temp home that is not intrustedCodexHomes→{outcome:'fresh', claimedCodexProvenance:true}.pty.test.tsdrives the realresolveCodexSessionResumeProvenanceend-to-end throughpty:spawnand asserts the PTY receivescodex\nand never the session id. That suite mocksfs, so the rollout is declared present viafileIsRegular: () => trueand the only variable left between the two paired cases is whether the home is trusted — which is exactly what the guard exists for. Its sibling case (same file present, home trusted) asserts the resume argv survives andCODEX_HOMEpins to the origin.Gates
All green:
A regression caught mid-review, worth flagging: the first draft always
awaited the resume resolution, which added a microtask tick to every spawn and broke 3 pane-spawn-reservation race tests inpty.test.ts.resolveCodexResumeLaunchis now only awaited for actual Codex resume spawns; non-Codex spawns take a synchronous path. Verified against a cleanorigin/mainworktree that those 3 pass at baseline.Not verified
dropAgentResumeArgvFromCommandcovers all three shells via the realbuildAgentResumeStartupPlan), but the twopty.test.tscases that assert the delivered PTY bytes areposixOnlyIt— matching how the surrounding command-delivery tests in that file are already written.transcriptPathwhose rollout is in no trusted home drops the argv silently (claimedCodexProvenanceis false with no path to inspect). Resume genuinely cannot work there, so starting fresh is right, but arguably it deserves the banner too. Left as specified; possible follow-up.origin/mainworktree with the same command (15 failures there, a superset) — pre-existing parallelism flake on this machine (Node 26 vs the repo's pinned Node 24), not from this change. All 6 pass when run alone.