Skip to content

fix(codex): execute accepted account-switch restarts for unmounted panes - #12146

Merged
brennanb2025 merged 8 commits into
mainfrom
brennanb2025/codex-restart-strand-fix
Aug 3, 2026
Merged

brennanb2025 merged 8 commits into
mainfrom
brennanb2025/codex-restart-strand-fix

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The prior worktree-wide Codex account-switch prompt queued restarts for every awaiting pane, but execution only happened inside mounted TerminalPane instances. A pane without a mounted transport could be stranded: its prompt disappeared, keyboard input stayed blocked, and Codex kept running against the old account's CODEX_HOME until the tab was revealed.

This PR makes an accepted restart execute for every queued pane regardless of renderer mount state:

  • Detached executor (codex-detached-pane-restart.ts): a store-level driver watches pendingCodexPaneRestartIds. 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 through pty: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.
  • Pane-local decisions: each restart prompt is portaled into its owning terminal pane and selects one exact PTY notice. Restart/Keep affects only that pane, including split panes; siblings keep their own prompt and session. Only the active visible pane may take dialog focus, and replacement PTYs resolve through the live transport with the persisted leaf binding as fallback.
  • Race-safe ownership: worktree, tab generation, old PTY, layout leaf, and mounted ownership are revalidated before and after spawn. Mounted-owner handoffs requeue before cleanup; tab retirement during spawn reaps the replacement. Best-effort cleanup cannot block later restart requests.
  • Never a silent input block: success clears the notice and unblocks input. A failed respawn re-offers the prompt instead of leaving the pane muted. A removed pane clears its notice, while sleep-retained and foreign-machine panes remain on their existing lifecycle paths.
  • App-restart safety: sweepRestoredCodexPanesForStaleAccounts queues every restored PTY id for stale-account inspection at startup, including panes whose tabs never mount.
  • Managed-auth readiness: CODEX_ACCOUNT_RESTART_STARTUP carries launchAgent: 'codex', so both restart paths use main's managed-auth readiness gate and Codex launch preparation.
  • Bounded hot path: the store subscriber uses reference equality before inspecting restart work, avoiding allocations or scans on unrelated Zustand updates. Detached hidden replacements start at 80×24 and converge through the normal mount-fit path, without waiting on a possibly hung getSize call.

Screenshots

Before — two split PTYs each present their own account-specific restart prompt:

Per-pane restart prompts

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:

One pane restarted independently

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 lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality regression tests

Focused validation after review:

  • 88 tests across the four Codex restart suites
  • 92 tests across the five terminal-session.layout-pty-ownership reliability suites
  • 101 focused per-pane/restart tests, plus 5 restored-layout/geometry tests, after the pane-local UI correction
  • pnpm typecheck
  • Targeted lint, React Doctor, and git diff --check
  • Electron validation through the account-switch prompt and real Codex PTY replacement

Key regression coverage asserts actual pty:spawn/pty:kill behavior 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 test run: 43,509 passed; 18 failures across five unrelated files reproduced identically on base commit 99b94a38eb and 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 CLEAN at 578dcddb6dd1ba20ce544d970e58d7f6d040b63f.

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.kill APIs and main-side PTY/session, startup-cwd, and folder-workspace validation. Restart commands are constant, environment additions are the existing store-derived ORCA_* pane identity fields, and kill targets come from renderer store bindings.

Notes

  • Detached relay-environment respawn remains deliberately out of scope because it needs the remote transport's spawn assembly; those panes continue through their mounted path.
  • src/main/codex/codex-stale-pane-accounts.ts needed no change: the account registry already forgets records on real PTY teardown, while restored-stale prompt recovery is handled by the renderer startup sweep.

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.
@coderabbitai

coderabbitai Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The 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 codex as the launch agent. Terminal state adds restart-prompt reopening and layout-leaf PTY replacement methods. Tests cover startup sweeping, detached execution, layout handling, deferral, failures, and state lifecycles.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely identifies the main change: executing accepted Codex account-switch restarts for unmounted panes.
Description check ✅ Passed The description covers the required sections, user-visible behavior, testing, review, security, platform considerations, and known test limitations.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

@greptile-apps

greptile-apps Bot commented Aug 2, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a bug where accepted Codex account-switch restarts were only executed inside mounted TerminalPane instances, leaving panes in unmounted or hidden tabs stranded with blocked keyboard input. The solution introduces a store-level detached executor and moves the restart prompt from a worktree-wide chip to a per-pane chip portaled into each managed pane's container.

  • Detached executor (codex-detached-pane-restart.ts + scheduler): a Zustand subscriber watches pendingCodexPaneRestartIds and, via generation-fenced single-flight microtask scheduling, kill-and-respawns any pane no mounted transport has claimed, rebinding the layout so a later mount reattaches cleanly.
  • Per-pane chip (CodexRestartChip.tsx, TerminalPane.tsx): the old worktree-wide chip is removed from Terminal.tsx; each pane in a mounted TerminalPane gets its own chip portaled to its container, keyed by pane.id + ptyId. Only the active visible pane may take dialog focus.
  • Startup stale-account sweep (codex-stale-pane-sweep.ts): sweepRestoredCodexPanesForStaleAccounts is called post-reconnect in App.tsx to queue every restored PTY id for inspection, covering panes whose tabs never mount this session.

Confidence Score: 5/5

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

Important Files Changed

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
Loading

Reviews (4): Last reviewed commit: "fix(codex): contain detached restart swe..." | Re-trigger Greptile

@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

🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/codex-detached-pane-restart-scheduler.ts (1)

17-24: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Short-circuit the subscription before enumerating keys.

This listener runs on every store update. pendingCodexPaneRestartIds is empty in the common case, but Object.keys still 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3a71d3f and 2aa7d76.

📒 Files selected for processing (4)
  • src/renderer/src/App.tsx
  • src/renderer/src/components/terminal-pane/codex-detached-pane-restart-scheduler.ts
  • src/renderer/src/components/terminal-pane/codex-detached-pane-restart.test.ts
  • src/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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron QA and iterative review are complete at 19bc70ae15c0d7a6a6abd64a1a63a58bf873fc81.

The real account-switch prompt was accepted through the UI. Backing state confirmed the old PTY died, a replacement Codex PTY became live in the same terminal tab, and the pending restart/notice maps cleared.

Before After
Restart prompt Replacement Codex session

The isolated profile retained the hidden tab as a mounted hot view, so the fully detached ownership branch is covered by deterministic race/hang tests rather than a mocked UI state. The same-model review loop returned CLEAN; focused Codex and terminal-ownership suites, typecheck, lint checks, and all PR CI checks pass.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Follow-up review and Electron QA are complete at 578dcddb6dd1ba20ce544d970e58d7f6d040b63f. This supersedes the earlier worktree-wide prompt evidence.

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.

Independent pane prompts Left pane restarted; right pane untouched
Two pane-local prompts One pane restarted independently

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 CLEAN; 101 focused restart tests plus restored-layout/geometry coverage, typecheck, lint, React Doctor, reliability checks, and commit hooks passed.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Final same-model review is CLEAN at e4e8674b9d5506a02a348dc6180d4b99d4c87616.

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:

  • 89 focused Codex restart tests passed
  • 92 terminal-session.layout-pty-ownership reliability tests passed
  • Full typecheck, targeted lint/React Doctor, formatting, and git diff --check passed
  • All required PR checks passed, including Node 24/26 shards and macOS/Windows packaging
  • Local, remote, and PR heads match; worktree is clean

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.

@brennanb2025
brennanb2025 merged commit bcf7d1d into main Aug 3, 2026
43 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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
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.

1 participant