Skip to content
Merged
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
83 changes: 82 additions & 1 deletion src/utils/__tests__/usage-fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,8 @@ function seedUsageCache(profile: TokenHome, contents: Record<string, unknown>):
}

describe('fetchUsageData error handling', () => {
const nowMs = 2200000000000;
// Before the fixtures' 2030 resets, so their cached windows are still open
const nowMs = 1800000000000;
const successResponseBody = JSON.stringify({
five_hour: {
utilization: 42,
Expand Down Expand Up @@ -2209,6 +2210,86 @@ describe('fetchUsageData error handling', () => {
}
});

// Overnight, last night's 95% would otherwise stay on screen after its
// window reset, for as long as the API keeps refusing
it.each([
{ requiredFields: [] },
{ requiredFields: ['sessionUsage', 'weeklyUsage'] }
])('leaves out stale cached windows that have already reset with required fields $requiredFields', ({ requiredFields }) => {
const harness = createProbeHarness();

try {
const home = harness.createTokenHome('rate-limited-expired-window');
const sessionResetAt = new Date(nowMs + 60 * 60 * 1000).toISOString();
const weeklyResetAt = new Date(nowMs + 3 * 24 * 60 * 60 * 1000).toISOString();
harness.runProbe({
claudeConfigDir: home.claudeConfig,
home: home.home,
mode: 'success',
nowMs,
pathDir: home.bin,
responseBody: JSON.stringify({
five_hour: { utilization: 95, resets_at: sessionResetAt },
seven_day: { utilization: 40, resets_at: weeklyResetAt }
})
});
const fetchedAtMs = fs.statSync(usageFilePath(home, 'json')).mtimeMs;

// Two hours on, past the session reset
const rateLimitedResult = harness.runProbe({
claudeConfigDir: home.claudeConfig,
home: home.home,
mode: 'status',
nowMs: nowMs + 2 * 60 * 60 * 1000,
pathDir: home.bin,
responseBody: rateLimitedResponseBody,
responseHeaders: { 'retry-after': '3600' },
requiredFields,
statusCode: 429
});

expect(rateLimitedResult.first).toEqual({
weeklyUsage: 40,
weeklyResetAt,
...(requiredFields.length > 0 ? { error: 'rate-limited' } : {})
});
expect(rateLimitedResult.second).toEqual(rateLimitedResult.first);
expect(rateLimitedResult.requestCount).toBe(1);
expect(rateLimitedResult.fetchedAtMs).toBe(fetchedAtMs);
expect(rateLimitedResult.staleFallback).toEqual([true, true]);

const mixedResult = harness.runProbe({
claudeConfigDir: home.claudeConfig,
home: home.home,
mode: 'unexpected',
nowMs: nowMs + 2 * 60 * 60 * 1000 + 1000,
pathDir: home.bin,
requiredFields: ['sessionUsage', 'weeklyUsage']
});

expect(mixedResult.first).toEqual({ weeklyUsage: 40, weeklyResetAt, error: 'rate-limited' });
expect(mixedResult.second).toEqual(mixedResult.first);
expect(mixedResult.requestCount).toBe(0);
expect(mixedResult.fetchedAtMs).toBe(fetchedAtMs);
expect(mixedResult.staleFallback).toEqual([true, true]);

const sessionResult = harness.runProbe({
claudeConfigDir: home.claudeConfig,
home: home.home,
mode: 'unexpected',
nowMs: nowMs + 2 * 60 * 60 * 1000 + 1000,
pathDir: home.bin,
requiredFields: ['sessionUsage']
});

expect(sessionResult.first).toEqual({ error: 'rate-limited' });
expect(sessionResult.requestCount).toBe(0);
expect(sessionResult.fetchedAtMs).toBeNull();
} finally {
harness.cleanup();
}
});

it('returns rate-limited without stale cache and falls back to the default backoff when Retry-After is invalid', () => {
const harness = createProbeHarness();

Expand Down
30 changes: 30 additions & 0 deletions src/utils/__tests__/usage-prefetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import type { StatusJSON } from '../../types/StatusJSON';
import type { WidgetItem } from '../../types/Widget';
import * as usage from '../../utils/usage';
import { BlockResetTimerWidget } from '../../widgets/BlockResetTimer';
import { SessionUsageWidget } from '../../widgets/SessionUsage';
import { WeeklyUsageWidget } from '../../widgets/WeeklyUsage';
import {
extractUsageDataFromRateLimits,
hasUsageDependentWidgets,
Expand Down Expand Up @@ -307,6 +309,34 @@ describe('usage prefetch', () => {
expect(mockFetchUsageData.mock.calls.length).toBe(0);
});

it('renders valid weekly usage when the shared response reports an expired session window', async () => {
const partial: UsageData = { weeklyUsage: 40, weeklyResetAt: '2030-01-07T00:00:00.000Z', error: 'rate-limited' };
mockFetchUsageData.mockResolvedValue(partial);
const session: WidgetItem = { id: 'session', type: 'session-usage' };
const weekly: WidgetItem = { id: 'weekly', type: 'weekly-usage', rawValue: true };

const usageData = await prefetchUsageDataIfNeeded([[session, weekly]]);

expect(mockFetchUsageData.mock.calls).toEqual([[{ requiredFields: ['sessionUsage', 'weeklyUsage'] }]]);
expect(usageData).toEqual(partial);
const context = { isPreview: false, usageData: usageData ?? undefined };
expect(new WeeklyUsageWidget().render(weekly, context, DEFAULT_SETTINGS)).toBe('40.0%');
expect(new SessionUsageWidget().render(session, context, DEFAULT_SETTINGS)).toBe('[Rate limited]');
});

it('keeps valid reset data when suppressing an error for another expired window', async () => {
const weeklyResetAt = '2030-01-07T00:00:00.000Z';
mockFetchUsageData.mockResolvedValue({ weeklyUsage: 40, weeklyResetAt, error: 'rate-limited' });

const usageData = await prefetchUsageDataIfNeeded(makeLines([
{ id: 'session', type: 'reset-timer' },
{ id: 'weekly', type: 'weekly-reset-timer' }
]));

expect(mockFetchUsageData.mock.calls).toEqual([[{ requiredFields: ['sessionResetAt', 'weeklyResetAt'] }]]);
expect(usageData).toEqual({ weeklyUsage: 40, weeklyResetAt });
});

it('suppresses API errors when reset timer widgets are only missing reset data', async () => {
mockFetchUsageData.mockResolvedValue({ error: 'rate-limited' });

Expand Down
38 changes: 30 additions & 8 deletions src/utils/usage-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,7 @@ function cacheUsageData(data: UsageData, now: number, fetchedAtMs: number): Usag

/**
* When the usage API sent the values fetchUsageData last returned, in ms, or
* undefined after an error. Served from the cache, during a rate limit say,
* undefined when no usage data is available. Served from the cache during a rate limit,
* they can be hours old.
*/
export function getUsageFetchedAtMs(): number | undefined {
Expand Down Expand Up @@ -464,12 +464,18 @@ function getStaleUsageOrError(
errorCacheMaxAge = LOCK_MAX_AGE,
requiredFields: readonly UsageDataField[] = []
): UsageData {
const stale = readStaleUsageCache(cacheIdentity);
if (stale && !stale.data.error && hasRequiredUsageFields(stale.data, requiredFields)) {
if (hasUsageCacheOutlivedRefresh(now)) {
staleUsageFallbacks.add(stale.data);
const stale = readStaleUsageCache(cacheIdentity, now);
if (stale && !stale.data.error) {
const complete = hasRequiredUsageFields(stale.data, requiredFields);
if (complete || requiredFields.some(field => hasRequiredUsageField(stale.data, field))) {
// Widgets share this response: an expired window must not discard
// another widget's valid fields. Only missing fields use the error.
const data = complete ? stale.data : { ...stale.data, error };
if (hasUsageCacheOutlivedRefresh(now)) {
staleUsageFallbacks.add(data);
}
return cacheUsageData(data, now, stale.fetchedAtMs);
}
return cacheUsageData(stale.data, now, stale.fetchedAtMs);
}

return setCachedUsageError(error, now, errorCacheMaxAge);
Expand Down Expand Up @@ -762,6 +768,22 @@ function getUsageCredentialsWithBackoff(now: number): UsageCredentials | null {
return credentials;
}

// A stale cache can outlive its windows (overnight, while the API keeps
// failing). A window whose reset has passed no longer has that usage, so its
// usage and reset are left out rather than shown, as Claude Code drops a
// window from rate_limits once its resets_at passes.
function dropResetWindows(data: UsageData, now: number): UsageData {
const result: UsageData = { ...data };
for (const [resetField, usageField] of Object.entries(WINDOW_RESET_FIELD_SENTINELS)) {
const resetAt = result[resetField as UsageDataField];
if (typeof resetAt === 'string' && Date.parse(resetAt) <= now * 1000) {
setUsageField(result, resetField as UsageDataField, undefined);
setUsageField(result, usageField, undefined);
}
}
return result;
}

/**
* The login whose usage the status line shows: the usage cache's fingerprint
* of it (see getUsageCacheIdentity), or null with no OAuth login found. It
Expand All @@ -772,15 +794,15 @@ export function getUsageLoginFingerprint(): string | null {
return credentials ? getUsageCacheIdentity(credentials).preferredHash : null;
}

function readStaleUsageCache(cacheIdentity: UsageCacheIdentity | null): { data: UsageData; fetchedAtMs: number } | null {
function readStaleUsageCache(cacheIdentity: UsageCacheIdentity | null, now: number): { data: UsageData; fetchedAtMs: number } | null {
try {
const fetchedAtMs = fs.statSync(getUsageFilePath('json')).mtimeMs;
const rawCache = fs.readFileSync(getUsageFilePath('json'), 'utf8');
if (!tokenHashMatches(readCachedTokenHash(rawCache), cacheIdentity)) {
return null;
}
const data = parseCachedUsageData(rawCache);
return data ? { data, fetchedAtMs } : null;
return data ? { data: dropResetWindows(data, now), fetchedAtMs } : null;
} catch {
return null;
}
Expand Down
4 changes: 3 additions & 1 deletion src/utils/usage-prefetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,9 @@ export async function prefetchUsageDataIfNeeded(lines: WidgetItem[][], data?: St

const apiData = await fetchUsageData({ requiredFields: missingFields });
if (apiData.error && missingRequirements.suppressFetchError) {
return rateLimitsData;
return hasAnyUsageDataField(apiData)
? mergeUsageData(rateLimitsData, { ...apiData, error: undefined })
: rateLimitsData;
}

const usageData = mergeUsageData(rateLimitsData, apiData);
Expand Down
Loading