Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 194 additions & 0 deletions src/main/rate-limits/claude-fetcher-extra-usage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'
import { fetchClaudeRateLimits } from './claude-fetcher'
import { primeClaudeFetcherMocks, restorePlatform } from './claude-fetcher-test-harness'
import { readActiveClaudeKeychainCredentialsStrict } from '../claude-accounts/keychain'
import type { ClaudeRuntimeAuthPreparation } from '../claude-accounts/runtime-auth-service'

const { netFetchMock, readFileMock, resolveProxyMock, setProxyMock, appGetPathMock } = vi.hoisted(
() => ({
netFetchMock: vi.fn(),
readFileMock: vi.fn(),
resolveProxyMock: vi.fn(),
setProxyMock: vi.fn(),
appGetPathMock: vi.fn()
})
)

vi.mock('node:fs/promises', () => ({
readFile: readFileMock
}))

vi.mock('electron', () => ({
app: {
getPath: appGetPathMock
},
net: {
fetch: netFetchMock
},
session: {
defaultSession: {
resolveProxy: resolveProxyMock,
setProxy: setProxyMock
}
}
}))

vi.mock('./claude-pty', () => ({
fetchViaPty: vi.fn()
}))

vi.mock('../claude-accounts/keychain', () => ({
deleteActiveClaudeKeychainCredentialsStrict: vi.fn(),
readActiveClaudeKeychainCredentials: vi.fn(),
readActiveClaudeKeychainCredentialsStrict: vi.fn(),
readManagedClaudeKeychainCredentials: vi.fn(),
writeActiveClaudeKeychainCredentials: vi.fn(),
writeManagedClaudeKeychainCredentials: vi.fn()
}))

function oauthPrep(): ClaudeRuntimeAuthPreparation {
return {
configDir: '/Users/test/.claude',
envPatch: { CLAUDE_CONFIG_DIR: '/Users/test/.claude' },
stripAuthEnv: false,
provenance: 'system'
}
}

describe('fetchClaudeRateLimits extra usage', () => {
beforeEach(() => {
primeClaudeFetcherMocks({
netFetchMock,
readFileMock,
resolveProxyMock,
setProxyMock,
appGetPathMock
})
})

afterEach(() => {
restorePlatform()
})

it('maps the usage-credits spend object into a capped balance in major units', async () => {
vi.mocked(readActiveClaudeKeychainCredentialsStrict).mockResolvedValueOnce(
JSON.stringify({
claudeAiOauth: {
accessToken: 'oauth-token',
expiresAt: Date.now() + 60_000
}
})
)
netFetchMock.mockResolvedValueOnce(
new Response(
JSON.stringify({
five_hour: { utilization: 10 },
spend: {
used: { amount_minor: 5000, currency: 'EUR', exponent: 2 },
limit: { amount_minor: 200000, currency: 'EUR', exponent: 2 },
percent: 2.5,
enabled: true,
balance: { amount_minor: 1000, currency: 'EUR', exponent: 2 }
}
}),
{ status: 200 }
)
)

await expect(fetchClaudeRateLimits({ authPreparation: oauthPrep() })).resolves.toMatchObject({
provider: 'claude',
status: 'ok',
extraUsage: {
balance: 10,
spent: 50,
spendLimit: 2000,
spentPercent: 2.5,
currencyCode: 'EUR',
enabled: true,
disabledReason: null,
resetsAt: null
}
})
})

it('keeps the usage-credits cap visible but disabled when out of credits', async () => {
vi.mocked(readActiveClaudeKeychainCredentialsStrict).mockResolvedValueOnce(
JSON.stringify({
claudeAiOauth: {
accessToken: 'oauth-token',
expiresAt: Date.now() + 60_000
}
})
)
netFetchMock.mockResolvedValueOnce(
new Response(
JSON.stringify({
five_hour: { utilization: 10 },
spend: {
used: { amount_minor: 0, currency: 'EUR', exponent: 2 },
limit: { amount_minor: 200000, currency: 'EUR', exponent: 2 },
percent: 0,
enabled: false,
disabled_reason: 'out_of_credits',
balance: null
}
}),
{ status: 200 }
)
)

await expect(fetchClaudeRateLimits({ authPreparation: oauthPrep() })).resolves.toMatchObject({
provider: 'claude',
status: 'ok',
extraUsage: {
balance: 0,
spent: 0,
spendLimit: 2000,
spentPercent: 0,
currencyCode: 'EUR',
enabled: false,
disabledReason: 'out_of_credits'
}
})
})

it('keeps legacy extra_usage spend data without inventing a missing balance', async () => {
vi.mocked(readActiveClaudeKeychainCredentialsStrict).mockResolvedValueOnce(
JSON.stringify({
claudeAiOauth: {
accessToken: 'oauth-token',
expiresAt: Date.now() + 60_000
}
})
)
netFetchMock.mockResolvedValueOnce(
new Response(
JSON.stringify({
five_hour: { utilization: 10 },
extra_usage: {
is_enabled: true,
monthly_limit: 200000,
used_credits: 5000,
utilization: 2.5,
currency: 'EUR',
decimal_places: 2
}
}),
{ status: 200 }
)
)

await expect(fetchClaudeRateLimits({ authPreparation: oauthPrep() })).resolves.toMatchObject({
provider: 'claude',
status: 'ok',
extraUsage: {
balance: null,
spent: 50,
spendLimit: 2000,
spentPercent: 2.5,
currencyCode: 'EUR',
enabled: true
}
})
})
})
8 changes: 8 additions & 0 deletions src/main/rate-limits/claude-oauth-usage-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import { ensureElectronProxyFromEnvironment } from '../network/proxy-settings'
import { createOAuthUsageError } from './claude-oauth-usage-error'
import { mapClaudeUsageWindow, type ClaudeUsageWindowInput } from './claude-usage-window'
import { abortedClaudeRateLimitResult } from './claude-usage-result'
import {
mapClaudeExtraUsage,
type ClaudeOAuthExtraUsage,
type ClaudeOAuthSpend
} from './claude-usage-credits'

