Repository navigation
fix(codex): execute accepted account-switch restarts for unmounted panes - #12146
Conversation
Accepting the Codex account-switch restart prompt queued every awaiting pane but only mounted TerminalPane instances executed the queue, so background-tab and parked panes stayed input-blocked on the old account with no prompt. - Add a detached store-level driver (codex-detached-pane-restart) that kill-and-respawns any queued pane no mounted transport claims, rebinding tab/layout state so a later mount reattaches to the replacement PTY. - Re-offer the prompt when a detached execution fails, and clear the notice when the pane is gone, so input is never silently blocked. - Sweep restored PTY ids at startup so stale panes in never-mounted tabs are re-offered after an app restart. - Carry launchAgent codex on the restart respawn so it waits for managed-auth readiness and records the pane's launch account.
|
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:
📝 WalkthroughWalkthroughThe change adds detached Codex pane restart execution with PTY respawn, layout rebinding, failure recovery, and cleanup. Startup now sweeps restored Codex panes for stale accounts and installs the detached restart executor. Restart configuration identifies 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 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 |
Greptile SummaryThis PR fixes a bug where accepted Codex account-switch restarts were only executed inside mounted
Confidence Score: 5/5Safe to merge. The ownership protocol eliminates double-execute and orphaned-PTY risks; failure paths uniformly reopen the prompt rather than leaving panes input-blocked. The detached executor correctly defers to mounted transports via ptyDataHandlers and hasRegisteredRuntimeTerminalTab guards, handles all race paths (tab retirement mid-spawn, mounted-owner handoff, generation mismatch), and restores the prompt on every failure. The per-pane chip migration is straightforward with correct key-based remounting. No new logic issues were identified beyond the two items already addressed in previous review threads. Files Needing Attention: No files require special attention. The test file codex-detached-pane-restart.test.ts retains a now-unused getSize mock (the implementation switched to fixed 80x24), but this is inert.
|
| Filename | Overview |
|---|---|
| src/renderer/src/components/terminal-pane/codex-detached-pane-restart.ts | Core detached executor: locates pane, validates ownership before and after spawn, reaps unbound PTYs, rebinds layout leaf, reopens prompt on any failure path. Race guards are thorough. |
| src/renderer/src/components/terminal-pane/codex-detached-pane-restart-scheduler.ts | Single-flight scheduler with generation fencing; handles StrictMode double-mount and concurrent sweeps correctly via sweepRunning/sweepRequestedAfterRun state machine. |
| src/renderer/src/components/CodexRestartChip.tsx | Simplified from worktree-wide to per-pane chip; O(1) selector, focus gated by shouldFocus prop, dismiss correctly calls forgetStalePanes for only the one pane. |
| src/renderer/src/components/terminal-pane/TerminalPane.tsx | Adds per-pane CodexRestartChip portals with ptyId derived from live transport or savedLayout fallback; shouldFocus correctly limited to active visible pane. |
| src/renderer/src/lib/codex-stale-pane-sweep.ts | Adds sweepRestoredCodexPanesForStaleAccounts to queue all restored PTY ids at startup; correctly delegates to existing notifyCodexPaneBoundForStaleSweep with foreign-machine guard. |
| src/renderer/src/store/slices/terminals.ts | Adds queueCodexPaneRestarts, consumePendingCodexPaneRestart, reopenCodexRestartPrompt, replaceTerminalLayoutPanePtyId to state; pendingCodexPaneRestartIds properly migrated across updateTabPtyId, clearTabPtyId, and sleep paths. |
| src/renderer/src/App.tsx | Installs detached executor via useEffect and calls sweepRestoredCodexPanesForStaleAccounts after reconnect; correct placement after PTY ids are published. |
| src/renderer/src/lib/codex-session-restart.ts | CODEX_ACCOUNT_RESTART_STARTUP now carries launchAgent: 'codex' so managed-auth readiness gate fires on both mounted and detached restart paths. |
| src/renderer/src/components/terminal-pane/codex-detached-pane-restart.test.ts | Comprehensive race coverage; stale getSize mock present but harmless since implementation now uses fixed 80x24 dimensions. |
| src/renderer/src/components/Terminal.tsx | Removes worktree-level CodexRestartChip instances cleanly; per-pane chips now live in TerminalPane portals. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Account Switch Detected] --> B[markLiveCodexSessionsForRestart]
B --> C[codexRestartNoticeByPtyId updated for each stale pane]
C --> D{Is pane tab mounted?}
D -- Yes --> E[TerminalPane renders per-pane CodexRestartChip portal]
D -- No --> F[Notice exists in store, no chip shown until tab revealed]
E --> G{User clicks Restart}
G --> H[queueCodexPaneRestarts of single ptyId]
H --> I[scheduleClaimSweep via Zustand subscriber]
H --> J[TerminalPane effect fires on pendingCodexPaneRestartIds change]
J --> K{Transport bound for ptyId?}
K -- Yes --> L[consumePendingCodexPaneRestart - handleRestartCodexPane in-place]
K -- No --> M[Effect skips; detached executor claims it]
I --> N[sweepUnclaimedCodexPaneRestarts microtask]
N --> O{ptyDataHandlers.has or inFlightPtyIds.has?}
O -- Yes --> P[Skip: mounted pane owns it]
O -- No --> Q{locateCodexPane finds tab?}
Q -- No --> R[clearCodexRestartNotice if notice muting input]
Q -- Yes --> S{hasRegisteredRuntimeTerminalTab?}
S -- Yes --> T[Skip: tab registering, leave for mount]
S -- No --> U[consumePendingCodexPaneRestart - inFlightPtyIds.add]
U --> V[pty.spawn with fixed 80x24, CODEX_ACCOUNT_RESTART_STARTUP]
V --> W{isLocatedCodexPaneCurrent after spawn?}
W -- No --> X[reopenCurrentCodexRestartPrompt + reapUnboundCodexPty]
W -- Yes --> Y{Mounted owner raced in?}
Y -- Yes --> Z[queueCodexPaneRestarts requeue + reapUnboundCodexPty]
Y -- No --> AA[updateTabPtyId + rebindCodexPaneLayoutLeaf]
AA --> AB[clearCodexRestartNotice spawned + original]
AB --> AC[killReplacedCodexPanePty]
F --> AD{User reveals hidden tab} --> E
Reviews (4): Last reviewed commit: "fix(codex): contain detached restart swe..." | Re-trigger Greptile
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/codex-detached-pane-restart-scheduler.ts (1)
17-24: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueShort-circuit the subscription before enumerating keys.
This listener runs on every store update.
pendingCodexPaneRestartIdsis empty in the common case, butObject.keysstill allocates an array on each write to a high-traffic store. Compare the slice reference first, then enumerate only when it changed.♻️ Proposed refactor
const unsubscribe = useAppStore.subscribe((state, previousState) => { + if (state.pendingCodexPaneRestartIds === previousState.pendingCodexPaneRestartIds) { + return + } const addedPendingId = Object.keys(state.pendingCodexPaneRestartIds).some( (ptyId) => !previousState.pendingCodexPaneRestartIds[ptyId] ) if (addedPendingId) { scheduleClaimSweep() } })
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c459f4f2-7b09-416f-bd15-8d1a6ebd0771
📒 Files selected for processing (4)
src/renderer/src/App.tsxsrc/renderer/src/components/terminal-pane/codex-detached-pane-restart-scheduler.tssrc/renderer/src/components/terminal-pane/codex-detached-pane-restart.test.tssrc/renderer/src/components/terminal-pane/codex-detached-pane-restart.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/renderer/src/App.tsx
|
Follow-up review and Electron QA are complete at The restart prompt is now owned by its exact terminal pane. In a real two-PTY split, each pane showed its own account-specific prompt. Clicking Restart in the left pane killed/replaced only the left PTY and launched Codex there; the right PTY remained alive with its own unanswered prompt.
Backing state: old left PTY dead; replacement left PTY alive; original right PTY alive; pending restart map empty; only the right pane's notice remained. The same-model review loop returned |
|
Final same-model review is CLEAN at The review found one material current-head issue: an unexpected failure before the detached restart executor entered its original per-pane try/catch could reject the whole scheduler sweep, surface an unhandled renderer rejection, and prevent later queued panes from progressing. The pushed fix contains failures per PTY, restores the affected unanswered prompt, allows sibling restarts to continue, and keeps a last-resort scheduler rejection guard. A deterministic regression test covers the failure plus later-pane progress. The two Greptile threads were already addressed by the existing cleanup and bounded-size changes. Verification:
Electron was not rerun because the exact visible workflow is already attached in the current PR QA comment, as allowed by the follow-up request. I rechecked both uncropped images: two split panes show independent prompts, then restarting the left pane launches Codex there while the right PTY and its prompt remain untouched. This final commit changes only background failure containment, not the rendered UI. The fully detached ownership path remains covered by the deterministic restart/race tests. |
…nes (stablyai#12146) * fix(codex): execute accepted account-switch restarts for unmounted panes Accepting the Codex account-switch restart prompt queued every awaiting pane but only mounted TerminalPane instances executed the queue, so background-tab and parked panes stayed input-blocked on the old account with no prompt. - Add a detached store-level driver (codex-detached-pane-restart) that kill-and-respawns any queued pane no mounted transport claims, rebinding tab/layout state so a later mount reattaches to the replacement PTY. - Re-offer the prompt when a detached execution fails, and clear the notice when the pane is gone, so input is never silently blocked. - Sweep restored PTY ids at startup so stale panes in never-mounted tabs are re-offered after an app restart. - Carry launchAgent codex on the restart respawn so it waits for managed-auth readiness and records the pane's launch account. * fix(codex): fence detached restart ownership races * fix(codex): unblock detached restart handoffs * fix(codex): contain detached restart cleanup * fix(codex): detach restart progress from cleanup * fix(codex): avoid detached restart size wait * fix(terminal): scope Codex restart prompt to pane * fix(codex): contain detached restart sweep failures




Summary
The prior worktree-wide Codex account-switch prompt queued restarts for every awaiting pane, but execution only happened inside mounted
TerminalPaneinstances. A pane without a mounted transport could be stranded: its prompt disappeared, keyboard input stayed blocked, and Codex kept running against the old account'sCODEX_HOMEuntil the tab was revealed.This PR makes an accepted restart execute for every queued pane regardless of renderer mount state:
codex-detached-pane-restart.ts): a store-level driver watchespendingCodexPaneRestartIds. Generation-fenced, single-flight microtask scheduling lets mounted panes claim their own restarts first without a timing delay. A still-unowned pane is kill-and-respawned throughpty:spawn/pty:kill, then its tab and layout bindings are rebound so a later mount reattaches to the replacement PTY. Mounted panes keep the existing in-place path, including split-pane ownership.sweepRestoredCodexPanesForStaleAccountsqueues every restored PTY id for stale-account inspection at startup, including panes whose tabs never mount.CODEX_ACCOUNT_RESTART_STARTUPcarrieslaunchAgent: 'codex', so both restart paths use main's managed-auth readiness gate and Codex launch preparation.getSizecall.Screenshots
Before — two split PTYs each present their own account-specific restart prompt:
After — accepting Restart in the left pane replaced only its PTY and launched Codex there; the right PTY stayed alive with its own unanswered prompt:
Electron backing-state validation confirmed the old left PTY was dead, its replacement was alive, the untouched right PTY was still alive, and only the right notice remained. The detached ownership path remains covered deterministically by the race tests below.
Testing
pnpm lintpnpm typecheckpnpm testpnpm buildFocused validation after review:
terminal-session.layout-pty-ownershipreliability suitespnpm typecheckgit diff --checkKey regression coverage asserts actual
pty:spawn/pty:killbehavior and covers mounted-owner handoff, split/rootless layouts, tab/worktree generation races, cleanup rejection and hangs, stale-state prompt recovery, sleep-retained and foreign-machine ids, startup stale-account sweep, managed-auth launch metadata, O(1) unrelated-store writes, and the 80×24-to-mounted-fit path.Note on the full local
pnpm testrun: 43,509 passed; 18 failures across five unrelated files reproduced identically on base commit99b94a38eband were caused by machine environment. All files touched by this PR are green, and the PR's Node 24/26 CI shards pass.AI Review Report
The iterative review checked the queue/claim protocol for double execution, renderer cleanup and StrictMode generation races, mounted/background/split/rootless/sleep/foreign ownership, pane-local prompt/action ownership, parked-tab exit handling, orphaned-PTY windows, prompt/input recovery, and repeated restart progress when kill cleanup rejects or hangs. The final same-model review returned
CLEANat578dcddb6dd1ba20ce544d970e58d7f6d040b63f.The performance review verified O(1) per-PTY prompt selectors, an O(1) reference gate on unrelated restart-store updates, single-flight scheduling per restart generation, and no unbounded pre-spawn provider-size wait.
Cross-platform behavior remains behind existing runtime abstractions. The detached spawn mirrors the mounted path's execution context and startup cwd handling, preserving native, Windows/WSL, SSH/relay, folder-workspace, and git-worktree behavior. Foreign-machine panes remain on their existing mounted transport path.
Security Audit
No new IPC surface is introduced. The driver uses the existing preload
pty.spawn/pty.killAPIs and main-side PTY/session, startup-cwd, and folder-workspace validation. Restart commands are constant, environment additions are the existing store-derivedORCA_*pane identity fields, and kill targets come from renderer store bindings.Notes
src/main/codex/codex-stale-pane-accounts.tsneeded no change: the account registry already forgets records on real PTY teardown, while restored-stale prompt recovery is handled by the renderer startup sweep.