Repository navigation
fix(codex): stop a transient filesystem error from logging out the active account - #15046
Conversation
📝 WalkthroughWalkthroughThe PR adds verdict-based managed Codex home ownership checks with separate handling for untrusted and temporarily unavailable homes. Runtime-home, launch, resume, rate-limit, and configuration-sync flows now preserve selection or reject operations when managed files cannot be read. Rate-limit APIs return structured resolution states. Reauthentication gains optional activation for empty selections. The renderer adds sign-in feedback, synchronization retries, and localized status messages. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 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: 4
🧹 Nitpick comments (3)
src/renderer/src/components/status-bar/codex-status-sign-in.test.tsx (1)
2-9: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten the test preambles.
Keep only the non-obvious test setup rationale.
src/renderer/src/components/status-bar/codex-status-sign-in.test.tsx#L2-L9: reduce the symptom narrative to a brief setup-specific comment.src/main/codex-accounts/service-reauthenticate-activation.test.ts#L1-L8: reduce the workflow narrative to the race condition that the test requires.As per coding guidelines, “Comments must be concise, non-obvious, and brief.”
Source: Coding guidelines
src/main/codex-accounts/host-codex-managed-home-ownership.ts (1)
13-21: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten the rationale comments.
These three comment blocks span 6 to 9 lines each and narrate the caller behavior. Reduce each to one line that states the non-obvious constraint, for example:
untrustedmay clear the persisted selection,indeterminatemay not (#STA-4422).As per coding guidelines: "Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code."
Also applies to: 64-69, 190-196
Source: Coding guidelines
src/main/rate-limits/service.ts (1)
1812-1824: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd direct tests for the
skipresolution paths.Test a full cycle with
{ kind: 'skip' }to confirm that Codex does not fetch, prior Codex state remains unchanged, and other providers continue. Test a Codex-only cycle to confirm that it does not set a fetching state. Test a ready-to-skip transition while a fetch is in flight to confirm that the result is not applied.Also applies to: 1901-1905, 1942-1946
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: efc54fb4-f53d-4f36-8302-22ac8c65e152
📥 Commits
Reviewing files that changed from the base of the PR and between b279f66 and 4bd6e7a20682f2a13456a359007c07e6fc58fbb8.
📒 Files selected for processing (37)
src/main/codex-accounts/host-codex-managed-home-ownership.tssrc/main/codex-accounts/runtime-home-managed-auth-recovery.test.tssrc/main/codex-accounts/runtime-home-mirrored-status-home.test.tssrc/main/codex-accounts/runtime-home-per-account-homes.test.tssrc/main/codex-accounts/runtime-home-real-home-lane-routing.test.tssrc/main/codex-accounts/runtime-home-resume-selection-gate.test.tssrc/main/codex-accounts/runtime-home-retained-auth-provenance.test.tssrc/main/codex-accounts/runtime-home-service-per-account-migration.test.tssrc/main/codex-accounts/runtime-home-service.tssrc/main/codex-accounts/runtime-home-wsl-managed-accounts.test.tssrc/main/codex-accounts/runtime-home-wsl-system-default.test.tssrc/main/codex-accounts/service-reauthenticate-activation.test.tssrc/main/codex-accounts/service-reset-credit-target-routing.test.tssrc/main/codex-accounts/service-test-harness.tssrc/main/codex-accounts/service.tssrc/main/codex-accounts/sta-4422-transient-ownership-error.test.tssrc/main/index.tssrc/main/ipc/codex-accounts.tssrc/main/ipc/codex-config-sync.test.tssrc/main/ipc/codex-config-sync.tssrc/main/ipc/pty-spawn-codex-home-unavailable.test.tssrc/main/ipc/pty.tssrc/main/rate-limits/service-account-target-selection.test.tssrc/main/rate-limits/service-inactive-account-previews.test.tssrc/main/rate-limits/service.tssrc/main/text-generation/commit-message-agent-environment.test.tssrc/preload/api/agent-account-api.tssrc/preload/index.tssrc/renderer/src/components/settings/AccountsPane.tsxsrc/renderer/src/components/status-bar/StatusBar.tsxsrc/renderer/src/components/status-bar/codex-status-sign-in.test.tsxsrc/renderer/src/i18n/locales/en.jsonsrc/renderer/src/i18n/locales/es.jsonsrc/renderer/src/i18n/locales/ja.jsonsrc/renderer/src/i18n/locales/ko.jsonsrc/renderer/src/i18n/locales/zh.jsonsrc/shared/codex-config-sync-types.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 0 remain after this review.
| await fetchSettings() | ||
| if (mountedRef.current && accountsExpandedRef.current) { | ||
| const nextActiveAccountId = getCodexStatusActiveId(next, target) | ||
| if (previousActiveAccountId !== nextActiveAccountId) { | ||
| // Why: sign-in that lands on a new active account changes pane credentials | ||
| // exactly like an explicit switch, so it owes the same restart prompt. | ||
| await markLiveCodexSessionsForRestart({ | ||
| previousAccountLabel: resolveCodexRestartPromptAccountLabel( | ||
| accountState.accounts, | ||
| previousActiveAccountId | ||
| ), | ||
| nextAccountLabel: resolveCodexRestartPromptAccountLabel( | ||
| next.accounts, | ||
| nextActiveAccountId | ||
| ), | ||
| previousAccountId: previousActiveAccountId ?? null, | ||
| nextAccountId: nextActiveAccountId ?? null, | ||
| target | ||
| }) | ||
| if (mountedRef.current) { | ||
| setAccountsExpanded(false) | ||
| } | ||
| } else if (mountedRef.current && accountsExpandedRef.current) { | ||
| await fetchInactiveCodexAccountUsage() | ||
| } | ||
| toast.success( | ||
| translate('auto.components.status.bar.StatusBar.codexSignInSuccess', 'Signed in to Codex') | ||
| ) | ||
| } catch (error) { | ||
| console.error('Failed to re-authenticate Codex account from status bar:', error) | ||
| toast.error( | ||
| translate( | ||
| 'auto.components.status.bar.StatusBar.codexSignInError', | ||
| 'Codex sign-in failed. Please try again.' | ||
| ) | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Do not report a completed sign-in as failed.
fetchSettings() and markLiveCodexSessionsForRestart() run after reauthenticate() succeeds. If either operation rejects, the outer catch shows the sign-in failure toast even though Codex credentials were updated. Handle post-sign-in synchronization failures separately, then preserve the success result.
| toast.success( | ||
| translate('auto.components.status.bar.StatusBar.codexSignInSuccess', 'Signed in to Codex') | ||
| ) | ||
| } catch (error) { | ||
| console.error('Failed to re-authenticate Codex account from status bar:', error) | ||
| toast.error( | ||
| translate( | ||
| 'auto.components.status.bar.StatusBar.codexSignInError', | ||
| 'Codex sign-in failed. Please try again.' |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Use generated renderer localization keys.
Replace codexSignInSuccess and codexSignInError with keys generated from <filePath>:<text>. The new suffixes do not follow the renderer localization key format.
Based on learnings, generate locale keys as the first 10 characters of the SHA-1 hash of <filePath>:<text>.
Source: Learnings
…tive account A single unreadable read of a managed Codex home's ownership marker cleared the user's active account selection, permanently. On Windows any exclusive lock — Defender real-time scanning, a backup agent, a sync client — makes every read of that marker fail with EBUSY, and the background rate-limit poll runs every 15 minutes plus once at every app start. Root cause: the ownership gate answered two very different questions through one channel. "This home is not ours" (a successful observation that failed a trust check) and "we could not read it" both surfaced as a throw, which the caller flattened to null, which three call sites took as proof the home was untrustworthy and wrote activeCodexManagedAccountId: null. Refusing to USE an unverified home is correct. Erasing the user's account selection because a file was briefly locked is not. The gate now returns a tri-state verdict. `untrusted` comes only from a proven trust failure or a definitive ENOENT/ENOTDIR where absence is itself the verdict; every other filesystem exception is `indeterminate`. Only `untrusted` may touch persisted state. Because `null` already meant "fall through to the system default" on both the launch and poll paths, not-clearing on its own would have run a DIFFERENT account behind a UI still showing the selected one. So the refusal needed real channels rather than a sentinel: - the poll returns an explicit skip; returning null would not have skipped at all, since the fetcher maps null to ~/.codex and would have spawned a token-refreshing app-server inside the user's real credential home - pane launch throws a typed temporary-unavailability error that both PTY implementations convert into a clean refusal with a retry message, including the re-resolution after the async auth-readiness wait - automatic session resume resolves the selected home eagerly, so an unreadable account can no longer be silently replaced by another one in the ranking - config-sync status reports a distinct managed-home-unavailable stall instead of "synced", with a bounded renderer retry so it clears on its own Also fixes the ticket's second symptom. The status bar's Sign in button called a re-auth that captured the selection before login and restored it after, so re-authenticating a deselected account restored `null` — a successful login that left the account inactive, with no success toast to distinguish it from failure. It now activates the account it just signed in, but only when the pre-login selection was empty, so it cannot silently switch accounts for multi-account users, and it runs the same restart prompt an explicit switch does. No retry or grace window inside the synchronous gate: it runs on the Electron main process in a loop over accounts, so a sleep there would freeze the UI. Recovery is simply the next readable evaluation. The WSL lane has the same class of defect, including one path that deletes a credential mirror. It is pre-existing, unreachable from these host code paths, and deliberately left for its own change; the host clearing sites cannot reach a WSL account because getSelfContainedManagedHostAccount excludes them. Fixes STA-4422
cbd99ec to
7ac8420
Compare
…tive account (#15046) * fix(codex): stop a transient filesystem error from logging out the active account A single unreadable read of a managed Codex home's ownership marker cleared the user's active account selection, permanently. On Windows any exclusive lock — Defender real-time scanning, a backup agent, a sync client — makes every read of that marker fail with EBUSY, and the background rate-limit poll runs every 15 minutes plus once at every app start. Root cause: the ownership gate answered two very different questions through one channel. "This home is not ours" (a successful observation that failed a trust check) and "we could not read it" both surfaced as a throw, which the caller flattened to null, which three call sites took as proof the home was untrustworthy and wrote activeCodexManagedAccountId: null. Refusing to USE an unverified home is correct. Erasing the user's account selection because a file was briefly locked is not. The gate now returns a tri-state verdict. `untrusted` comes only from a proven trust failure or a definitive ENOENT/ENOTDIR where absence is itself the verdict; every other filesystem exception is `indeterminate`. Only `untrusted` may touch persisted state. Because `null` already meant "fall through to the system default" on both the launch and poll paths, not-clearing on its own would have run a DIFFERENT account behind a UI still showing the selected one. So the refusal needed real channels rather than a sentinel: - the poll returns an explicit skip; returning null would not have skipped at all, since the fetcher maps null to ~/.codex and would have spawned a token-refreshing app-server inside the user's real credential home - pane launch throws a typed temporary-unavailability error that both PTY implementations convert into a clean refusal with a retry message, including the re-resolution after the async auth-readiness wait - automatic session resume resolves the selected home eagerly, so an unreadable account can no longer be silently replaced by another one in the ranking - config-sync status reports a distinct managed-home-unavailable stall instead of "synced", with a bounded renderer retry so it clears on its own Also fixes the ticket's second symptom. The status bar's Sign in button called a re-auth that captured the selection before login and restored it after, so re-authenticating a deselected account restored `null` — a successful login that left the account inactive, with no success toast to distinguish it from failure. It now activates the account it just signed in, but only when the pre-login selection was empty, so it cannot silently switch accounts for multi-account users, and it runs the same restart prompt an explicit switch does. No retry or grace window inside the synchronous gate: it runs on the Electron main process in a loop over accounts, so a sleep there would freeze the UI. Recovery is simply the next readable evaluation. The WSL lane has the same class of defect, including one path that deletes a credential mirror. It is pre-existing, unreachable from these host code paths, and deliberately left for its own change; the host clearing sites cannot reach a WSL account because getSelfContainedManagedHostAccount excludes them. Fixes STA-4422 * test(codex): cover pending reset home ownership
…tive account (stablyai#15046) * fix(codex): stop a transient filesystem error from logging out the active account A single unreadable read of a managed Codex home's ownership marker cleared the user's active account selection, permanently. On Windows any exclusive lock — Defender real-time scanning, a backup agent, a sync client — makes every read of that marker fail with EBUSY, and the background rate-limit poll runs every 15 minutes plus once at every app start. Root cause: the ownership gate answered two very different questions through one channel. "This home is not ours" (a successful observation that failed a trust check) and "we could not read it" both surfaced as a throw, which the caller flattened to null, which three call sites took as proof the home was untrustworthy and wrote activeCodexManagedAccountId: null. Refusing to USE an unverified home is correct. Erasing the user's account selection because a file was briefly locked is not. The gate now returns a tri-state verdict. `untrusted` comes only from a proven trust failure or a definitive ENOENT/ENOTDIR where absence is itself the verdict; every other filesystem exception is `indeterminate`. Only `untrusted` may touch persisted state. Because `null` already meant "fall through to the system default" on both the launch and poll paths, not-clearing on its own would have run a DIFFERENT account behind a UI still showing the selected one. So the refusal needed real channels rather than a sentinel: - the poll returns an explicit skip; returning null would not have skipped at all, since the fetcher maps null to ~/.codex and would have spawned a token-refreshing app-server inside the user's real credential home - pane launch throws a typed temporary-unavailability error that both PTY implementations convert into a clean refusal with a retry message, including the re-resolution after the async auth-readiness wait - automatic session resume resolves the selected home eagerly, so an unreadable account can no longer be silently replaced by another one in the ranking - config-sync status reports a distinct managed-home-unavailable stall instead of "synced", with a bounded renderer retry so it clears on its own Also fixes the ticket's second symptom. The status bar's Sign in button called a re-auth that captured the selection before login and restored it after, so re-authenticating a deselected account restored `null` — a successful login that left the account inactive, with no success toast to distinguish it from failure. It now activates the account it just signed in, but only when the pre-login selection was empty, so it cannot silently switch accounts for multi-account users, and it runs the same restart prompt an explicit switch does. No retry or grace window inside the synchronous gate: it runs on the Electron main process in a loop over accounts, so a sleep there would freeze the UI. Recovery is simply the next readable evaluation. The WSL lane has the same class of defect, including one path that deletes a credential mirror. It is pre-existing, unreachable from these host code paths, and deliberately left for its own change; the host clearing sites cannot reach a WSL account because getSelfContainedManagedHostAccount excludes them. Fixes STA-4422 * test(codex): cover pending reset home ownership
…tive account (stablyai#15046) * fix(codex): stop a transient filesystem error from logging out the active account A single unreadable read of a managed Codex home's ownership marker cleared the user's active account selection, permanently. On Windows any exclusive lock — Defender real-time scanning, a backup agent, a sync client — makes every read of that marker fail with EBUSY, and the background rate-limit poll runs every 15 minutes plus once at every app start. Root cause: the ownership gate answered two very different questions through one channel. "This home is not ours" (a successful observation that failed a trust check) and "we could not read it" both surfaced as a throw, which the caller flattened to null, which three call sites took as proof the home was untrustworthy and wrote activeCodexManagedAccountId: null. Refusing to USE an unverified home is correct. Erasing the user's account selection because a file was briefly locked is not. The gate now returns a tri-state verdict. `untrusted` comes only from a proven trust failure or a definitive ENOENT/ENOTDIR where absence is itself the verdict; every other filesystem exception is `indeterminate`. Only `untrusted` may touch persisted state. Because `null` already meant "fall through to the system default" on both the launch and poll paths, not-clearing on its own would have run a DIFFERENT account behind a UI still showing the selected one. So the refusal needed real channels rather than a sentinel: - the poll returns an explicit skip; returning null would not have skipped at all, since the fetcher maps null to ~/.codex and would have spawned a token-refreshing app-server inside the user's real credential home - pane launch throws a typed temporary-unavailability error that both PTY implementations convert into a clean refusal with a retry message, including the re-resolution after the async auth-readiness wait - automatic session resume resolves the selected home eagerly, so an unreadable account can no longer be silently replaced by another one in the ranking - config-sync status reports a distinct managed-home-unavailable stall instead of "synced", with a bounded renderer retry so it clears on its own Also fixes the ticket's second symptom. The status bar's Sign in button called a re-auth that captured the selection before login and restored it after, so re-authenticating a deselected account restored `null` — a successful login that left the account inactive, with no success toast to distinguish it from failure. It now activates the account it just signed in, but only when the pre-login selection was empty, so it cannot silently switch accounts for multi-account users, and it runs the same restart prompt an explicit switch does. No retry or grace window inside the synchronous gate: it runs on the Electron main process in a loop over accounts, so a sleep there would freeze the UI. Recovery is simply the next readable evaluation. The WSL lane has the same class of defect, including one path that deletes a credential mirror. It is pre-existing, unreachable from these host code paths, and deliberately left for its own change; the host clearing sites cannot reach a WSL account because getSelfContainedManagedHostAccount excludes them. Fixes STA-4422 * test(codex): cover pending reset home ownership



Fixes STA-4422 · closes #14737
The bug
A user reported Codex accounts logging out at random, and logins that report success while the account stays inactive.
One unreadable read of a managed Codex home's ownership marker cleared the active account selection, permanently. On Windows any exclusive lock — Defender real-time scanning, a backup agent, a sync client — makes every read of that marker fail with
EBUSY. The background rate-limit poll runs every 15 minutes, plus once at every app start (when antivirus is busiest, which matches the "I opened Orca and I was logged out" reports).Reproduced live on a Windows host against an isolated Orca profile, driven over CDP:
A rig replicating the gate's exact call sequence on that box measured the trigger's reliability: 18,522 iterations idle → 0 failures; 23,257 under the lock → 23,257 failures (100%); 11,205 after release → 0. The gate isn't flaky under contention — it is totally broken for the lock's duration. The poll only has to land inside one such window, once, ever.
Root cause
The ownership gate answered two very different questions through one channel:
EBUSY. The home may be perfectly valid.Both surfaced as a throw, which the caller flattened to
null, which three call sites took as proof the home was untrustworthy and wroteactiveCodexManagedAccountId: null.Refusing to use an unverified home is correct. Erasing the user's account selection because a file was briefly locked is not.
The fix
The gate now returns a tri-state verdict.
untrustedcomes only from a proven trust failure, or a definitiveENOENT/ENOTDIRwhere absence is itself the verdict. Every other filesystem exception isindeterminate. Onlyuntrustedmay touch persisted state.The subtle part:
nullalready meant "fall through to the system default" on both the launch and poll paths. So simply not-clearing would have run a different account behind a UI still showing the selected one — a credential-identity bug, worse than the logout. The refusal needed real channels rather than a sentinel:indeterminateskip. Returningnullwould not have skipped — the fetcher mapsnullto~/.codexand would have spawned a token-refreshing app-server inside the user's real credential homemanaged-home-unavailablestall instead of reportingsynced, with a bounded renderer retry (30s × 10) so it clears without a remountDeliberately no retry or grace window inside the gate: it is synchronous, runs on the Electron main process, and startup iterates every managed account — a sleep there would freeze the UI. Recovery is just the next readable evaluation.
Second symptom: "login succeeded but the account is still inactive"
The status bar's Sign in button called a re-auth that captured the selection before login and restored it after — so re-authenticating a deselected account restored
null. A fully successful login left the account inactive, with no success toast to distinguish it from a failure. That's the reporter's second screenshot.It now activates the account it just signed in — but only when the pre-login selection was empty, so it can't silently switch accounts for multi-account users from a control labelled "Sign in to see usage". It uses the pre-login capture, not a post-login read, because the runtime poll runs outside the account mutation queue and could clear the primary while OAuth is open. It also runs the same restart prompt an explicit switch does, plus success and error toasts.
Not in this change
The WSL lane has the same class of defect, including a path that
rmSyncs a credential mirror on a transient read. It is pre-existing, and these host code paths cannot reach it —getSelfContainedManagedHostAccountexcludes WSL accounts, so the tri-state change leaves that lane byte-for-byte as it was. It needs distro-scoped read-back suppression and a restart-safe ownership contract, which is a design change rather than a bug fix. Filed separately with a full specification.Two pre-existing session-tree probes can also route a resume to another account (
existsSync(sessions)and a blanketlstatcatch). Also filed separately — they route to another account today with the ownership gate uninvolved, so they are not regressions of this change.This does not eliminate every logout. The Codex CLI's own credential manager collapses any read error into "not logged in" and persists
auth.jsonby truncate-in-place, so some reported logouts originate below Orca. There is also an independent refresh-token rotation race, where the quota probe can race a user's live Codex pane over one rotating token; that is a real, unrecoverable logout and is tracked separately.Testing
updateSettingsis never called, repeated evaluations never accumulate into a destructive verdict, and recovery is automatic.untrustedand still deselects.nullre-resolution intentionally launches withoutCODEX_HOME.terminal-history-async-delete.test.ts, a wall-clock assertion (elapsedMs < 150) in a file this branch does not touch; it passes in isolation and fails only under full-suite parallel load.Known coverage gap
src/main/index.tshas no unit-test entry point in this repo, so the eager resume-gate wiring is covered by typecheck plus tests at both ends rather than directly. The AI Vault propagation paths (index.ts:1468-1475,:2591-2597) are likewise uncovered.