Repository navigation
fix(terminal): restart a Codex pane into a fresh process after an account switch - #24350
brennanb2025 wants to merge 7 commits into
Conversation
Keep binding retirement inside the existing host pane reservation and preserve explicit fresh-agent startup over saved recovery state. Co-authored-by: itisvincent <[email protected]>
… own bind The account restart used to clear the old pane binding as its own durable write, between stopping the old process and launching the new one. That left a persisted "pane unbound" state that writers outside the pane reservation could see and undo. A debounced renderer layout patch that still carried the old id put the killed process back, and the restart then reattached it and failed with TerminalKilledError: the original blank-pane bug. The extra write also gated the launch. If its save failed, the binding rolled back to the killed process, and the renderer's recovery remount (a plain spawn) blanked again. Now the replacing spawn stops the owner and keeps its binding. Owner resolution for that spawn ignores the stopped id, and the fresh bind swaps old for new in one fenced write. The fence accepts a leaf that still names the stopped id or one the renderer already cleared. A strict match on the old binding would refuse a normal split-pane or SSH restart, because the renderer clears its leaf before connecting. Any other owner wins, and the replacement is reaped. If the replacement fails after the stop, a best-effort, binding-only clear of the stopped id lets the remount start fresh. A failure of that clear is only logged. The sequence lives in pane/pane-owner-replacement.ts, so the paired-runtime restart can reuse it.
…-connect clear The mounted restart clears its own leaf in the renderer before connecting. A split tab's partial layout map, or the SSH lease the stop marks terminated, lets that clear withdraw the stopped binding in main before the replacement binds. A strict expected-binding fence would then refuse the restart and reap the new process. These tests cover the local split-pane case and the SSH terminated-lease case against the real store, plus the spawn path with the binding withdrawn mid-spawn. A why-comment on the fence records the reason.
…he restart stop PtySpawnIpcDeps declares runtime and store as optional properties, so the stop's parameter has to as well. The restart test's session fake also takes the host id that its partition lookup already receives. These are type-only changes with no change in behaviour.
TypeScript refuses `delete` on a required property, and the fixture's literal map made the leaf key required. The test that withdraws the binding the way a renderer patch does needs that delete. This is a type-only change with no change in behaviour.
…he real bind end to end The restart harness answered a missing SSH partition with the local session. The real store returns an empty session there. So a swap fence reading the wrong partition, or a failure clear dropping the SSH host id, passed every test. The SSH pane now lives only in its own partition, with an unrelated local binding. New direct-SSH cases cover the successor refusal and the failure clear followed by a plain remount. The renderer-to-host account-restart test mocked persistPtyBinding, so the swap never ran there. It now uses the real binding operations and asserts the host binding ends on the replacement. Also shortens the fence comment and fixes an import order. There is no change in behaviour.
The registered handler is typed as returning unknown, and the helper's restart callback must return a promise. Making the callback async fixes the type without a cast. There is no change in behaviour.
Review status (head fd2e6cf, still draft)Problem: after switching the Orca-managed Codex account and pressing Restart on a Codex terminal, the pane went blank. The restart stopped the old Codex, then the new spawn looked up the pane's saved owner, found the process it had just stopped, and tried to reattach it; the terminal daemon refused ( What changes for users: Restart now always leaves the same pane running one fresh plain Fixed during review:
Deferred (not blocking):
Verified:
Not verified: live direct-SSH restart (by code reading it did not go blank on main and now uses the same mechanism), live paired restart, Windows/Linux/WSL, real Codex accounts, and the deferred restart-on-reveal path (in the live rig every hidden pane restarted immediately). |
|
Run failed. View the logs →
|
|
| const bound = | ||
| store.getWorkspaceSession(hostId).terminalLayoutsByTabId?.[binding.tabId]?.ptyIdsByLeafId?.[ | ||
| binding.leafId | ||
| ] | ||
| // Unbound is ok: the renderer's pre-connect clear can withdraw it (split tab, SSH lease ended). | ||
| return bound === undefined || bound === replaced.ptyId ? binding : null |
There was a problem hiding this comment.
Closed split pane reappears If a user closes a split pane while its account-switch restart is in progress, the close removes that leaf from the saved layout. This check treats the missing leaf as an ordinary cleared binding, so the binding writer adds it back and binds the new process to a pane the user closed. Only accept an unbound leaf when it still exists in the layout.
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. 🧰 Additional context used📚 Code guidelines (1)📝 WalkthroughWalkthroughThe PTY restart flow now tracks the replaced pane owner, excludes that owner during stable-owner resolution, and swaps the old pane binding for the replacement binding. Binding retirement updates local or host-specific session state and restores the prior session if a durable write fails. Renderer restart handling starts a fresh spawn when a replaced PTY is pending. Tests cover local, SSH, and folder-workspace restarts, ownership races, and remote-runtime reconnection. Priority: ⬇️ Low Merge Risk: 🔵 Low · up to Restarting a Codex pane after an account switch now starts a fresh process. One small renderer gap remains: the replacement pane may inherit idle-cache timing from the old process. This is a one-line fix; otherwise the change looks ready to merge. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to The restart flow adds ownership checks and protects a newer terminal process from being overwritten. No introduced security finding was established, but recovery after storage failures and paired-remote restart behavior remain limitations. Retained concerns Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
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.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: d3ffe3a8-c160-4387-b441-b1635597045a
📒 Files selected for processing (13)
src/main/ipc/pty-pane-restart-replace.test.tssrc/main/ipc/pty/ipc/spawn-begin.tssrc/main/ipc/pty/ipc/spawn-commit-persist.tssrc/main/ipc/pty/ipc/spawn-execute.tssrc/main/ipc/pty/ipc/spawn-run.tssrc/main/ipc/pty/ipc/spawn-state.tssrc/main/ipc/pty/pane/pane-owner-replacement.test.tssrc/main/ipc/pty/pane/pane-owner-replacement.tssrc/main/persistence/loading-store/pty-binding-persistence.tssrc/main/persistence/loading-store/pty-binding-restart-retirement.test.tssrc/main/persistence/loading-store/replaced-pane-binding.tssrc/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-choice.tstests/e2e/terminal-account-restart.unit.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| // An explicit replacement owns its startup; saved recovery state must not substitute another agent. | ||
| if (session.pendingReplacedPtyId) { | ||
| session.startFreshSpawn() | ||
| return | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Inspect how allowInitialIdleCacheSeed and startFreshSpawn interact for replacement spawns.
rg -nP -C4 '\ballowInitialIdleCacheSeed\b' src/renderer/src/components/terminal-pane
rg -nP -C6 '\bpendingReplacedPtyId\b' src/renderer/src
rg -nP -C8 'startFreshSpawn\s*[:=(]' src/renderer/src/components/terminal-paneRepository: stablyai/orca
Length of output: 31725
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- deferred choice imports and flow ---'
sed -n '1,35p;145,225p' src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-choice.ts
printf '%s\n' '--- fresh spawn implementation ---'
sed -n '1,145p' src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts
printf '%s\n' '--- cache seed consumer ---'
sed -n '1,110p' src/renderer/src/components/terminal-pane/pty-connection/title-spawn-bell.ts
printf '%s\n' '--- runtime graph sync definitions/usages ---'
rg -n -C6 'scheduleRuntimeGraphSync|runtimeGraphSync' src/renderer/src/components/terminal-pane/pty-connection src/renderer/src | head -240Repository: stablyai/orca
Length of output: 42276
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- cache-seeding predicate ---'
rg -n -C8 'function shouldSeedCacheTimerOnInitialTitle|const shouldSeedCacheTimerOnInitialTitle|shouldSeedCacheTimerOnInitialTitle' src/renderer/src/components/terminal-pane
printf '%s\n' '--- idle-cache flag assignments and reads in PTY connection code ---'
rg -n -C3 '\ballowInitialIdleCacheSeed\b' src/renderer/src/components/terminal-pane/pty-connectionRepository: stablyai/orca
Length of output: 45665
Disable idle-cache seeding for replacement sessions.
When session.pendingReplacedPtyId is set, the early return calls startFreshSpawn() without setting allowInitialIdleCacheSeed to false. startFreshSpawn() does not reset this flag. A replacement session can therefore remain eligible for initial idle-cache seeding, although fresh spawns should not inherit the stopped process state.
The runtime graph sync omission is not a separate failure. Spawn or attach completion schedules a later sync.
Suggested fix
if (session.pendingReplacedPtyId) {
+ session.allowInitialIdleCacheSeed = false
session.startFreshSpawn()
return
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // An explicit replacement owns its startup; saved recovery state must not substitute another agent. | |
| if (session.pendingReplacedPtyId) { | |
| session.startFreshSpawn() | |
| return | |
| } | |
| // An explicit replacement owns its startup; saved recovery state must not substitute another agent. | |
| if (session.pendingReplacedPtyId) { | |
| session.allowInitialIdleCacheSeed = false | |
| session.startFreshSpawn() | |
| return | |
| } |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — reviewed the full diff of 13 files (7 commits) against main (5f728f78): the host restart-replacement flow, the new binding retirement/swap persistence, the renderer replacement guard, and the four added/updated test suites. I ran the touched suites locally — all pass.
- Replacement ordered inside the pane reservation —
stopReplacedPaneOwnervalidates the pane's current owner, stops it, and records it; every owner resolution for that spawn then excludes the stopped id so the replacement launches fresh (pane-owner-replacement.ts,spawn-run/spawn-begin/spawn-execute). - The replacement's bind is the swap — one durable mutation overwrites the stopped binding, accepting a leaf still naming the stopped id or one the renderer already cleared, and refusing any other owner (
swapReplacedPaneBinding,spawn-commit-persist.ts). - Failure cleanup — a failed replacement retires the stopped binding (id-fenced) before releasing the reservation, so the remount's fresh spawn cannot reattach the dead process (
runPtyIpcSpawncatch,releaseStoppedPaneBinding). retirePtyBinding— new store method that keeps the pane and clears only the process binding, publishing directly so the renderer snapshot repair cannot re-add the removed binding (pty-binding-persistence.ts,replaced-pane-binding.ts).- Renderer guard — an explicit replacement now forces
startFreshSpawn()rather than letting saved recovery substitute a resume command (deferred-session-reattach-choice.ts). - Tests — real-handler host tests against a fake daemon throwing the real
TerminalKilledError, SQLite-backed split/SSH retirement tests, and a renderer-to-host end-to-end restart test.
ℹ️ Two retirement implementations now coexist
retirePtyBinding (pty-binding-persistence.ts:73) and retirePersistedStablePaneOwner (stable-owner.ts:125) both retire a stopped pane's binding, but fence differently (id-only vs id+incarnation) and publish differently (direct state assignment vs setWorkspaceSession). The direct publish is deliberate — routing through setWorkspaceSession would let preserveMissingWorkspaceSessionTerminalBindings re-add the binding being removed — but a future caller could easily pick the wrong one. Worth a one-line comment near each, or a consolidation follow-up once the paired-runtime work reuses this helper.
Technical details
# Dual retirement paths
## Affected sites
- src/main/persistence/loading-store/pty-binding-persistence.ts:73 — retirePtyBinding: id-only fence, direct publish, no topology-revision advance
- src/main/ipc/pty/pane/stable-owner.ts:125 — retirePersistedStablePaneOwner: id+incarnation fence, setWorkspaceSession
## Open questions for the human
- Is retirePtyBinding intended to replace retirePersistedStablePaneOwner eventually, or is this a long-term dual track?|
Integrated this PR's atomic pane-replacement implementation and regression coverage into #25485, alongside selected-account conversation resume adapted from #14877 and a terminal-handshake fix. Thank you @brennanb2025; the PR body and commit trailers credit you and @itisvincent. The combined version was reproduced and tested in a hidden macOS Electron instance with real Codex: A→B→A restarts preserve the conversation, the new account completes a prompt, Ctrl+C works, and no stale account notices remain. The rebased patch passes 165 focused tests plus typecheck and changed-code quality checks. #25485 includes before/after screenshots and explicit platform/goal-state coverage gaps. |
…5485) fix(codex): restart account switches without blanking or repinning the pane Integrate the atomic pane replacement from #24350 and adapt the explicit conversation resume from #14877. Keep terminal protocol replies flowing while account notices block user input. Ordinary restores retain provenance. Co-authored-by: Brennan Benson <[email protected]> Co-authored-by: itisvincent <[email protected]> Co-authored-by: rayim <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
|
Closing as incorporated into merged #25485. The atomic pane-owner replacement, guarded binding swap, failed-replacement cleanup, and regression tests from this PR landed there, together with selected-account conversation resume and terminal-handshake handling. Thank you @brennanb2025 and @itisvincent; attribution is in the merged PR and commit trailers. |

