fix: surface codex account auth errors (#3510)

This commit is contained in:
Jinjing
2026-05-30 00:07:22 -07:00
committed by GitHub
parent 504b98d873
commit 6b8a2b6b26
7 changed files with 397 additions and 16 deletions
@@ -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<typeof vi.fn> }
kill: ReturnType<typeof vi.fn>
}
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
})
})
})
+7 -2
View File
@@ -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<Provi
session: null,
weekly: null,
updatedAt: Date.now(),
error: withMacTailscaleDnsHint('PTY timeout', output),
error: extractCodexAuthError(output) ?? withMacTailscaleDnsHint('PTY timeout', output),
status: 'error'
})
}
@@ -464,7 +465,8 @@ async function fetchViaPty(options?: FetchCodexRateLimitsOptions): Promise<Provi
error:
session || weekly
? null
: withMacTailscaleDnsHint('CLI exited before status was available', clean),
: (extractCodexAuthError(clean) ??
withMacTailscaleDnsHint('CLI exited before status was available', clean)),
status: session || weekly ? 'ok' : 'error'
})
}
@@ -488,6 +490,9 @@ export async function fetchCodexRateLimits(
if (rpcResult.status === 'ok' || rpcResult.status === 'unavailable') {
return rpcResult
}
if (isCodexAuthError(rpcResult.error)) {
return rpcResult
}
if (options?.allowPtyFallback === false) {
return rpcResult
}
@@ -15,7 +15,7 @@ import { Input } from '../ui/input'
import { Label } from '../ui/label'
import { Separator } from '../ui/separator'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select'
import { Loader2, Plus, RefreshCw, Trash2 } from 'lucide-react'
import { AlertTriangle, Loader2, Plus, RefreshCw, Trash2 } from 'lucide-react'
import { useAppStore } from '../../store'
import { ClaudeIcon, GeminiIcon, OpenAIIcon, OpenCodeGoIcon } from '../status-bar/icons'
import { toast } from 'sonner'
@@ -39,6 +39,7 @@ import {
DialogHeader,
DialogTitle
} from '../ui/dialog'
import { getCodexAccountAuthWarning } from './codex-account-auth-warning'
export { ACCOUNTS_PANE_SEARCH_ENTRIES }
@@ -234,6 +235,8 @@ export function AccountsPane({
wslCapabilitiesLoading = false
}: AccountsPaneProps): React.JSX.Element {
const searchQuery = useAppStore((s) => 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<Set<'cookie' | 'workspaceId'>>(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<void> => {
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 ? (
<div className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive">
<AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
<span>
{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.`}
</span>
</div>
) : null}
<div className="flex items-center justify-between gap-3">
<div className="space-y-0.5">
<Label>Accounts</Label>
@@ -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`}
>
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
@@ -762,9 +791,23 @@ export function AccountsPane({
Active
</Badge>
) : null}
{systemCodexNeedsReauthentication ? (
<Badge
variant="destructive"
className="h-4 shrink-0 rounded px-1.5 text-[10px] font-medium leading-none"
>
Needs sign-in
</Badge>
) : null}
</div>
<span className="truncate text-[11px] text-muted-foreground">
Use your current {accountRuntime.label} Codex login.
<span
className={`truncate text-[11px] ${
systemCodexNeedsReauthentication ? 'text-destructive' : 'text-muted-foreground'
}`}
>
{systemCodexNeedsReauthentication
? `Codex reported this ${accountRuntime.label} login is out of date.`
: `Use your current ${accountRuntime.label} Codex login.`}
</span>
</div>
</button>
@@ -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({
<div
key={account.id}
className={`flex w-full items-center justify-between gap-3 rounded-md border px-3 py-2.5 text-left transition-colors ${
isActive
? 'border-foreground/20 bg-accent/15'
: 'border-border/70 hover:border-border hover:bg-accent/8'
needsReauthentication
? 'border-destructive/50 bg-destructive/5'
: isActive
? 'border-foreground/20 bg-accent/15'
: 'border-border/70 hover:border-border hover:bg-accent/8'
}`}
>
<div className="flex w-full items-center justify-between gap-3 max-md:flex-col max-md:items-start">
@@ -820,12 +873,28 @@ export function AccountsPane({
Active
</Badge>
) : null}
{needsReauthentication ? (
<Badge
variant="destructive"
className="h-4 shrink-0 rounded px-1.5 text-[10px] font-medium leading-none"
>
Needs re-auth
</Badge>
) : null}
</div>
<div className="flex min-w-0 items-center gap-1.5 text-[11px] text-muted-foreground max-sm:flex-wrap">
{account.workspaceLabel ? (
<div
className={`flex min-w-0 items-center gap-1.5 text-[11px] max-sm:flex-wrap ${
needsReauthentication ? 'text-destructive' : 'text-muted-foreground'
}`}
>
{needsReauthentication ? (
<span className="truncate">
Codex reported this sign-in is out of date
</span>
) : account.workspaceLabel ? (
<span className="truncate">{account.workspaceLabel}</span>
) : null}
{account.workspaceLabel ? (
{needsReauthentication || account.workspaceLabel ? (
<span className="shrink-0 opacity-50">•</span>
) : null}
<span className="shrink-0">
@@ -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']
}
]
@@ -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)
})
})
@@ -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.'
}
+37
View File
@@ -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
}