Skip to content
Closed
14 changes: 14 additions & 0 deletions src/main/rate-limits/claude-active-usage-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,24 @@ export async function fetchActiveClaudeRateLimits(

const credentialClassification = classifyClaudeCredentialAbsence({
hasRefreshableCredentials: oauthCredentials.hasRefreshableCredentials,
hasEmptyStoredEntry: oauthCredentials.hasEmptyStoredEntry,
keychainUnavailable: oauthCredentials.keychainUnavailable,
managedRefreshDeferredByLivePty: options?.authPreparation?.managedRefreshDeferredByLivePty
})

// Why: terminal signed-out means there is no token to try and no CLI
// fallback is sanctioned — return before any refresh or PTY attempts.
if (credentialClassification.failureKind === 'signed-out') {
return makeClaudeUsageResult('error', 'Claude sign-in expired', {
...metadataForClaudeUsageAttempt({
attemptedSources: attempts.attemptedSources,
oauthCredentials,
authPreparation: options?.authPreparation,
failureKind: 'signed-out'
})
})
}

if (shouldDeferClaudeUsageForLiveSession(options?.authPreparation, credentialClassification)) {
return makeLiveClaudeUsageDeferredResult({
attempts,
Expand Down
50 changes: 50 additions & 0 deletions src/main/rate-limits/claude-fetcher-keychain-credentials.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,56 @@ describe('fetchClaudeRateLimits', () => {
)
})

it('reports signed-out instead of unavailable when the Keychain entry holds no tokens', async () => {
const configDir = '/Users/test/.claude'
const authPreparation: ClaudeRuntimeAuthPreparation = {
configDir,
runtime: 'host',
envPatch: {},
stripAuthEnv: false,
provenance: 'system'
}
vi.mocked(readActiveClaudeKeychainCredentialsStrict)
.mockResolvedValueOnce(null)
.mockResolvedValueOnce(
JSON.stringify({
claudeAiOauth: { accessToken: '', refreshToken: '', expiresAt: 0 }
})
)

// Why: no allowPtyFallback override — signed-out must return before the
// generic CLI plan step even when the caller allows PTY fallback.
await expect(fetchClaudeRateLimits({ authPreparation })).resolves.toMatchObject({
provider: 'claude',
status: 'error',
error: 'Claude sign-in expired',
usageMetadata: {
failureKind: 'signed-out',
credentialSource: 'legacy-keychain',
authProvenance: 'system'
}
})

expect(netFetchMock).not.toHaveBeenCalled()
expect(fetchViaPty).not.toHaveBeenCalled()
})

it('reports signed-out when only the credentials file holds an emptied entry', async () => {
readFileMock.mockResolvedValue(
JSON.stringify({ claudeAiOauth: { accessToken: '', refreshToken: '' } })
)

await expect(fetchClaudeRateLimits({ allowPtyFallback: false })).resolves.toMatchObject({
provider: 'claude',
status: 'error',
error: 'Claude sign-in expired',
usageMetadata: { failureKind: 'signed-out', credentialSource: 'credentials-file' }
})

expect(netFetchMock).not.toHaveBeenCalled()
expect(fetchViaPty).not.toHaveBeenCalled()
})

it('tries OAuth usage even when local credential metadata is expired', async () => {
const configDir = '/Users/test/.claude'
const authPreparation: ClaudeRuntimeAuthPreparation = {
Expand Down
40 changes: 33 additions & 7 deletions src/main/rate-limits/claude-oauth-credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ export type ClaudeOAuthCredentialReadResult = {
hasRefreshableCredentials: boolean
source: ClaudeOAuthCredentialSource
keychainUnavailable?: boolean
// Why: a stored entry with blank tokens means signed-out, not
// never-configured — the status bar shows a sign-in state instead of hiding.
hasEmptyStoredEntry?: boolean
}

type ClaudeOAuthCredentialReadOptions = {
Expand All @@ -41,11 +44,24 @@ export function parseClaudeOAuthCredentialsJson(
const oauth = (JSON.parse(raw) as ClaudeCredentials)?.claudeAiOauth
const hasRefreshableCredentials =
typeof oauth?.refreshToken === 'string' && oauth.refreshToken.trim() !== ''
if (!oauth?.accessToken || typeof oauth.accessToken !== 'string') {
return { token: null, hasRefreshableCredentials, source }
// Why: a whitespace-only token is unusable — treat it as absent so the
// entry counts as emptied (signed-out) instead of reaching the OAuth path.
const accessToken =
typeof oauth?.accessToken === 'string' && oauth.accessToken.trim() !== ''
? oauth.accessToken.trim()
: null
if (accessToken == null) {
return {
token: null,
hasRefreshableCredentials,
source,
...(oauth != null && !hasRefreshableCredentials
? { hasEmptyStoredEntry: true as const }
: {})
}
}
// Why: expiresAt is not authoritative for the usage endpoint; let the server decide.
return { token: oauth.accessToken, hasRefreshableCredentials, source }
return { token: accessToken, hasRefreshableCredentials, source }
} catch {
return emptyClaudeOAuthCredentialReadResult()
}
Expand Down Expand Up @@ -86,9 +102,10 @@ async function readFromKeychain(configDir?: string): Promise<ClaudeOAuthCredenti
if (legacy.hasRefreshableCredentials) {
return legacy
}
return scoped.keychainUnavailable || legacy.keychainUnavailable
? unavailableKeychainResult()
: legacy
if (scoped.keychainUnavailable || legacy.keychainUnavailable) {
return unavailableKeychainResult()
}
return scoped.hasEmptyStoredEntry ? scoped : legacy
}

try {
Expand Down Expand Up @@ -144,7 +161,16 @@ export async function readClaudeOAuthCredentials(
if (file.token || file.hasRefreshableCredentials) {
return file
}
return keychain.keychainUnavailable ? keychain : emptyClaudeOAuthCredentialReadResult()
if (keychain.keychainUnavailable) {
return keychain
}
if (keychain.hasEmptyStoredEntry) {
return keychain
}
if (file.hasEmptyStoredEntry) {
return file
}
return emptyClaudeOAuthCredentialReadResult()
}

export function resolveClaudeOAuthCredentialReadOptions(
Expand Down
14 changes: 14 additions & 0 deletions src/main/rate-limits/claude-usage-error-classification.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,20 @@ describe('classifyClaudeCredentialAbsence', () => {
})
})

it('classifies a stored-but-empty entry as signed-out, not missing', () => {
expect(
classifyClaudeCredentialAbsence({
hasRefreshableCredentials: false,
hasEmptyStoredEntry: true
})
).toMatchObject({
failureKind: 'signed-out',
shouldAttemptCliFallback: false,
shouldAttemptDelegatedRefresh: false,
terminal: true
})
})

it('classifies live Claude ownership as a deferred state', () => {
expect(
classifyClaudeCredentialAbsence({
Expand Down
4 changes: 4 additions & 0 deletions src/main/rate-limits/claude-usage-error-classification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,16 @@ export function classifyClaudeOAuthUsageError(error: unknown): ClaudeUsageErrorC

export function classifyClaudeCredentialAbsence(input: {
hasRefreshableCredentials: boolean
hasEmptyStoredEntry?: boolean
keychainUnavailable?: boolean
managedRefreshDeferredByLivePty?: boolean
}): ClaudeUsageErrorClassification {
if (input.managedRefreshDeferredByLivePty) {
return terminal('deferred-by-live-session')
}
if (input.hasEmptyStoredEntry) {
return terminal('signed-out')
}
if (input.keychainUnavailable) {
return fallbackOnly('keychain-unavailable')
}
Expand Down
21 changes: 21 additions & 0 deletions src/renderer/src/components/settings/AccountsPane.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
import { getRemoteAccountsPaneScope } from './provider-account-scope'
import { ProviderHostScopeControl } from './ProviderHostScopeControl'
import { matchesSettingsSearch } from './settings-search'
import { getClaudeSystemDefaultSignInWarning } from './claude-account-auth-warning'
import { getCodexAccountAuthWarning } from './codex-account-auth-warning'
import { getCodexConfigSyncWarning } from './codex-config-sync-warning'
import {
Expand Down Expand Up @@ -72,6 +73,8 @@ export function AccountsPane({
accountOwnerPlatform = null
}: AccountsPaneProps): React.JSX.Element {
const searchQuery = useAppStore((s) => s.settingsSearchQuery)
const claudeRateLimits = useAppStore((s) => s.rateLimits.claude)
const claudeRateLimitTarget = useAppStore((s) => s.rateLimits.claudeTarget)
const codexRateLimits = useAppStore((s) => s.rateLimits.codex)
const codexRateLimitTarget = useAppStore((s) => s.rateLimits.codexTarget)
const miniMaxRateLimits = useAppStore((s) => s.rateLimits.minimax)
Expand Down Expand Up @@ -143,6 +146,7 @@ export function AccountsPane({
const [codexAction, setCodexAction] = useState<CodexAccountAction>('idle')
const [claudeAccounts, setClaudeAccounts] =
useState<ClaudeRateLimitAccountsState>(emptyClaudeAccountsState)
const [claudeAccountsLoaded, setClaudeAccountsLoaded] = useState(false)
const [claudeAction, setClaudeAction] = useState<ClaudeAccountAction>('idle')
// Why: capture the account's runtime slot when the dialog opens; the roster
// can change underneath an open dialog and lose the slot to diff for restarts.
Expand Down Expand Up @@ -213,6 +217,16 @@ export function AccountsPane({
const codexConfigSyncWarning = getCodexConfigSyncWarning(codexConfigSync)
const systemCodexMissingSignIn = activeCodexAuthWarning === 'missing-sign-in'
const systemCodexNeedsSignIn = activeCodexAccountId === null && Boolean(activeCodexAuthWarning)
// Why: remote snapshots own their system-default login, but the desktop's
// usage poll must not be misattributed to a remote account owner (#7973).
const systemClaudeNeedsSignIn =
claudeAccountsLoaded &&
getClaudeSystemDefaultSignInWarning({
limits: isRemoteAccountScope ? null : claudeRateLimits,
target: claudeRateLimitTarget,
runtime: accountRuntime,
systemActive: systemClaudeActive
})
const accountRuntimeUnavailable =
accountRuntime.runtime === 'wsl' && !wslAvailable && !wslCapabilitiesLoading

Expand Down Expand Up @@ -249,6 +263,10 @@ export function AccountsPane({
}, [])

useEffect(() => {
// Why: a runtime switch replaces the roster underneath; keep the loaded
// gate shut until the new owner's snapshot arrives so empty-roster
// derivations (like the system-default warning) cannot flash stale state.
setClaudeAccountsLoaded(false)
// Why: remote snapshots stream usage refreshes after the synchronous ready
// message, so the watcher stays open for the pane's lifetime; the local
// path resolves once and the close() is a no-op.
Expand All @@ -264,6 +282,7 @@ export function AccountsPane({
}
if (!snapshot.failedProviders?.includes('claude')) {
setClaudeAccounts(snapshot.claude)
setClaudeAccountsLoaded(true)
}
},
onError: (error) => {
Expand Down Expand Up @@ -299,6 +318,7 @@ export function AccountsPane({
isRemoteAccountScope,
claudeAccounts,
setClaudeAccounts,
setClaudeAccountsLoaded,
setClaudeAction,
fetchSettings,
recordFeatureInteraction
Expand All @@ -325,6 +345,7 @@ export function AccountsPane({
claudeAction,
visibleClaudeAccounts,
systemClaudeActive,
systemClaudeNeedsSignIn,
setRemoveClaudeTarget,
runClaudeAccountAction,
codexAccounts,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ type ClaudeActionContext = {
isRemoteAccountScope: boolean
claudeAccounts: ClaudeRateLimitAccountsState
setClaudeAccounts: Dispatch<SetStateAction<ClaudeRateLimitAccountsState>>
setClaudeAccountsLoaded: Dispatch<SetStateAction<boolean>>
setClaudeAction: Dispatch<SetStateAction<ClaudeAccountAction>>
fetchSettings: () => Promise<void>
recordFeatureInteraction: (featureId: FeatureInteractionId) => void
Expand All @@ -159,10 +160,12 @@ export function createClaudeAccountActionRunner(
isRemoteAccountScope,
recordFeatureInteraction,
setClaudeAccounts,
setClaudeAccountsLoaded,
setClaudeAction
} = context
const syncClaudeAccounts = async (next: ClaudeRateLimitAccountsState): Promise<void> => {
setClaudeAccounts(next)
setClaudeAccountsLoaded(true)
if (!isRemoteAccountScope) {
await fetchSettings()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export function renderClaudeAccountsSection(model: AccountsPaneSectionModel): Re
setRemoveClaudeTarget,
settings,
systemClaudeActive,
systemClaudeNeedsSignIn,
visibleClaudeAccounts,
wslCapabilitiesLoading
} = model
Expand Down Expand Up @@ -131,26 +132,38 @@ export function renderClaudeAccountsSection(model: AccountsPaneSectionModel): Re
}
disabled={claudeAction !== 'idle' || accountRuntimeUnavailable}
className={`flex w-full items-center justify-between gap-3 rounded-md border px-3 py-2.5 text-left transition-colors ${
systemClaudeActive
? 'border-foreground/20 bg-accent/15'
: 'border-border/70 hover:border-border hover:bg-accent/8'
systemClaudeNeedsSignIn
? 'border-destructive/50 bg-destructive/5'
: systemClaudeActive
? '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">
<div className="flex min-w-0 items-center gap-2">
<span className="truncate text-sm font-medium">
{translate('auto.components.settings.AccountsPane.f2a265f8c7', 'System default')}
</span>
{systemClaudeActive ? (
{/* Why: a row cannot read as both selected-healthy and broken — the warning replaces Active, not joins it. */}
{systemClaudeActive && !systemClaudeNeedsSignIn ? (
<Badge
variant="outline"
className="h-4 shrink-0 rounded px-1.5 text-[10px] font-medium leading-none text-foreground/80"
>
{translate('auto.components.settings.AccountsPane.e74831fb6b', 'Active')}
</Badge>
) : null}
{systemClaudeNeedsSignIn ? (
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
<Badge variant="destructive" size="compact">
{translate('auto.components.settings.AccountsPane.93c47b333a', 'Needs sign-in')}
</Badge>
) : null}
</div>
<span className="truncate text-[11px] text-muted-foreground">
<span
className={`truncate text-[11px] ${
systemClaudeNeedsSignIn ? 'text-destructive' : 'text-muted-foreground'
}`}
>
{translate(
'auto.components.settings.AccountsPane.e05d0ff737',
'Use your current {{value0}} Claude login.',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ export type AccountsPaneSectionModel = {
claudeAction: ClaudeAccountAction
visibleClaudeAccounts: ClaudeRateLimitAccountsState['accounts']
systemClaudeActive: boolean
systemClaudeNeedsSignIn: boolean
setRemoveClaudeTarget: Dispatch<SetStateAction<RemoveAccountTarget | null>>
runClaudeAccountAction: ClaudeAccountActionRunner
codexAccounts: CodexRateLimitAccountsState
Expand Down
Loading