Skip to content

fix(codex): serialize session restart after PTY shutdown - #18190

Closed
itisvincent wants to merge 1 commit into
stablyai:mainfrom
itisvincent:fix/codex-restart-pty-shutdown-race
Closed

itisvincent wants to merge 1 commit into
stablyai:mainfrom
itisvincent:fix/codex-restart-pty-shutdown-race

Conversation

@itisvincent

Copy link
Copy Markdown
Contributor

ELI5

Restart now waits for the old Codex terminal process to finish shutting down before Orca starts its replacement. This prevents the replacement from accidentally reconnecting to the same outdated process and showing the setup-change dialog again.

What Changed

  • Make local PTY transport shutdown awaitable and retain the PTY identity when shutdown fails so a retry can target the same process.
  • Serialize the full mounted-pane restart transaction, clear only the captured old layout binding, and recheck pane ownership before reconnecting.
  • Reopen the restart prompt after a failed shutdown instead of clearing state as though the restart succeeded.
  • Add regression coverage for shutdown ordering, concurrent ownership changes, duplicate restart suppression, and failed-shutdown retries.

Why

Mounted Codex restarts previously launched the replacement immediately after requesting shutdown of the old PTY. Because shutdown is asynchronous, the replacement could reclaim the stable pane while the old PTY was still available, reattach the stale session, and trigger the same setup-change notice again.

Linked Issue

Fixes #18174

Visual Proof

N/A. This changes PTY lifecycle ordering and failure recovery; it does not change dialog layout or styling.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Validated on Windows:

  • 7 focused Vitest files: 124 tests passed
  • Renderer typecheck: tsc --noEmit -p config/tsconfig.tc.web.json
  • Targeted oxlint and React Doctor lint passed on all 5 changed files
  • oxfmt --write completed with no remaining changes
  • Electron Vite production build passed (existing CSS highlight and chunk-size warnings only)
  • git diff upstream/main...HEAD --check passed

Full cross-platform coverage is left to CI. The behavior is transport-agnostic and preserves the existing SSH/remote transport contract; only the local IPC transport exposes the optional failed-shutdown identity.

AI Disclosure

OpenAI Codex was used to diagnose, implement, review, and verify this change.

Review

Pre-landing and adversarial review found no concrete issues. The main residual test limitation is that the failure retry is triggered through a hook rerender rather than a literal dialog click; the store prompt lifecycle is covered separately.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Security: no new trust boundary or external input handling.
  • Cross-platform: no platform-specific commands, paths, or shortcuts added.
  • Remote SSH: no remote wire or execution-host contract changes.
  • Mobile: no mobile code paths changed.
  • Backwards compatibility: the new transport method is optional and the disconnect return type still accepts synchronous implementations.
  • Performance: restart work is serialized per pane only while shutdown is in flight.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • 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)

@coderabbitai

coderabbitai Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PTY transport now supports asynchronous shutdown and retains the PTY ID after a failed kill for retry. Cleanup runs only after successful shutdown. Codex pane restarts await transport destruction, preserve newer replacements, clear pane-specific layout bindings, and reopen the restart prompt after failure. Concurrent restarts are deduplicated. Tests cover shutdown timing, retry behavior, restart ordering, replacement preservation, and failed shutdown recovery.

Merge Risk: 🟡 Moderate · up to 7ef09

Restart cleanup can currently notify the application before the old terminal process has fully stopped, and a failed shutdown can lose the callbacks needed for retry. This may allow stale-session behavior or leave restart recovery incomplete, so the PR is not merge-ready until shutdown cleanup is deferred until successful termination.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 5 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 and concisely describes the primary change: serializing Codex session restart until PTY shutdown completes.
Description check ✅ Passed The description is complete and follows the repository template. It explains the problem and solution, links issue #18174, documents testing, provides visual proof as N/A with a reason, and addresses …
Linked Issues check ✅ Passed The changes satisfy issue #18174. They await asynchronous PTY shutdown, prevent stale PTY reuse, recheck pane ownership, clear the captured old binding, reopen the restart prompt after failure, and ad…
Out of Scope Changes check ✅ Passed The changes are limited to PTY shutdown handling, Codex pane restart sequencing, related transport types, and regression tests. No unrelated product or infrastructure changes are present.
Full details: Description check

Explanation

The description is complete and follows the repository template. It explains the problem and solution, links issue #18174, documents testing, provides visual proof as N/A with a reason, and addresses compatibility and scope considerations.

Full details: Linked Issues check

Explanation

