import type { Quota, UsageSummary } from './api'; import type { UsageDays } from './usageWatch'; // What the daemon says was used (`GET /usage`) and what the providers say is // left (the quota readings on `GET /server`), made ready to draw: short counts, // day names in the client's own days, bars as exact shares, and the standing of // each limit. The usage window and the top-bar menu both draw from this. /** What a day or a model used, as `GET /usage` reports it. */ export type Totals = Pick< UsageSummary['days'][number], | 'calls' | 'errors' | 'input_tokens' | 'cached_input_tokens' | 'cache_creation_tokens' | 'output_tokens' | 'reasoning_tokens' >; /** The windows the usage window offers. The watcher owns what may be asked for; this is how they are named. */ export const USAGE_WINDOWS: readonly { days: UsageDays; label: string }[] = [ { days: 1, label: 'today' }, { days: 7, label: 'last 7 days' }, { days: 30, label: 'last 30 days' }, ]; /** A window in words, for a heading: "today", "the last 7 days". */ export const windowText = (days: UsageDays): string => days === 1 ? 'today' : `the last ${days} days`; /** What a bar measures: what went in and came out. Cache reads are already inside the input, so they are not added again. */ export const sizeOf = (totals: Totals): number => totals.input_tokens + totals.output_tokens; const noTotals = (): Totals => ({ calls: 0, errors: 0, input_tokens: 0, cached_input_tokens: 0, cache_creation_tokens: 0, output_tokens: 0, reasoning_tokens: 0, }); /** * Every day of a window added up: the whole of what was used, which is the sum * of the days and not of the model lines (those stop at the busiest hundred). */ export function totalsOf(days: readonly Totals[]): Totals { const total = noTotals(); for (const day of days) for (const key of Object.keys(total) as (keyof Totals)[]) total[key] += day[key] ?? 0; return total; } /** A token count short enough for a row, in three figures at most: 940, 9.8k, 340k, 1.4m, 208m, 2.2b, as the terminal and the context chip write them. */ export function countText(count: number): string { if (count < 1000) return String(count); const [size, unit] = count >= 999_500_000 ? [1e9, 'b'] : count >= 999_500 ? [1e6, 'm'] : [1e3, 'k']; const value = count / size; return `${value >= 9.95 ? Math.round(value) : value.toFixed(1).replace(/\.0$/, '')}${unit}`; } /** * A call count: exact under a hundred thousand, because calls are the number a * person reconciles against the provider's own dashboard, and short above it. */ export const callsText = (calls: number): string => calls < 100_000 ? calls.toLocaleString() : countText(calls); /** * Failed calls are call counts: they take the same thousands and units as the * calls they are a share of, so "1,294 failed" reads beside "66,418 provider calls". */ export const failedText = (errors: number): string => callsText(errors); /** `part` as a whole percent of `whole`, or null when there is nothing to say it of. */ export function percentOf(part: number, whole: number): number | null { return whole > 0 && part > 0 && part <= whole ? Math.round((part / whole) * 100) : null; } /** * A bar's length in percent of its track, exact and clamped, with no floor: a * day a hundredth of the busiest is drawn a hundredth as tall, and a share too * small to see is told as a number beside the chart rather than drawn larger. */ export const fillPercent = (value: number, whole: number): number => value > 0 && whole > 0 ? Math.min(100, (value / whole) * 100) : 0; const dayFormat = new Intl.DateTimeFormat('en-GB', { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC', }); /** * A day against the clock it was read at: today, yesterday, then its weekday * and date. `start` is the day's midnight and `now` the moment of the read, both * Unix milliseconds, and `offset` the client's minutes ahead of UTC; shifting by * it makes the UTC calendar the client's, whatever zone this page runs in. */ function dayName(start: number, now: number, offset: number): string { const shifted = start + offset * 60_000; const today = Math.floor((now + offset * 60_000) / 86_400_000) * 86_400_000; if (shifted === today) return 'today'; if (shifted === today - 86_400_000) return 'yesterday'; return dayFormat.format(shifted).replace(',', ''); } /** Whether a day's midnight is the client's own today, on the same shifted clock. */ export function isToday(start: number, now: number, offset: number): boolean { return ( Math.floor((start + offset * 60_000) / 86_400_000) === Math.floor((now + offset * 60_000) / 86_400_000) ); } /** A day's weekday and date on the shifted clock, whatever `dayName` calls it ("fri 23 oct"). */ export const dayDate = (start: number, offset: number): string => dayFormat .format(start + offset * 60_000) .replace(',', '') .toLowerCase(); const weekdayFormat = new Intl.DateTimeFormat('en-GB', { weekday: 'short', timeZone: 'UTC', }); /** A day's weekday, short and lowercase ("wed"), on the same shifted clock as `dayName`. */ export const weekdayName = (start: number, offset: number): string => weekdayFormat.format(start + offset * 60_000).toLowerCase(); /** The day a strip under the chart is about: today while it runs, else its weekday and date ("wed 4 nov"). */ export const dayLabel = (start: number, now: number, offset: number): string => isToday(start, now, offset) ? 'today so far' : dayDate(start, offset); /** The minutes the page's own clock is ahead of UTC, which is what `GET /usage` asks for. */ export const localOffset = (date = new Date()): number => -date.getTimezoneOffset(); /** An offset as a clock says it: UTC+5:30, UTC−6. */ export function offsetName(minutes: number): string { const abs = Math.abs(Math.round(minutes)); const hours = Math.floor(abs / 60); const rest = abs % 60; return `UTC${minutes < 0 ? '\u2212' : '+'}${hours}${rest ? `:${String(rest).padStart(2, '0')}` : ''}`; } /** One model's use in the window, or one profile's, named the way a row says it. */ export type Line = UsageSummary['lines'][number]; /** An account label that names nobody: the id or hash a provider falls back to when it has no email. */ const opaque = (account: string): boolean => /^[0-9a-f]{8,}(-[0-9a-f]{4,})*$/i.test(account); /** An account as a row says it: an email or a name as it is, an id or hash only when several accounts need telling apart, and then its first six characters. */ function accountText(account: string, several: boolean): string | null { if (!opaque(account)) return account; return several ? account.slice(0, 6) : null; } export const lineName = (line: Line): string => line.model; /** * Who made a model's calls: its profile, and its account when that says * something or the profile has more than one among `lines`. An account named * after its own profile says nothing the line has not said already, and the one * recorded with no account says that much, so two rows of one profile never read * alike. */ export function lineWho(line: Line, lines: Line[] = []): string { const several = new Set( lines .filter((other) => other.profile === line.profile) .map((other) => other.account), ).size > 1; const account = line.account ? accountText(line.account, several) : null; if (account && account !== line.profile) return `${line.profile} · ${account}`; return several && !line.account ? `${line.profile} · no account` : line.profile; } /** * The names people know a provider by, from the host of the endpoint its calls * went to. The daemon records a provider as `:` * (`responses:https://chatgpt.com/backend-api`), so the name comes from the host * alone. A host that is not listed is shown as itself, never guessed at, and a * string that is not `:` is shown exactly as it is. The * terminal's usage view keeps the same table; change both together * (robot-docs/web.md). */ const PROVIDERS: readonly (readonly [RegExp, string])[] = [ [/^chatgpt\.com$/, 'ChatGPT'], [/^api\.openai\.com$/, 'OpenAI'], [/^api\.anthropic\.com$/, 'Anthropic'], [/^ollama\.com$/, 'Ollama'], [/^(generativelanguage|cloudcode-pa)\.googleapis\.com$/, 'Google'], [/^([a-z0-9-]+-)?aiplatform\.googleapis\.com$/, 'Vertex AI'], [/^bedrock-runtime\.[a-z0-9-]+\.amazonaws\.com$/, 'Bedrock'], [/^opencode\.ai$/, 'OpenCode'], [/^openrouter\.ai$/, 'OpenRouter'], [/^api\.deepseek\.com$/, 'DeepSeek'], [/^[a-z0-9-]+\.aliyuncs\.com$/, 'Alibaba'], [/^api\.githubcopilot\.com$/, 'GitHub Copilot'], ]; /** The endpoint a recorded provider points at, or null for a string that is not `:`. */ function endpointOf(provider: string): URL | null { const at = provider.indexOf(':'); if (at <= 0) return null; try { return new URL(provider.slice(at + 1)); } catch { return null; } } /** What to call a recorded provider: the name of the host it points at, that host (with its port), or the string itself. */ export function providerName(provider: string): string { const endpoint = endpointOf(provider); if (!endpoint) return provider; const host = endpoint.hostname.toLowerCase(); for (const [pattern, name] of PROVIDERS) if (pattern.test(host)) return name; return endpoint.host; } /** * A name for each of `providers` in the order given: `providerName`, with the * path added where two endpoints share a name and would otherwise read alike * (two local servers on one port, say). */ function providerNames(providers: string[]): Map { const names = new Map(); const used = new Map(); for (const provider of providers) { const name = providerName(provider); names.set(provider, name); used.set(name, (used.get(name) ?? 0) + 1); } for (const [provider, name] of names) { const path = (used.get(name) ?? 0) > 1 ? endpointOf(provider)?.pathname.replace(/\/$/, '') : ''; if (path) names.set(provider, `${name}${path}`); } return names; } /** * What a limit's provider is called. A limit's provider is the daemon's own id for * the account it polls (`src/albedo/daemon/quota.gleam`), never an endpoint, so * this table is separate from `PROVIDERS` above: "openai-codex" is the same * service as "ChatGPT" but arrives by another road. One entry for each provider * the daemon can read a limit for, and an id in neither list is shown exactly as * the daemon spells it. */ const LIMIT_PROVIDERS: Record = { anthropic: 'Anthropic', 'openai-codex': 'ChatGPT', 'google-antigravity': 'Antigravity', 'opencode-go': 'OpenCode Go', hyper: 'Hyper', deepseek: 'DeepSeek', alibaba: 'Alibaba', }; /** The readable name of the provider a limit belongs to, or its id when it is not one of these. */ const limitProviderName = (provider: string): string => LIMIT_PROVIDERS[provider] ?? provider; /** The account part of a scope's name: the account as it is, the profiles that used it when it says nothing, and "no account" for the unlabelled one. */ function accountName( account: string, profiles: string[], several: boolean, ): string { const label = account === '' ? null : accountText(account, several); return ( label ?? (profiles.join(', ') || (account ? account.slice(0, 6) : 'no account')) ); } /** A UI filter: absent account selects the provider; null selects its no-account rows. */ export type Scope = { provider: string; account?: string | null }; /** * The distinct provider and account pairs the window's calls were made under, * however the totals were filtered (the daemon answers with all of them), less * any that cannot be drawn: no pairs at all leaves the window no selector. */ export function scopesOf(summary: UsageSummary | null | undefined): { scopes: Scope[]; truncated: boolean; } { const sent: unknown = summary?.scopes; const scopes = Array.isArray(sent) ? sent.filter( (scope: Scope) => typeof scope?.provider === 'string' && scope.provider !== '' && (scope.account === null || typeof scope.account === 'string'), ) : []; return { scopes, truncated: summary?.scopes_truncated === true }; } /** What a chosen scope is kept as: one string for a provider and account, empty for all of them. */ export const scopeKey = (scope: Scope | null | undefined): string => scope?.provider ? JSON.stringify( scope.account === undefined ? [scope.provider] : [scope.provider, scope.account ?? ''], ) : ''; /** * The scope `GET /usage` takes for a chosen one: nothing for all of them, else * the provider and its account, or the empty account that means the provider * has none (leaving it out would ask for every account of that provider). */ export function scopeFilter(scope: Scope | null | undefined): { provider?: string; account?: string; } { if (!scope?.provider) return {}; return scope.account === undefined ? { provider: scope.provider } : { provider: scope.provider, account: scope.account ?? '' }; } /** * A scope as the selector says it: the provider by the name people know its * endpoint by, then the account, separated by the " · " every other line uses. */ export function scopeText( scope: Scope, scopes: Scope[] = [], labels: ReadonlyMap = new Map(), ): string { const named = labels.get(scopeKey(scope)); if (named) return named; const name = providerName(scope.provider); if (scope.account === undefined) return `${name} · all accounts`; const several = new Set( scopes .filter((other) => other.provider === scope.provider) .map((other) => other.account ?? ''), ).size > 1; return `${name} · ${accountName(scope.account ?? '', [], several)}`; } /** * Names for a scope selector's choices, out of what the window itself recorded: * the provider's endpoint, then the account by its own text or by the profiles * that made its calls. A usage identity is not an account handle, so a scope is * never named after a current login, and no name becomes a query key. */ export function scopeLabels( scopes: Scope[], lines: Line[], ): Map { const labels = new Map(); const distinct = (values: string[]) => [...new Set(values.filter(Boolean))].sort(); const providers = [...new Set(scopes.map((scope) => scope.provider))]; const names = providerNames(providers); for (const provider of providers) { const name = names.get(provider) as string; // In the daemon's order, and keeping the empty account: it is the provider's unlabelled one, a filter of its own. const accounts = [ ...new Set( scopes .filter((scope) => scope.provider === provider) .map((scope) => scope.account ?? ''), ), ]; const several = accounts.length > 1; const rows = lines.filter((line) => line.provider === provider); const named = accounts.map((account) => { const profiles = distinct( rows .filter((line) => (line.account ?? '') === account) .map((line) => line.profile), ); return { account, text: accountName(account, profiles, several) }; }); // Two accounts that shorten alike are told apart by the whole of them, rather than by a suffix // no one reads. The account recorded with no label has no whole to show, so it says that // instead: those rows were made outside any account the endpoint named, and a blank after the // separator names nothing. const used = new Map(); for (const entry of named) used.set(entry.text, (used.get(entry.text) ?? 0) + 1); for (const { account, text } of named) { const label = `${name} · ${(used.get(text) ?? 0) > 1 ? account || 'no account' : text}`; labels.set(scopeKey({ provider, account }), label); // With one account the provider's own choice asks for the same rows, so it reads the same. if (!several) labels.set(scopeKey({ provider }), label); } if (several) labels.set(scopeKey({ provider }), `${name} · all accounts`); } return labels; } export interface ScopeOption { key: string; text: string; scope: Scope | null; } /** One provider's choices in a scope selector: a `` and the account filters under it. */ export interface ScopeGroup { provider: string; name: string; options: ScopeOption[]; } export interface ScopeChoices { /** The unfiltered choice, which the selector always offers first. */ all: ScopeOption; groups: ScopeGroup[]; /** Every choice in the selector's order, which is how a chosen key finds its scope again. */ options: ScopeOption[]; } /** Everything, which is the only filter with no provider. */ const ALL_PROVIDERS: ScopeOption = { key: '', text: 'all providers', scope: null, }; /** A scope chosen earlier that this period has nothing to say about, still offered and still selected. */ const unusedText = (label: string) => `${label} (no use in this period)`; /** * The choices a scope selector offers, grouped by provider: "all providers" * first, then each provider with its accounts in the order the daemon gave. A * provider with one account offers one choice for it rather than the same data * twice under two names. `kept` is the scope chosen before a period or a filter * stopped reporting it; it keeps its place in its provider's group, or a group * of its own, named as it was rather than by its raw key. */ export function scopeChoices( scopes: Scope[], labels: ReadonlyMap = new Map(), kept: Scope | null = null, ): ScopeChoices { const providers = [...new Set(scopes.map((scope) => scope.provider))]; const names = providerNames(providers); const groups: ScopeGroup[] = providers.map((provider) => { const accounts = new Map(); for (const scope of scopes) if (scope.provider === provider && !accounts.has(scope.account ?? '')) accounts.set(scope.account ?? '', scope); // One account needs one choice for the provider; several need the provider's own choice and each account. const pairs = accounts.size > 1 ? [{ provider }, ...accounts.values()] : [{ provider }]; return { provider, name: names.get(provider) as string, options: pairs.map((scope) => ({ key: scopeKey(scope), text: scopeText(scope, scopes, labels), scope, })), }; }); // A choice is kept when the selector no longer offers it, which is not the same as the // period not reporting its provider: a provider with one account offers that account, and a // provider-wide choice is that same ask. const offered = groups.some((group) => group.options.some((option) => option.key === scopeKey(kept)), ); if (kept && !offered) { const option = { key: scopeKey(kept), text: unusedText(scopeText(kept, scopes, labels)), scope: kept, }; const group = groups.find( (candidate) => candidate.provider === kept.provider, ); if (group) group.options.push(option); else groups.push({ provider: kept.provider, name: providerName(kept.provider), options: [option], }); } return { all: ALL_PROVIDERS, groups, options: [ALL_PROVIDERS, ...groups.flatMap((group) => group.options)], }; } // A reading older than this was not polled on schedule: the daemon polls at least every ten minutes. const STALE_MS = 30 * 60_000; export type Standing = 'fresh' | 'old' | 'failed' | 'unknown'; /** * How far to trust a limit's reading: failed, without a percent, with a stamp * that cannot be read at all, stale or past its own reset, or fresh. A stamp * that does not parse is not fresh: nothing says when it was taken. */ export function standing(limit: Quota, now: number): Standing { if (limit.error) return 'failed'; const at = Date.parse(limit.observed_at); if (limit.used_percent == null || Number.isNaN(at)) return 'unknown'; const resets = limit.resets_at ? Date.parse(limit.resets_at) : NaN; if (now - at > STALE_MS || (!Number.isNaN(resets) && resets <= now)) return 'old'; return 'fresh'; } /** * A span in two units at most, for a row or a tooltip: 1m, 40m, 2h14m, 3d4h. * Anything under a minute is "a minute": a symbol for it reads as a code, and * the first minute of a span is a minute either way. */ function spanText(ms: number): string { const minutes = Math.max(1, Math.floor(Math.max(ms, 0) / 60_000)); if (minutes < 2) return 'a minute'; if (minutes < 60) return `${minutes}m`; const units = (big: number, bigName: string, smallName: string) => { const rest = Math.floor((minutes % big) / (big === 60 ? 1 : 60)); return `${Math.floor(minutes / big)}${bigName}${rest ? `${rest}${smallName}` : ''}`; }; return minutes < 1440 ? units(60, 'h', 'm') : units(1440, 'd', 'h'); } /** How long ago, in words: "just now", "4 min ago", "2 h ago", "3 d ago". */ export function sinceText(ms: number): string { const minutes = Math.floor(Math.max(ms, 0) / 60_000); if (minutes < 1) return 'just now'; if (minutes < 60) return `${minutes} min ago`; const hours = Math.floor(minutes / 60); if (hours < 24) return `${hours} h ago`; return `${Math.floor(hours / 24)} d ago`; } /** How long ago a limit's reading was taken, as "2h14m", or null when its stamp cannot be read. */ export function observedAge(limit: Quota, now: number): string | null { const at = Date.parse(limit.observed_at); return Number.isNaN(at) ? null : spanText(now - at); } /** When a limit resets, as "in 2h14m", or null when it has no reset to say or has passed it. */ export function resetText(limit: Quota, now: number): string | null { if (!limit.resets_at) return null; const resets = Date.parse(limit.resets_at); return Number.isNaN(resets) || resets <= now ? null : `in ${spanText(resets - now)}`; } /** What a limit is called: its label, or what happened when it has none. */ export function limitName(limit: Quota): string { return ( limit.label || (limit.error ? 'last poll failed' : limit.limit_id || 'no limits reported') ); } /** * A limit in full, for the hover of its row: when it was read and how long ago, * when it resets and how long is left, and why there is no reading at all. A * stamp that cannot be read says so rather than claiming a time. */ export function limitTitle(limit: Quota, now: number): string { const parts: string[] = []; const at = Date.parse(limit.observed_at); parts.push( Number.isNaN(at) ? 'its reading time cannot be read' : `read ${new Date(at).toLocaleString()} (${sinceText(now - at)})`, ); const resets = limit.resets_at ? Date.parse(limit.resets_at) : NaN; if (!Number.isNaN(resets)) parts.push( `resets ${new Date(resets).toLocaleString()} (${resets <= now ? 'passed' : `in ${spanText(resets - now)}`})`, ); else if (limit.resets_at) parts.push('its reset time cannot be read'); if (limit.error) parts.push( `the last poll failed: ${limit.error.detail ?? limit.error.code}`, ); return parts.join(' · '); } /** The provider and account a limit belongs to, which its rows sit under. */ function limitSection(limit: Quota, several = false): string { const provider = limitProviderName(limit.provider); if (limit.account_id === limit.provider) return provider; const account = accountText(limit.account_id, several); return account ? `${provider} · ${account}` : provider; } export interface LimitGroup { /** The provider and account it is for, which tells it from another group that reads the same. */ id: string; /** The provider as the daemon names it ("anthropic", "openai-codex"), which is what its mark comes from. */ provider: string; name: string; limits: Quota[]; } /** The limits grouped by provider and account, each group in the order the daemon gave. */ export function groupLimits(limits: Quota[]): LimitGroup[] { const accounts = new Map>(); for (const { provider, account_id } of limits) accounts.set( provider, (accounts.get(provider) ?? new Set()).add(account_id), ); const groups = new Map(); for (const limit of limits) { const id = `${limit.provider}\n${limit.account_id}`; const group = groups.get(id) ?? { id, provider: limit.provider, name: limitSection(limit, (accounts.get(limit.provider)?.size ?? 0) > 1), limits: [], }; group.limits.push(limit); groups.set(id, group); } return [...groups.values()]; } /** From this a bar runs warm, and from `HOT` hot; the daemon polls busier from the same 80. */ const WARM = 80; export const HOT = 95; export type Heat = 'cool' | 'warm' | 'hot'; export const heatOf = (percent: number): Heat => percent >= HOT ? 'hot' : percent >= WARM ? 'warm' : 'cool'; /** Whether a group holds a limit that is nearly used up and still current: the one a person must not have to open. */ export const groupHot = (group: LimitGroup, now: number): boolean => group.limits.some( (limit) => standing(limit, now) === 'fresh' && (limit.used_percent ?? 0) >= HOT, ); /** * A group's highest cap in a few characters, for the summary of a fold. It is * the highest of its limits and not all of them, and it says so in words when * there is no number to give. */ export function accountCap(group: LimitGroup, now: number): string { const readable = group.limits.filter( (limit) => standing(limit, now) !== 'failed' && limit.used_percent != null, ); if (!readable.length) return group.limits.some((limit) => limit.error) ? 'no reading' : 'no percentage'; return `${Math.round(Math.max(...readable.map((limit) => limit.used_percent as number)))}%`; } export interface LimitFold { shown: LimitGroup[]; folded: LimitGroup[]; } /** * Which account groups to show at once and which to keep behind a summary line: * the first `keep` in the daemon's order, then the rest, whatever they hold, so * rows never move or swap places as a percentage changes. A folded group is told * by its highest cap, and the caller opens the fold when one of them is hot. */ export function foldGroups(groups: LimitGroup[], keep = 3): LimitFold { return { shown: groups.slice(0, keep), folded: groups.slice(keep) }; } /** * From this share of a window's calls failed, its failure count is shown as a * problem rather than as a note. One call in twenty going wrong is the account * or the network; the odd one in a thousand is a retry, a rotation or a timeout * the daemon already recovered from, and colouring those teaches people to * ignore the colour. */ const TROUBLED_ERRORS = 0.05; /** Whether a window's failures are a real share of its calls, and so worth the alarm colour. */ export const troubled = (errors: number, calls: number): boolean => errors > 0 && calls > 0 && errors / calls >= TROUBLED_ERRORS; /** * What the menu, the window and the phone's sheet say about the same reading, * so one idea is never worded three ways. Lowercase like the rest of the * client, and "albedo" is a name in a sentence rather than the start of one. */ export const USAGE_COPY = { /** Under "limits": a cap belongs to the account, not to the period or scope on screen. */ limitsNote: 'account-wide · may include use outside albedo', readingLimits: 'reading the limits…', limitsFailed: "couldn't read the limits", limitsStale: "couldn't refresh the limits", readingUsage: 'reading the usage…', usageFailed: "couldn't read the usage", usageStale: "couldn't refresh the usage", /** The daemon polls each signed-in provider account; there is no switch for it here. */ noLimits: 'no limits reported; they come from each signed-in provider account', retry: 'try again', details: 'usage details', refresh: 'refresh', } as const; /** What the totals cover, under their heading: every session on this machine, in the reader's own day. */ export const usageNote = (offset: string): string => `all sessions · your local time (${offset})`;