Skip to content

fix(codex): land an account-switch restart on the newly selected account - #14877

Closed
tonite31 wants to merge 3 commits into
stablyai:mainfrom
tonite31:fix/codex-account-switch-restart
Closed

tonite31 wants to merge 3 commits into
stablyai:mainfrom
tonite31:fix/codex-account-switch-restart

Conversation

@tonite31

Copy link
Copy Markdown
Contributor

ELI5

You switch Codex to account B and press Restart on the card. The terminal comes back… still on account A. This PR makes that one press actually land on B, keeps your conversation going there (codex resume), and moves your /goal along with it. When the conversation can't follow (switching to the system default account), the card says so before you press.

What Changed

  • An account-switch restart now declares itself: the relaunch carries a codexAccountSwitchRestart flag from the renderer through pty:spawn. The flag survives a failed spawn, a reattach answer, and a rejected admission — it is only spent by a fresh spawn that actually ran the switch path.
  • With the flag set, resume preparation follows the current selection instead of the home that owns the rollout being resumed.
  • The conversation carries over: the specific rollout is hardlinked into the selected account's home ahead of the background sweep (the session bridge already hardlinks rollouts across managed homes), and the relaunch runs codex resume <id> instead of a bare codex.
  • The /goal objective, status and budget travel via thread/goal/get / thread/goal/set. tokens_used and the limit statuses stay behind — both were metered against the account being left. (Note: the app-server's status enum is camelCase — usageLimited / budgetLimited — not the snake_case spellings the goals sqlite stores; sending the latter is rejected.)
  • Switching to the system default account cannot carry the conversation (Orca never writes into ~/.codex), so it switches, starts fresh, and the card copy says so before the user presses.
  • Two adjacent paper cuts: adding an account no longer raises the restart card when the selection did not change, and the card copy now says what restarting the terminal does instead of "Restart this session" ("session" read as the Codex session; quitting Codex and retyping it keeps the old account because CODEX_HOME is baked into the shell at spawn).

Why

pty:spawn pins the launch CODEX_HOME to the home that owns the session being resumed, and never consults the current selection. That is correct for a cold restore, where the pane should come back as the account that recorded the conversation. An account-switch restart takes the same path, so it relaunches under the account the user just left.

Deterministic repro (two managed accounts, A selected): run Codex in a terminal, exchange one message so a rollout exists, switch the active account to B, press Restart once. The pane comes back on A — <userData>/codex-pane-accounts.json records the account each spawn actually launched under, so this is observable without guessing. Pressing Restart a second time usually works, which makes this read as flaky, but that is a timing artifact: the first respawn's shell has not yet registered a session for the pin to find, so the second press falls through to the current selection. Wait long enough and the second press fails too.

#12146 covers a different path — it executes restarts for unmounted panes; this PR is about a mounted pane resolving the wrong home.

Linked Issue

Addresses the account-switch restart bug in #12098 (the automatic-rotation feature request in that issue is out of scope here, so no closing keyword).

Visual Proof

The visible change is the card copy and which account the relaunched pane lands on. Before/after copy:

Before: "Restart this session to use {account}. It stays on the previous account until you do."

After (managed account): "Restarting this terminal switches it to {account}. Your work carries over, and usage is counted against the account you switch to."

After (system default): "Restarting this terminal switches it to {account}, and this conversation will not come along — the terminal starts a new one. To carry a conversation across a switch, add a separate Codex account and switch to that instead."

The behavioral proof is the launch-account registry: after one Restart press, the pane's codex-pane-accounts.json entry names the newly selected account, where it previously kept naming the old one. My local screenshots carry personal account emails; happy to attach a redacted screen recording if useful.

Testing

Verified live on macOS (codex-cli 0.147): three consecutive account switches each moved the pane on one press, the conversation continued across all three in a single rollout (the model answered a fact memorised before the first switch; 17,152 of 18,083 input tokens served from cache), and the goal row landed in the new account's database with tokens_used at 0.

Automated:

  • codex-account-switch-resume-repin.test.ts — resume preparation follows the current selection, only for a declared account-switch restart.

  • codex-thread-goal-transfer.test.ts — which goal fields travel vs. stay, status-name remap, missing-goal and rejected-set paths.

  • codex-account-restart-startup.test.ts — startup command: codex resume <id> vs. fresh codex, system-default fallback.

  • pty-transport-connect-spawn.test.ts — flag lifecycle across failed spawn / reattach / rejected admission / later spawns.

  • codex-restart-chip.test.tsx, codex-session-restart.test.ts, codex-account-session-bridge.test.ts — card copy per target account, restart contract, rollout hardlink into the selected home.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Implemented with Claude Code (Claude Fable 5). Live verification on macOS was done by hand.

Review

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

  • Windows path handling goes through normalizeRuntimePathForComparison and getSpawnArgsForWindows; no new platform-specific behavior outside existing guards.
  • The new pty:spawn field is optional, so older renderers simply never send it (same-machine IPC, both sides ship together anyway).
  • Goal transfer only touches the two managed homes involved in the switch, over the existing app-server session.

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)

