From 8e8a08ac7cef393677f7ec578de57ffebf94f7c9 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Thu, 2 Jul 2026 17:45:15 -0700 Subject: [PATCH] fix: supplement Claude Fable usage from CLI (#7167) --- src/main/rate-limits/claude-fetcher.test.ts | 105 ++++++++++++++++++++ src/main/rate-limits/claude-fetcher.ts | 72 +++++++++++++- src/main/rate-limits/service.test.ts | 17 ++-- src/main/rate-limits/service.ts | 12 ++- 4 files changed, 196 insertions(+), 10 deletions(-) diff --git a/src/main/rate-limits/claude-fetcher.test.ts b/src/main/rate-limits/claude-fetcher.test.ts index 0790374ce..24ee44f7c 100644 --- a/src/main/rate-limits/claude-fetcher.test.ts +++ b/src/main/rate-limits/claude-fetcher.test.ts @@ -205,6 +205,111 @@ describe('fetchClaudeRateLimits', () => { }) }) + it('supplements managed-account OAuth usage with Fable from the CLI usage panel', async () => { + const configDir = '/Users/test/.claude' + const authPreparation: ClaudeRuntimeAuthPreparation = { + configDir, + envPatch: { CLAUDE_CONFIG_DIR: configDir }, + stripAuthEnv: false, + provenance: 'managed:account-1' + } + vi.mocked(readActiveClaudeKeychainCredentialsStrict).mockResolvedValueOnce( + JSON.stringify({ + claudeAiOauth: { + accessToken: 'oauth-token', + expiresAt: Date.now() + 60_000 + } + }) + ) + netFetchMock.mockResolvedValueOnce( + new Response( + JSON.stringify({ + five_hour: { used_percentage: 23.5, resets_at: 1770000000 }, + seven_day: { used_percentage: 41.2, resets_at: 1770604800 } + }), + { status: 200 } + ) + ) + vi.mocked(fetchViaPty).mockResolvedValueOnce({ + provider: 'claude', + session: { usedPercent: 91, windowMinutes: 300, resetsAt: null, resetDescription: null }, + weekly: null, + fableWeekly: { + usedPercent: 12.3, + windowMinutes: 10080, + resetsAt: null, + resetDescription: '3d 2h' + }, + updatedAt: 1, + error: null, + status: 'ok' + }) + + await expect(fetchClaudeRateLimits({ authPreparation })).resolves.toMatchObject({ + provider: 'claude', + status: 'ok', + session: { usedPercent: 23.5, resetsAt: 1770000000000 }, + weekly: { usedPercent: 41.2, resetsAt: 1770604800000 }, + fableWeekly: { usedPercent: 12.3, resetDescription: '3d 2h' }, + usageMetadata: { + source: 'oauth', + attemptedSources: ['oauth', 'cli'] + } + }) + expect(fetchViaPty).toHaveBeenCalledWith({ authPreparation }) + }) + + it('supplements system OAuth usage when the service explicitly allows usage-panel reads', async () => { + const configDir = '/Users/test/.claude' + const authPreparation: ClaudeRuntimeAuthPreparation = { + configDir, + envPatch: { CLAUDE_CONFIG_DIR: configDir }, + stripAuthEnv: false, + provenance: 'system' + } + vi.mocked(readActiveClaudeKeychainCredentialsStrict).mockResolvedValueOnce( + JSON.stringify({ + claudeAiOauth: { + accessToken: 'oauth-token', + expiresAt: Date.now() + 60_000 + } + }) + ) + vi.mocked(fetchViaPty).mockResolvedValueOnce({ + provider: 'claude', + session: null, + weekly: null, + fableWeekly: { + usedPercent: 58, + windowMinutes: 10080, + resetsAt: null, + resetDescription: '4d' + }, + updatedAt: 1, + error: null, + status: 'ok' + }) + + await expect( + fetchClaudeRateLimits({ + authPreparation, + allowPtyFallback: false, + allowUsagePanelSupplement: true + }) + ).resolves.toMatchObject({ + provider: 'claude', + status: 'ok', + session: { usedPercent: 12 }, + weekly: { usedPercent: 34 }, + fableWeekly: { usedPercent: 58, resetDescription: '4d' }, + usageMetadata: { + source: 'oauth', + attemptedSources: ['oauth', 'cli'] + } + }) + expect(fetchViaPty).toHaveBeenCalledWith({ authPreparation }) + }) + it('ignores bare Fable OAuth usage because the window length is ambiguous', async () => { const configDir = '/Users/test/.claude' const authPreparation: ClaudeRuntimeAuthPreparation = { diff --git a/src/main/rate-limits/claude-fetcher.ts b/src/main/rate-limits/claude-fetcher.ts index c89aef047..5f283e58e 100644 --- a/src/main/rate-limits/claude-fetcher.ts +++ b/src/main/rate-limits/claude-fetcher.ts @@ -518,6 +518,64 @@ async function fetchClaudeUsageViaCli(input: { ) } +function isManagedClaudeAuth(authPreparation: ClaudeRuntimeAuthPreparation | undefined): boolean { + return authPreparation?.provenance.startsWith('managed:') === true +} + +function canSupplementOAuthUsageFromCli(input: { + oauthLimits: ProviderRateLimits + authPreparation?: ClaudeRuntimeAuthPreparation + allowUsagePanelSupplement: boolean +}): boolean { + // Why: Fable is visible in Claude's interactive /usage panel even when the + // OAuth usage endpoint only reports documented 5h/7d windows. This runs only + // after OAuth succeeds, so it must not become a broad auth-recovery fallback. + return Boolean( + input.allowUsagePanelSupplement && + !input.authPreparation?.managedRefreshDeferredByLivePty && + !input.oauthLimits.fableWeekly && + (input.oauthLimits.session || input.oauthLimits.weekly) + ) +} + +function mergeClaudeUsageWindows( + primary: ProviderRateLimits, + supplement: ProviderRateLimits | null +): ProviderRateLimits { + if (!supplement) { + return primary + } + return { + ...primary, + session: primary.session ?? supplement.session, + weekly: primary.weekly ?? supplement.weekly, + fableWeekly: primary.fableWeekly ?? supplement.fableWeekly ?? null + } +} + +async function supplementOAuthUsageFromCli(input: { + oauthLimits: ProviderRateLimits + authPreparation?: ClaudeRuntimeAuthPreparation + oauthCredentials: OAuthCredentialReadResult + attempts: ClaudeUsageAttemptState + allowUsagePanelSupplement: boolean +}): Promise { + if (!canSupplementOAuthUsageFromCli(input)) { + return input.oauthLimits + } + try { + const cliLimits = await fetchClaudeUsageViaCli({ + authPreparation: input.authPreparation, + oauthCredentials: input.oauthCredentials, + attempts: input.attempts + }) + return mergeClaudeUsageWindows(input.oauthLimits, cliLimits) + } catch (err) { + warnClaudeUsageFetchFailure(input.authPreparation, input.oauthCredentials, err) + return input.oauthLimits + } +} + function shouldDeferForLiveClaude( authPreparation: ClaudeRuntimeAuthPreparation | undefined, classification: ClaudeUsageErrorClassification @@ -588,8 +646,9 @@ async function attemptCliRepairThenRetryOAuth(input: { recordAttempt(input.attempts, 'oauth') try { const oauthRetry = await fetchViaOAuth(refreshedCredentials.token) + const supplemented = mergeClaudeUsageWindows(oauthRetry, cliResult) return withClaudeUsageMetadata( - oauthRetry, + supplemented, metadataForAttempt({ attemptedSources: input.attempts.attemptedSources, oauthCredentials: refreshedCredentials, @@ -612,6 +671,7 @@ async function attemptCliRepairThenRetryOAuth(input: { export type FetchClaudeRateLimitsOptions = { authPreparation?: ClaudeRuntimeAuthPreparation allowPtyFallback?: boolean + allowUsagePanelSupplement?: boolean } export async function fetchClaudeRateLimits( @@ -643,7 +703,15 @@ export async function fetchClaudeRateLimits( if (plan.steps.some((step) => step.source === 'oauth') && oauthCredentials.token) { recordAttempt(attempts, 'oauth') try { - const limits = await fetchViaOAuth(oauthCredentials.token) + const oauthLimits = await fetchViaOAuth(oauthCredentials.token) + const limits = await supplementOAuthUsageFromCli({ + oauthLimits, + authPreparation: options?.authPreparation, + oauthCredentials, + attempts, + allowUsagePanelSupplement: + options?.allowUsagePanelSupplement ?? isManagedClaudeAuth(options?.authPreparation) + }) return withClaudeUsageMetadata( limits, metadataForAttempt({ diff --git a/src/main/rate-limits/service.test.ts b/src/main/rate-limits/service.test.ts index 303942462..c5c389bd0 100644 --- a/src/main/rate-limits/service.test.ts +++ b/src/main/rate-limits/service.test.ts @@ -353,7 +353,8 @@ describe('RateLimitService', () => { expect(fetchClaudeRateLimits).toHaveBeenCalledTimes(1) expect(fetchClaudeRateLimits).toHaveBeenCalledWith({ authPreparation: undefined, - allowPtyFallback: false + allowPtyFallback: false, + allowUsagePanelSupplement: true }) expect(fetchCodexRateLimits).toHaveBeenCalledTimes(1) expect(fetchGeminiRateLimits).toHaveBeenCalledTimes(1) @@ -459,7 +460,8 @@ describe('RateLimitService', () => { wslLinuxConfigDir: '/home/jin/.claude', stripAuthEnv: true }), - allowPtyFallback: true + allowPtyFallback: true, + allowUsagePanelSupplement: true }) expect(service.getState().claudeTarget).toEqual({ runtime: 'wsl', wslDistro: 'Ubuntu' }) }) @@ -483,7 +485,8 @@ describe('RateLimitService', () => { expect(fetchClaudeRateLimits).toHaveBeenCalledWith({ authPreparation: expect.objectContaining({ provenance: 'system' }), - allowPtyFallback: false + allowPtyFallback: false, + allowUsagePanelSupplement: true }) }) @@ -497,7 +500,8 @@ describe('RateLimitService', () => { expect(fetchClaudeRateLimits).toHaveBeenCalledWith({ authPreparation: undefined, - allowPtyFallback: false + allowPtyFallback: false, + allowUsagePanelSupplement: true }) }) @@ -521,7 +525,8 @@ describe('RateLimitService', () => { expect(fetchClaudeRateLimits).toHaveBeenCalledWith({ authPreparation: expect.objectContaining({ provenance: 'wsl:Ubuntu:system' }), - allowPtyFallback: false + allowPtyFallback: false, + allowUsagePanelSupplement: true }) }) @@ -580,7 +585,7 @@ describe('RateLimitService', () => { }) expect(fetchClaudeRateLimits).toHaveBeenLastCalledWith( - expect.objectContaining({ allowPtyFallback: true }) + expect.objectContaining({ allowPtyFallback: true, allowUsagePanelSupplement: true }) ) expect(service.getState().inactiveClaudeAccounts).not.toEqual( diff --git a/src/main/rate-limits/service.ts b/src/main/rate-limits/service.ts index 42d8f8c35..af7431bca 100644 --- a/src/main/rate-limits/service.ts +++ b/src/main/rate-limits/service.ts @@ -818,6 +818,12 @@ export class RateLimitService { return !isSystemDefaultClaudeAuth(authPreparation) } + private shouldAllowClaudeUsagePanelSupplement(): boolean { + // Why: this supplement runs only after OAuth has already returned usage + // data. Keep it off on Windows where hidden PTYs are still less reliable. + return process.platform !== 'win32' + } + private withFetchingStatus( current: ProviderRateLimits | null, provider: 'claude' | 'codex' | 'gemini' | 'opencode-go' | 'kimi' @@ -881,7 +887,8 @@ export class RateLimitService { await Promise.allSettled([ fetchClaudeRateLimits({ authPreparation: claudeAuthPreparation, - allowPtyFallback: this.shouldAllowClaudePtyFallback(claudeAuthPreparation) + allowPtyFallback: this.shouldAllowClaudePtyFallback(claudeAuthPreparation), + allowUsagePanelSupplement: this.shouldAllowClaudeUsagePanelSupplement() }), missingWslCodexHome ?? fetchCodexRateLimits({ @@ -1056,7 +1063,8 @@ export class RateLimitService { const claude = await fetchClaudeRateLimits({ authPreparation: claudeAuthPreparation, - allowPtyFallback: this.shouldAllowClaudePtyFallback(claudeAuthPreparation) + allowPtyFallback: this.shouldAllowClaudePtyFallback(claudeAuthPreparation), + allowUsagePanelSupplement: this.shouldAllowClaudeUsagePanelSupplement() }).catch( (err): ProviderRateLimits => ({ provider: 'claude',