// The usage window and the top-bar menu draw from these: a count that reads // wrong, a day named for the wrong date, a limit shown as fresh when it is // stale, or a bar floored so a sliver looks like a tenth is visible only in a // browser with a daemon that has been used for days. 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/usage.ts', import.meta.url), 'utf8'), ); const { HOT, accountCap, dayDate, dayLabel, fillPercent, foldGroups, groupHot, groupLimits, isToday, limitName, lineWho, limitTitle, observedAge, percentOf, scopeChoices, scopeFilter, scopeKey, scopeLabels, scopeText, scopesOf, sizeOf, standing, totalsOf, weekdayName, windowText, } = await import( `data:text/javascript;base64,${Buffer.from(source).toString('base64')}` ); const NOW = Date.parse('2026-10-25T18:00:00Z'); 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, }); const day = (extra) => ({ start: '2026-10-25T06:00:00Z', calls: 3, errors: 0, input_tokens: 1200, cached_input_tokens: 240, cache_creation_tokens: 60, output_tokens: 300, reasoning_tokens: 0, ...extra, }); const line = (extra) => ({ profile: 'work', provider: 'anthropic', account: 'me@example.com', model: 'claude-opus-5', calls: 3, errors: 0, input_tokens: 1200, cached_input_tokens: 240, cache_creation_tokens: 60, output_tokens: 300, reasoning_tokens: 0, ...extra, }); test('a share is a whole percent only of something, and never more than the whole', () => { assert.equal(percentOf(36, 48), 75); assert.equal(percentOf(0, 48), null); assert.equal(percentOf(5, 0), null); assert.equal(percentOf(9, 4), null); }); test('a bar’s length is the exact percent of its track, with no floor and no overflow', () => { assert.equal(fillPercent(40, 100), 40); assert.equal(fillPercent(1, 100), 1); assert.equal(fillPercent(0, 100), 0); assert.equal(fillPercent(140, 100), 100); assert.equal(fillPercent(-5, 100), 0); assert.equal(fillPercent(5, 0), 0); // A day a thousandth of the busiest is a thousandth as tall, not four percent. assert.equal(fillPercent(3, 3000), 0.1); // What a bar measures is the input and the output together, and cache reads are already inside the input. assert.equal( sizeOf({ input_tokens: 10, output_tokens: 3, cached_input_tokens: 9 }), 13, ); }); test('a window adds up its days, and says what it is in words', () => { const total = totalsOf([ day({}), day({ start: '2026-10-24T06:00:00Z', calls: 2, errors: 1, input_tokens: 800, cached_input_tokens: 0, cache_creation_tokens: 0, output_tokens: 200, reasoning_tokens: 90, }), ]); assert.deepEqual(total, { calls: 5, errors: 1, input_tokens: 2000, cached_input_tokens: 240, cache_creation_tokens: 60, output_tokens: 500, reasoning_tokens: 90, }); assert.deepEqual(totalsOf([]), { calls: 0, errors: 0, input_tokens: 0, cached_input_tokens: 0, cache_creation_tokens: 0, output_tokens: 0, reasoning_tokens: 0, }); assert.deepEqual([1, 7, 30].map(windowText), [ 'today', 'the last 7 days', 'the last 30 days', ]); }); test("a day is the client's today exactly when its own midnight is that day's", () => { // Six hours behind UTC: local midnight is 06:00 UTC, and it is noon on the 25th. assert.equal(isToday(Date.parse('2026-10-25T06:00:00Z'), NOW, -360), true); assert.equal(isToday(Date.parse('2026-10-24T06:00:00Z'), NOW, -360), false); }); test("a day also reads as a date and a weekday, cut at the client's midnight", () => { assert.equal(dayDate(Date.parse('2026-10-23T06:00:00Z'), -360), 'fri 23 oct'); assert.equal(weekdayName(Date.parse('2026-10-23T06:00:00Z'), -360), 'fri'); assert.equal(weekdayName(Date.parse('2026-10-22T18:00:00Z'), 360), 'fri'); assert.deepEqual( ['2026-10-24', '2026-10-25', '2026-10-26'].map((date) => weekdayName(Date.parse(`${date}T00:00:00Z`), 0), ), ['sat', 'sun', 'mon'], ); }); test('the strip under the chart names the day it is about', () => { // Today's own numbers are still moving, so its label says so; any other day is named by its date. assert.equal( dayLabel(Date.parse('2026-10-25T06:00:00Z'), NOW, -360), 'today so far', ); assert.equal( dayLabel(Date.parse('2026-10-21T06:00:00Z'), NOW, -360), 'wed 21 oct', ); assert.equal( dayLabel(Date.parse('2026-10-24T06:00:00Z'), NOW, -360), 'sat 24 oct', ); }); test('a limit is trusted by how recently and how well it was read', () => { assert.equal(standing(limit({}), NOW), 'fresh'); assert.equal( standing( limit({ error: { code: 'quota_failed', detail: 'rejected' } }), NOW, ), 'failed', ); assert.equal(standing(limit({ used_percent: null }), NOW), 'unknown'); assert.equal( standing(limit({ observed_at: '2026-10-25T17:00:00Z' }), NOW), 'old', ); assert.equal( standing(limit({ resets_at: '2026-10-25T17:59:00Z' }), NOW), 'old', ); assert.equal(standing(limit({ resets_at: null }), NOW), 'fresh'); }); test('a reading whose timestamp cannot be read is unknown, never fresh', () => { // A NaN age made `now - NaN > STALE` false, so an unreadable stamp passed for a current reading. assert.equal(standing(limit({ observed_at: '' }), NOW), 'unknown'); assert.equal(standing(limit({ observed_at: 'not a date' }), NOW), 'unknown'); assert.equal(standing(limit({ observed_at: null }), NOW), 'unknown'); assert.equal(observedAge(limit({ observed_at: '' }), NOW), null); assert.equal(observedAge(limit({}), NOW), '5m'); assert.equal( observedAge(limit({ observed_at: '2026-10-25T15:00:00Z' }), NOW), '3h', ); }); test('a limit says when it was read, when it resets, and why it has no reading', () => { // Every row can give its exact times, not only a fresh one: a tooltip or a reading-out needs both. assert.match( limitTitle(limit({}), NOW), /^read .+\(5 min ago\) · resets .+\(in 2h14m\)$/, ); assert.match( limitTitle(limit({ resets_at: '2026-10-25T17:00:00Z' }), NOW), /\(passed\)$/, ); assert.match( limitTitle( limit({ resets_at: null, observed_at: '2026-10-25T15:00:00Z' }), NOW, ), /^read .+\(3 h ago\)$/, ); assert.match( limitTitle( limit({ error: { code: 'quota_failed', detail: 'rejected' } }), NOW, ), /the last poll failed: rejected$/, ); // A stamp that cannot be read says so instead of claiming a time. assert.equal( limitTitle(limit({ observed_at: '', resets_at: null }), NOW), 'its reading time cannot be read', ); assert.match( limitTitle(limit({ resets_at: 'whenever' }), NOW), /its reset time cannot be read$/, ); }); test('limits are grouped by provider and account in the order given, and named for what they are', () => { const groups = groupLimits([ limit({}), limit({ limit_id: 'seven_day', label: '7 day' }), limit({ account_id: 'anthropic', label: 'Other' }), limit({ provider: 'hyper', account_id: 'hyper' }), ]); assert.deepEqual( groups.map((group) => [group.name, group.limits.length]), [ ['Anthropic · me@example.com', 2], ['Anthropic', 1], ['Hyper', 1], ], ); assert.equal( limitName(limit({ label: '', error: { code: 'x', detail: 'y' } })), 'last poll failed', ); assert.equal(limitName(limit({ label: '' })), 'five_hour'); assert.equal( limitName(limit({ label: '', limit_id: '' })), 'no limits reported', ); }); test('accounts past the third fold in a fixed order, each summarised by its highest cap', () => { const groups = groupLimits([ limit({ provider: 'a', account_id: 'a' }), limit({ provider: 'b', account_id: 'b', used_percent: 61 }), limit({ provider: 'c', account_id: 'c' }), limit({ provider: 'd', account_id: 'd', used_percent: HOT }), limit({ provider: 'e', account_id: 'e', used_percent: null }), ]); const fold = foldGroups(groups); assert.deepEqual( fold.shown.map((group) => group.name), ['a', 'b', 'c'], ); assert.deepEqual( fold.folded.map((group) => group.name), ['d', 'e'], ); // A folded group is told by its highest cap only, so a hot one is visible and opens the fold. assert.deepEqual( fold.folded.map((group) => accountCap(group, NOW)), [`${HOT}%`, 'no percentage'], ); assert.deepEqual( fold.folded.map((group) => groupHot(group, NOW)), [true, false], ); // The order never follows the percentages: the same three stay shown when they get busier. const busier = groupLimits([ limit({ provider: 'a', account_id: 'a', used_percent: 3 }), limit({ provider: 'b', account_id: 'b', used_percent: 99 }), limit({ provider: 'c', account_id: 'c', used_percent: 1 }), ]); assert.deepEqual( foldGroups(busier).shown.map((group) => group.name), ['a', 'b', 'c'], ); // Three or fewer accounts are all shown, and nothing folds. assert.deepEqual(foldGroups(groups.slice(0, 3)), { shown: groups.slice(0, 3), folded: [], }); // A stale reading cannot make a group hot, and a failed one has no cap to give. const stale = groupLimits([ limit({ provider: 'f', account_id: 'f', used_percent: 99, observed_at: '2026-10-20T00:00:00Z', }), ]); assert.equal(groupHot(stale[0], NOW), false); assert.equal(accountCap(stale[0], NOW), '99%'); assert.equal( accountCap( groupLimits([ limit({ provider: 'g', account_id: 'g', used_percent: null, error: { code: 'x', detail: 'y' }, }), ])[0], NOW, ), 'no reading', ); }); test('a line says who made the calls, with the account when there is one', () => { assert.equal(lineWho(line({})), 'work · me@example.com'); assert.equal(lineWho(line({ profile: 'home', account: null })), 'home'); // An account labelled with its own profile's name reads as "ollama · ollama" otherwise, and the // row recorded with no account says so, since two rows of one profile must stay apart. const noAccount = line({ profile: 'ollama', provider: 'chat_completions:https://ollama.com/v1', account: null, }); const named = line({ profile: 'ollama', provider: 'chat_completions:https://ollama.com/v1', account: 'ollama', }); assert.equal(lineWho(noAccount, [noAccount, named]), 'ollama · no account'); assert.equal(lineWho(named, [noAccount, named]), 'ollama'); // A lone profile with no account needs no such line, and its other accounts still tell rows apart. assert.equal( lineWho(line({ profile: 'home', account: null }), [ line({ profile: 'home', account: null }), ]), 'home', ); assert.equal( lineWho(line({ profile: 'me', account: 'me@example.com' }), [ line({ profile: 'me', account: 'other@example.com' }), ]), 'me · me@example.com', ); }); test('an id or a hash is no name: it is left off, unless several accounts need telling apart', () => { const uuid = 'df3eba1d-874a-4762-8d64-7e2feb475634'; const hash = '1ba6a50e45eecfdf'; assert.equal(lineWho(line({ profile: 'codex', account: uuid })), 'codex'); assert.equal( lineWho(line({ profile: 'codex', account: uuid }), [ line({ profile: 'codex', account: uuid }), line({ profile: 'codex', account: uuid }), line({ profile: 'ollama', account: null }), ]), 'codex', ); const two = [ line({ profile: 'codex', account: uuid }), line({ profile: 'codex', account: '0a1b2c3d-0000-4000-8000-000000000000' }), ]; assert.equal(lineWho(two[0], two), 'codex · df3eba'); assert.equal( lineWho(line({ profile: 'codex', account: 'me@example.com' }), two), 'codex · me@example.com', ); assert.deepEqual( groupLimits([limit({ account_id: hash })]).map((group) => group.name), ['Anthropic'], ); const several = groupLimits([ limit({ account_id: hash }), limit({ account_id: 'ffeeddccbbaa9988' }), limit({ account_id: 'me@example.com' }), ]); assert.deepEqual( several.map((group) => group.name), ['Anthropic · 1ba6a5', 'Anthropic · ffeedd', 'Anthropic · me@example.com'], ); // Two accounts that shorten alike stay two groups. assert.equal( groupLimits([ limit({ account_id: 'abcdef0000000001' }), limit({ account_id: 'abcdef0000000002' }), ]).length, 2, ); }); test('the scopes a window offers are the unfiltered ones, less any that cannot be drawn', () => { const summary = { generated_at: '2026-10-25T18:02:00Z', utc_offset_minutes: -360, days: [day({})], lines: [line({})], }; // Nothing to offer is no selector, and a response with no scopes reads as none rather than failing. assert.deepEqual(scopesOf(summary), { scopes: [], truncated: false }); assert.deepEqual(scopesOf(null), { scopes: [], truncated: false }); const scopes = [ { provider: 'anthropic', account: 'me@example.com' }, { provider: 'codex', account: null }, ]; assert.deepEqual(scopesOf({ ...summary, scopes, scopes_truncated: true }), { scopes, truncated: true, }); // Nonsense in the field is dropped, not drawn. assert.deepEqual( scopesOf({ ...summary, scopes: [ { provider: '' }, { account: 'x' }, { provider: 'hyper', account: null }, ], }).scopes, [{ provider: 'hyper', account: null }], ); }); test('provider-wide, no-account and exact account filters have distinct identities', () => { const all = { provider: 'codex' }; const none = { provider: 'codex', account: null }; const exact = { provider: 'codex', account: 'me@example.com' }; assert.deepEqual(scopeFilter(null), {}); assert.deepEqual(scopeFilter(all), { provider: 'codex' }); assert.deepEqual(scopeFilter(none), { provider: 'codex', account: '' }); assert.deepEqual(scopeFilter(exact), exact); assert.equal( new Set([scopeKey(null), scopeKey(all), scopeKey(none), scopeKey(exact)]) .size, 4, ); assert.notEqual( scopeKey({ provider: 'a\nb', account: 'c' }), scopeKey({ provider: 'a', account: 'b\nc' }), ); const choices = scopeChoices([none, exact]); assert.deepEqual( choices.options.map((option) => option.scope), [null, all, none, exact], ); assert.deepEqual( choices.options.map((option) => option.text), [ 'all providers', 'codex · all accounts', 'codex · no account', 'codex · me@example.com', ], ); // One group per provider, which is what the selector opens as an . assert.deepEqual( choices.groups.map((group) => group.name), ['codex'], ); assert.equal(scopeText(none), 'codex · no account'); }); // The daemon E2E suite cannot exercise the browser's scope naming at all, and // this client may not assume a mapping from a usage identity to an account // handle: none is verified, so none may be shown. test("scope names lead with the provider and come from the window's own rows", () => { const provider = 'responses:https://chatgpt.com/backend-api'; const scopes = [ { provider, account: 'workspace-one' }, { provider, account: 'workspace-two' }, ]; const lines = [ { provider, account: 'workspace-one', profile: 'codex alt' }, { provider, account: 'workspace-two', profile: 'codex' }, ]; const labels = scopeLabels(scopes, lines); const choices = scopeChoices(scopes, labels); assert.deepEqual( choices.options.map((option) => option.text), [ 'all providers', 'ChatGPT · all accounts', 'ChatGPT · workspace-one', 'ChatGPT · workspace-two', ], ); assert.deepEqual( choices.options.map((item) => item.key), scopeChoices(scopes).options.map((item) => item.key), ); assert.deepEqual(scopeFilter(choices.options[2].scope), { provider, account: 'workspace-one', }); // A name no row of the window carries never names a scope, however real it is: the label falls back to the // account's own text, and the provider to its endpoint. const unrecorded = { provider, account: 'workspace-three' }; assert.equal( scopeLabels([unrecorded], []).get(scopeKey(unrecorded)), 'ChatGPT · workspace-three', ); }); // A provider with one account needs one choice, not the same data twice under two names, and a scope a // period no longer reports keeps the label it had rather than falling back to its raw key. test('a provider offers one choice per account, and a scope with no use this period keeps its name', () => { const provider = 'chat_completions:https://ollama.com/v1'; const only = { provider, account: null }; const single = scopeChoices( [only], scopeLabels([only], [{ ...only, profile: 'home' }]), ); assert.deepEqual( single.options.map((option) => option.text), ['all providers', 'Ollama · home'], ); assert.equal(single.groups.length, 1); // The provider-wide choice of that one account is what the selector already offers: it is not kept twice. const labels = scopeLabels([only], [{ ...only, profile: 'home' }]); assert.equal(scopeChoices([only], labels, { provider }).options.length, 2); // Chosen last week, nothing used this week: still offered, still selected, and named as it was. const kept = scopeChoices([], labels, only); assert.deepEqual( kept.options.map((option) => option.text), ['all providers', 'Ollama · home (no use in this period)'], ); assert.deepEqual( kept.groups.map((group) => group.name), ['Ollama'], ); assert.equal(kept.options[1].key, scopeKey(only)); }); // The real thing: one profile's calls recorded with no account at all next to calls recorded under // an account named after that same profile. Both are rows of their own, and neither may be nameless. test('a scope recorded with no account is told apart from an account named after its profile', () => { const provider = 'chat_completions:https://ollama.com/v1'; const none = { provider, account: null }; const named = { provider, account: 'ollama' }; const scopes = [none, named]; const lines = [ { provider, account: null, profile: 'ollama' }, { provider, account: 'ollama', profile: 'ollama' }, ]; const labels = scopeLabels(scopes, lines); assert.equal(labels.get(scopeKey(none)), 'Ollama · no account'); assert.equal(labels.get(scopeKey(named)), 'Ollama · ollama'); // They select different rows, so they stay two choices under two names rather than one. const choices = scopeChoices(scopes, labels); assert.deepEqual( choices.options.map((option) => option.text), [ 'all providers', 'Ollama · all accounts', 'Ollama · no account', 'Ollama · ollama', ], ); assert.deepEqual( choices.options.map((option) => scopeFilter(option.scope)), [ {}, { provider }, { provider, account: '' }, { provider, account: 'ollama' }, ], ); }); test('a scope with no rows, no account, or an account that names nobody still reads as one filter each', () => { const provider = 'responses:https://chatgpt.com/backend-api'; const local = { provider: 'chat_completions:https://ollama.com/v1', account: null, }; assert.equal( scopeLabels([local], [{ ...local, profile: 'home' }]).get(scopeKey(local)), 'Ollama · home', ); assert.equal( scopeLabels([local], []).get(scopeKey(local)), 'Ollama · no account', ); // An id or a hash is no name: the profiles that used it stand in, and its first characters only when nothing else can. const hashed = { provider, account: '1ba6a50e45eecfdf' }; assert.equal( scopeLabels([hashed], []).get(scopeKey(hashed)), 'ChatGPT · 1ba6a5', ); assert.equal( scopeLabels([hashed], [{ ...hashed, profile: 'codex alt' }]).get( scopeKey(hashed), ), 'ChatGPT · codex alt', ); const email = { provider, account: 'me@example.com' }; assert.equal( scopeLabels([email], []).get(scopeKey(email)), 'ChatGPT · me@example.com', ); // Two exact filters that would shorten alike stay two, told apart by the whole of what they filter on. const first = { provider, account: 'abcdef0000000001' }; const second = { provider, account: 'abcdef0000000002' }; const short = scopeLabels([first, second], []); assert.equal(short.get(scopeKey(first)), 'ChatGPT · abcdef0000000001'); assert.equal(short.get(scopeKey(second)), 'ChatGPT · abcdef0000000002'); assert.deepEqual( scopesOf({ scopes: [{ provider }, { provider, account: 42 }] }).scopes, [], ); });