🤖 Generated with Claude Code

@tonite31
tonite31 requested a review from brennanb2025 as a code owner August 16, 2026 10:45
@coderabbitai

coderabbitai Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 27d065cd-1c10-46ec-8e2f-0f322be6828a

📥 Commits

Reviewing files that changed from the base of the PR and between 604169f and 5f3ae17.

📒 Files selected for processing (32)
  • src/main/codex/codex-account-session-bridge.test.ts
  • src/main/codex/codex-account-session-bridge.ts
  • src/main/codex/codex-account-switch-resume-repin.test.ts
  • src/main/codex/codex-account-switch-resume-repin.ts
  • src/main/codex/codex-thread-goal-transfer.test.ts
  • src/main/codex/codex-thread-goal-transfer.ts
  • src/main/index.ts
  • src/main/ipc/pty.ts
  • src/main/runtime/orca-runtime.ts
  • src/preload/api/pty-api.ts
  • src/preload/index.ts
  • src/renderer/src/components/CodexRestartChip.tsx
  • src/renderer/src/components/codex-restart-chip.test.tsx
  • src/renderer/src/components/settings/AccountsPane.tsx
  • src/renderer/src/components/terminal-pane/TerminalPane.tsx
  • src/renderer/src/components/terminal-pane/codex-detached-pane-restart.ts
  • src/renderer/src/components/terminal-pane/pty-connection-types.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-transport-connect-spawn.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-lifecycle.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/lib/codex-account-restart-startup.test.ts
  • src/renderer/src/lib/codex-account-restart-startup.ts
  • src/renderer/src/lib/codex-session-restart.test.ts
  • src/renderer/src/lib/codex-session-restart.ts
  • src/renderer/src/store/slices/terminals.ts
🚧 Files skipped from review as they are similar to previous changes (32)
  • src/renderer/src/components/terminal-pane/pty-connection-types.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts
  • src/preload/api/pty-api.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/codex/codex-account-switch-resume-repin.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • src/renderer/src/lib/codex-session-restart.ts
  • src/main/codex/codex-account-session-bridge.test.ts
  • src/preload/index.ts
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/components/terminal-pane/codex-detached-pane-restart.ts
  • src/renderer/src/components/terminal-pane/pty-transport-connect-spawn.test.ts
  • src/renderer/src/lib/codex-session-restart.test.ts
  • src/renderer/src/components/settings/AccountsPane.tsx
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/components/codex-restart-chip.test.tsx
  • src/main/index.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/store/slices/terminals.ts
  • src/main/codex/codex-thread-goal-transfer.test.ts
  • src/main/ipc/pty.ts
  • src/renderer/src/components/terminal-pane/TerminalPane.tsx
  • src/renderer/src/components/CodexRestartChip.tsx
  • src/main/codex/codex-account-session-bridge.ts
  • src/renderer/src/lib/codex-account-restart-startup.test.ts
  • src/renderer/src/lib/codex-account-restart-startup.ts
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/ja.json
  • src/main/codex/codex-account-switch-resume-repin.test.ts
  • src/renderer/src/i18n/locales/zh.json
  • src/main/codex/codex-thread-goal-transfer.ts

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


📝 Walkthrough

Walkthrough

