Repository navigation
fix(codex): prevent transient managed-auth onboarding - #11731
Conversation
Greptile SummaryThis PR addresses a race condition where a transient
Confidence Score: 5/5Safe to merge — the change is fail-closed (no spawn on unrecoverable auth), all three local Codex spawn lanes are covered, and bypass conditions for WSL, SSH, system-default, and non-managed homes are explicit and tested. The core race is addressed by gating every host-local Codex PTY creation on a structurally validated credential, with a bounded retry window. Identity preservation during transient auth.json replacement is correct: the trusted-home path returns the managed home without clearing selection, while the untrusted path still clears it. The two-iteration cap in continueCodexHomeAfterManagedAuthWait prevents infinite loops even under rapid account switching. The final isCodexHomeAuthReadyForLaunch guard ensures nothing unvalidated is returned after the retry loop exits. Test coverage is thorough across sync-ready, missing, partial, timeout, fallback-to-system-default, resume-gate, cascading-unavailable, and all-auth-mode scenarios. Files Needing Attention: No files require special attention. The most complex logic is in continueCodexHomeAfterManagedAuthWait (pty.ts) and the credential shape validation in managed-codex-auth-readiness.ts, both of which are well-exercised by the new test suite.
|
| Filename | Overview |
|---|---|
| src/main/codex-accounts/managed-codex-auth-readiness.ts | New file: credential readiness gate with 1.5 s / 25 ms retry logic and per-auth-mode structural validation; all bypass conditions (WSL, SSH, null path, non-managed home) are correct. |
| src/main/ipc/pty.ts | Adds resolveCodexHomeAfterManagedAuthReadiness and wires it into all three host-local Codex spawn lanes; codexHomePathOverride now always forwards the resolved home to the local provider (was only set on resume), and pinnedByResume is correctly narrowed to the actual resume-home match. |
| src/main/codex-accounts/runtime-home-service.ts | prepareSelfContainedManagedHomeForLaunch and syncSelfContainedManagedSelection no longer clear the selection on a missing auth.json; clearing only happens when the home is untrusted or when waitForManagedCodexAuthReady confirms the credential has not recovered. |
| src/main/rate-limits/codex-fetcher.ts | fetchViaPty now detects Sign in with ChatGPT in PTY output, kills the PTY immediately, and resolves as an auth error without writing /status. |
| src/shared/codex-auth-errors.ts | Adds /sign in with chatgpt/i to CODEX_AUTH_ERROR_PATTERNS so the fetcher and shared auth-error helpers classify the onboarding screen as an auth error. |
| src/main/index.ts | Threads unavailableManagedHomePath through prepareCodexRuntimeHomeForLaunch and imports CodexHomeLaunchContext type from pty.ts; changes type import of TuiAgent. |
Sequence Diagram
sequenceDiagram
participant R as Renderer (pty:spawn)
participant P as pty.ts handler
participant W as waitForManagedCodexAuthReady
participant H as runtime-home-service
participant FS as auth.json (filesystem)
participant D as Daemon / LocalPtyProvider
R->>P: "pty:spawn { launchAgent: 'codex' }"
P->>H: prepareForCodexLaunch()
P->>W: resolveCodexHomeAfterManagedAuthReadiness()
W->>FS: hasStoredCodexCredential(auth.json)
alt credential present (sync)
FS-->>W: valid JSON
W-->>P: selectedCodexHomePath (no wait)
else credential missing / partial
loop retry every 25 ms, up to 1500 ms
W->>FS: hasStoredCodexCredential()
FS-->>W: missing / invalid
end
alt recovered within 1500 ms
FS-->>W: valid JSON
W-->>P: selectedCodexHomePath
else still missing
W-->>P: resolveAfterUnavailable()
Note over H: clears managed selection, returns null
W-->>P: null OR throws if resume required
end
end
P->>D: spawn(env CODEX_HOME, ORCA_CODEX_HOME)
Reviews (2): Last reviewed commit: "fix(codex): recover unavailable managed ..." | Re-trigger Greptile
📝 WalkthroughWalkthroughThis PR adds managed Codex credential readiness checks with polling and credential-format validation. Trusted managed homes remain selected while credentials are replaced, while explicitly unavailable homes can clear selection. Local PTY launches resolve and forward the selected Codex home, enforce readiness for fresh and resumed sessions, and preserve resume-home attribution. Rate-limit probes now stop on Codex authentication errors, including “Sign in with ChatGPT.” 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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 |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/ipc/pty.ts (1)
3779-3797: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winGate Codex auth readiness on Codex use, not managed
CODEX_HOME. Both spawn paths callwaitForManagedCodexAuthReadyfor every host PTY whenselectedCodexHomePathpoints at a managed account, including plain shell spawns with nolaunchAgent. ThewaitForManagedCodexAuthReadyhelper returns only whenruntime === 'host', the path is managed, and credentials are present; otherwise it waits 1.5 seconds and throws. Apply the same scope decision at both wait sites, e.g. gate it withargs.launchAgent === 'codex'.
🧹 Nitpick comments (1)
src/main/codex-accounts/managed-codex-auth-readiness.ts (1)
44-56: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winConsider async file reads in the polling loop.
hasStoredCodexCredentialusesreadFileSyncinsidewaitForStoredCodexCredential, called up to 60 times over 1.5 seconds. Electron's main process is single-threaded. Each synchronous read blocks all other main-process work, including unrelated IPC handling. On a slow or network-backed filesystem, this can add noticeable jank across the whole application during the retry window.Use
fs.promises.readFilein the poll loop so the event loop stays free between retries. The initial check inwaitForManagedCodexAuthReadycan also become async without changing its exported contract, since it already returns aPromise<void> | undefined.Also applies to: 72-88
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 81c34af4-efaa-4c6e-9be3-c4b78462bd02
📒 Files selected for processing (12)
src/main/codex-accounts/managed-codex-auth-readiness.test.tssrc/main/codex-accounts/managed-codex-auth-readiness.tssrc/main/codex-accounts/runtime-home-service-per-account-migration.test.tssrc/main/codex-accounts/runtime-home-service.test.tssrc/main/codex-accounts/runtime-home-service.tssrc/main/index.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/main/rate-limits/codex-fetcher-auth-errors.test.tssrc/main/rate-limits/codex-fetcher.tssrc/shared/codex-auth-errors.test.tssrc/shared/codex-auth-errors.ts
|
Compared this with #11720. I think this is the right fix for the transient-auth failure reproduced here: a fresh Codex process can latch unauthenticated state if the selected managed auth is missing or partial during startup, and preserving the selected identity plus gating local process creation fails closed at the right boundary. The deterministic app-server reproduction is materially stronger evidence for the reported new-process/onboarding/immediate-retry symptom. The relationship between the PRs is:
The visible symptom overlaps, but the mechanisms are separate. I think this PR should land independently/first; we can rebase #11720 on it and revalidate the retained-PTY reproduction rather than treating #11720 as a substitute for this fix. One scope boundary to keep in mind: the readiness gate protects new-PTY/automatic-launch paths. A manual |
|
Final review/validation update for
Deliberate boundary: manually typing |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/ipc/pty.ts (1)
5102-5141: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider extracting the duplicated readiness-resolution wiring.
This block repeats the controller-path block at Lines 3906-3934. The two copies differ only in the launch env (
baseEnvversusenv) and the reattach predicate (args.sessionId === undefinedversuscallerRequestedSessionId === undefined). TheresolveCurrentandresolveAfterUnavailableclosures are otherwise identical.Both call sites live inside
registerPtyHandlers, so a local factory can build the argument object once. This keeps the gate from drifting if a later change updates only one spawn lane.♻️ Sketch of the shared factory
// Inside registerPtyHandlers, near prepareCodexResumeHome. const codexHomeResolutionArgs = (opts: { selectedCodexHomePath: string | null launchEnv: Record<string, string> | undefined target: CodexAccountSelectionTarget cwd: string | undefined requiredCodexHomePath?: string }) => ({ selectedCodexHomePath: opts.selectedCodexHomePath, getSettings: () => getSettings?.(), ...(opts.requiredCodexHomePath ? { requiredCodexHomePath: opts.requiredCodexHomePath } : {}), target: opts.target, resolveCurrent: () => getCompatibleSelectedCodexHomePath( opts.target, getSelectedCodexHomePath?.(opts.target, opts.launchEnv, { workspacePath: opts.cwd, launchAgent: 'codex' }) ?? null ), resolveAfterUnavailable: (unavailableManagedHomePath: string) => getCompatibleSelectedCodexHomePath( opts.target, getSelectedCodexHomePath?.(opts.target, opts.launchEnv, { workspacePath: opts.cwd, launchAgent: 'codex', unavailableManagedHomePath }) ?? null ) })
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 115f73dd-c17c-4538-a1c9-799647e7740f
📒 Files selected for processing (7)
src/main/codex-accounts/managed-codex-auth-readiness.test.tssrc/main/codex-accounts/managed-codex-auth-readiness.tssrc/main/codex-accounts/runtime-home-service.test.tssrc/main/codex-accounts/runtime-home-service.tssrc/main/index.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.ts
* fix(codex): gate terminal spawn on managed auth readiness * fix(codex): recover unavailable managed auth safely --------- Co-authored-by: Brennan Benson <[email protected]>