const OAUTH_USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
const API_TIMEOUT_MS = 10_000
Expand All @@ -22,6 +27,8 @@ type OAuthUsageResponse = {
fable_weekly?: ClaudeUsageWindowInput
fable_seven_day?: ClaudeUsageWindowInput
seven_day_fable?: ClaudeUsageWindowInput
spend?: ClaudeOAuthSpend
extra_usage?: ClaudeOAuthExtraUsage
limits?: OAuthUsageLimit[] | null
}

Expand Down Expand Up @@ -90,6 +97,7 @@ export async function fetchClaudeOAuthUsage(
session: mapClaudeUsageWindow(data.five_hour, 300),
weekly: mapClaudeUsageWindow(data.seven_day, 10080),
fableWeekly: mapFableWeeklyWindow(data),
extraUsage: mapClaudeExtraUsage(data),
updatedAt: Date.now(),
error: null,
status: 'ok'
Expand Down
116 changes: 116 additions & 0 deletions src/main/rate-limits/claude-usage-credits.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import type { ExtraUsageBalance } from '../../shared/rate-limit-types'

// Money is reported as minor units plus an exponent (e.g. 200000 @ exp 2 = €2000).
type OAuthMoney = {
amount_minor?: number
currency?: string
exponent?: number
}

// The current "usage credits" shape: spent/limit as money, a live balance, and
// whether spending is currently possible. This is what Claude Code's own /usage
// panel renders as "Usage credits" (monthly spend limit + current balance).
export type ClaudeOAuthSpend = {
used?: OAuthMoney
limit?: OAuthMoney
percent?: number
enabled?: boolean
disabled_reason?: string | null
cap?: { money?: OAuthMoney | null } | null
balance?: OAuthMoney | number | null
}

// Legacy shape kept as a fallback for older responses that only send `extra_usage`.
export type ClaudeOAuthExtraUsage = {
is_enabled?: boolean
monthly_limit?: number
used_credits?: number
utilization?: number
currency?: string
decimal_places?: number
disabled_reason?: string | null
}

function clampPercent(value: number): number {
return Math.min(100, Math.max(0, value))
}

function moneyToMajor(money: OAuthMoney | number | null | undefined): number | null {
if (typeof money === 'number') {
return Number.isFinite(money) ? money : null
}
if (!money || typeof money.amount_minor !== 'number' || !Number.isFinite(money.amount_minor)) {
return null
}
const exponent = typeof money.exponent === 'number' ? money.exponent : 2
if (!Number.isInteger(exponent) || exponent < 0 || exponent > 6) {
return null
}
return money.amount_minor / 10 ** exponent
}

// Prefer the richer `spend` object; fall back to the legacy `extra_usage` shape.
export function mapClaudeExtraUsage(data: {
spend?: ClaudeOAuthSpend
extra_usage?: ClaudeOAuthExtraUsage
}): ExtraUsageBalance | null {
return mapSpend(data.spend) ?? mapLegacyExtraUsage(data.extra_usage)
}

function mapSpend(spend: ClaudeOAuthSpend | undefined): ExtraUsageBalance | null {
if (!spend) {
return null
}
const spent = moneyToMajor(spend.used)
const spendLimit = moneyToMajor(spend.limit) ?? moneyToMajor(spend.cap?.money)
const balance = moneyToMajor(spend.balance) ?? 0
// Nothing worth showing when the account has neither a configured cap nor a balance.
if (spendLimit === null && balance === 0) {
return null
}
const spentPercent =
typeof spend.percent === 'number'
? clampPercent(spend.percent)
: spendLimit !== null && spendLimit > 0 && spent !== null
? clampPercent((spent / spendLimit) * 100)
: null
return {
balance,
unit: 'currency',
currencyCode:
spend.used?.currency ?? spend.limit?.currency ?? spend.cap?.money?.currency ?? 'USD',
enabled: spend.enabled === true,
disabledReason: spend.disabled_reason ?? null,
spent,
spendLimit,
spentPercent,
resetsAt: null
}
}

function mapLegacyExtraUsage(extra: ClaudeOAuthExtraUsage | undefined): ExtraUsageBalance | null {
if (!extra || typeof extra.monthly_limit !== 'number') {
return null
}
// Amounts are minor units; `decimal_places` gives the exponent (default cents).
const divisor = 10 ** (typeof extra.decimal_places === 'number' ? extra.decimal_places : 2)
const spendLimit = extra.monthly_limit / divisor
const spent = typeof extra.used_credits === 'number' ? extra.used_credits / divisor : null
const spentPercent =
typeof extra.utilization === 'number'
? clampPercent(extra.utilization)
: spendLimit > 0 && spent !== null
? clampPercent((spent / spendLimit) * 100)
: null
return {
balance: null,
unit: 'currency',
currencyCode: extra.currency?.trim() || 'USD',
enabled: extra.is_enabled === true,
disabledReason: extra.disabled_reason ?? null,
spent,
spendLimit,
spentPercent,
resetsAt: null
}
}
4 changes: 3 additions & 1 deletion src/main/rate-limits/claude-usage-result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,9 @@ export function mergeClaudeUsageWindows(
...primary,
session: primary.session ?? supplement.session,
weekly: primary.weekly ?? supplement.weekly,
fableWeekly: primary.fableWeekly ?? supplement.fableWeekly ?? null
fableWeekly: primary.fableWeekly ?? supplement.fableWeekly ?? null,
// Only OAuth reports the extra-usage cap; keep it when the CLI supplements windows.
extraUsage: primary.extraUsage ?? supplement.extraUsage ?? null
}
}

