// The usage window and the menu read the same data on a timer, and a browser // tab is the wrong place to be unsure about what it asked for or when: a read // stacked on another, a clock still running while the tab is away, a source // that fails or hangs and takes the healthy one's polling with it, or a read // that answers after its watcher was replaced are all invisible in daemon E2E // and costly in a browser nobody is watching. So the watcher runs here against // a controlled clock, timers, document and fetch. import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { stripTypeScriptTypes } from 'node:module'; import test from 'node:test'; const source = stripTypeScriptTypes( ( await readFile(new URL('../src/lib/usageWatch.ts', import.meta.url), 'utf8') ).replace(/^import [\s\S]*?;$/gm, ''), ); let imports = 0; // The module's two neighbours are the daemon's own thin request helpers; they // are stood in for here so a test can decide what each read answers, and so // what the watcher handed them (days, offset, scope, signal) can be read back. const prelude = ` const __usage = globalThis.__usage; const ask = (url, signal) => fetch(url, { signal }).then((response) => { if (!response.ok) throw new Error(url + ' answered ' + response.status); return response.json(); }); const getUsage = (days, at, signal, scope) => { __usage.reads.push({ what: 'usage', days, at, scope, signal }); const narrowed = scope && (scope.provider !== undefined || scope.account !== undefined); const query = 'days=' + days + '&utc_offset_minutes=' + at + (narrowed ? '&provider=' + (scope.provider ?? '') + '&account=' + (scope.account ?? '') : ''); return ask('/api/usage?' + query, signal); }; const getLimits = (signal) => { __usage.reads.push({ what: 'limits', signal }); return ask('/api/server', signal).then((server) => server.quota ?? []); }; const localOffset = () => __usage.offset; `; /** A browser stand-in: its clock, its timers, its document and its network. */ async function browser(t) { const saved = new Map(); const timers = new Map(); const listeners = new Set(); const requests = []; const reads = []; const watched = { added: 0, removed: 0 }; let nextTimer = 0; const clock = { at: Date.parse('2026-10-25T18:00:00Z') }; const document = { hidden: false, addEventListener(name, callback) { assert.equal(name, 'visibilitychange'); watched.added++; listeners.add(callback); }, removeEventListener(name, callback) { assert.equal(name, 'visibilitychange'); watched.removed++; listeners.delete(callback); }, }; const install = (name, value) => { saved.set(name, Object.getOwnPropertyDescriptor(globalThis, name)); Object.defineProperty(globalThis, name, { configurable: true, writable: true, value, }); }; t.after(() => { for (const [name, descriptor] of saved) { if (descriptor) Object.defineProperty(globalThis, name, descriptor); else delete globalThis[name]; } delete globalThis.__usage; }); install('document', document); install('Date', { now: () => clock.at }); install('setTimeout', (callback, delay) => { const id = ++nextTimer; timers.set(id, { callback, delay }); return id; }); install('clearTimeout', (id) => timers.delete(id)); install('fetch', (url, options = {}) => { const request = { url, signal: options.signal, done: false, aborted: false, stubborn: false, }; requests.push(request); return new Promise((resolve, reject) => { const abort = () => { request.aborted = true; // A request that ignores being called off can still answer, as a socket may. if (request.stubborn) return; request.done = true; reject(new Error('aborted')); }; if (options.signal?.aborted) return abort(); options.signal?.addEventListener('abort', abort, { once: true }); request.respond = (body, status = 200) => { if (request.done) return; request.done = true; resolve({ ok: status < 300, status, json: () => Promise.resolve(body), }); }; request.fail = (status = 500) => { if (request.done) return; request.done = true; resolve({ ok: false, status, json: () => Promise.resolve({}) }); }; }); }); globalThis.__usage = { reads, offset: 120 }; const module = await import( `data:text/javascript;base64,${Buffer.from(prelude + source).toString('base64')}#${++imports}` ); /** Lets every read that has an answer run into the watcher. */ const settle = () => new Promise((resolve) => setImmediate(resolve)); const at = (delay) => [...timers].filter(([, timer]) => timer.delay === delay); return { ...module, requests, reads, watched, clock, document, timers, settle, /** The delays of the timers waiting right now, soonest first. */ delays: () => [...timers.values()].map((timer) => timer.delay).sort((a, b) => a - b), /** Runs the one timer waiting at `delay`, as the browser would. */ fire(delay) { const matches = at(delay); assert.equal( matches.length, 1, `expected one ${delay}ms timer, saw ${JSON.stringify([...timers.values()].map((timer) => timer.delay))}`, ); const [id, timer] = matches[0]; timers.delete(id); timer.callback(); }, /** Runs every timer waiting at `delay`, one source's or the clock's. */ fireAll(delay) { const matches = at(delay); assert.ok( matches.length > 0, `expected a ${delay}ms timer, saw ${JSON.stringify([...timers.values()].map((timer) => timer.delay))}`, ); for (const [id, timer] of matches) { timers.delete(id); timer.callback(); } }, /** The page travels, or its clock crosses a DST change: what `localOffset()` reads next. */ travelled(minutes) { globalThis.__usage.offset = minutes; }, visibility(hidden) { document.hidden = hidden; for (const callback of [...listeners]) callback(); }, /** Every request of one kind that has no answer yet. */ open(kind) { return requests.filter( (request) => request.url.includes(kind) && !request.done, ); }, }; } const usage = (calls) => ({ days: [ { start: '2026-10-25', calls, input_tokens: 0, output_tokens: 0, cached_input_tokens: 0, reasoning_tokens: 0, }, ], lines: [], scopes: [], scopes_truncated: false, lines_truncated: false, }); const limit = (extra = {}) => ({ provider: 'anthropic', account_id: 'me@example.com', limit_id: 'five_hour', label: '5 hour', used_percent: 40, observed_at: '2026-10-25T17:55:00Z', resets_at: '2026-10-25T20:14:00Z', error: null, ...extra, }); test('a watch says loading at once and reads its day and the limits once', async (t) => { const page = await browser(t); const seen = []; page.watchUsage((reading) => seen.push(reading)); // Nothing has been read yet, so the first thing said is that nothing is known. assert.equal(seen.length, 1); assert.deepEqual(seen[0].usage, { data: null, state: 'loading', refreshedAt: null, }); assert.deepEqual(seen[0].limits, { data: null, state: 'loading', refreshedAt: null, }); assert.equal(seen[0].now, page.clock.at); assert.equal(seen[0].offset, 120); assert.deepEqual( page.requests.map((request) => request.url), ['/api/usage?days=1&utc_offset_minutes=120', '/api/server'], ); page.requests[0].respond(usage(7)); page.requests[1].respond({ quota: [limit()] }); await page.settle(); const ready = seen.at(-1); assert.deepEqual(ready.usage, { data: usage(7), state: 'ready', refreshedAt: page.clock.at, }); assert.deepEqual(ready.limits, { data: [limit()], state: 'ready', refreshedAt: page.clock.at, }); // Each source waits its half minute, and the page's clock ticks beside them. assert.deepEqual(page.delays(), [ page.USAGE_MS.clock, page.USAGE_MS.shown, page.USAGE_MS.shown, ]); }); test('every caller of one query shares its read, and a narrow query leaves the limits whole', async (t) => { const page = await browser(t); const first = []; const second = []; page.watchUsage((reading) => first.push(reading), { days: 1 }); page.watchUsage((reading) => second.push(reading), { days: 1, provider: 'anthropic', account: 'work', }); await page.settle(); // One read per query and one set of limits for both, not one each. assert.deepEqual( page.reads.map((read) => read.what), ['usage', 'limits', 'usage'], ); assert.deepEqual( page.reads.map((read) => read.days ?? null), [1, null, 1], ); assert.equal(page.reads[0].scope, undefined); assert.deepEqual(page.reads[2].scope, { provider: 'anthropic', account: 'work', }); // The limits are account-wide: the usage filter never reaches them. assert.equal(page.reads[1].scope, undefined); assert.equal( page.requests.filter((request) => request.url === '/api/server').length, 1, ); page.requests[0].respond(usage(3)); page.requests[1].respond({ quota: [limit()] }); page.requests[2].respond(usage(1)); await page.settle(); assert.equal(first.at(-1).usage.data.days[0].calls, 3); assert.equal(second.at(-1).usage.data.days[0].calls, 1); // Both saw the same limits read, once. assert.deepEqual(first.at(-1).limits.data, second.at(-1).limits.data); }); test('a caller arriving to a reading made a moment ago is shown it without another read', async (t) => { const page = await browser(t); page.watchUsage(() => {}, { days: 1 }); page.requests[0].respond(usage(4)); page.requests[1].respond({ quota: [limit()] }); await page.settle(); const reads = page.reads.length; // The window opens on another query: its own day is read, the limits it already shares are not. const week = []; page.watchUsage((reading) => week.push(reading), { days: 7 }); assert.equal(week.length, 1); assert.equal(week[0].limits.state, 'ready'); assert.deepEqual( page.requests.slice(2).map((request) => request.url), ['/api/usage?days=7&utc_offset_minutes=120'], ); assert.equal(page.reads.length, reads + 1); // A second caller of a query read a moment ago is told straight away, and reads nothing. const again = []; page.watchUsage((reading) => again.push(reading), { days: 1 }); assert.deepEqual(again[0].usage, { data: usage(4), state: 'ready', refreshedAt: page.clock.at, }); assert.equal(page.reads.length, reads + 1); assert.equal(page.requests.length, 3); }); test('an account that is empty is a filter of its own, not the unfiltered read', async (t) => { const page = await browser(t); page.watchUsage(() => {}, { days: 1, provider: 'anthropic', account: '' }); page.watchUsage(() => {}, { days: 1, provider: 'anthropic' }); await page.settle(); // Two reads, because "all accounts" and "the account with no label" are two questions. assert.equal(page.reads.filter((read) => read.what === 'usage').length, 2); assert.deepEqual(page.reads[0].scope, { provider: 'anthropic', account: '' }); assert.deepEqual(page.reads[2].scope, { provider: 'anthropic', account: undefined, }); }); test('a tick that changes nothing says nothing, and the clock alone moves now', async (t) => { const page = await browser(t); const seen = []; page.watchUsage((reading) => seen.push(reading)); page.requests[0].respond(usage(3)); page.requests[1].respond({ quota: [] }); await page.settle(); const told = seen.length; const fetched = page.requests.length; // The clock ticks but the page's time has not moved: nothing is said. page.fire(page.USAGE_MS.clock); assert.equal(seen.length, told); // A few seconds later the age of the reading has changed, and only `now` with it. page.clock.at += 4_000; page.fire(page.USAGE_MS.clock); assert.equal(seen.length, told + 1); assert.equal(seen.at(-1).now, page.clock.at); // `refreshedAt` is when the browser read it, not when the clock last moved. assert.equal(seen.at(-1).usage.refreshedAt, page.clock.at - 4_000); assert.equal(page.requests.length, fetched); }); test('a failed usage read leaves the limits standing and comes back sooner', async (t) => { const page = await browser(t); const seen = []; page.watchUsage((reading) => seen.push(reading)); page.requests[0].fail(500); await page.settle(); // Settled on its own, before the limits answered at all: one source failing is not the other's failure. assert.deepEqual(seen.at(-1).usage, { data: null, state: 'error', refreshedAt: null, }); assert.deepEqual(seen.at(-1).limits, { data: null, state: 'loading', refreshedAt: null, }); page.requests[1].respond({ quota: [limit()] }); await page.settle(); assert.deepEqual(seen.at(-1).limits, { data: [limit()], state: 'ready', refreshedAt: page.clock.at, }); assert.deepEqual(seen.at(-1).usage, { data: null, state: 'error', refreshedAt: null, }); // The one that failed is retried in ten seconds, the one that answered in thirty. assert.deepEqual(page.delays(), [ page.USAGE_MS.clock, page.USAGE_MS.retry, page.USAGE_MS.shown, ]); }); test('a read that fails after a good one keeps the last numbers, marked stale', async (t) => { const page = await browser(t); const seen = []; page.watchUsage((reading) => seen.push(reading)); page.requests[0].respond(usage(5)); page.requests[1].respond({ quota: [limit()] }); await page.settle(); const good = seen.at(-1); page.clock.at += page.USAGE_MS.shown; page.fireAll(page.USAGE_MS.shown); page.requests[2].fail(); page.requests[3].fail(); await page.settle(); const stale = seen.at(-1); assert.equal(stale.usage.state, 'stale'); assert.equal(stale.usage.data, good.usage.data); assert.equal(stale.usage.refreshedAt, good.usage.refreshedAt); assert.equal(stale.limits.state, 'stale'); assert.equal(stale.limits.data, good.limits.data); assert.equal(stale.now, page.clock.at); }); test('a poke during a read is answered by that read and queues no second one', async (t) => { const page = await browser(t); const seen = []; page.watchUsage((reading) => seen.push(reading)); await page.settle(); const opening = page.requests.length; assert.equal(opening, 2); // The menu opening while the first read runs wants what that read is already fetching. page.pokeUsage(); page.pokeUsage(); assert.equal(page.requests.length, opening); page.requests[0].respond(usage(1)); page.requests[1].respond({ quota: [] }); await page.settle(); // One batch for the watch and the pokes together: nothing trails the settling read. assert.equal(page.requests.length, opening); assert.deepEqual(seen.at(-1).usage, { data: usage(1), state: 'ready', refreshedAt: page.clock.at, }); assert.deepEqual(seen.at(-1).limits, { data: [], state: 'ready', refreshedAt: page.clock.at, }); assert.deepEqual(page.delays(), [ page.USAGE_MS.clock, page.USAGE_MS.shown, page.USAGE_MS.shown, ]); }); test('a source that never answers is given up on without stopping the other', async (t) => { const page = await browser(t); const seen = []; page.watchUsage((reading) => seen.push(reading)); page.requests[1].respond({ quota: [limit()] }); await page.settle(); assert.equal(seen.at(-1).limits.state, 'ready'); assert.equal(seen.at(-1).usage.state, 'loading'); // The healthy source keeps its own half minute while the other is still hanging. page.clock.at += page.USAGE_MS.shown; page.fire(page.USAGE_MS.shown); assert.equal(page.open('usage').length, 1); assert.equal( page.requests.filter((request) => request.url === '/api/server').length, 2, ); page.requests[2].respond({ quota: [limit({ used_percent: 55 })] }); await page.settle(); assert.equal(seen.at(-1).limits.data[0].used_percent, 55); assert.equal(seen.at(-1).usage.state, 'loading'); // The one that hangs is given up on, says so, and is retried in ten seconds. page.fire(page.USAGE_MS.timeout); assert.equal(page.requests[0].aborted, true); assert.deepEqual(seen.at(-1).usage, { data: null, state: 'error', refreshedAt: null, }); assert.deepEqual(page.delays(), [ page.USAGE_MS.clock, page.USAGE_MS.retry, page.USAGE_MS.shown, ]); }); test('nothing is read or timed while the tab is hidden, even from the first watch', async (t) => { const page = await browser(t); page.document.hidden = true; const seen = []; page.watchUsage((reading) => seen.push(reading)); // A page opened in a background tab reads nothing and arms nothing. assert.deepEqual(page.delays(), []); assert.equal(page.requests.length, 0); assert.equal(seen[0].usage.state, 'loading'); page.pokeUsage(); assert.equal(page.requests.length, 0); // Back: the clock starts, and both sources are read at once, each with its own giving-up timer. page.visibility(false); assert.equal(page.requests.length, 2); assert.deepEqual(page.delays(), [ page.USAGE_MS.clock, page.USAGE_MS.timeout, page.USAGE_MS.timeout, ]); }); test('a read that answers while the tab is away keeps what it found and arms nothing', async (t) => { const page = await browser(t); const seen = []; page.watchUsage((reading) => seen.push(reading)); // The tab goes away with both reads already running, and they answer anyway. page.visibility(true); page.requests[0].respond(usage(6)); page.requests[1].respond({ quota: [limit()] }); await page.settle(); // What they found is kept for the return, and no timer is left waiting over a hidden tab. assert.deepEqual(seen.at(-1).usage, { data: usage(6), state: 'ready', refreshedAt: page.clock.at, }); assert.deepEqual(page.delays(), []); page.visibility(false); assert.equal(page.requests.length, 4); }); test('a read the tab walked away from is called off with nothing left behind', async (t) => { const page = await browser(t); const seen = []; page.watchUsage((reading) => seen.push(reading)); page.requests[0].respond(usage(6)); page.requests[1].respond({ quota: [limit()] }); await page.settle(); page.visibility(true); assert.deepEqual(page.delays(), []); // A watch that starts and stops while the tab is away asks nothing. const later = page.watchUsage(() => {}, { days: 7 }); assert.equal(page.requests.length, 2); later(); assert.deepEqual(page.delays(), []); // Back: how old the reading is, and a read of each source now rather than after the wait. page.clock.at += 120_000; page.visibility(false); assert.equal(seen.at(-1).now, page.clock.at); assert.equal(page.requests.length, 4); assert.equal(page.watched.added - page.watched.removed, 1); }); test('an abandoned read that answers anyway cannot touch the watcher that replaced it', async (t) => { const page = await browser(t); const abandoned = []; const stop = page.watchUsage((reading) => abandoned.push(reading)); // The request ignores being called off, as a socket already in flight may. page.requests[0].stubborn = true; page.requests[1].stubborn = true; stop(); assert.equal(page.requests[0].aborted, true); const seen = []; page.watchUsage((reading) => seen.push(reading)); await page.settle(); assert.equal(seen.length, 1); assert.equal(seen[0].usage.state, 'loading'); const [oldUsage, oldLimits] = page.requests.slice(0, 2); // Its answer arrives late: it is neither the new watcher's news nor its next timing. oldUsage.respond(usage(99)); oldLimits.respond({ quota: [limit({ used_percent: 99 })] }); await page.settle(); assert.equal(seen.length, 1); assert.equal(seen[0].usage.state, 'loading'); assert.equal(abandoned.length, 1); // Nothing the abandoned read would have scheduled: only the new reads' own giving-up timers and the clock. assert.deepEqual(page.delays(), [ page.USAGE_MS.clock, page.USAGE_MS.timeout, page.USAGE_MS.timeout, ]); // Only the watcher that is still here is answered, and only by its own read. page.requests[2].respond(usage(9)); page.requests[3].respond({ quota: [] }); await page.settle(); assert.deepEqual(seen.at(-1).usage, { data: usage(9), state: 'ready', refreshedAt: page.clock.at, }); assert.deepEqual(seen.at(-1).limits, { data: [], state: 'ready', refreshedAt: page.clock.at, }); assert.deepEqual(page.delays(), [ page.USAGE_MS.clock, page.USAGE_MS.shown, page.USAGE_MS.shown, ]); }); test('a caller that leaves from its own callback stops that source for good', async (t) => { const page = await browser(t); const leaveOther = page.watchUsage(() => {}, { days: 7 }); let leave; leave = page.watchUsage( (reading) => { if (reading.usage.state === 'ready') leave(); }, { days: 1 }, ); page.requests[0].respond(usage(2)); page.requests[1].respond({ quota: [] }); await page.settle(); page.open('days=1')[0].respond(usage(1)); await page.settle(); // The days=1 listener has gone and its slot was dropped, but the read it was told about settled into a // dead slot: the callback that dropped it ran before the next read was armed, and that read must not be // armed at all. Only the week and the limits keep their half minute, beside the clock. assert.deepEqual(page.delays(), [ page.USAGE_MS.clock, page.USAGE_MS.shown, page.USAGE_MS.shown, ]); const asked = page.requests.length; page.fireAll(page.USAGE_MS.shown); assert.equal(page.requests.length, asked + 2); assert.deepEqual(page.open('days=1'), []); // The last caller to leave stops everything: no timer outlives it, and no request it started outlives it. leaveOther(); assert.deepEqual(page.delays(), []); assert.deepEqual( page.requests.filter((request) => !request.done && !request.aborted), [], ); }); test('the last watcher to leave stops the clock and drops the caches', async (t) => { const page = await browser(t); const stopWeek = page.watchUsage(() => {}, { days: 7 }); page.requests[0].respond(usage(4)); page.requests[1].respond({ quota: [] }); await page.settle(); stopWeek(); // No read is left to happen, and no listener is left on the document. assert.deepEqual(page.delays(), []); assert.equal(page.watched.added - page.watched.removed, 0); // Coming back asks again rather than trusting what was dropped, and asks for what it now wants. page.watchUsage(() => {}, { days: 1 }); await page.settle(); assert.deepEqual( page.requests.slice(2).map((request) => request.url), ['/api/usage?days=1&utc_offset_minutes=120', '/api/server'], ); }); test('a page that travels reads at its new offset and keeps its cached days labelled the old way', async (t) => { const page = await browser(t); const seen = []; page.watchUsage((reading) => seen.push(reading)); page.requests[0].respond({ ...usage(2), utc_offset_minutes: 120 }); page.requests[1].respond({ quota: [limit()] }); await page.settle(); assert.equal(seen.at(-1).offset, 120); // Eight hours the other way: what is shown was cut at the old midnight, so it keeps saying so. page.travelled(-300); page.clock.at += 4_000; page.fire(page.USAGE_MS.clock); assert.equal(seen.at(-1).offset, 120); assert.equal(seen.at(-1).usage.data.utc_offset_minutes, 120); // The next read asks with the offset the page has now, and its answer relabels the days. page.clock.at += page.USAGE_MS.shown; page.fireAll(page.USAGE_MS.shown); assert.equal(page.reads.filter((read) => read.what === 'usage')[1].at, -300); assert.equal(seen.at(-1).offset, 120); page.requests[2].respond({ ...usage(2), utc_offset_minutes: -300 }); page.requests[3].respond({ quota: [limit()] }); await page.settle(); assert.equal(seen.at(-1).offset, -300); }); test('limits keep the provider own observation time beside the browser read time', async (t) => { const page = await browser(t); const seen = []; page.watchUsage((reading) => seen.push(reading)); page.requests[0].respond(usage(1)); page.requests[1].respond({ quota: [limit({ observed_at: '2026-10-25T17:00:00Z' })], }); await page.settle(); assert.equal(seen.at(-1).limits.data[0].observed_at, '2026-10-25T17:00:00Z'); assert.equal(seen.at(-1).limits.refreshedAt, page.clock.at); });