Codex account-switch restarts now repin rollout transcripts into the selected account home and transfer supported thread goals between homes. Resume preparation returns a fresh-session result when repinning fails. Renderer startup builds pane-specific resume commands and propagates account-switch metadata through terminal state, PTY transport, preload, and IPC. Account prompts and localized restart notices now distinguish preserved work from conversations that start fresh. Tests cover filesystem linking, resume outcomes, goal transfer, startup planning, transport retries, and UI messaging.

Merge Risk: 🟡 Moderate · up to 5f3ae

The PR changes account-switch restarts to resume conversations and transfer goals, but custom-shell terminals may restart with an incorrectly constructed resume command, while invalid budget values may cause the transferred objective to be lost. These bounded correctness issues should be fixed or explicitly accepted before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.17% 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
Title check ✅ Passed The title clearly and concisely describes the primary change: restarting Codex under the newly selected account.
Description check ✅ Passed The description is detailed and covers the change, rationale, linked issue, testing, review considerations, and checklist; visual proof is described but not attached.
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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/renderer/src/components/terminal-pane/TerminalPane.tsx (1)

1570-1580: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Pass terminalTab.shellOverride to the restart startup builder.

When a resumable Codex pane uses a custom shell, this call generates resume arguments for the default shell. The command can then fail to parse in the tab's actual shell. Pass terminalTab?.shellOverride and add it to the handleRestartCodexPane dependency array.

🧹 Nitpick comments (4)
src/main/codex/codex-thread-goal-transfer.ts (1)

86-91: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Apply the same defensive filtering to tokenBudget that status already receives.

Lines 101-103 drop an unrecognized status so a rejected field cannot fail the whole transfer and lose the objective. tokenBudget has no equivalent guard. A negative or fractional value passes Number.isFinite and reaches thread/goal/set, which can reject the request and return 'failed'.

♻️ Proposed guard
-  const tokenBudget = record.tokenBudget ?? record.token_budget
+  const tokenBudget = record.tokenBudget ?? record.token_budget
+  const usableTokenBudget =
+    typeof tokenBudget === 'number' && Number.isInteger(tokenBudget) && tokenBudget > 0
   return {
     objective,
     ...(status ? { status } : {}),
-    ...(typeof tokenBudget === 'number' && Number.isFinite(tokenBudget) ? { tokenBudget } : {})
+    ...(usableTokenBudget ? { tokenBudget } : {})
   }
src/renderer/src/lib/codex-account-restart-startup.ts (1)

74-77: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename the shadowing callback parameter.

The find callback parameter on Line 75 is named entry, which shadows the agent-status entry from Line 50. The current logic is correct, but a later edit inside the callback could read the wrong entry.

♻️ Proposed rename
-  const repo = worktree ? state.repos.find((entry) => entry.id === worktree.repoId) : null
+  const repo = worktree ? state.repos.find((repoEntry) => repoEntry.id === worktree.repoId) : null
src/renderer/src/lib/codex-account-restart-startup.test.ts (1)

88-97: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a case for the WSL bare relaunch.

The builder returns the bare startup for a resolved WSL runtime. That branch carries the strongest failure mode in the module: a resume argv against a home that does not list the rollout. The suite does not cover it.

Add a test that seeds a Codex session plus a resolved WSL project runtime and asserts command === 'codex' and resumeProviderSession === undefined.

src/renderer/src/components/terminal-pane/codex-detached-pane-restart.ts (1)

230-240: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Read all startup fields from restartStartup.

Line 230 takes command from restartStartup, but Lines 231-233 take startupCommandDelivery, launchAgent, and codexAccountSwitchRestart from CODEX_ACCOUNT_RESTART_STARTUP. The values match today because the builder spreads the const. A later builder change that varies delivery or agent would silently not reach this spawn.

♻️ Proposed change
     command: restartStartup.command,
-    startupCommandDelivery: CODEX_ACCOUNT_RESTART_STARTUP.startupCommandDelivery,
-    launchAgent: CODEX_ACCOUNT_RESTART_STARTUP.launchAgent,
-    codexAccountSwitchRestart: CODEX_ACCOUNT_RESTART_STARTUP.codexAccountSwitchRestart,
+    startupCommandDelivery: restartStartup.startupCommandDelivery,
+    launchAgent: restartStartup.launchAgent,
+    codexAccountSwitchRestart: restartStartup.codexAccountSwitchRestart,

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 686e155c-3f03-42ac-bcdb-bca4ecd0061b

📥 Commits

Reviewing files that changed from the base of the PR and between e4e54a1 and 09e4b472a2321782029d2bd336ecf98090f678cb.

📒 Files selected for processing (32)
  • src/main/codex/codex-account-session-bridge.test.ts
  • src/main/codex/codex-account-session-bridge.ts
  • src/main/codex/codex-account-switch-resume-repin.test.ts
  • src/main/codex/codex-account-switch-resume-repin.ts
  • src/main/codex/codex-thread-goal-transfer.test.ts
  • src/main/codex/codex-thread-goal-transfer.ts
  • src/main/index.ts
  • src/main/ipc/pty.ts
  • src/main/runtime/orca-runtime.ts
  • src/preload/api/pty-api.ts
  • src/preload/index.ts
  • src/renderer/src/components/CodexRestartChip.tsx
  • src/renderer/src/components/codex-restart-chip.test.tsx
  • src/renderer/src/components/settings/AccountsPane.tsx
  • src/renderer/src/components/terminal-pane/TerminalPane.tsx
  • src/renderer/src/components/terminal-pane/codex-detached-pane-restart.ts
  • src/renderer/src/components/terminal-pane/pty-connection-types.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-transport-connect-spawn.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-lifecycle.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/lib/codex-account-restart-startup.test.ts
  • src/renderer/src/lib/codex-account-restart-startup.ts
  • src/renderer/src/lib/codex-session-restart.test.ts
  • src/renderer/src/lib/codex-session-restart.ts
  • src/renderer/src/store/slices/terminals.ts

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

Comment thread src/renderer/src/i18n/locales/en.json Resolved
tonite31 and others added 3 commits August 18, 2026 11:13
pty:spawn pinned the launch CODEX_HOME to the home owning the session
being resumed and never consulted the current selection — right for a
cold restore, wrong for an account-switch restart, which shares the
path. The pane relaunched under the account the user just left, and a
second press only appeared to fix it because the first respawn had not
yet registered a session for the pin to find.

The restart now declares itself (codexAccountSwitchRestart), resume
preparation follows the current selection, the rollout is hardlinked
into the selected account's home ahead of the background sweep, and the
relaunch runs `codex resume <id>` so the conversation continues. The
/goal objective, status and budget travel via thread/goal/get /
thread/goal/set; tokens_used and the limit statuses stay behind.
Switching to the system default cannot carry the conversation (Orca
never writes into ~/.codex), so it switches, starts fresh, and the card
says so before the press.

Co-Authored-By: Claude Fable 5 <[email protected]>
Review follow-up (PR stablyai#14877):
- pass the tab's shellOverride to buildCodexAccountRestartStartup on the
  mounted restart path, matching the detached driver
- skip the symlink-replacement test on Windows, where symlink creation
  needs elevation or Developer Mode
- cover the WSL bare-relaunch branch in the startup builder's suite

Co-Authored-By: Claude Fable 5 <[email protected]>
"usage is counted against the account you switch to" reads as existing
usage counters and limit statuses moving with the switch. Say "new usage"
in the restart notice across all five locales; counters stay put.

Co-Authored-By: Claude Fable 5 <[email protected]>
@tonite31
tonite31 force-pushed the fix/codex-account-switch-restart branch from c3bbf84 to 5f3ae17 Compare August 18, 2026 04:15
@coderabbitai

coderabbitai Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@nwparker

nwparker commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

#25485 adapts this PR's explicit conversation resume and selected-account handling to the current terminal modules, together with #24350's atomic pane replacement. Credit to @tonite31 is in the PR body and commit coauthor trailers (including the original AI coauthor).

This is a partial integration: the goal-state transfer and settings/copy changes here are not included, so #25485 does not claim to supersede this entire PR. Real Codex A→B→A restarts, conversation continuity, a completed prompt under the selected account, and Ctrl+C were verified in an isolated macOS Electron instance.

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

Copy link
Copy Markdown
Contributor

Thanks @tonite31 for the work here. Closing as superseded: your explicit-resume and selected-account handling was adapted into #25485, with credit in the PR. Appreciate the contribution, and feel free to open a fresh PR against current main if you see anything still missing.

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

4 participants