Summary
Prevent a fresh Orca-launched Codex session from latching unauthenticated state while a selected managed account's
auth.jsonis temporarily missing or incomplete.This revision keeps the fix at the Codex launch boundary and avoids turning a credential problem into a terminal-wide outage:
Sign in with ChatGPT.User symptom and evidence
With an authenticated managed account selected, a newly opened Codex tab could intermittently show onboarding, while an immediate retry opened the authenticated composer.
A deterministic real-Codex reproduction established the latch behavior: start Codex while a valid copied
auth.jsonis temporarily absent, restore the file before reading the account, and that process remains unauthenticated while a new process against the restored home is authenticated. This proves the startup-latch failure mode. The exact production writer and timing for each historical occurrence were not captured, so this PR does not claim more specific causality.The Orca regression surface dates to #9501 (
e58de71f5e, 2026-07-20), which made managed account homes live self-containedCODEX_HOMEdirectories and treated a missingauth.jsonas a reason to abandon the selected account at launch. #9451 is similar by symptom but is not treated as a confirmed duplicate.Implementation
Credential readiness
Known complete Codex credential forms are accepted:
chatgpt/chatgptAuthTokenstoken records;apikey;personalAccessToken;bedrockApiKey;agentIdentityrecords with the required runtime ID and private key.Known partial records retry. Genuinely unknown future modes or parseable object shapes fail open so a new Codex schema cannot strand terminal creation. Missing, malformed, or unreadable files use the bounded retry/fallback path.
Identity and availability safety
The readiness decision is scoped to fresh Codex launches. After the wait, Orca re-checks the selected account before it creates a PTY. A permanent credential failure restores the previous safe system-default behavior instead of rejecting every terminal indefinitely. Resume-pinned sessions remain pinned and reject if their original managed credential is unavailable.
The same rules are enforced for renderer-to-daemon, renderer local fallback, and runtime-controller Codex launches. Trusted managed-home ownership checks remain in place.
No-regression and performance evidence
/statusThe healthy path is covered by an explicit synchronous-return test, and the PTY suite verifies that non-Codex launches and reattaches do not gain the readiness wait.
Verification
Final candidate
1017c2589630e4aa2d55c6f727df0d0a2572585e:pnpm typecheck: node, CLI, and web passed;pnpm lint: passed, including 56 reliability gates, max-lines ratchet, bundled-skill checks, and localization checks;pnpm exec oxfmt --checkon changed files: passed;git diff --check: passed;A same-model review loop continued until a fresh reviewer returned CLEAN. Earlier completed iterations found and drove fixes for real Codex credential shapes, permanent-auth terminal lockout, over-broad terminal gating, selection races, the healthy-path Promise tick, and partial Agent Identity records. The final review found no remaining correctness, availability, identity, scope, platform, or performance issue.
Electron validation
An isolated source build was launched from this exact worktree with a disposable user-data profile. Settings showed the disposable managed Codex account active; New tab → Codex opened Codex 0.146.0 directly at the authenticated composer, not onboarding. Process inspection confirmed that the launched Codex process received the disposable managed account's
CODEX_HOME; no credential values were displayed or captured.Deliberate boundary
This guards Orca's fresh Codex launch action. If a user opens a bare shell and manually types
codexmuch later, Orca cannot intercept that future shell command at PTY-spawn time; that path remains outside this launch-scoped fix.