Repository navigation
fix(codex): make quota probes credential-safe - #12145
Conversation
Codex OAuth uses rotating refresh tokens, and Orca's quota probes spawned real codex app-server processes inside live credential homes, hard-killed them at a 10s deadline (cold starts run 10-25s), re-probed every inactive account on each switch, and deselected accounts on torn auth.json reads. - arm the RPC read deadline only after initialize responds (30s/40s boot budget), and terminate probes via stdin EOF + SIGTERM with a bounded drain before any hard kill; resolve only once the child exits - serialize Orca-spawned codex processes per credential home (probe vs probe, probe vs commit-message/PR-fields/branch-name/model-discovery) - keep the inactive-probe debounce across account switches and stagger inactive probes; the active account still refreshes immediately - grade credential reads (present/missing/unreadable/no-credential) and require absence to outlive a grace window before deselecting
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe changes classify Codex credential files and apply a grace period to transient absence. Runtime account selection and synchronization now distinguish transient from durable absence. Codex home operations use normalized per-home locks. Local generation supports queued cancellation. Rate-limit probes use separate startup and request deadlines, graceful termination, and home locking. Inactive account probes retain debounce state and run with abort-aware two-second spacing. Tests cover these credential, locking, shutdown, timeout, and scheduling behaviors. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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.
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 (2)
src/main/codex-accounts/runtime-home-service.ts (2)
740-771: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winFix the absence check to cover
no-credentialand to act ondurableforunreadable.This block has two gaps compared to the correct handling in
prepareSelfContainedManagedHomeForLaunch(lines 309-321) and the design intent stated at lines 90-92 ofmanaged-codex-auth-readiness.ts.First, the
ifat line 742 only matches'missing'or'unreadable'. WhenauthAbsence.stateis'no-credential'(a settled logout — valid JSON with no credential fields), execution falls through this check entirely. The code then readsactiveAuthPathagain at line 792 and writes that credential-less content into the runtime home instead of deselecting the account. The design comment onreadStoredCodexCredentialStatestates a settled logout must not be treated the same as an in-flight rotation, but this path does exactly that by ignoring it.Second, at line 743,
authAbsence.state === 'unreadable'always short-circuits to "keep selection," regardless ofauthAbsence.durable. Ifauth.jsonstays unreadable permanently (a persistent permission error, or a file that never heals), the account is never deselected and the system default is never restored. Thedurableflag computed for'unreadable'inCodexCredentialAbsenceGrace.assess()becomes unreachable dead logic in this call site.🐛 Proposed fix
const activeAuthPath = join(activeAccount.managedHomePath, 'auth.json') const authAbsence = this.credentialAbsenceGrace.assess(activeAuthPath) - if (authAbsence.state === 'missing' || authAbsence.state === 'unreadable') { - if (authAbsence.state === 'unreadable' || !authAbsence.durable) { + if (authAbsence.state !== 'present') { + if (!authAbsence.durable) { // Why: mid-rotation reads look missing/unreadable for a moment; skip // this sync without deselecting and let a settled read decide later. console.warn( '[codex-runtime-home] Active managed account auth.json unavailable, keeping selection through grace window' ) return }Once fixed, add regression tests mirroring the ones added for
prepareForCodexLaunch(missing/unreadable → durable deselect) but exercised throughsyncForCurrentSelection's shared-home path, plus a case for a settledno-credentialfile.
1028-1048: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winApply absence-grace handling to WSL active
auth.jsonreads.
syncWslRuntimeForCurrentSelectionstill uses a plainexistsSync(activeAuthPath)check before clearing the active WSL selection, so a rotation-in-flight read can deselect the WSL managed account. UsecredentialAbsenceGrace.assess(activeAuthPath)and only restore the system default when the absence is durable.
🧹 Nitpick comments (1)
src/main/codex-accounts/codex-credential-absence-grace.test.ts (1)
1-65: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for the missing-parent-directory branch.
The three tests cover the torn-write, heal, and settled-empty-JSON cases. No test covers the branch where
state === 'missing'and the parent directory itself does not exist (codex-credential-absence-grace.tslines 35-38). This branch is the one place the class treats a missing file as durable without waiting for the grace window, so it is worth locking in with a test.🧪 Proposed additional test
it('reports settled credential-free JSON as durable immediately', () => { const grace = new CodexCredentialAbsenceGrace() writeFileSync(authPath, '{}', 'utf-8') expect(grace.assess(authPath, 1_000)).toEqual({ state: 'no-credential', durable: true }) }) + + it('treats a gone home directory as durable immediately, bypassing the grace window', () => { + const grace = new CodexCredentialAbsenceGrace() + rmSync(dir, { recursive: true, force: true }) + expect(grace.assess(authPath, 1_000)).toEqual({ state: 'missing', durable: true }) + }) })
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: b1f12e2e-6833-4f37-b686-601b72c36160
📒 Files selected for processing (17)
src/main/codex-accounts/codex-credential-absence-grace.test.tssrc/main/codex-accounts/codex-credential-absence-grace.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/codex-cli/codex-home-process-lock.test.tssrc/main/codex-cli/codex-home-process-lock.tssrc/main/rate-limits/codex-fetcher-auth-errors.test.tssrc/main/rate-limits/codex-fetcher-probe-shutdown.test.tssrc/main/rate-limits/codex-fetcher-session-supplement.test.tssrc/main/rate-limits/codex-fetcher.test.tssrc/main/rate-limits/codex-fetcher.tssrc/main/rate-limits/codex-probe-termination.test.tssrc/main/rate-limits/codex-probe-termination.tssrc/main/rate-limits/service.test.tssrc/main/rate-limits/service.tssrc/main/text-generation/commit-message-text-generation.ts
Greptile SummaryThis PR hardens Codex OAuth credential safety across four axes: (1) graceful probe shutdown with a two-phase
Confidence Score: 5/5Safe to merge — all credential-safe termination paths are consistent, the per-home FIFO lock self-cleans, and the grace-window logic correctly distinguishes mid-rotation reads from durable logouts. The prior review concern about Files Needing Attention: No files require special attention. Test files exercise the new code paths thoroughly including graceful-drain sequencing, per-home lock behavior, and credential-absence grace transitions.
|
| Filename | Overview |
|---|---|
| src/main/rate-limits/codex-probe-termination.ts | New graceful-kill helper: stdin EOF → SIGTERM → 5s drain → Windows tree-kill → SIGKILL. Platform-injectable for testing; waitForExit uses once listeners and idempotent promise resolution. Sound implementation. |
| src/main/codex-cli/codex-home-process-lock.ts | New FIFO mutex keyed by normalized home path. Tail-promise pattern is rejection-safe and self-cleaning. WSL UNC vs in-distro path normalization is correctly handled; sentinel for unknowable distro defaults is an acknowledged limitation. |
| src/main/rate-limits/codex-fetcher.ts | Two-phase RPC deadline (init budget / read budget), per-home lock wrapping both RPC and PTY paths, stdin error listener with deferred detach via once('close'), and onError now consistently passes { kill: true } — addressing the lock-release-before-exit gap noted in prior review. |
| src/main/codex-accounts/codex-credential-absence-grace.ts | New 5s grace-window tracker. Correctly treats valid-JSON states (present, incomplete, no-credential) as immediately durable (write is complete). Structurally-absent homes bypass the grace window. Clean implementation. |
| src/main/codex-accounts/managed-codex-auth-readiness.ts | Replaces boolean hasStoredCodexCredential with a five-state enum. Correctly distinguishes ENOENT/ENOTDIR (missing) from EPERM/EBUSY (unreadable/transient) and torn JSON (unreadable) from a settled empty credential (no-credential). |
| src/main/codex-accounts/runtime-home-service.ts | Sync path uses CodexCredentialAbsenceGrace with grace window; incomplete state keeps selection consistent with pre-PR behaviour. Launch path deselects on durable non-present state, preserving the old !hasStoredCodexCredential semantics. Intentional asymmetry between sync and launch paths. |
| src/main/rate-limits/service.ts | Removes lastInactiveCodexFetchAt = 0 from switch handler (preserves 60s debounce), adds 2s inter-probe stagger with post-stagger account-validity re-check, and delayUnlessAborted correctly handles already-aborted signals. |
| src/main/text-generation/commit-message-text-generation.ts | Refactors runLocalPlan to return LocalProcessExecution<T> (result + processClosed). Codex agent runs acquire the per-home lock and hold it until process close; non-codex agents keep zero added promise hops. Cancel-while-queued via queuedCancelToken correctly publishes the result before the lock fn executes. |
Sequence Diagram
sequenceDiagram
participant S as RateLimitService
participant L as withCodexHomeProcessLock
participant F as fetchViaRpc
participant C as codex app-server
participant T as terminateCodexProbeChild
S->>L: acquire homeLockKey
L->>F: fn() - fetchViaRpc(options)
F->>C: spawn(codex -s read-only app-server)
F->>F: "armRpcDeadline(initTimeoutMs=30s/40s WSL)"
C-->>F: JSON-RPC initialize response
F->>F: "armRpcDeadline(rpcTimeoutMs=10s/25s WSL)"
F->>C: account/rateLimits/read
alt success
C-->>F: rateLimits response
F->>T: "terminateCodexProbeChild kill=true"
T->>C: stdin.end() + SIGTERM (non-Windows)
C-->>T: exit within 5s drain window
T-->>F: resolved
F-->>L: resolve(result)
else timeout / error / abort
F->>T: "terminateCodexProbeChild kill=true"
T->>C: stdin.end() + SIGTERM
C-->>T: "drain timeout -> SIGKILL"
T-->>F: resolved
F-->>L: resolve(errorResult)
end
L-->>S: "release home lock -> next queued fn starts"
Reviews (3): Last reviewed commit: "fix(codex): preserve incomplete shared c..." | Re-trigger Greptile
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/rate-limits/codex-fetcher-probe-shutdown.test.ts (1)
260-261: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReplace the repeated 1 ms advances with an intent-revealing flush.
The two consecutive
await vi.advanceTimersByTimeAsync(1)calls drain microtasks by count, not by condition. The required count depends on the number of chained awaits infetchCodexRateLimitsafter the lock releases (withBackendSessionWindow, thenwithBackendRateLimitResetCredits). If that chain gains one more await, this test fails even though the shutdown behavior is unchanged.Use a condition-based flush so the test tracks the observable outcome instead of the await count.
♻️ Proposed condition-based flush
expect(firstChild.kill).toHaveBeenCalledWith('SIGKILL') expect(childSpawnMock).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(1) - await vi.advanceTimersByTimeAsync(1) + await vi.runOnlyPendingTimersAsync() await expect(first).resolves.toMatchObject({ status: 'error', error: 'stdio failed' }) await expect(second).resolves.toMatchObject({ status: 'ok' })
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 61f5799a-950f-43e8-9501-de0e7883b65f
📒 Files selected for processing (10)
src/main/codex-accounts/runtime-home-service.test.tssrc/main/codex-accounts/runtime-home-service.tssrc/main/codex-cli/codex-home-process-lock.test.tssrc/main/codex-cli/codex-home-process-lock.tssrc/main/rate-limits/codex-fetcher-probe-shutdown.test.tssrc/main/rate-limits/codex-fetcher.tssrc/main/rate-limits/codex-probe-termination.test.tssrc/main/rate-limits/codex-probe-termination.tssrc/main/text-generation/commit-message-text-generation.test.tssrc/main/text-generation/commit-message-text-generation.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- src/main/codex-cli/codex-home-process-lock.ts
- src/main/codex-accounts/runtime-home-service.ts
- src/main/rate-limits/codex-probe-termination.ts
- src/main/rate-limits/codex-fetcher.ts
- src/main/text-generation/commit-message-text-generation.ts
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d77be44b-195b-4373-97d3-193a33e5bff0
📒 Files selected for processing (4)
src/main/rate-limits/codex-fetcher.test.tssrc/main/rate-limits/codex-fetcher.tssrc/main/text-generation/commit-message-text-generation.test.tssrc/main/text-generation/commit-message-text-generation.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/rate-limits/codex-fetcher.test.ts
- src/main/rate-limits/codex-fetcher.ts
| let terminationComplete: Promise<void> | null = null | ||
| let detachChildListeners = (): void => {} | ||
| const startTermination = (): void => { | ||
| terminationComplete ??= killProcessTree(child) | ||
| } | ||
| settled = true | ||
| if (timer) { | ||
| clearTimeout(timer) | ||
| timer = null | ||
| const markClosedAfterTermination = (): void => { | ||
| void (terminationComplete ?? Promise.resolve()).then(markProcessClosed) | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Termination-tracker logic is duplicated verbatim.
The terminationComplete/startTermination/markClosedAfterTermination closures at Lines 378-385 in discoverCommitMessageModelsLocal and Lines 667-674 in runLocalPlan are identical except for variable capture. Both places memoize killProcessTree(child) and chain markProcessClosed after it resolves. Extract a shared helper to keep the two call sites in sync as this logic evolves (for example, if a future change adds a hard-kill escalation step).
♻️ Proposed extraction
+function createTerminationTracker(
+ child: ChildProcess,
+ markProcessClosed: () => void
+): { startTermination: () => void; markClosedAfterTermination: () => void } {
+ let terminationComplete: Promise<void> | null = null
+ return {
+ startTermination: () => {
+ terminationComplete ??= killProcessTree(child)
+ },
+ markClosedAfterTermination: () => {
+ void (terminationComplete ?? Promise.resolve()).then(markProcessClosed)
+ }
+ }
+}Then, in both startDiscovery and runLocalPlan:
- let terminationComplete: Promise<void> | null = null
- let detachChildListeners = (): void => {}
- const startTermination = (): void => {
- terminationComplete ??= killProcessTree(child)
- }
- const markClosedAfterTermination = (): void => {
- void (terminationComplete ?? Promise.resolve()).then(markProcessClosed)
- }
+ let detachChildListeners = (): void => {}
+ const { startTermination, markClosedAfterTermination } = createTerminationTracker(
+ child,
+ markProcessClosed
+ )Aside from the duplication, the design itself is sound: the dedicated once('close', markClosedAfterTermination) listener at Lines 452-456 and 772-774 is necessary, not redundant, because detachChildListeners() removes the primary onClose handler as soon as cancellation, a timeout, or an output-limit violation calls finish/finalize early, before the process has actually closed. Waiting on terminationComplete even after the child's own close event fires is also correct on Windows, since terminateWindowsProcessTree uses /T to kill the whole descendant tree, and that cleanup can outlast the immediate child's own exit.
Also applies to: 401-402, 412-412, 438-438, 452-456, 667-674, 696-704, 715-715, 724-732, 748-748, 772-774, 787-787
Electron QA — final headValidated Visible proof: opened Settings → AI Provider Accounts through the real UI. The Codex surface rendered in full app context as System default · Active · Needs sign-in, with “No Codex sign-in was found for this device.” The config-sync warning is expected because the isolated HOME intentionally has no Backing proof: Remaining gap: a real Codex login/terminal credential hot-swap was not exercised to avoid using live credentials. Credential mirroring, process-lock, shutdown, and grace behavior are covered by deterministic main-process tests. |
* fix(codex): make quota probes credential-safe Codex OAuth uses rotating refresh tokens, and Orca's quota probes spawned real codex app-server processes inside live credential homes, hard-killed them at a 10s deadline (cold starts run 10-25s), re-probed every inactive account on each switch, and deselected accounts on torn auth.json reads. - arm the RPC read deadline only after initialize responds (30s/40s boot budget), and terminate probes via stdin EOF + SIGTERM with a bounded drain before any hard kill; resolve only once the child exits - serialize Orca-spawned codex processes per credential home (probe vs probe, probe vs commit-message/PR-fields/branch-name/model-discovery) - keep the inactive-probe debounce across account switches and stagger inactive probes; the active account still refreshes immediately - grade credential reads (present/missing/unreadable/no-credential) and require absence to outlive a grace window before deselecting * fix(codex): close remaining credential races * fix(codex): keep failed probes under home lock * fix(codex): observe probe pipe failures * fix(codex): await Windows generation tree kills * fix(codex): preserve incomplete shared credentials

Summary
Addresses #11969 (users repeatedly logged out of connected Codex accounts, correlated with account switching). Codex OAuth uses rotating refresh tokens, and Orca's quota probes handled them dangerously in four ways, each fixed here:
codex app-serverinside the account's live credential home and hard-killed it at a 10s deadline, while cold starts (including an in-flight token refresh) are documented at 10–25s — a kill landing mid-rotation can permanently invalidate the stored credential. Now the request deadline is armed only after the app-server answersinitialize(boot budget: 30s host / 40s WSL), and every probe termination first requests shutdown (stdin EOF + SIGTERM; stdin EOF alone on Windows, where Node'skill()is always forceful) with a bounded 5s drain window before any hard kill. The fetch resolves only once the child has actually exited.withCodexHomeProcessLockFIFO mutex, keyed by the normalized codex home (WSL\\wsl$UNC and in-distro Linux paths collide onto one key). Quota probes (RPC and PTY paths) and Orca's own codex spawns for commit messages, PR fields, branch names, and model discovery all share it, so Orca never runs two of its own codex processes against oneauth.json. Stop/cancel still works while a generation is queued behind a probe. User terminal panes are intentionally not serialized (out of scope).present/missing/unreadable/no-credential. A transient missing or torn (mid-write)auth.jsonno longer deselects the active managed account: absence must persist past a 5s grace window before deselection — unless the managed home directory itself is gone, which is structural (not a rotation) and still deselects immediately. Settled valid-JSON-without-credential (a real logout) also still deselects immediately.Screenshots
No visual change
Testing
pnpm lintpnpm typecheckpnpm testpnpm build(left to CI — desktop + native packaging)pnpm test(node 24): 43,511 passed. The only failures on my machine (20 tests across 6 files:ipc/pty,relay/*,daemon/pty-subprocess,setup-agent-sequencing,check-root-directory-entries) are environment-sensitive and fail identically at the parent commit on main — verified by running the same files atHEAD~1under identical conditions and diffing the failure sets. Every suite touching this change passes.New coverage: graceful-drain sequencing with a fake child (SIGTERM → drain → SIGKILL escalation, Windows stdin-EOF-only lane, bounded resolution for a child that never exits, already-exited no-op); boot-budget vs read-deadline arming (a 20s-cold app-server is no longer killed); per-home lock behavior (same-key queueing, cross-key concurrency, release after rejection, WSL UNC ↔ Linux-path key collision); fetcher-level "no second spawn for the same home while one probe runs"; switch-debounce and 2s stagger in
RateLimitService; credential-absence grace transitions; and runtime-home-service "transient unreadable then valid auth.json does not deselect" plus grace-then-durable deselect.AI Review Report
Reviewed the change for lock leaks (per-home lock tail is rejection-safe and self-cleaning; probe resolution waits for child exit so the lock can't release mid-drain), cancellation races (a queued codex generation registers a pre-lock cancel token so Stop works while waiting), non-codex regression (the non-codex generation path keeps zero added promise hops, preserving cancellation timing byte-for-byte), and deselect-behavior regressions (structurally missing managed homes still deselect immediately at startup).
Cross-platform compatibility was explicitly checked for macOS, Linux, and Windows:
kill()is TerminateProcess, so the graceful phase uses stdin EOF only and escalates tokill()after the drain; the login-flowtaskkill /ttree-kill path is untouched; the background-probe ConPTY PTY fallback remains disabled on Windows;EPERM/EBUSYreads during auth.json rotation are classified as transientunreadable.\\wsl$/\\wsl.localhostUNC and Linux paths onto one key per distro.runRemotePlan/provider execution and is untouched; folder workspaces are unaffected (no worktree assumptions anywhere in the change).Security Audit
auth.jsonis only read (never written) by the new code, torn reads no longer influence deselection, and no credential material is logged.normalizeRuntimePathForComparisonoutput is used for comparison keys only, never spliced back into real paths.Notes
RPC timeoutfor both phases, so existing error classification is unchanged.cleanupHiddenRateLimitPtystill kills immediately; the per-home lock already prevents overlapping spawns there)syncWslRuntimeForCurrentSelection) still deselects without grace; the same grace could be applied~/.codexisn't resolvable from the host), so they serialize with each other but not with probes that pass an explicit UNC home