Expand Down
25 changes: 25 additions & 0 deletions src/main/rate-limits/codex-credit-balance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import type { ExtraUsageBalance } from '../../shared/rate-limit-types'
import type { CodexRateLimitWindowsSnapshot } from './codex-rate-limit-window-classification'

// Codex's pay-as-you-go credit balance, reported alongside the rate windows.
// `balance` is a plain credit count (string), not a currency amount.
type RpcCredits = NonNullable<CodexRateLimitWindowsSnapshot['credits']>

// Codex credits are a unitless count, not currency. Only surface the balance
// when the account actually has credits (or unlimited) so accounts that never
// bought any don't get an empty "0 credits" row.
export function mapCodexCredits(raw: RpcCredits | null | undefined): ExtraUsageBalance | null {
if (!raw || (raw.hasCredits !== true && raw.unlimited !== true)) {
return null
}
const parsed = typeof raw.balance === 'string' ? Number(raw.balance) : raw.balance
const balance = typeof parsed === 'number' && Number.isFinite(parsed) ? Math.max(0, parsed) : 0
return {
balance,
unit: 'credits',
unlimited: raw.unlimited === true,
enabled: raw.hasCredits === true || raw.unlimited === true,
disabledReason: null,
resetsAt: null
}
}
Loading
Loading