Skip to content

fix(terminal): restart a Codex pane into a fresh process after an account switch - #24350

Closed
brennanb2025 wants to merge 7 commits into
mainfrom
brennanb2025/codex-account-restart-blank
Closed

brennanb2025 wants to merge 7 commits into
mainfrom
brennanb2025/codex-account-restart-blank

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1023 $\color{#cf222e}{\Huge{\mathbf{−}}}$​20 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1003
Prod 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​251 $\color{#cf222e}{\Huge{\mathbf{−}}}$​35 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​216

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 with TerminalKilledError, 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 in src/main/ipc/pty/pane/pane-owner-replacement.ts so 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 codex under 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 TerminalKilledError as "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/claude CLIs, 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 TerminalKilledError and spawn-left-pane-unbound. PR: plain codex, exactly one new process, CODEX_HOME = the newly selected account.

main: pane blank after account-switch Restart
PR: fresh codex after account-switch Restart

Claude orchestrator plus Codex worker in another tab (the STA-9012 flow), switch account, restart the worker. main: blank. PR: plain codex with the new account. No claude command was typed on either build.

main: worker pane blank after Restart
PR: worker pane runs fresh codex after Restart

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.

main: hidden-tab pane blank after Restart all
PR: hidden-tab pane runs fresh codex after Restart all

Ordinary restore (quit, stop the daemon, relaunch): every pane resumed its own saved session on both builds, with no error UI.

PR: panes resumed after relaunch

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

  • I manually tested these changes locally
  • Automated tests added/updated

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.ts and the renderer deferred-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:spawn handler and the real binding write, refusal and rollback logic, against a fake daemon that throws the real TerminalKilledError.

Cases covered:

  • Exactly one binding write, and the pane is never unbound mid-restart.
  • The old binding re-published mid-spawn still gives a fresh launch.
  • The renderer withdrawing the binding before the swap still lets it land.
  • A successor binding during the spawn is kept, and the new process is shut down.
  • A spawn failure, and separately a save failure, followed by an ordinary remount that starts fresh.
  • Direct SSH with the pane in its own host partition: the swap, successor refusal, and failure clear plus remount.
  • Folder workspaces on simulated darwin, linux and win32.
  • A stop failure, and a reveal that arrives mid-stop.

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:

  • Production code reverted to this PR's first version: the re-publish test fails with TerminalKilledError.
  • The stopped-id exclusion removed: most host restart tests and the renderer-to-host test fail with TerminalKilledError.
  • The failure-path clear removed: both remount tests fail with TerminalKilledError.
  • The swap accepting only an exact match: the split-pane, SSH and withdrawn-binding tests fail.
  • The swap reading the local partition for SSH, or the failure clear dropping the SSH host: one new SSH test each fails.
  • The swap always refusing: the renderer-to-host test fails.

Node and web typecheck, oxlint, the changed-code quality gate and git diff --check pass. 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 replacesPtyId go through unchanged code paths (identity at every changed site). CLI, mobile and paired terminal.create paths are untouched. No wire contract, preload, shared type or liveness check changed.

Agent skill upstream boundary

  • Not applicable; no upstream skill source is copied.

Notes

Known weaknesses:

  • Paired-runtime restart reattaches the old process and starts no new one (known gap, unchanged). Fixing it needs a capability-negotiated host operation; that follow-up will reuse pane-owner-replacement.ts.
  • The failure-path clear is best-effort. If saving keeps failing, its own write rolls back and the remount can still hit TerminalKilledError until the app restarts; the remount's own save would fail in that state anyway.
  • The failure-path clear is awaited before the error reply, so a failed restart reports one queued save later.
  • If another owner took the pane during the stop itself (no real path found), the restart attaches to that owner rather than refusing.
  • The renderer guard keys on the replaced process id, so a hidden pane without a usable layout leaf (which restarts without a replacement id) is not covered by it. A wrong resume there is unproven.
  • No live UI validation beyond Visual Proof.

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

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

brennanb2025 and others added 7 commits October 1, 2026 03:07
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.
@brennanb2025 brennanb2025 changed the title fix(terminal): retire the old pane owner during account restart fix(terminal): restart a Codex pane into a fresh process after an account switch Oct 1, 2026
@brennanb2025

Copy link
Copy Markdown
Contributor Author

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 (TerminalKilledError) and the pane was left with no process. This happened for the Restart chip on a visible pane and for the status-bar "Restart N Sessions" action on panes in hidden tabs.

What changes for users: Restart now always leaves the same pane running one fresh plain codex under the newly selected account. It starts a new Codex conversation by design (same as the hidden-pane restart already intended); resuming a conversation across an account switch is the separate #14877. Ordinary quit-and-relaunch restore is unchanged.

Fixed during review:

  • The first version wrote a separate "pane unbound" record before launching. A delayed layout save from the app could write the old process id back in between, which recreated the blank pane, and a failed save left the pane pointing at the dead process. Replaced with: the spawn ignores only the process it just stopped, and the new process's binding replaces the old one in a single guarded write; a failure after the stop clears the dead binding best-effort without ever blocking the user.
  • The guarded write accepts a pane the app has already cleared (split tabs, SSH after the stop), which a strict check would have refused on a normal restart.
  • Tests now run the real binding write end to end, keep SSH panes in their own saved-state partition, and fail when each part of the fix is removed.
  • PR description rewritten for the final design.

Deferred (not blocking):

  • Paired-runtime restart (a pane served by a paired remote Orca) still reattaches the old process and starts no new one. It does not go blank and is unchanged by this PR; it needs a negotiated host operation in a follow-up.
  • If a hidden-tab restart fails AND the tab is revealed before pressing Restart again, the app's stale copy of the old id could still be re-saved (unproven chain, needs a spawn failure first).
  • Maintainability: a binding-only clear (retirePtyBinding) sits beside the existing surface-removal retire; it is used only on the failure path.
  • If the app quits between the stop and the new binding being saved, the saved binding still names the stopped process; main has the same window.
  • Copy mismatch, not caused by this PR: the "Restart N Sessions" prompt says other panes restart when their worktree becomes active, but on main and on this PR hidden panes restart immediately.
  • STA-9012 / [Bug] Restarting a Claude-spawned Codex worker after switching Codex accounts launches claude commands. #24103: the reporter's claude --resume <codex id> line did not reproduce live on main. This PR stops the account-restart path from substituting a saved session's resume command, so it partly helps; cold restore, worktree wake and the resume sweep still depend on fix(agents): keep terminal resume identity with its provider owner #24297.

Verified:

  • Live on a remote Mac with stub CLIs, isolated homes and two fake managed accounts, main vs PR (screenshots in the description): visible-pane restart blank on main / fresh codex with the new account's CODEX_HOME on the PR; Claude-orchestrator-plus-Codex-worker restart blank on main / fresh codex on the PR with no claude command typed; status-bar restart of 4 hidden panes 4/4 blank on main / 4/4 fresh on the PR; quit-and-relaunch restore identical on both.
  • Node and web typecheck clean at fd2e6cf; CI green on fd2e6cf; 56 related test files (546 tests) pass; oxlint clean on all changed files.
  • Two full review rounds (including an architecture review), a narrow check of the last test-only fixes, and a readiness checklist: no open P0/P1/P2 code issues.

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).

@brennanb2025
brennanb2025 marked this pull request as ready for review October 1, 2026 11:34
@pullfrog

pullfrog Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Run failed. View the logs →

Pullfrog  | Rerun failed job ➔ | View workflow run | via Pullfrog | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@greptile-apps

greptile-apps Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 4/5

[High risk] Refactors terminal process restart and pane binding lifecycle.

The PR should not merge until a restart can no longer restore a split pane closed while the replacement is in flight.

Findings

  1. P1 Closed split pane reappears ▶

Summary

The PR makes Codex account-switch restarts stop the previous PTY, exclude it from pane-owner reattachment, and durably bind a fresh process. It also clears a stopped binding after a failed replacement and makes explicit renderer replacements use their requested startup. The replacement swap needs to distinguish a renderer-cleared binding from a pane that was closed during the restart.

Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Restart reserves pane] --> B[Stop old PTY]
  B --> C[Spawn fresh PTY]
  C --> D{Saved leaf binding}
  D -->|Old ID| E[Swap to new ID]
  D -->|Unbound, leaf still present| E
  D -->|Different ID| F[Refuse and stop new PTY]
  D -->|Leaf closed during restart| G[Currently grafts closed leaf back]
