Skip to content

fix(codex): prevent transient managed-auth onboarding - #11731

Merged
brennanb2025 merged 2 commits into
stablyai:mainfrom
nwparker:nwparker/codex-login-screen
Jul 31, 2026
Merged

brennanb2025 merged 2 commits into
stablyai:mainfrom
nwparker:nwparker/codex-login-screen

Conversation

@nwparker

@nwparker nwparker commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Prevent a fresh Orca-launched Codex session from latching unauthenticated state while a selected managed account's auth.json is 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:

  • fresh host-local Codex launches wait up to 1.5 seconds for a known incomplete credential to recover;
  • a credential that is valid on the first read stays on a synchronous, timer-free path;
  • if auth remains unavailable, Orca clears only the still-selected host account and falls back through the existing system-default launch path;
  • selection changes during the wait are re-resolved and fenced, so a recovered old account cannot launch after the user selects another account;
  • resumed/pinned Codex sessions never switch identities; unavailable origin auth rejects the resume;
  • bare shells, other agents, SSH, WSL, daemon reattaches, system-default homes, and unmanaged homes bypass this gate;
  • hidden Codex quota probes still stop immediately if Codex renders 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.json is 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-contained CODEX_HOME directories and treated a missing auth.json as 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 / chatgptAuthTokens token records;
  • apikey;
  • personalAccessToken;
  • bedrockApiKey;
  • object-backed agentIdentity records 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

Lane/state Result
Valid managed auth on first read Synchronous return; no Promise tick or polling timer
Transient missing/partial auth Bounded wait, then spawn with the still-selected managed home
Permanently unavailable auth Clear only the still-selected host account and use normal fallback
Selection changes during wait Re-resolve/fence; never launch the stale account
Resume-pinned Codex session Keep original account; reject rather than switch identity
Bare shell or another agent No Codex readiness read or wait
Codex daemon reattach No current-account gate
SSH / WSL Existing remote and distro-local behavior unchanged
Folder workspace / Git worktree Shared PTY boundary; no worktree-only assumption
Hidden quota PTY shows onboarding Stop immediately; never send /status

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

  • focused Vitest suite: 6 files, 549 tests passed;
  • 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 --check on changed files: passed;
  • git diff --check: passed;
  • pre-commit oxlint, react-doctor, and formatting hooks: 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.

Fresh Codex launch opens the authenticated composer

Deliberate boundary

This guards Orca's fresh Codex launch action. If a user opens a bare shell and manually types codex much later, Orca cannot intercept that future shell command at PTY-spawn time; that path remains outside this launch-scoped fix.

@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR addresses a race condition where a transient auth.json replacement window during Codex startup could cause a managed account to silently launch as the system default (showing onboarding) rather than waiting for the credential file to become complete.

  • Identity preservation: CodexRuntimeHomeService now distinguishes between a trusted home with temporarily unavailable auth (preserves selection) and an untrusted/invalid home (clears selection), replacing the previous unconditional clear-on-absence behavior.
  • Pre-spawn readiness gate: A new waitForManagedCodexAuthReady utility retries up to 1.5 s in 25 ms increments before any local PTY is created; the gate is applied to all host-local Codex spawn lanes (renderer→daemon, renderer→local-fallback, runtime-controller).
  • Early onboarding detection: The hidden quota PTY now kills itself and resolves as an auth error when it sees Sign in with ChatGPT in output, without issuing /status.

Confidence Score: 5/5

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

Important Files Changed

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)
Loading

Reviews (2): Last reviewed commit: "fix(codex): recover unavailable managed ..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.18% 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 summarizes the primary change: preventing transient managed Codex authentication onboarding.
Description check ✅ Passed The description clearly covers the change, testing, screenshots, risks, platform behavior, and scope, although some template headings are implicit.

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.

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 win

Gate Codex auth readiness on Codex use, not managed CODEX_HOME. Both spawn paths call waitForManagedCodexAuthReady for every host PTY when selectedCodexHomePath points at a managed account, including plain shell spawns with no launchAgent. The waitForManagedCodexAuthReady helper returns only when runtime === '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 with args.launchAgent === 'codex'.

🧹 Nitpick comments (1)
src/main/codex-accounts/managed-codex-auth-readiness.ts (1)

44-56: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Consider async file reads in the polling loop.

hasStoredCodexCredential uses readFileSync inside waitForStoredCodexCredential, 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.readFile in the poll loop so the event loop stays free between retries. The initial check in waitForManagedCodexAuthReady can also become async without changing its exported contract, since it already returns a Promise<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

📥 Commits

Reviewing files that changed from the base of the PR and between f23b330 and a77f927.

📒 Files selected for processing (12)
  • src/main/codex-accounts/managed-codex-auth-readiness.test.ts
  • src/main/codex-accounts/managed-codex-auth-readiness.ts
  • src/main/codex-accounts/runtime-home-service-per-account-migration.test.ts
  • src/main/codex-accounts/runtime-home-service.test.ts
  • src/main/codex-accounts/runtime-home-service.ts
  • src/main/index.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/rate-limits/codex-fetcher-auth-errors.test.ts
  • src/main/rate-limits/codex-fetcher.ts
  • src/shared/codex-auth-errors.test.ts
  • src/shared/codex-auth-errors.ts

@brennanb2025

Copy link
Copy Markdown
Contributor

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 codex invocation later inside an already-open shell is outside that gate, so if that exact reproduction persists it would be follow-up evidence rather than evidence against this fix.

@brennanb2025

Copy link
Copy Markdown
Contributor

Final review/validation update for 1017c2589630e4aa2d55c6f727df0d0a2572585e:

  • Same-model review loop continued through a fresh CLEAN verdict. Findings fixed along the way: real Codex credential schemas, permanent-auth terminal lockout, over-broad terminal gating, account-selection races, the valid-auth Promise tick, and partial Agent Identity records.
  • Focused validation passed: 6 files / 549 tests, full node/CLI/web typecheck, full lint and reliability gates, changed-file format check, diff check, and pre-commit hooks.
  • Healthy managed auth remains synchronous and timer-free; non-Codex spawns, SSH, WSL, and reattaches bypass the readiness gate.
  • Electron validation from the exact source worktree passed: New tab → Codex opened directly at the authenticated composer under the disposable managed CODEX_HOME, not onboarding.

Fresh Codex launch opens the authenticated composer

Deliberate boundary: manually typing codex much later in an already-open bare shell remains outside this spawn-time launch gate.

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

🧹 Nitpick comments (1)
src/main/ipc/pty.ts (1)

5102-5141: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider 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 (baseEnv versus env) and the reattach predicate (args.sessionId === undefined versus callerRequestedSessionId === undefined). The resolveCurrent and resolveAfterUnavailable closures 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

📥 Commits

Reviewing files that changed from the base of the PR and between a77f927 and 1017c25.

📒 Files selected for processing (7)
  • src/main/codex-accounts/managed-codex-auth-readiness.test.ts
  • src/main/codex-accounts/managed-codex-auth-readiness.ts
  • src/main/codex-accounts/runtime-home-service.test.ts
  • src/main/codex-accounts/runtime-home-service.ts
  • src/main/index.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts

@brennanb2025
brennanb2025 merged commit 9f30a78 into stablyai:main Jul 31, 2026
44 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(codex): gate terminal spawn on managed auth readiness

* fix(codex): recover unavailable managed auth safely

---------

Co-authored-by: Brennan Benson <[email protected]>
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.

2 participants