fix: supplement Claude Fable usage from CLI (#7167)

This commit is contained in:
Neil
2026-07-02 17:45:15 -07:00
committed by GitHub
parent 2fff91e289
commit 8e8a08ac7c
4 changed files with 196 additions and 10 deletions
+105
View File
@@ -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 = {
+70 -2
View File
@@ -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<ProviderRateLimits> {
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({
+11 -6
View File
@@ -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(
+10 -2
View File
@@ -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',