Loading

Reviews (1) · Last reviewed commit: "test(terminal): type the SSH restart cal..."

Comment on lines +73 to +78
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 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.

@coderabbitai

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

🧰 Additional context used
📚 Code guidelines (1)
AGENTS.md — auto-discovered
📝 Walkthrough

Walkthrough

The 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 fd2e6

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 Review

Security architecture risk: 🔵 Low · up to fd2e6

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
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The reviewed sensitive outcomes are stopping terminal processes and changing local or SSH-host persisted pane ownership. Binding mutations are host-partitioned and identity-conditional. Broader authorization scope for ownerless stop requests was not fully established.

Trust Boundaries and Controls

  • inferred — Renderer-supplied replacement identity reaches the main-process stop helper. When an owner resolves, mismatched identity is rejected; when no owner resolves, the helper still invokes the stopper. The supplied base-change description identifies a preexisting direct stop call, so this branch is not established as newly widened authority. Complete upstream authorization remains a coverage gap, not a verified vulnerability.

Resilience and Maintainability Implications

  • inferred — Storage failure can leave recovery state naming a stopped process despite the new cleanup attempt. This limits restart recovery guarantees, but the inspected behavior does not establish process resurrection, credential crossover, or a newly worsened security condition.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 13 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: restarting a Codex pane into a fresh process after an account switch.
