fix: show a rolled-over usage window as unknown, not 0%

91203d8 rendered an expired window as 0% unconditionally. If the post-reset
refetch fails (network error, 429) the 0% stayed for as long as fetches
kept failing, the same stale-value bug in the other direction. An expired
window now renders as -1 (the empty "─────" unknown cell) until a fetch
succeeds and brings the new window's real value.

Tests: expired window -> -1 for Claude and Codex rows; refetch failing at
+1 min and +60 min stays unknown, then success shows 3%; 429 shows the
429 indicator; renderer draws -1 as the placeholder cell.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codex
2026-10-19 23:10:51 +09:00
parent 91203d84fc
commit 97cc670e34
5 changed files with 128 additions and 27 deletions

View File

@@ -150,39 +150,93 @@ 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' },
},
// Production case (2026-10-19): fetched 99% at 22:59:04 KST for a 5h window
// resetting at 23:00:00; the 5-min throttle kept serving 99% until 23:04.
const staleCache = {
'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 freshBody = {
five_hour: { utilization: 3, resets_at: '2026-10-19T19:00:00Z' },
seven_day: { utilization: 27, resets_at: '2026-10-19T20:00:00Z' },
};
function okResponse(body: unknown): Response {
return { ...makeResponse(200), json: async () => body } as Response;
}
async function dashboardRow() {
const { fetchClaudeUsage } = await import('./claude-usage.js');
const { buildClaudeUsageRows } = await import('./dashboard-usage-rows.js');
return buildClaudeUsageRows(await fetchClaudeUsage())[0];
}
// Before the reset: throttled, no API call.
await fetchClaudeUsage();
beforeEach(() => {
vi.useFakeTimers();
readJsonFileMock.mockReturnValue(structuredClone(staleCache));
});
it('skips the 5-minute throttle once when the cached window has reset', async () => {
vi.setSystemTime(new Date('2026-10-19T13:59:30Z'));
const fetchMock = vi.fn(async () => okResponse(freshBody));
vi.stubGlobal('fetch', fetchMock);
// Before the reset: throttled, no API call, cached value still valid.
expect(await dashboardRow()).toMatchObject({ h5pct: 99, d7pct: 27 });
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(await dashboardRow()).toMatchObject({ h5pct: 3, d7pct: 27 });
expect(fetchMock).toHaveBeenCalledTimes(1);
// The throttle applies again after that one refetch.
vi.setSystemTime(new Date('2026-10-19T14:00:40Z'));
await fetchClaudeUsage();
await dashboardRow();
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('shows the expired window as unknown while refetches fail, then the real value', async () => {
const fetchMock = vi
.fn()
.mockRejectedValueOnce(new Error('ECONNRESET'))
.mockRejectedValueOnce(new Error('ECONNRESET'))
.mockResolvedValueOnce(okResponse(freshBody));
vi.stubGlobal('fetch', fetchMock);
// +1 min after reset: refetch fails -> unknown, never 99% or 0%.
vi.setSystemTime(new Date('2026-10-19T14:01:00Z'));
expect(await dashboardRow()).toMatchObject({ h5pct: -1, h5reset: '' });
expect(fetchMock).toHaveBeenCalledTimes(1);
// +60 min: still failing -> still unknown.
vi.setSystemTime(new Date('2026-10-19T15:00:00Z'));
expect(await dashboardRow()).toMatchObject({ h5pct: -1, h5reset: '' });
expect(fetchMock).toHaveBeenCalledTimes(2);
// Next allowed attempt succeeds -> real new-window value.
vi.setSystemTime(new Date('2026-10-19T15:05:30Z'));
expect(await dashboardRow()).toMatchObject({ h5pct: 3, d7pct: 27 });
expect(fetchMock).toHaveBeenCalledTimes(3);
});
it('shows the 429 indicator (not a stale %) when the post-reset refetch is rate limited', async () => {
const fetchMock = vi.fn(async () =>
makeResponse(429, { 'retry-after': '120' }),
);
vi.stubGlobal('fetch', fetchMock);
vi.setSystemTime(new Date('2026-10-19T14:01:00Z'));
expect(await dashboardRow()).toMatchObject({
h5pct: -1,
d7pct: -1,
error: '429',
});
});
});
describe('getCachedClaudeUsageLimitResetAt', () => {

View File

@@ -0,0 +1,32 @@
import { describe, expect, it, vi } from 'vitest';
const { statusMock } = vi.hoisted(() => ({ statusMock: vi.fn() }));
vi.mock('./codex-auth.js', () => ({
getCodexAccountStatus: statusMock,
getCodexAuthPath: () => null,
updateCodexUsage: vi.fn(),
claimCodexUsagePollLease: vi.fn(),
}));
import { buildCodexUsageRowsFromState } from './codex-usage-collector.js';
describe('Codex usage rows after a window rolls over', () => {
it('rebuilds from state: expired window is unknown (-1), live window keeps its value', () => {
// Production case: 22:58 poll stored 29% resetting 23:00:07; the row
// string was frozen until the next 5-min poll.
statusMock.mockReturnValue({
cachedUsagePct: 29,
cachedUsageD7Pct: 13,
resetAt: new Date(Date.now() - 60_000).toISOString(),
resetD7At: new Date(Date.now() + 5 * 86_400_000).toISOString(),
});
const [row] = buildCodexUsageRowsFromState();
expect(row).toMatchObject({
name: 'Codex',
h5pct: -1,
h5reset: '',
d7pct: 13,
});
expect(row.d7reset).not.toBe('');
});
});

View File

@@ -136,7 +136,7 @@ describe('dashboard Claude usage rows', () => {
});
describe('rolled-over usage windows', () => {
it('shows 0% and no countdown once a window reset time has passed', () => {
it('shows an expired window as unknown (-1) with no countdown', () => {
const now = Date.now();
const rows = buildClaudeUsageRows({
usage: {
@@ -150,7 +150,7 @@ describe('rolled-over usage windows', () => {
},
},
});
expect(rows[0]).toMatchObject({ h5pct: 0, h5reset: '', d7pct: 27 });
expect(rows[0]).toMatchObject({ h5pct: -1, h5reset: '', d7pct: 27 });
expect(rows[0].d7reset).not.toBe('');
});
@@ -160,6 +160,6 @@ describe('rolled-over usage windows', () => {
expect(currentWindowPct(-1, past)).toBe(-1);
expect(currentWindowPct(42, future)).toBe(42);
expect(currentWindowPct(42, undefined)).toBe(42);
expect(currentWindowPct(42, past)).toBe(0);
expect(currentWindowPct(42, past)).toBe(-1);
});
});

View File

@@ -20,8 +20,9 @@ function resetTimeMs(value: string | number | undefined): number | null {
/**
* 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.
* the last fetched value (e.g. 99%) describes a window that has ended, and the
* new window's usage is not known until a fetch succeeds — return -1 (shown as
* the empty "unknown" cell) rather than a stale or guessed number.
*/
export function currentWindowPct(
pct: number,
@@ -29,7 +30,7 @@ export function currentWindowPct(
): number {
if (pct < 0) return pct;
const resetMs = resetTimeMs(resetsAt);
return resetMs != null && resetMs <= Date.now() ? 0 : pct;
return resetMs != null && resetMs <= Date.now() ? -1 : pct;
}
export function formatResetRemaining(value: string | number): string {
@@ -39,7 +40,7 @@ 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();
// Window already rolled over: no countdown (its % is shown as 0).
// Window already rolled over: no countdown (its % is shown as unknown).
if (diffMs <= 0) return '';
const hours = Math.floor(diffMs / 3_600_000);
const minutes = Math.floor((diffMs % 3_600_000) / 60_000);

View File

@@ -162,6 +162,20 @@ describe('renderUsageTable', () => {
expect(lines.some((l) => l.includes('Codex'))).toBe(true);
});
it('renders an unknown (-1) window as the empty placeholder, not a %', () => {
const lines = renderUsageTable(
[{ ...claudeRow, h5pct: -1 }],
[{ ...codexRow, h5pct: -1 }],
);
const claudeLine = lines.find((l) => l.startsWith('Claude'))!;
const codexLine = lines.find((l) => l.startsWith('Codex'))!;
for (const line of [claudeLine, codexLine]) {
expect(line).toContain('─────');
// Only the 7d column carries a percentage.
expect(line.match(/%/g)).toHaveLength(1);
}
});
it('returns fallback text when both groups are empty', () => {
const lines = renderUsageTable([], []);
expect(lines).toEqual(['_조회 불가_']);