diff --git a/src/claude-usage-backoff.test.ts b/src/claude-usage-backoff.test.ts index af179dd..8e68fff 100644 --- a/src/claude-usage-backoff.test.ts +++ b/src/claude-usage-backoff.test.ts @@ -149,6 +149,42 @@ describe('Claude usage 429 Retry-After backoff', () => { }); }); +describe('Claude usage refetch after a window rolls over', () => { + it('skips the 5-minute throttle once when the cached window has reset', async () => { + // Production case (2026-10-19): fetched 99% at 22:59:04 for a 5h window + // resetting at 23:00:00; the throttle kept serving 99% until 23:04. + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-10-19T13:59:30Z')); + readJsonFileMock.mockReturnValue({ + 'account-0': { + fetchedAt: Date.parse('2026-10-19T13:59:04Z'), + lastAttemptAt: Date.parse('2026-10-19T13:59:04Z'), + usage: { + five_hour: { utilization: 99, resets_at: '2026-10-19T14:00:00Z' }, + seven_day: { utilization: 27, resets_at: '2026-10-19T20:00:00Z' }, + }, + }, + }); + const fetchMock = vi.fn(async () => makeResponse(200)); + vi.stubGlobal('fetch', fetchMock); + const { fetchClaudeUsage } = await import('./claude-usage.js'); + + // Before the reset: throttled, no API call. + await fetchClaudeUsage(); + expect(fetchMock).not.toHaveBeenCalled(); + + // Just after the reset: fetch the new window despite the throttle. + vi.setSystemTime(new Date('2026-10-19T14:00:10Z')); + await fetchClaudeUsage(); + expect(fetchMock).toHaveBeenCalledTimes(1); + + // The throttle applies again after that one refetch. + vi.setSystemTime(new Date('2026-10-19T14:00:40Z')); + await fetchClaudeUsage(); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); +}); + describe('getCachedClaudeUsageLimitResetAt', () => { it('returns the later reset of the exhausted windows', async () => { readJsonFileMock.mockReturnValue({ diff --git a/src/claude-usage.ts b/src/claude-usage.ts index 76fbdd7..76591a3 100644 --- a/src/claude-usage.ts +++ b/src/claude-usage.ts @@ -183,6 +183,23 @@ export function parseRetryAfterMs(header: string | null): number | null { return null; } +/** + * True when a cached window's reset time fell between the last attempt and + * now: the cached numbers describe a window that has ended, so the throttle + * is skipped once to fetch the new window. The attempt that follows is later + * than that reset, so this cannot repeat for the same window. + */ +function windowRolledOverSince( + usage: ClaudeUsageData | undefined, + lastAttempt: number, + now: number = Date.now(), +): boolean { + return [usage?.five_hour, usage?.seven_day].some((window) => { + const resetMs = Date.parse(window?.resets_at ?? ''); + return Number.isFinite(resetMs) && resetMs > lastAttempt && resetMs <= now; + }); +} + async function fetchUsageForToken( token: string, refreshAttempted = false, @@ -231,7 +248,8 @@ async function fetchUsageForToken( if ( !refreshAttempted && cached && - Date.now() - lastAttempt < MIN_FETCH_INTERVAL_MS + Date.now() - lastAttempt < MIN_FETCH_INTERVAL_MS && + !windowRolledOverSince(cached.usage, lastAttempt) ) { // Within the throttle window: replay the last outcome without an API call. // On a 429 we report rateLimited and DO NOT serve the stale value. diff --git a/src/codex-usage-collector.ts b/src/codex-usage-collector.ts index 02a7d8e..fc76de7 100644 --- a/src/codex-usage-collector.ts +++ b/src/codex-usage-collector.ts @@ -9,7 +9,11 @@ import { getCodexAuthPath, updateCodexUsage, } from './codex-auth.js'; -import { formatResetRemaining, type UsageRow } from './dashboard-usage-rows.js'; +import { + currentWindowPct, + formatResetRemaining, + type UsageRow, +} from './dashboard-usage-rows.js'; import { logger } from './logger.js'; export interface CodexRateLimit { @@ -297,9 +301,15 @@ export function buildCodexUsageRowsFromState(): UsageRow[] { return [ { name: 'Codex', - h5pct: acct.cachedUsagePct != null ? acct.cachedUsagePct : -1, + h5pct: + acct.cachedUsagePct != null + ? currentWindowPct(acct.cachedUsagePct, acct.resetAt) + : -1, h5reset: acct.resetAt ? formatResetRemaining(acct.resetAt) : '', - d7pct: acct.cachedUsageD7Pct != null ? acct.cachedUsageD7Pct : -1, + d7pct: + acct.cachedUsageD7Pct != null + ? currentWindowPct(acct.cachedUsageD7Pct, acct.resetD7At) + : -1, d7reset: acct.resetD7At ? formatResetRemaining(acct.resetD7At) : '', }, ]; diff --git a/src/dashboard-usage-rows.test.ts b/src/dashboard-usage-rows.test.ts index f09dce6..1f38fa1 100644 --- a/src/dashboard-usage-rows.test.ts +++ b/src/dashboard-usage-rows.test.ts @@ -8,6 +8,7 @@ vi.mock('./claude-usage.js', () => ({ import { buildClaudeUsageRows, + currentWindowPct, extractCodexUsageRows, mergeClaudeDashboardUsage, } from './dashboard-usage-rows.js'; @@ -92,8 +93,15 @@ describe('extractCodexUsageRows staleness', () => { describe('dashboard Claude usage rows', () => { const cachedUsage: ClaudeUsageSnapshot = { usage: { - five_hour: { utilization: 0.4, resets_at: '2026-03-24T04:00:00+09:00' }, - seven_day: { utilization: 0.7, resets_at: '2026-03-29T04:00:00+09:00' }, + // Future resets: a passed reset now reads as a rolled-over (0%) window. + five_hour: { + utilization: 0.4, + resets_at: new Date(Date.now() + 3_600_000).toISOString(), + }, + seven_day: { + utilization: 0.7, + resets_at: new Date(Date.now() + 86_400_000).toISOString(), + }, }, }; @@ -126,3 +134,32 @@ describe('dashboard Claude usage rows', () => { expect(mergeClaudeDashboardUsage(null, cachedUsage)).toBe(cachedUsage); }); }); + +describe('rolled-over usage windows', () => { + it('shows 0% and no countdown once a window reset time has passed', () => { + const now = Date.now(); + const rows = buildClaudeUsageRows({ + usage: { + five_hour: { + utilization: 99, + resets_at: new Date(now - 60_000).toISOString(), + }, + seven_day: { + utilization: 27, + resets_at: new Date(now + 6 * 3_600_000).toISOString(), + }, + }, + }); + expect(rows[0]).toMatchObject({ h5pct: 0, h5reset: '', d7pct: 27 }); + expect(rows[0].d7reset).not.toBe(''); + }); + + it('keeps unknown (-1) and future windows unchanged', () => { + const past = new Date(Date.now() - 1000).toISOString(); + const future = new Date(Date.now() + 60_000).toISOString(); + expect(currentWindowPct(-1, past)).toBe(-1); + expect(currentWindowPct(42, future)).toBe(42); + expect(currentWindowPct(42, undefined)).toBe(42); + expect(currentWindowPct(42, past)).toBe(0); + }); +}); diff --git a/src/dashboard-usage-rows.ts b/src/dashboard-usage-rows.ts index f3a746d..22438a0 100644 --- a/src/dashboard-usage-rows.ts +++ b/src/dashboard-usage-rows.ts @@ -11,6 +11,27 @@ export type UsageRow = { error?: string; }; +function resetTimeMs(value: string | number | undefined): number | null { + if (value === '' || value == null) return null; + const ms = + typeof value === 'number' ? value * 1000 : new Date(value).getTime(); + return Number.isNaN(ms) ? null : ms; +} + +/** + * Usage % to display for a window. Once the window's reset time has passed + * the window has rolled over, so the last fetched value (e.g. 99%) no longer + * applies — show 0% until the next fetch brings the new window's number. + */ +export function currentWindowPct( + pct: number, + resetsAt: string | number | undefined, +): number { + if (pct < 0) return pct; + const resetMs = resetTimeMs(resetsAt); + return resetMs != null && resetMs <= Date.now() ? 0 : pct; +} + export function formatResetRemaining(value: string | number): string { if (value === '' || value == null) return ''; try { @@ -18,7 +39,8 @@ export function formatResetRemaining(value: string | number): string { typeof value === 'number' ? new Date(value * 1000) : new Date(value); if (Number.isNaN(date.getTime())) return ''; const diffMs = date.getTime() - Date.now(); - if (diffMs <= 0) return ' reset'; + // Window already rolled over: no countdown (its % is shown as 0). + if (diffMs <= 0) return ''; const hours = Math.floor(diffMs / 3_600_000); const minutes = Math.floor((diffMs % 3_600_000) / 60_000); if (hours >= 24) { @@ -61,9 +83,9 @@ export function buildClaudeUsageRows( return [ { name: profile ? `Claude ${profile.planType}` : 'Claude', - h5pct: h5 ? toPct(h5.utilization) : -1, + h5pct: h5 ? currentWindowPct(toPct(h5.utilization), h5.resets_at) : -1, h5reset: h5 ? formatResetRemaining(h5.resets_at) : '', - d7pct: d7 ? toPct(d7.utilization) : -1, + d7pct: d7 ? currentWindowPct(toPct(d7.utilization), d7.resets_at) : -1, d7reset: d7 ? formatResetRemaining(d7.resets_at) : '', error: snapshot.usageRateLimited ? '429' : undefined, }, diff --git a/src/unified-dashboard.ts b/src/unified-dashboard.ts index f140dee..da15cd9 100644 --- a/src/unified-dashboard.ts +++ b/src/unified-dashboard.ts @@ -20,7 +20,10 @@ import { fetchClaudeUsage, type ClaudeUsageSnapshot, } from './claude-usage.js'; -import { refreshCodexUsage } from './codex-usage-collector.js'; +import { + buildCodexUsageRowsFromState, + refreshCodexUsage, +} from './codex-usage-collector.js'; import { composeDashboardContent, formatElapsed, @@ -629,7 +632,9 @@ async function buildUsageContent(): Promise { // or fall back to snapshot from separate Codex service. const codexBotRows: UsageRow[] = []; if (cachedCodexUsageRows.length > 0) { - codexBotRows.push(...cachedCodexUsageRows); + // Rebuild from the cached state at render time so the reset countdown + // and a rolled-over window stay current between the 5-min polls. + codexBotRows.push(...buildCodexUsageRowsFromState()); } else { const codexSnapshot = readStatusSnapshots(STATUS_SNAPSHOT_MAX_AGE_MS).find( (s) => s.serviceId === 'codex-main' || s.serviceId === 'codex',