The changes satisfy issue #18174. They await asynchronous PTY shutdown, prevent stale PTY reuse, recheck pane ownership, clear the captured old binding, reopen the restart prompt after failure, and add regression tests for the restart ordering and retry behavior.

  • Fix all pre-merge checks with AI

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: Team

Run ID: bbf1dedb-1f8c-4a45-b2be-c7f93baef577

📥 Commits

Reviewing files that changed from the base of the PR and between f737f34 and 7ef0992.

📒 Files selected for processing (5)
  • src/renderer/src/components/terminal-pane/pty-transport-detach-attach-handoff.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-codex-restart-order.test.tsx
  • src/renderer/src/components/terminal-pane/use-terminal-pane-process-exit-actions.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines 205 to +209
} finally {
handlers.unregisterAll(id)
storedCallbacks.onDisconnect?.()
if (disconnectsLivePty) {
handlers.unregisterAll(id)
storedCallbacks.onDisconnect?.()
}

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 | 🟠 Major | ⚡ Quick win

Defer disconnect cleanup until kill succeeds.

The finally block runs when killPromise.then(...) is returned. It does not wait for the kill promise to settle. Lines 207-208 unregister handlers and emit onDisconnect while shutdown is still pending, and also after a failed shutdown.

A consumer can react to onDisconnect before the old PTY stops. A rejected kill also removes the handlers needed while the retained PTY ID waits for retry. Move this cleanup into the fulfillment path. Preserve a cleanup-required flag so a successful retry also unregisters the original PTY handlers.

Proposed fix
+      const cleanupAfterSuccessfulShutdown =
+        disconnectsLivePty || pendingShutdownPtyId === id
       if (id) {
         try {
           const killPromise = Promise.resolve(window.api.pty.kill(id))
           return killPromise.then(
             () => {
               if (pendingShutdownPtyId === id) {
                 pendingShutdownPtyId = null
               }
+              if (cleanupAfterSuccessfulShutdown) {
+                handlers.unregisterAll(id)
+                storedCallbacks.onDisconnect?.()
+              }
             },
             (error: unknown) => {
               pendingShutdownPtyId = id
               throw error
             }
           )
         } catch (error) {
           pendingShutdownPtyId = id
           throw error
-        } finally {
-          if (disconnectsLivePty) {
-            handlers.unregisterAll(id)
-            storedCallbacks.onDisconnect?.()
-          }
         }
       }

@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 — a focused renderer-side fix that serializes the mounted Codex account-switch restart until the outgoing local PTY shutdown completes, plus regression coverage for shutdown ordering, concurrent ownership changes, duplicate-restart suppression, and failed-shutdown retry.

  • Awaitable local PTY shutdown — PtyTransport.disconnect/destroy now return void | Promise<void>; the IPC transport resolves disconnect only after pty.kill settles and retains a pendingShutdownPtyId on failure so a retry targets the same process. handlers.unregisterAll/onDisconnect still fire synchronously (gated on disconnectsLivePty so a retry doesn't double-fire them).
  • Serialized restart transaction — runRestartCodexPane awaits destroy, reopens the restart prompt on failure instead of clearing state as if it succeeded, clears only the captured old leaf binding via clearExitedPanePtyLayoutBindingForLeaf, and rechecks pane ownership before reconnecting.
  • Duplicate-restart suppression — a per-pane in-flight useRef map collapses concurrent restart requests for the same pane onto one transaction.
  • Tests — new use-terminal-pane-codex-restart-order.test.tsx, plus shutdown-ordering and failed-shutdown-identity cases in pty-transport-detach-attach-handoff.test.ts.

The type changes are backward compatible (disconnect/destroy accept sync implementations; getPendingShutdownPtyId is optional), so the remote and unresolved-owner transports are unaffected. Non-restart callers of destroy/disconnect (e.g. terminal-pane-pane-closed.ts) discard the returned promise, but that is the same floating-rejection class as the pre-existing unawaited pty.kill, not a regression.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker

nwparker commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Closing this older implementation as superseded by merged #25485, which adopts #24350's host-owned replacement transaction. Shutdown is awaited inside the pane reservation before spawning the replacement, and the stopped process cannot be reattached. @itisvincent is credited in the merged PR and commit trailers for the restart-ordering diagnosis.

The separate failed-shutdown prompt/retry behavior proposed here was not adopted. This closure marks the ordering implementation as superseded; it does not claim that additional behavior landed.

@nwparker nwparker closed this Oct 5, 2026
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.

[Bug]: Codex setup changed dialog reappears after restarting a resumed session

2 participants