Description check ✅ Passed The description is detailed and covers the user impact, implementation, rationale, linked issues, visual proof, testing, known gaps, and checklist. The manual-testing and full-command checklist items …
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: d3ffe3a8-c160-4387-b441-b1635597045a

📥 Commits

Reviewing files that changed from the base of the PR and between 5f728f7 and fd2e6cf.

📒 Files selected for processing (13)
  • src/main/ipc/pty-pane-restart-replace.test.ts
  • src/main/ipc/pty/ipc/spawn-begin.ts
  • src/main/ipc/pty/ipc/spawn-commit-persist.ts
  • src/main/ipc/pty/ipc/spawn-execute.ts
  • src/main/ipc/pty/ipc/spawn-run.ts
  • src/main/ipc/pty/ipc/spawn-state.ts
  • src/main/ipc/pty/pane/pane-owner-replacement.test.ts
  • src/main/ipc/pty/pane/pane-owner-replacement.ts
  • src/main/persistence/loading-store/pty-binding-persistence.ts
  • src/main/persistence/loading-store/pty-binding-restart-retirement.test.ts
  • src/main/persistence/loading-store/replaced-pane-binding.ts
  • src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-choice.ts
  • tests/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.

Comment on lines +21 to +25
// An explicit replacement owns its startup; saved recovery state must not substitute another agent.
if (session.pendingReplacedPtyId) {
session.startFreshSpawn()
return
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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-pane

Repository: 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 -240

Repository: 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-connection

Repository: 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.

Suggested change
// 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
}

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — stopReplacedPaneOwner validates 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 (runPtyIpcSpawn catch, 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?

@nwparker

nwparker commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

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.

nwparker added a commit that referenced this pull request Oct 5, 2026
…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]>
@nwparker

nwparker commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

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.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants