diff --git a/src/main/rate-limits/codex-fetcher-auth-errors.test.ts b/src/main/rate-limits/codex-fetcher-auth-errors.test.ts new file mode 100644 index 000000000..08674c9d9 --- /dev/null +++ b/src/main/rate-limits/codex-fetcher-auth-errors.test.ts @@ -0,0 +1,130 @@ +import { EventEmitter } from 'node:events' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { childSpawnMock, resolveCodexCommandMock, ptySpawnMock } = vi.hoisted(() => ({ + childSpawnMock: vi.fn(), + resolveCodexCommandMock: vi.fn(), + ptySpawnMock: vi.fn() +})) + +vi.mock('node:child_process', () => ({ + spawn: childSpawnMock +})) + +vi.mock('../codex-cli/command', () => ({ + resolveCodexCommand: resolveCodexCommandMock +})) + +vi.mock('node-pty', () => ({ + spawn: ptySpawnMock +})) + +import { fetchCodexRateLimits } from './codex-fetcher' + +function makeDisposable() { + return { dispose: vi.fn() } +} + +function makeRpcChild() { + const child = new EventEmitter() as EventEmitter & { + stdout: EventEmitter + stderr: EventEmitter + stdin: { write: ReturnType } + kill: ReturnType + } + child.stdout = new EventEmitter() + child.stderr = new EventEmitter() + child.stdin = { write: vi.fn() } + child.kill = vi.fn() + return child +} + +describe('fetchCodexRateLimits auth errors', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.clearAllMocks() + resolveCodexCommandMock.mockReturnValue('codex') + }) + + it('returns Codex RPC auth refresh errors without masking them behind PTY fallback', async () => { + const rpcChild = makeRpcChild() + const authError = + 'Your access token could not be refreshed because your refresh token was already used. Please log out and sign in again.' + + childSpawnMock.mockReturnValue(rpcChild) + rpcChild.stdin.write.mockImplementation((line: string) => { + const msg = JSON.parse(line) as { id?: number; method?: string } + if (msg.method === 'initialize') { + setTimeout(() => { + rpcChild.stdout.emit( + 'data', + Buffer.from(`${JSON.stringify({ jsonrpc: '2.0', id: msg.id, result: {} })}\n`) + ) + }, 0) + } + if (msg.method === 'account/rateLimits/read') { + setTimeout(() => { + rpcChild.stdout.emit( + 'data', + Buffer.from( + `${JSON.stringify({ + jsonrpc: '2.0', + id: msg.id, + error: { code: -32000, message: authError } + })}\n` + ) + ) + }, 0) + } + }) + + const resultPromise = fetchCodexRateLimits() + await vi.advanceTimersByTimeAsync(1) + await vi.advanceTimersByTimeAsync(1) + + await expect(resultPromise).resolves.toMatchObject({ + provider: 'codex', + session: null, + weekly: null, + status: 'error', + error: authError + }) + expect(ptySpawnMock).not.toHaveBeenCalled() + }) + + it('preserves Codex PTY auth errors when the CLI exits before status is available', async () => { + const ptyHandlers: { onData?: (data: string) => void; onExit?: () => void } = {} + const authError = + 'Error loading configuration: Your authentication session could not be refreshed automatically.' + + childSpawnMock.mockImplementation(() => { + throw new Error('rpc unavailable') + }) + ptySpawnMock.mockReturnValue({ + onData: vi.fn((callback) => { + ptyHandlers.onData = callback + return makeDisposable() + }), + onExit: vi.fn((callback) => { + ptyHandlers.onExit = callback + return makeDisposable() + }), + write: vi.fn(), + kill: vi.fn() + }) + + const resultPromise = fetchCodexRateLimits() + await vi.advanceTimersByTimeAsync(0) + + ptyHandlers.onData?.(`${authError}\n`) + ptyHandlers.onExit?.() + + await expect(resultPromise).resolves.toMatchObject({ + provider: 'codex', + session: null, + weekly: null, + status: 'error', + error: authError + }) + }) +}) diff --git a/src/main/rate-limits/codex-fetcher.ts b/src/main/rate-limits/codex-fetcher.ts index feec38d98..d46da8c40 100644 --- a/src/main/rate-limits/codex-fetcher.ts +++ b/src/main/rate-limits/codex-fetcher.ts @@ -8,6 +8,7 @@ import { withMacTailscaleDnsHint } from '../network/macos-tailscale-dns-diagnost import { getCmdExePath, getSpawnArgsForWindows } from '../win32-utils' import { cleanupHiddenRateLimitPty } from './hidden-pty-cleanup' import { parseWslUncPath } from '../../shared/wsl-paths' +import { extractCodexAuthError, isCodexAuthError } from '../../shared/codex-auth-errors' const RPC_TIMEOUT_MS = 10_000 const WSL_RPC_TIMEOUT_MS = 25_000 @@ -395,7 +396,7 @@ async function fetchViaPty(options?: FetchCodexRateLimitsOptions): Promise s.settingsSearchQuery) + const codexRateLimits = useAppStore((s) => s.rateLimits.codex) + const codexRateLimitTarget = useAppStore((s) => s.rateLimits.codexTarget) const recordFeatureInteraction = useAppStore((s) => s.recordFeatureInteraction) const fetchSettings = useAppStore((s) => s.fetchSettings) const recordedOpenCodeSettingEditsRef = useRef>(new Set()) @@ -249,6 +252,7 @@ export function AccountsPane({ activeAccountId: null, activeAccountIdsByRuntime: { host: null, wsl: {} } }) + const [codexAccountsLoaded, setCodexAccountsLoaded] = useState(false) const [codexAction, setCodexAction] = useState< 'idle' | 'adding' | `reauth:${string}` | `remove:${string}` | `select:${string | 'system'}` >('idle') @@ -270,6 +274,17 @@ export function AccountsPane({ ) const activeCodexAccountId = getActiveCodexAccountIdForRuntime(codexAccounts, accountRuntime) const activeClaudeAccountId = getActiveClaudeAccountIdForRuntime(claudeAccounts, accountRuntime) + const activeCodexAuthWarning = codexAccountsLoaded + ? getCodexAccountAuthWarning({ + limits: codexRateLimits, + target: codexRateLimitTarget, + runtime: accountRuntime, + activeAccountId: activeCodexAccountId, + accountId: activeCodexAccountId + }) + : null + const systemCodexNeedsReauthentication = + activeCodexAccountId === null && Boolean(activeCodexAuthWarning) const accountRuntimeUnavailable = accountRuntime.runtime === 'wsl' && !wslAvailable && !wslCapabilitiesLoading @@ -289,6 +304,7 @@ export function AccountsPane({ const nextCodex = await window.api.codexAccounts.list() if (!stale) { setCodexAccounts(nextCodex) + setCodexAccountsLoaded(true) } } catch (error) { if (!stale) { @@ -324,6 +340,7 @@ export function AccountsPane({ const syncCodexAccounts = async (next: CodexRateLimitAccountsState): Promise => { setCodexAccounts(next) + setCodexAccountsLoaded(true) await fetchSettings() } @@ -700,6 +717,16 @@ export function AccountsPane({ the status-bar account switcher. Keeping a stable DOM anchor here avoids dumping the user at the top of Accounts and making them hunt for the actual Codex account controls. */} + {activeCodexAuthWarning ? ( +
+ + + {activeCodexAccountId + ? 'Codex reported that the active account needs a fresh sign-in. Re-authenticate it before starting new Codex sessions.' + : `Codex reported that the ${accountRuntime.label} login needs a fresh sign-in. Sign in again before starting new Codex sessions.`} + +
+ ) : null}
@@ -746,9 +773,11 @@ export function AccountsPane({ } disabled={codexAction !== 'idle' || accountRuntimeUnavailable} className={`flex w-full items-center justify-between gap-3 rounded-md border px-3 py-2.5 text-left transition-colors ${ - activeCodexAccountId === null - ? 'border-foreground/20 bg-accent/15' - : 'border-border/70 hover:border-border hover:bg-accent/8' + systemCodexNeedsReauthentication + ? 'border-destructive/50 bg-destructive/5' + : activeCodexAccountId === null + ? 'border-foreground/20 bg-accent/15' + : 'border-border/70 hover:border-border hover:bg-accent/8' } disabled:cursor-default disabled:opacity-100`} >
@@ -762,9 +791,23 @@ export function AccountsPane({ Active ) : null} + {systemCodexNeedsReauthentication ? ( + + Needs sign-in + + ) : null}
- - Use your current {accountRuntime.label} Codex login. + + {systemCodexNeedsReauthentication + ? `Codex reported this ${accountRuntime.label} login is out of date.` + : `Use your current ${accountRuntime.label} Codex login.`}
@@ -776,6 +819,14 @@ export function AccountsPane({ ) : ( visibleCodexAccounts.map((account) => { const isActive = activeCodexAccountId === account.id + const accountAuthWarning = getCodexAccountAuthWarning({ + limits: codexRateLimits, + target: codexRateLimitTarget, + runtime: accountRuntime, + activeAccountId: activeCodexAccountId, + accountId: account.id + }) + const needsReauthentication = Boolean(accountAuthWarning) const isReauthing = codexAction === `reauth:${account.id}` const isRemoving = codexAction === `remove:${account.id}` const isBusy = codexAction !== 'idle' || accountRuntimeUnavailable @@ -784,9 +835,11 @@ export function AccountsPane({
@@ -820,12 +873,28 @@ export function AccountsPane({ Active ) : null} + {needsReauthentication ? ( + + Needs re-auth + + ) : null}
-
- {account.workspaceLabel ? ( +
+ {needsReauthentication ? ( + + Codex reported this sign-in is out of date + + ) : account.workspaceLabel ? ( {account.workspaceLabel} ) : null} - {account.workspaceLabel ? ( + {needsReauthentication || account.workspaceLabel ? ( • ) : null} diff --git a/src/renderer/src/components/settings/accounts-search.ts b/src/renderer/src/components/settings/accounts-search.ts index 73016c18f..3057f9369 100644 --- a/src/renderer/src/components/settings/accounts-search.ts +++ b/src/renderer/src/components/settings/accounts-search.ts @@ -21,12 +21,22 @@ export const ACCOUNTS_CODEX_SEARCH_ENTRIES: SettingsSearchEntry[] = [ { title: 'Codex Accounts', description: 'Optional account switching for Codex and live rate limit fetching.', - keywords: ['codex', 'account', 'rate limit', 'status bar', 'quota', 'optional'] + keywords: [ + 'codex', + 'account', + 'rate limit', + 'status bar', + 'quota', + 'optional', + 'reauthenticate', + 'expired', + 'out of date' + ] }, { title: 'Active Codex Account', description: 'Choose which optional saved Codex account powers live quota reads.', - keywords: ['codex', 'account', 'switch', 'active', 'status bar', 'optional'] + keywords: ['codex', 'account', 'switch', 'active', 'status bar', 'optional', 'sign in'] } ] diff --git a/src/renderer/src/components/settings/codex-account-auth-warning.test.ts b/src/renderer/src/components/settings/codex-account-auth-warning.test.ts new file mode 100644 index 000000000..ea8de210b --- /dev/null +++ b/src/renderer/src/components/settings/codex-account-auth-warning.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from 'vitest' +import { isCodexAuthError } from '../../../../shared/codex-auth-errors' +import type { ProviderRateLimits } from '../../../../shared/rate-limit-types' +import { + codexRateLimitTargetMatchesAccountRuntime, + getCodexAccountAuthWarning +} from './codex-account-auth-warning' + +function codexLimits(error: string | null, status: ProviderRateLimits['status'] = 'error') { + return { + provider: 'codex', + session: null, + weekly: null, + updatedAt: 1, + error, + status + } satisfies ProviderRateLimits +} + +describe('codex account auth warning', () => { + it('recognizes Codex refresh-token failures as re-auth errors', () => { + expect( + isCodexAuthError( + 'Your access token could not be refreshed because your refresh token was already used. Please log out and sign in again.' + ) + ).toBe(true) + expect( + isCodexAuthError( + 'Error loading configuration: Your authentication session could not be refreshed automatically.' + ) + ).toBe(true) + }) + + it('does not treat generic Codex availability failures as auth errors', () => { + expect(isCodexAuthError('RPC timeout')).toBe(false) + expect( + isCodexAuthError('Codex CLI found but could not run - Node.js may not be in your PATH') + ).toBe(false) + }) + + it('matches the active host account on the current rate-limit target', () => { + expect( + getCodexAccountAuthWarning({ + limits: codexLimits( + 'Your access token could not be refreshed. Please log out and sign in again.' + ), + target: { runtime: 'host', wslDistro: null }, + runtime: { runtime: 'host' }, + activeAccountId: 'account-1', + accountId: 'account-1' + }) + ).toContain('access token could not be refreshed') + }) + + it('does not warn for inactive accounts or a different runtime', () => { + const limits = codexLimits( + 'Your access token could not be refreshed. Please log out and sign in again.' + ) + + expect( + getCodexAccountAuthWarning({ + limits, + target: { runtime: 'host', wslDistro: null }, + runtime: { runtime: 'host' }, + activeAccountId: 'account-1', + accountId: 'account-2' + }) + ).toBeNull() + expect( + getCodexAccountAuthWarning({ + limits, + target: { runtime: 'wsl', wslDistro: 'Ubuntu' }, + runtime: { runtime: 'host' }, + activeAccountId: 'account-1', + accountId: 'account-1' + }) + ).toBeNull() + }) + + it('allows a WSL default account location to receive the active WSL target warning', () => { + expect( + codexRateLimitTargetMatchesAccountRuntime( + { runtime: 'wsl', wslDistro: 'Ubuntu' }, + { runtime: 'wsl', wslDistro: null } + ) + ).toBe(true) + }) +}) diff --git a/src/renderer/src/components/settings/codex-account-auth-warning.ts b/src/renderer/src/components/settings/codex-account-auth-warning.ts new file mode 100644 index 000000000..b9d824576 --- /dev/null +++ b/src/renderer/src/components/settings/codex-account-auth-warning.ts @@ -0,0 +1,42 @@ +import type { + ProviderRateLimits, + RateLimitRuntimeTarget +} from '../../../../shared/rate-limit-types' +import { isCodexAuthError } from '../../../../shared/codex-auth-errors' + +type AccountRuntime = { + runtime: 'host' | 'wsl' + wslDistro?: string | null +} + +export function codexRateLimitTargetMatchesAccountRuntime( + target: RateLimitRuntimeTarget, + runtime: AccountRuntime +): boolean { + if (target.runtime !== runtime.runtime) { + return false + } + if (runtime.runtime === 'host') { + return true + } + return !runtime.wslDistro || target.wslDistro === runtime.wslDistro +} + +export function getCodexAccountAuthWarning(args: { + limits: ProviderRateLimits | null + target: RateLimitRuntimeTarget + runtime: AccountRuntime + activeAccountId: string | null + accountId: string | null +}): string | null { + if (args.accountId !== args.activeAccountId) { + return null + } + if (!codexRateLimitTargetMatchesAccountRuntime(args.target, args.runtime)) { + return null + } + if (args.limits?.status !== 'error' || !isCodexAuthError(args.limits.error)) { + return null + } + return args.limits.error?.trim() || 'Codex reported that this sign-in needs re-authentication.' +} diff --git a/src/shared/codex-auth-errors.ts b/src/shared/codex-auth-errors.ts new file mode 100644 index 000000000..8a31aabd4 --- /dev/null +++ b/src/shared/codex-auth-errors.ts @@ -0,0 +1,37 @@ +const CODEX_AUTH_ERROR_PATTERNS = [ + /access token could not be refreshed/i, + /authentication session could not be refreshed/i, + /refresh token (?:has expired|was already used|was revoked)/i, + /you have since logged out or signed in to another account/i, + /please (?:log out and )?sign in again/i, + /please reauthenticate/i, + /not logged in/i, + /token data is not available/i, + /auth (?:is missing|tokens are missing|does not expose)/i +] +const ANSI_ESCAPE_RE = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[a-zA-Z]`, 'g') + +export function isCodexAuthError(error: string | null | undefined): boolean { + const message = error?.trim() + if (!message) { + return false + } + return CODEX_AUTH_ERROR_PATTERNS.some((pattern) => pattern.test(message)) +} + +export function extractCodexAuthError(output: string | null | undefined): string | null { + const cleanOutput = output?.replace(ANSI_ESCAPE_RE, '').trim() + if (!cleanOutput) { + return null + } + + const matchingLine = cleanOutput + .split(/\r?\n/) + .map((line) => line.trim()) + .find(isCodexAuthError) + if (matchingLine) { + return matchingLine + } + + return isCodexAuthError(cleanOutput) ? cleanOutput.slice(0, 4_000) : null +}