Skip to content

fix(codex): make quota probes credential-safe - #12145

Merged
brennanb2025 merged 6 commits into
mainfrom
brennanb2025/codex-probe-credential-safety
Aug 3, 2026
Merged

brennanb2025 merged 6 commits into
mainfrom
brennanb2025/codex-probe-credential-safety

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

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:

  1. Graceful probe shutdown. The RPC probe spawned codex app-server inside 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 answers initialize (boot budget: 30s host / 40s WSL), and every probe termination first requests shutdown (stdin EOF + SIGTERM; stdin EOF alone on Windows, where Node's kill() is always forceful) with a bounded 5s drain window before any hard kill. The fetch resolves only once the child has actually exited.
  2. Per-credential-home serialization. New withCodexHomeProcessLock FIFO 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 one auth.json. Stop/cancel still works while a generation is queued behind a probe. User terminal panes are intentionally not serialized (out of scope).
  3. No more switch-storm. Account switches no longer zero the inactive-probe debounce (previously every switch re-probed every inactive account's credential home at once). The 60s debounce holds, the switcher shows the cached snapshot (seeded from the outgoing account), inactive probes are staggered 2s apart, and the newly active account still gets its immediate refresh.
  4. Parse-error grace. Credential reads now distinguish present / missing / unreadable / no-credential. A transient missing or torn (mid-write) auth.json no 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 lint
  • pnpm typecheck
  • pnpm test
  • pnpm build (left to CI — desktop + native packaging)
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

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 at HEAD~1 under 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:

  • Windows: Node's kill() is TerminateProcess, so the graceful phase uses stdin EOF only and escalates to kill() after the drain; the login-flow taskkill /t tree-kill path is untouched; the background-probe ConPTY PTY fallback remains disabled on Windows; EPERM/EBUSY reads during auth.json rotation are classified as transient unreadable.
  • WSL: the boot budget is 40s (cold WSL starts exceed host budgets); stdin EOF propagates to the in-distro codex through the existing fd-isolated login-shell plumbing; lock keys normalize \\wsl$/\\wsl.localhost UNC and Linux paths onto one key per distro.
  • macOS/Linux: stdin EOF + SIGTERM, then SIGKILL after the drain.
  • SSH: remote generation goes through runRemotePlan/provider execution and is untouched; folder workspaces are unaffected (no worktree assumptions anywhere in the change).

Security Audit

  • No new command execution: the same codex binaries/arguments are spawned; the lock and grace logic are purely in-process.
  • auth.json is only read (never written) by the new code, torn reads no longer influence deselection, and no credential material is logged.
  • Path handling: normalizeRuntimePathForComparison output is used for comparison keys only, never spliced back into real paths.
  • No IPC surface changes; no new dependencies.

Notes

  • The deadline error stays RPC timeout for both phases, so existing error classification is unchanged.
  • Follow-ups (deliberately out of scope, per the one-theme rule):
    • WSL bidirectional auth mirroring fork
    • hook-lane flip handling
    • multi-pane token refresh coordination
    • graceful drain for the PTY fallback path (cleanupHiddenRateLimitPty still kills immediately; the per-home lock already prevents overlapping spawns there)
    • the WSL managed-account missing-auth deselect (syncWslRuntimeForCurrentSelection) still deselects without grace; the same grace could be applied
    • system-default WSL commit-message runs key the lock with a distro-scoped sentinel (the distro's ~/.codex isn't resolvable from the host), so they serialize with each other but not with probes that pass an explicit UNC home

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

coderabbitai Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

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

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% 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 summarizes the main change: making Codex quota probes safe for rotating credentials.
Description check ✅ Passed The description covers all required sections, testing status, AI review, cross-platform checks, security audit, and follow-up notes.
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.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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 (2)
src/main/codex-accounts/runtime-home-service.ts (2)

740-771: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Fix the absence check to cover no-credential and to act on durable for unreadable.

This block has two gaps compared to the correct handling in prepareSelfContainedManagedHomeForLaunch (lines 309-321) and the design intent stated at lines 90-92 of managed-codex-auth-readiness.ts.

First, the if at line 742 only matches 'missing' or 'unreadable'. When authAbsence.state is 'no-credential' (a settled logout — valid JSON with no credential fields), execution falls through this check entirely. The code then reads activeAuthPath again at line 792 and writes that credential-less content into the runtime home instead of deselecting the account. The design comment on readStoredCodexCredentialState states 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 of authAbsence.durable. If auth.json stays unreadable permanently (a persistent permission error, or a file that never heals), the account is never deselected and the system default is never restored. The durable flag computed for 'unreadable' in CodexCredentialAbsenceGrace.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 through syncForCurrentSelection's shared-home path, plus a case for a settled no-credential file.


1028-1048: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Apply absence-grace handling to WSL active auth.json reads.

syncWslRuntimeForCurrentSelection still uses a plain existsSync(activeAuthPath) check before clearing the active WSL selection, so a rotation-in-flight read can deselect the WSL managed account. Use credentialAbsenceGrace.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 win

Add 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.ts lines 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2efc6e5 and 5a198d4.

📒 Files selected for processing (17)
  • src/main/codex-accounts/codex-credential-absence-grace.test.ts
  • src/main/codex-accounts/codex-credential-absence-grace.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/codex-cli/codex-home-process-lock.test.ts
  • src/main/codex-cli/codex-home-process-lock.ts
  • src/main/rate-limits/codex-fetcher-auth-errors.test.ts
  • src/main/rate-limits/codex-fetcher-probe-shutdown.test.ts
  • src/main/rate-limits/codex-fetcher-session-supplement.test.ts
  • src/main/rate-limits/codex-fetcher.test.ts
  • src/main/rate-limits/codex-fetcher.ts
  • src/main/rate-limits/codex-probe-termination.test.ts
  • src/main/rate-limits/codex-probe-termination.ts
  • src/main/rate-limits/service.test.ts
  • src/main/rate-limits/service.ts
  • src/main/text-generation/commit-message-text-generation.ts

@greptile-apps

greptile-apps Bot commented Aug 2, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR hardens Codex OAuth credential safety across four axes: (1) graceful probe shutdown with a two-phase SIGTERM→drain→SIGKILL sequence via terminateCodexProbeChild, (2) a per-credential-home FIFO mutex (withCodexHomeProcessLock) so Orca never runs two processes against the same auth.json concurrently, (3) preserving the 60s inactive-probe debounce across account switches to avoid token-rotation storms, and (4) a 5s grace window before treating a missing or torn auth.json as a durable logout.

  • codex-probe-termination.ts introduces a platform-aware graceful-kill helper with a bounded drain window; codex-home-process-lock.ts adds the FIFO queue keyed by normalized home path, shared across probe and commit-message codex spawns.
  • codex-fetcher.ts now arms the RPC deadline only after initialize responds (boot budget vs read deadline), attaches a stdin error listener for EPIPE during shutdown, and passes { kill: true } to settle() consistently so the home lock never releases while a draining process may still rewrite auth.json.
  • codex-credential-absence-grace.ts / managed-codex-auth-readiness.ts replace the binary hasStoredCodexCredential boolean with a five-state enum (present / incomplete / missing / unreadable / no-credential) and a grace-window tracker, preventing mid-rotation reads from triggering immediate deselection.

Confidence Score: 5/5

Safe 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 onError releasing the home lock before child exit has been addressed: onError now consistently passes { kill: true } to settle(), so the lock releases only after terminateCodexProbeChild completes. All other lock-release paths were already correct. The FIFO queue, two-phase RPC deadline, stagger logic, and credential absence grace window are all implemented correctly with comprehensive test coverage.

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.

Important Files Changed

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

Reviews (3): Last reviewed commit: "fix(codex): preserve incomplete shared c..." | Re-trigger Greptile

@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/rate-limits/codex-fetcher-probe-shutdown.test.ts (1)

260-261: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Replace 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 in fetchCodexRateLimits after the lock releases (withBackendSessionWindow, then withBackendRateLimitResetCredits). 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

📥 Commits

Reviewing files that changed from the base of the PR and between 5a198d4 and c9422ed.

📒 Files selected for processing (10)
  • src/main/codex-accounts/runtime-home-service.test.ts
  • src/main/codex-accounts/runtime-home-service.ts
  • src/main/codex-cli/codex-home-process-lock.test.ts
  • src/main/codex-cli/codex-home-process-lock.ts
  • src/main/rate-limits/codex-fetcher-probe-shutdown.test.ts
  • src/main/rate-limits/codex-fetcher.ts
  • src/main/rate-limits/codex-probe-termination.test.ts
  • src/main/rate-limits/codex-probe-termination.ts
  • src/main/text-generation/commit-message-text-generation.test.ts
  • src/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

@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: Pro Plus

Run ID: d77be44b-195b-4373-97d3-193a33e5bff0

📥 Commits

Reviewing files that changed from the base of the PR and between 7ddd8d0 and c3b832b.

📒 Files selected for processing (4)
  • src/main/rate-limits/codex-fetcher.test.ts
  • src/main/rate-limits/codex-fetcher.ts
  • src/main/text-generation/commit-message-text-generation.test.ts
  • src/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

Comment on lines +378 to 385
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)
}

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.

📐 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

@brennanb2025

brennanb2025 commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Electron QA — final head

Validated a291c9c685b2bc090aeabfa28b2562b7c3e1a666 in an isolated Electron profile through CDP. The automation identity matched brennanb2025/codex-probe-credential-safety and this worktree.

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 .codex/config.toml.

Backing proof: window.api.codexAccounts.list() returned no managed accounts, activeAccountId: null, and system default { hasAuth: false, authKind: "none" }, matching the visible state. Renderer console: 0 errors; 3 unrelated dev-only Tooltip/React Grab warnings.

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.

AI Provider Accounts on final Electron head

@brennanb2025
brennanb2025 merged commit 1e46121 into main Aug 3, 2026
43 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* 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
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.

1 participant