What this fixes
After you switch the Orca-managed Codex account and press Restart on a Codex terminal pane, the pane can go blank: the old Codex is gone and no new one starts.
Who hits it: anyone with an Orca-managed Codex account who restarts a local Codex terminal after an account switch. That covers the Restart chip on a visible pane and the status-bar "restart stale Codex panes" sweep for panes in hidden tabs, in git worktrees and folder workspaces alike.
Not affected: ordinary session restore and reattach, restarting a pane whose process already exited, worktree wake, native chat, and any spawn that does not replace a running process. Direct-SSH restarts, by code reading only (not run live), did not go blank on main because the relay reports a stopped session as absent and the spawn already started fresh; they now use the same mechanism as local panes.
Paired-runtime panes (a pane served by a paired remote Orca host) are a known gap: Restart there reattaches the old process and starts no new one. It does not go blank, and it is unchanged by this PR.
ELI5
Restart used to stop the old Codex but leave its name written on the pane, so the next step looked at the pane, saw that name, and tried to reconnect to the process it had just stopped. Now the restart remembers which process it stopped, skips it when deciding what the pane holds, and writes the new process's name over the old one in a single step.
What Changed
Before: the restart asked the host to spawn with
replacesPtyId(the id of the running process to replace). The host stopped that process, and the stop deliberately keeps the pane's saved binding so a replacement can take the pane over. The spawn then looked up the pane's owner, found the saved binding still naming the stopped process, and tried to reattach it. The local terminal daemon refuses a process it has killed withTerminalKilledError, which is not treated as "process is gone", so the spawn failed and the pane was left with no process. The old restart test fixture threw a different error (SessionNotFoundError) and so hid this.After: inside the existing per-pane spawn reservation, the host checks that the pane's current owner is still the process being replaced (otherwise
terminal_pane_owner_changed), stops it, and records it as the replaced owner. That sequence lives insrc/main/ipc/pty/pane/pane-owner-replacement.tsso the paired-runtime follow-up can reuse it.For the rest of that one spawn, owner lookup ignores the stopped process id (spawn-begin and spawn-execute), so the spawn launches fresh. No other spawn is affected, and the general "process is gone" error check is unchanged.
The new process's binding is written once, and that write is the swap. Inside the write's own durable mutation it accepts a pane that still names the stopped id, or one the renderer has already cleared, and refuses one that names any other process. A refusal shuts the new process down, so a newer owner always wins.
"Already cleared" has to be accepted because the renderer clears its own copy of the pane binding before it connects, and in a split tab, or over SSH after the stop marks the remote lease terminated, that clear removes the saved binding before the swap lands. Requiring an exact match would refuse a normal restart there.
If the replacement fails after the stop (spawn error or failed save), the host clears the stopped id from the pane binding before reporting the error, so the renderer's recovery remount (an ordinary spawn without
replacesPtyId) starts fresh instead of reattaching the dead process. This clear is best-effort: it only logs a warning if it fails, and it never replaces the original error.Renderer: an explicit replacement now always starts its requested startup command. Saved session recovery can no longer substitute another agent's resume command. Ordinary restore keeps its existing behavior.
Restart starts a FRESH Codex conversation, by design: plain
codexunder the new account, the same as the hidden-pane restart already did on main. On main, the visible-pane path would have resumed the pane's saved session if its spawn had not failed; in practice it went blank. Resuming a conversation across an account switch is a separate feature, #14877.Why
The host owns both the replacement and the saved process identity, so the fix belongs inside its existing pane reservation.
Rejected: a separate durable "retire the old binding" write before launch (this PR's first version). It created a saved "pane unbound" state that writers outside the reservation could undo. A debounced renderer layout update still carrying the old id restored the killed process, and the restart failed with the same
TerminalKilledError. That write also gated the launch: if its save failed, the binding rolled back to the killed process and the renderer's remount went blank again.Rejected: treating
TerminalKilledErroras "process is gone". That widens a check other callers rely on. Its recovery path also removes and re-creates the pane's saved layout entry, which is churn on every restart.Rejected: a renderer retry. The renderer cannot see the host's state, and a retry would hit the same reattach.
Rejected: clearing the binding inside the stop itself. The stop only knows the process id, not the pane, and it deliberately keeps the pane for the replacement.
Bug class removed: a restart can no longer reattach the process it just stopped, whatever re-publishes the old binding during the restart. Bookkeeping failures no longer leave the pane pointing at a dead process.
Linked Issue
Related: #24103, STA-9012. No closing keyword. The STA-9012 reporter saw Orca type
claude --dangerously-skip-permissions --resume <codex session id>after an account switch and restart. That line did not reproduce live on main. The renderer change here stops the account-restart path from substituting a saved session's resume command, so it partly helps STA-9012 / #24103 but does not close them. Cold restore, worktree wake and the resume sweep can still read a mixed-up saved identity until #24297's resume-identity work lands; the two PRs touch different code and merge cleanly.Visual Proof
Live QA ran on a remote macOS machine (Apple silicon) against an isolated Orca dev build with stub
codex/claudeCLIs, an isolated HOME and CODEX_HOME, and two fake Orca-managed Codex accounts. main = 5f728f7, PR = 96e45b3 (final head fd2e6cf differs only in tests, a comment and import order).Restart after switching account, visible Codex pane. main: blank, nothing typed, log shows
TerminalKilledErrorandspawn-left-pane-unbound. PR: plaincodex, exactly one new process, CODEX_HOME = the newly selected account.Claude orchestrator plus Codex worker in another tab (the STA-9012 flow), switch account, restart the worker. main: blank. PR: plain
codexwith the new account. Noclaudecommand was typed on either build.Status-bar "Restart 4 Sessions" with three Codex panes in hidden tabs and one in a background worktree. main: 4 of 4 blank. PR: 4 of 4 fresh on the new account, restarted while still hidden.
Ordinary restore (quit, stop the daemon, relaunch): every pane resumed its own saved session on both builds, with no error UI.
Not covered live: direct-SSH restart (needs SSH keys in the isolated home), paired-runtime restart, Windows and Linux, and the deferred restart-on-reveal path (every hidden pane restarted immediately in this rig). Real Codex was never launched.
Testing
Key files:
src/main/ipc/pty-pane-restart-replace.test.ts,src/main/ipc/pty/pane/pane-owner-replacement.test.ts,src/main/persistence/loading-store/pty-binding-restart-retirement.test.ts,tests/e2e/terminal-account-restart.unit.test.tsand the rendererdeferred-session-reattach-live-bookmark.test.ts: 37/37 pass. 102 neighbouring files (pty IPC, pane, binding persistence, e2e): 890 passed, 6 skipped, 0 failed. These were direct Vitest runs on macOS.The host restart tests run the real registered
pty:spawnhandler and the real binding write, refusal and rollback logic, against a fake daemon that throws the realTerminalKilledError.Cases covered:
SQLite-backed tests prove the split-pane and SSH terminated-lease cases against the real store, where an exact-match check refuses and the swap succeeds.
The renderer-to-host test (
tests/e2e/terminal-account-restart.unit.test.ts) drives the real restart hook, connection, transport and host spawn with the real binding write, and asserts the pane ends bound to the new process.Ablations, each run with the change removed:
TerminalKilledError.TerminalKilledError.TerminalKilledError.Node and web typecheck, oxlint, the changed-code quality gate and
git diff --checkpass. No live Windows, Linux, SSH or paired host run. Live macOS UI evidence is under Visual Proof.AI Disclosure
Review
Reviewed in multiple rounds: host persistence, renderer behaviour, architecture, proof quality and other callers. Spawns without
replacesPtyIdgo through unchanged code paths (identity at every changed site). CLI, mobile and pairedterminal.createpaths are untouched. No wire contract, preload, shared type or liveness check changed.Agent skill upstream boundary
Notes
Known weaknesses:
pane-owner-replacement.ts.TerminalKilledErroruntil the app restarts; the remount's own save would fail in that state anyway.Credit: #18190 by itisvincent identified the same restart-ordering problem from the renderer side. No code from #18190 is included here. The first commit carries a Co-authored-by trailer for itisvincent for that overlap. #18190's separate failed-shutdown prompt behaviour is not covered by this PR.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)