diff --git a/AGENTS.md b/AGENTS.md
index f64666d..77bccdc 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -55,8 +55,11 @@ a laptop.
`docs/design/v3/day/` (the prototype and its README); `built/` holds the built page's shots.
- `public/usage/`: the private usage page's files (setkernel-live#71), served by the Worker only with
a `USAGE_AUD` token (`run_worker_first` in `wrangler.jsonc`, pinned by `test/usage-page.test.mjs`).
- `table.js` (a month's rows, cells and the box's text) is pure and tested; `page.js` draws it, tested
- against a stand-in document. Never move them out of `/usage`.
+ `table.js` (a month's totals, rows, cells, the box's text and each seat's trend) and `limits.js` (the
+ 5-hour and weekly windows: alert, limit, stale, not reported, Codex) are pure and tested; `page.js`
+ draws them, tested against a stand-in document. `usage.css` carries its own palette (contrast checked
+ in that test) and loads only `public/usage/fonts/`. `docs/design/usage/shoot.mjs` takes its shots.
+ Never move them out of `/usage`.
- `public/lib/`: ES modules for the page. `state.js` is the public state, the Halifax day
(`homeDay`, `homeMidnight`) and the 24-hour replay buffer; the Durable Object and `?demo` both
run it. `line.js` derives each engineer's stage (state.js keeps the lanes). `words.js` (wording,
diff --git a/README.md b/README.md
index 6ea26c9..c47fb7f 100644
--- a/README.md
+++ b/README.md
@@ -242,10 +242,16 @@ Everything under `/usage` (the page Raghav reads it on, setkernel-live#71, and i
`wrangler.jsonc` runs the Worker first for `/usage` and `/usage/*` (without it the assets are served
before the Worker sees the request). `/usage/data` names the newest hour stored, in any month, in a
`Usage-Newest-Hour` header (absent while nothing is stored); the body keeps its shape.
-`public/usage/table.js` turns a month into the page's rows: fresh tokens are input + output + cache
-writes, and a day or seat with no data is a dash, not zero. `public/usage/index.html`, `usage.css`
-and `page.js` draw it (setkernel-live#78): `?month=YYYY-MM` picks the month, the newest hour is
-the header's, and a 403, 503 or expired login shows a message. Its shots are in `docs/design/usage/`.
+`public/usage/table.js` turns a month into the page's totals, seats, rows and trends: fresh tokens
+are input + output + cache writes, and a day or seat with no data is a dash, not zero. The seats are
+the ones the data names. `public/usage/limits.js` reads each seat's 5-hour and weekly windows from a
+`limits` object in the answer, with the wall's rules (alerts at 80% and 70%, a limit hit at 100% or on
+a rejected request, a reading from before its window reset is stale). `/usage/data` doesn't send
+`limits` yet, so the page says it can't check them and shows no figure. `public/usage/index.html`,
+`usage.css` (its own palette and the fonts in `public/usage/fonts/`) and `page.js` draw it
+(setkernel-live#78, v5 in #86): `?month=YYYY-MM` picks the month, the page also reads the two months
+before it for the 30-day trend, the newest hour is the header's, and a 403, 503 or expired login shows a
+message. `docs/design/usage/shoot.mjs` takes its shots, beside it, with the ones from before v5 in `before/`.
## When updates stop
diff --git a/docs/design/usage/before/usage-1440-dark.png b/docs/design/usage/before/usage-1440-dark.png
new file mode 100644
index 0000000..d905723
Binary files /dev/null and b/docs/design/usage/before/usage-1440-dark.png differ
diff --git a/docs/design/usage/before/usage-1440-light.png b/docs/design/usage/before/usage-1440-light.png
new file mode 100644
index 0000000..019a56a
Binary files /dev/null and b/docs/design/usage/before/usage-1440-light.png differ
diff --git a/docs/design/usage/before/usage-2560-dark.png b/docs/design/usage/before/usage-2560-dark.png
new file mode 100644
index 0000000..ab9f934
Binary files /dev/null and b/docs/design/usage/before/usage-2560-dark.png differ
diff --git a/docs/design/usage/before/usage-2560-light.png b/docs/design/usage/before/usage-2560-light.png
new file mode 100644
index 0000000..2bc2137
Binary files /dev/null and b/docs/design/usage/before/usage-2560-light.png differ
diff --git a/docs/design/usage/before/usage-375-dark.png b/docs/design/usage/before/usage-375-dark.png
new file mode 100644
index 0000000..6740a1d
Binary files /dev/null and b/docs/design/usage/before/usage-375-dark.png differ
diff --git a/docs/design/usage/before/usage-375-light.png b/docs/design/usage/before/usage-375-light.png
new file mode 100644
index 0000000..097bab3
Binary files /dev/null and b/docs/design/usage/before/usage-375-light.png differ
diff --git a/docs/design/usage/shoot.mjs b/docs/design/usage/shoot.mjs
new file mode 100644
index 0000000..c2eed34
--- /dev/null
+++ b/docs/design/usage/shoot.mjs
@@ -0,0 +1,150 @@
+// Takes the /usage page's screenshots (setkernel-live#86) in Playwright's chromium, in Halifax time at
+// the v5 prototypes' clock (Wednesday 28 October 2026, 15:04 ADT). It serves public/ itself, with the
+// headers from public/_headers, so a CSP violation fails the run, and answers GET /usage/data from the
+// sample month below: invented values in the real shapes (src/usage.js sumByDay; the seat limits as
+// public/usage/limits.js reads them). Every state is drawn light and dark at 375, 1440 and 2560 and
+// checked for errors and sideways scroll; KEEP picks the ones saved beside this file. "before" saves
+// the Normal state, without limits, into before/: run it on the base commit, before the change.
+// Playwright isn't a dependency of this repo: install it anywhere outside it.
+// npm i --prefix "$TMPDIR/pw" playwright && npx --prefix "$TMPDIR/pw" playwright install chromium
+// PLAYWRIGHT_DIR="$TMPDIR/pw" node docs/design/usage/shoot.mjs [before]
+import { createServer } from "node:http";
+import { mkdir, readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { fileURLToPath } from "node:url";
+
+const dir = process.env.PLAYWRIGHT_DIR;
+if (!dir) throw new Error("set PLAYWRIGHT_DIR to a folder with playwright installed");
+const { chromium } = createRequire(`${dir}/`)("playwright");
+const pub = new URL("../../../public/", import.meta.url);
+const before = process.argv[2] === "before";
+const out = (name) => fileURLToPath(new URL(before ? `before/${name}` : name, import.meta.url));
+
+// public/_headers' rules for /*, as the Worker's assets serve them
+const headers = Object.fromEntries((await readFile(new URL("_headers", pub), "utf8")).split("\n")
+ .filter((l) => /^\s+\S+:/.test(l)).map((l) => [l.trim().slice(0, l.trim().indexOf(":")), l.slice(l.indexOf(":") + 1).trim()]));
+const TYPES = { html: "text/html", js: "text/javascript", css: "text/css", svg: "image/svg+xml", woff2: "font/woff2", png: "image/png" };
+const server = createServer(async (req, res) => {
+ const path = new URL(req.url, "http://x").pathname.replace(/^\/usage\/?$/, "/usage/index.html");
+ try {
+ const body = await readFile(new URL(`.${path}`, pub));
+ res.writeHead(200, { ...headers, "Content-Type": TYPES[path.split(".").pop()] ?? "application/octet-stream" });
+ res.end(body);
+ } catch {
+ res.writeHead(404).end();
+ }
+}).listen(0);
+const origin = `http://localhost:${server.address().port}`;
+
+// ---- the sample: every Halifax day from 1 August to today, per seat, seeded so each run is the same
+const NOW = Date.UTC(2026, 9, 28, 18, 4); // Wednesday 28 October 2026, 15:04 ADT
+const SCALE = { vega: 7.2e6, rigel: 8.1e6, lyra: 8.8e6, orion: 9.4e6, polaris: 6.0e6, codex: 0.9e6 }; // fresh tokens a weekday
+let seed = 7;
+const rnd = () => (seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648;
+function counts(fresh) {
+ const input = Math.round(fresh * 0.1), output = Math.round(fresh * 0.15), cache_write = fresh - input - output;
+ const cache_read = Math.round(fresh * (10 + 4 * rnd()));
+ return { input, output, cache_read, cache_write, usd_micros: Math.round(15 * input + 75 * output + 18.75 * cache_write + 1.5 * cache_read), requests: Math.round(fresh / 9000) };
+}
+const DAYS = {};
+for (let t = Date.UTC(2026, 7, 1); t <= Date.UTC(2026, 9, 28); t += 86_400_000) {
+ const key = new Date(t).toISOString().slice(0, 10), weekend = [0, 6].includes(new Date(t).getUTCDay());
+ const growth = 0.8 + (0.4 * (t - Date.UTC(2026, 7, 1))) / (88 * 86_400_000);
+ DAYS[key] = {};
+ for (const [seat, scale] of Object.entries(SCALE)) {
+ if (rnd() < (weekend ? 0.35 : 0.04)) continue; // a day off: no data, not zero
+ DAYS[key][seat] = counts(Math.round(scale * growth * (weekend ? 0.3 : 1) * (0.6 + 0.8 * rnd())));
+ }
+}
+const scaled = (day, f) => Object.fromEntries(Object.entries(day).map(([s, c]) => [s, Object.fromEntries(Object.entries(c).map(([k, n]) => [k, Math.round(n * f)]))]));
+// GET /usage/data?month= as the Worker answers it; today holds the hours up to the newest one
+function month(m, hours, limits) {
+ const days = Object.fromEntries(Object.entries(DAYS).filter(([k]) => k.startsWith(m)).map(([k, d]) => [k, k === "2026-10-28" ? scaled(d, hours / 24) : d]));
+ const totals = {};
+ for (const d of Object.values(days)) for (const [s, c] of Object.entries(d)) totals[s] = Object.fromEntries(Object.entries(c).map(([k, n]) => [k, (totals[s]?.[k] ?? 0) + n]));
+ return { month: m, days, totals, ...(limits && { limits }) };
+}
+
+// the seats' limit windows, at a Halifax (ADT) clock time on a day of October
+const at = (h, min, d = 28) => new Date(Date.UTC(2026, 9, d, h + 3, min)).toISOString();
+const w = (utilization, resets_at, observed_at) => ({ utilization, resets_at, observed_at });
+const NORMAL = {
+ vega: { five_hour: w(0.42, at(17, 30), at(14, 58)), seven_day: w(0.38, at(21, 0, 30), at(14, 58)), event: null },
+ rigel: { five_hour: w(0.84, at(16, 10), at(14, 55)), seven_day: w(0.52, at(9, 0, 31), at(14, 55)), event: null },
+ lyra: { five_hour: w(0.31, at(18, 40), at(14, 57)), seven_day: w(0.73, at(6, 0, 29), at(14, 57)), event: null },
+ orion: { five_hour: w(0.56, at(16, 50), at(14, 59)), seven_day: w(0.47, at(13, 0, 30), at(14, 59)), event: null },
+ polaris: { five_hour: w(0.12, at(19, 20), at(14, 31)), seven_day: w(0.21, at(8, 0, 31), at(14, 31)), event: null },
+};
+const LIMIT = {
+ ...NORMAL,
+ rigel: { five_hour: w(1, at(16, 10), at(14, 47)), seven_day: w(0.66, at(9, 0, 31), at(14, 47)), event: { status: "rejected", rate_limit_type: "five_hour", resets_at: at(16, 10), received_at: at(14, 47) } },
+ orion: { ...NORMAL.orion, seven_day: w(0.91, at(13, 0, 30), at(14, 59)) },
+ lyra: { ...NORMAL.lyra, seven_day: w(0.78, at(6, 0, 29), at(14, 57)) },
+};
+const STALE = { ...NORMAL, orion: { ...NORMAL.orion, five_hour: w(0.62, at(12, 30), at(10, 14)) }, polaris: null };
+
+// [name, ?query, the newest hour, the hours of today stored, limits, or how /usage/data answers]
+const STATES = [
+ ["normal", "", "2026-10-28T17", 15, NORMAL],
+ ["limit", "", "2026-10-28T17", 15, LIMIT],
+ ["stale", "", "2026-10-28T13", 11, STALE],
+ ["unread", "", "2026-10-28T17", 15, null], // /usage/data without limits: what the Worker answers today
+ ["past", "?month=2026-09", "2026-10-28T17", 15, NORMAL],
+ ["loading", "", null, 0, "hang"],
+ ["refused", "", null, 0, 403],
+];
+const SIZES = [[375, 812], [1440, 900], [2560, 1440]];
+const KEEP = before
+ ? (s) => s === "unread"
+ : (s, theme, width) => s === "normal" || (["limit", "stale", "unread"].includes(s) && ((width === 1440 && theme === "light") || (width === 375 && theme === "dark"))) || (s === "past" && width === 1440 && theme === "dark") || (s === "loading" && width === 1440 && theme === "light");
+
+if (before) await mkdir(new URL("before/", import.meta.url), { recursive: true });
+const browser = await chromium.launch();
+for (const [state, query, newest, hours, limits] of STATES) {
+ for (const theme of ["light", "dark"]) {
+ for (const [width, height] of SIZES) {
+ const ctx = await browser.newContext({ viewport: { width, height }, timezoneId: "America/Halifax", locale: "en-CA", colorScheme: theme });
+ const p = await ctx.newPage();
+ await p.clock.setFixedTime(NOW);
+ const errors = [];
+ p.on("pageerror", (e) => errors.push(e.message));
+ p.on("console", (m) => {
+ if (typeof limits === "number" && /status of 403/.test(m.text())) return; // the refusal itself
+ if (m.type() === "error" || /Content Security Policy/.test(m.text())) errors.push(m.text());
+ });
+ p.on("request", (r) => { if (!r.url().startsWith(origin)) errors.push(`network: ${r.url()}`); });
+ await p.route("**/usage/data?month=*", (r) => {
+ if (limits === "hang") return; // never answered: the page as it first loads
+ if (typeof limits === "number") return r.fulfill({ status: limits, body: "Forbidden" });
+ const m = new URL(r.request().url()).searchParams.get("month");
+ return r.fulfill({ json: month(m, hours, limits), headers: { "Usage-Newest-Hour": newest, "Cache-Control": "no-store" } });
+ });
+ await p.goto(`${origin}/usage/${query}`);
+ await p.waitForFunction((hang) => document.fonts.status === "loaded" && (hang || !/^Loading/.test(document.getElementById("status")?.textContent ?? "") || document.getElementById("status").hidden), limits === "hang");
+ await p.waitForTimeout(300);
+ const sw = await p.evaluate(() => document.documentElement.scrollWidth);
+ if (sw > width) errors.push(`horizontal scroll: ${sw} > ${width}`);
+ const name = before ? `usage-${width}-${theme}.png` : `usage-${state}-${width}-${theme}.png`;
+ if (KEEP(state, theme, width)) await p.screenshot({ path: out(name) });
+ if (state === "normal" && width === 375 && theme === "light" && !before) await p.screenshot({ path: out("usage-normal-375-light-full.png"), fullPage: true });
+ // scrolled into the table: its head stuck to the top, each seat's strip showing
+ if (["normal", "stale"].includes(state) && width === 1440 && !before) {
+ await p.evaluate(() => scrollTo(0, document.getElementById("usage").getBoundingClientRect().top + scrollY + 420));
+ await p.waitForFunction(() => document.getElementById("usage").classList.contains("stuck"), null, { timeout: 3000 }).catch(() => errors.push("the table's strip didn't show once scrolled"));
+ await p.waitForTimeout(300);
+ await p.screenshot({ path: out(`usage-${state}-1440-${theme}-table.png`) });
+ }
+ // a seat whose reading is stale, dashed, at 375
+ if (state === "stale" && width === 375 && !before) {
+ await p.evaluate(() => document.getElementById("seat-orion").scrollIntoView());
+ await p.waitForTimeout(300);
+ await p.screenshot({ path: out(`usage-stale-375-${theme}-seat.png`) });
+ }
+ if (errors.length) { console.error(state, theme, width, errors); process.exitCode = 1; }
+ else console.log("ok", state, theme, width, KEEP(state, theme, width) ? name : "");
+ await ctx.close();
+ }
+ }
+}
+await browser.close();
+server.close();
diff --git a/docs/design/usage/usage-1440x900-dark.png b/docs/design/usage/usage-1440x900-dark.png
deleted file mode 100644
index 40b369b..0000000
Binary files a/docs/design/usage/usage-1440x900-dark.png and /dev/null differ
diff --git a/docs/design/usage/usage-1440x900.png b/docs/design/usage/usage-1440x900.png
deleted file mode 100644
index 75cbded..0000000
Binary files a/docs/design/usage/usage-1440x900.png and /dev/null differ
diff --git a/docs/design/usage/usage-375x812.png b/docs/design/usage/usage-375x812.png
deleted file mode 100644
index 1a79cd4..0000000
Binary files a/docs/design/usage/usage-375x812.png and /dev/null differ
diff --git a/docs/design/usage/usage-limit-1440-light.png b/docs/design/usage/usage-limit-1440-light.png
new file mode 100644
index 0000000..4cdda5b
Binary files /dev/null and b/docs/design/usage/usage-limit-1440-light.png differ
diff --git a/docs/design/usage/usage-limit-375-dark.png b/docs/design/usage/usage-limit-375-dark.png
new file mode 100644
index 0000000..38ca4d6
Binary files /dev/null and b/docs/design/usage/usage-limit-375-dark.png differ
diff --git a/docs/design/usage/usage-loading-1440-light.png b/docs/design/usage/usage-loading-1440-light.png
new file mode 100644
index 0000000..4c8c372
Binary files /dev/null and b/docs/design/usage/usage-loading-1440-light.png differ
diff --git a/docs/design/usage/usage-normal-1440-dark-table.png b/docs/design/usage/usage-normal-1440-dark-table.png
new file mode 100644
index 0000000..ec20cce
Binary files /dev/null and b/docs/design/usage/usage-normal-1440-dark-table.png differ
diff --git a/docs/design/usage/usage-normal-1440-dark.png b/docs/design/usage/usage-normal-1440-dark.png
new file mode 100644
index 0000000..d57a44a
Binary files /dev/null and b/docs/design/usage/usage-normal-1440-dark.png differ
diff --git a/docs/design/usage/usage-normal-1440-light-table.png b/docs/design/usage/usage-normal-1440-light-table.png
new file mode 100644
index 0000000..2a836a9
Binary files /dev/null and b/docs/design/usage/usage-normal-1440-light-table.png differ
diff --git a/docs/design/usage/usage-normal-1440-light.png b/docs/design/usage/usage-normal-1440-light.png
new file mode 100644
index 0000000..c5d5b12
Binary files /dev/null and b/docs/design/usage/usage-normal-1440-light.png differ
diff --git a/docs/design/usage/usage-normal-2560-dark.png b/docs/design/usage/usage-normal-2560-dark.png
new file mode 100644
index 0000000..5ca47ce
Binary files /dev/null and b/docs/design/usage/usage-normal-2560-dark.png differ
diff --git a/docs/design/usage/usage-normal-2560-light.png b/docs/design/usage/usage-normal-2560-light.png
new file mode 100644
index 0000000..a67e306
Binary files /dev/null and b/docs/design/usage/usage-normal-2560-light.png differ
diff --git a/docs/design/usage/usage-normal-375-dark.png b/docs/design/usage/usage-normal-375-dark.png
new file mode 100644
index 0000000..0dc41d5
Binary files /dev/null and b/docs/design/usage/usage-normal-375-dark.png differ
diff --git a/docs/design/usage/usage-normal-375-light-full.png b/docs/design/usage/usage-normal-375-light-full.png
new file mode 100644
index 0000000..d7e12fa
Binary files /dev/null and b/docs/design/usage/usage-normal-375-light-full.png differ
diff --git a/docs/design/usage/usage-normal-375-light.png b/docs/design/usage/usage-normal-375-light.png
new file mode 100644
index 0000000..76e09b6
Binary files /dev/null and b/docs/design/usage/usage-normal-375-light.png differ
diff --git a/docs/design/usage/usage-past-1440-dark.png b/docs/design/usage/usage-past-1440-dark.png
new file mode 100644
index 0000000..14ff409
Binary files /dev/null and b/docs/design/usage/usage-past-1440-dark.png differ
diff --git a/docs/design/usage/usage-stale-1440-dark-table.png b/docs/design/usage/usage-stale-1440-dark-table.png
new file mode 100644
index 0000000..2be5e03
Binary files /dev/null and b/docs/design/usage/usage-stale-1440-dark-table.png differ
diff --git a/docs/design/usage/usage-stale-1440-light-table.png b/docs/design/usage/usage-stale-1440-light-table.png
new file mode 100644
index 0000000..63dc299
Binary files /dev/null and b/docs/design/usage/usage-stale-1440-light-table.png differ
diff --git a/docs/design/usage/usage-stale-1440-light.png b/docs/design/usage/usage-stale-1440-light.png
new file mode 100644
index 0000000..b8f61e9
Binary files /dev/null and b/docs/design/usage/usage-stale-1440-light.png differ
diff --git a/docs/design/usage/usage-stale-375-dark-seat.png b/docs/design/usage/usage-stale-375-dark-seat.png
new file mode 100644
index 0000000..e23aced
Binary files /dev/null and b/docs/design/usage/usage-stale-375-dark-seat.png differ
diff --git a/docs/design/usage/usage-stale-375-dark.png b/docs/design/usage/usage-stale-375-dark.png
new file mode 100644
index 0000000..9d808fe
Binary files /dev/null and b/docs/design/usage/usage-stale-375-dark.png differ
diff --git a/docs/design/usage/usage-stale-375-light-seat.png b/docs/design/usage/usage-stale-375-light-seat.png
new file mode 100644
index 0000000..599f15c
Binary files /dev/null and b/docs/design/usage/usage-stale-375-light-seat.png differ
diff --git a/docs/design/usage/usage-unread-1440-light.png b/docs/design/usage/usage-unread-1440-light.png
new file mode 100644
index 0000000..869a638
Binary files /dev/null and b/docs/design/usage/usage-unread-1440-light.png differ
diff --git a/docs/design/usage/usage-unread-375-dark.png b/docs/design/usage/usage-unread-375-dark.png
new file mode 100644
index 0000000..4a1f0c9
Binary files /dev/null and b/docs/design/usage/usage-unread-375-dark.png differ
diff --git a/public/usage/fonts/OFL-IBM-Plex-Mono.txt b/public/usage/fonts/OFL-IBM-Plex-Mono.txt
new file mode 100644
index 0000000..83eac82
--- /dev/null
+++ b/public/usage/fonts/OFL-IBM-Plex-Mono.txt
@@ -0,0 +1,93 @@
+Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-ThinItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-ExtraLight.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-ExtraLightItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Light.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-LightItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Regular.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Italic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Medium.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-MediumItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-SemiBold.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-SemiBoldItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Bold.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-BoldItalic.ttf: Copyright 2017 IBM Corp. All rights reserved.
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/public/usage/fonts/OFL-Manrope.txt b/public/usage/fonts/OFL-Manrope.txt
new file mode 100644
index 0000000..462280f
--- /dev/null
+++ b/public/usage/fonts/OFL-Manrope.txt
@@ -0,0 +1,93 @@
+Copyright 2019 The Manrope Project Authors (https://github.com/sharanda/manrope)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/public/usage/fonts/ibm-plex-mono-latin-400-normal.woff2 b/public/usage/fonts/ibm-plex-mono-latin-400-normal.woff2
new file mode 100644
index 0000000..0804aaf
Binary files /dev/null and b/public/usage/fonts/ibm-plex-mono-latin-400-normal.woff2 differ
diff --git a/public/usage/fonts/ibm-plex-mono-latin-500-normal.woff2 b/public/usage/fonts/ibm-plex-mono-latin-500-normal.woff2
new file mode 100644
index 0000000..090f82f
Binary files /dev/null and b/public/usage/fonts/ibm-plex-mono-latin-500-normal.woff2 differ
diff --git a/public/usage/fonts/manrope-latin-400-normal.woff2 b/public/usage/fonts/manrope-latin-400-normal.woff2
new file mode 100644
index 0000000..7eaaa95
Binary files /dev/null and b/public/usage/fonts/manrope-latin-400-normal.woff2 differ
diff --git a/public/usage/fonts/manrope-latin-600-normal.woff2 b/public/usage/fonts/manrope-latin-600-normal.woff2
new file mode 100644
index 0000000..7cc09a3
Binary files /dev/null and b/public/usage/fonts/manrope-latin-600-normal.woff2 differ
diff --git a/public/usage/fonts/manrope-latin-800-normal.woff2 b/public/usage/fonts/manrope-latin-800-normal.woff2
new file mode 100644
index 0000000..b5cd400
Binary files /dev/null and b/public/usage/fonts/manrope-latin-800-normal.woff2 differ
diff --git a/public/usage/index.html b/public/usage/index.html
index 0947fc0..74f88aa 100644
--- a/public/usage/index.html
+++ b/public/usage/index.html
@@ -6,26 +6,49 @@
Fresh tokens are input, output and cache writes. Days run midnight to midnight, Halifax time.
+
Loading · Only Raghav can open this page
+
+
+
+
+
Usage per seat
+
-
Loading this month's usage…
-
-
Hover a number for its exact tokens, cache reads and dollars. On a phone, tap it.
-
-
Dollars are what the same tokens would cost at API prices. The seats are on subscriptions, so this is a size guide, not a bill. Polaris covers Raghav's own sessions. A dash means no data, not zero.
+
+
Needs a look
+
+
+
+
+
+
Seats
+
Trend
+
+
+
+
+
+
+
Day by day
+
Fewer more fresh tokens in a seat's day
+
+
Hover a number for its exact tokens, cache reads and dollars; on a touch screen, tap it.
+
+
Open a day for each seat's tokens and dollars.
+
+
+
diff --git a/public/usage/limits.js b/public/usage/limits.js
new file mode 100644
index 0000000..67faa34
--- /dev/null
+++ b/public/usage/limits.js
@@ -0,0 +1,86 @@
+// live.setkernel.com/usage (setkernel-live#86): each seat's 5-hour and weekly limit windows, as the
+// page says them. Pure and tested (test/usage-page.test.mjs). GET /usage/data is to carry them as
+// `limits`, from the seat view the wall reads (setkernel/hq observability/wall/limits.py):
+// { : { five_hour: { utilization: 0.84, resets_at, observed_at } | null, seven_day: { ... } | null,
+// event: { status: "rejected", rate_limit_type: "five_hour", resets_at, received_at } | null } }
+// with times as ISO 8601 strings. Until it does, the page says it can't check limits and shows no figure.
+// The rules are the wall's: a window with no reset time resets a window's length after it was read.
+import { homeDay } from "../lib/state.js";
+import { seatName } from "./table.js";
+
+// The alerts, in percent, as on the wall. usage.css places their ticks: .at80 and .at70.
+export const THRESHOLD = { five_hour: 80, seven_day: 70 };
+export const WINDOWS = [["five_hour", "5-hour"], ["seven_day", "weekly"]];
+const LENGTH = { five_hour: 5 * 3_600_000, seven_day: 7 * 86_400_000 };
+
+// Codex has no Claude limits, and "other" is usage no seat claimed: neither has a window to read.
+export const hasLimits = (seat) => seat !== "codex" && seat !== "other";
+
+const ms = (t) => (typeof t === "string" ? Date.parse(t) : typeof t === "number" ? t : NaN);
+const clock = new Intl.DateTimeFormat("en-US", { timeZone: "America/Halifax", weekday: "short", hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
+// An instant in Halifax: "16:10" on the same day as `now`, else "Thu 21:00".
+export function when(t, now) {
+ const p = Object.fromEntries(clock.formatToParts(t).map((x) => [x.type, x.value]));
+ return homeDay(t) === homeDay(now) ? `${p.hour}:${p.minute}` : `${p.weekday} ${p.hour}:${p.minute}`;
+}
+
+// One window of one seat at `now`:
+// nolimits the seat has none (Codex): never 0%
+// unread the page has no limits at all
+// none not reported
+// stale read before the window last reset, so it says nothing about now: the figure is not shown
+// fresh { level: ok | over | limit, pct, resets, read, hit }
+// The figure is rounded down, so what the page shows and the alert agree: over is pct >= the alert, as
+// on the wall; the limit is 100% or a request rejected for this window since it last opened.
+export function windowOf(limits, seat, name, now) {
+ if (!hasLimits(seat)) return { kind: "nolimits" };
+ if (!limits) return { kind: "unread" };
+ const s = limits[seat], w = s?.[name], read = ms(w?.observed_at);
+ if (!Number.isFinite(w?.utilization) || w.utilization < 0 || !Number.isFinite(read)) return { kind: "none" };
+ const resets = Number.isFinite(ms(w.resets_at)) ? ms(w.resets_at) : read + LENGTH[name];
+ if (resets <= now) return { kind: "stale", read };
+ const ev = s.event, at = ms(ev?.received_at);
+ const hit = ev?.status === "rejected" && ev.rate_limit_type === name && at > resets - LENGTH[name] && !(ms(ev.resets_at) <= now) ? at : null;
+ const pct = Math.floor(w.utilization * 100 + 1e-9);
+ return { kind: "fresh", level: pct >= 100 || hit != null ? "limit" : pct >= THRESHOLD[name] ? "over" : "ok", pct, resets, read, hit };
+}
+
+// What a meter says: the big figure, the flag beside it, the lines under it, and one label for a
+// screen reader. Colour only repeats the words.
+export function meter(v, seat, name, label, now) {
+ const t = THRESHOLD[name], who = `${seatName(seat)} ${label}`;
+ if (v.kind === "fresh") {
+ const flag = v.level === "limit" ? "LIMIT HIT" : `${v.level === "over" ? "over" : "under"} ${t}%`;
+ const meta = [`resets ${when(v.resets, now)}`, `read ${when(v.read, now)}`, ...(v.hit != null ? [`rejected ${when(v.hit, now)}`] : [])];
+ return { pct: v.pct, flag, meta, label: `${who}: ${v.pct}%, ${v.level === "limit" ? "limit hit" : flag}, ${meta.join(", ")}` };
+ }
+ if (v.kind === "stale") return { flag: `no fresh reading since ${when(v.read, now)}`, meta: ["it reset since; the old figure is not shown"], label: `${who}: no fresh reading since ${when(v.read, now)}` };
+ return { flag: "not reported", meta: ["no reading from this seat"], label: `${who}: not reported` };
+}
+
+// The sticky strip's few characters for a window.
+export const mini = (v) => (v.kind === "stale" ? "stale" : v.kind === "none" ? "not reported" : v.level === "limit" ? "LIMIT HIT" : `${v.pct}%`);
+
+// The worst of a seat's windows, for the mark down its row's left edge.
+export const alertOf = (views) =>
+ views.some((v) => v.level === "limit") ? "limit" : views.some((v) => v.level === "over") ? "over" : views.some((v) => v.kind === "stale" || v.kind === "none") ? "gap" : null;
+
+// "Needs a look": a sentence per problem, worst first, then in seat order; [] is nothing; null is
+// that there are no limits to check.
+export function needs(limits, seats, now) {
+ if (!limits) return null;
+ const items = [];
+ for (const seat of seats.filter(hasLimits)) {
+ const name = seatName(seat), gaps = [];
+ for (const [w, label] of WINDOWS) {
+ const v = windowOf(limits, seat, w, now), resets = v.resets && when(v.resets, now);
+ if (v.level === "limit") items.push({ sev: 0, kind: "limit", seat, text: v.hit != null ? `${name} hit the ${label} limit at ${when(v.hit, now)}, resets ${resets}` : `${name}'s ${label} is at ${v.pct}%, resets ${resets}` });
+ else if (v.level === "over") items.push({ sev: 1, kind: "over", seat, text: `${name}'s ${label} is at ${v.pct}%, resets ${resets}` });
+ else if (v.kind === "stale") items.push({ sev: 2, kind: "gap", seat, text: `${name}'s ${label} has no fresh reading since ${when(v.read, now)}` });
+ else if (v.kind === "none") gaps.push(label);
+ }
+ if (gaps.length === 2) items.push({ sev: 2, kind: "gap", seat, text: `${name} is not reporting` });
+ else if (gaps.length) items.push({ sev: 2, kind: "gap", seat, text: `${name}'s ${gaps[0]} is not reported` });
+ }
+ return items.sort((a, b) => a.sev - b.sev);
+}
diff --git a/public/usage/page.js b/public/usage/page.js
index 3b2896c..f3f5c43 100644
--- a/public/usage/page.js
+++ b/public/usage/page.js
@@ -1,10 +1,13 @@
-// live.setkernel.com/usage (setkernel-live#78): option B from setkernel-live#71, drawn from GET
-// /usage/data through buildMonth (table.js). Everything is built with textContent. Hovering,
-// focusing or tapping a number shows its box; Esc or a tap elsewhere closes it.
-// Tested with a stand-in document in test/usage-page.test.mjs.
+// live.setkernel.com/usage (setkernel-live#86): v5, Headroom's "Needs a look" and seat rows over
+// Ledger's month totals and seat-by-day table (setkernel/hq#972), from GET /usage/data for the month
+// and the two before it (the 30-day trend reaches back that far) through table.js and limits.js.
+// Everything is built with textContent. Hovering, focusing or tapping a number in the table shows its
+// box; Esc or a tap elsewhere closes it. Tested with a stand-in document in test/usage-page.test.mjs.
import { homeDay } from "../lib/state.js";
-import { asOf, buildMonth, monthName, shiftMonth, tip } from "./table.js";
+import { BAR, asOf, buildMonth, changeWords, colour, dayName, firstDay, monthName, seatName, shiftDay, shiftMonth, tip, trend, who } from "./table.js";
+import { THRESHOLD, WINDOWS, alertOf, hasLimits, meter, mini, needs, windowOf } from "./limits.js";
+const SVG = "http://www.w3.org/2000/svg";
const $ = (id) => document.getElementById(id);
function el(tag, cls, text) {
const e = document.createElement(tag);
@@ -12,6 +15,12 @@ function el(tag, cls, text) {
if (text != null) e.textContent = text;
return e;
}
+function svg(tag, attrs, ...kids) {
+ const e = document.createElementNS(SVG, tag);
+ for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
+ e.append(...kids);
+ return e;
+}
// What the page says when GET /usage/data doesn't answer with a month. 0 is no answer at all: an
// expired login is a redirect to Access's login page, which the CSP stops.
@@ -21,15 +30,16 @@ export function failure(status) {
return `Usage didn't load (${status ? `HTTP ${status}` : "no answer"}). Reload the page to try again; if your login expired, that signs you in.`;
}
-// An arrow drawn, not typed: the page's fonts have no left or right arrow (setkernel-live#80).
-// The month's name beside it says where the link goes.
-function arrow(d) {
- const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"), path = document.createElementNS("http://www.w3.org/2000/svg", "path");
- for (const [k, v] of Object.entries({ class: "arrow", viewBox: "0 0 12 12", "aria-hidden": "true", focusable: "false" })) svg.setAttribute(k, v);
- path.setAttribute("d", d);
- svg.append(path);
- return svg;
-}
+// Shapes, drawn rather than typed (setkernel-live#80), each beside words that say the same: a stop
+// for a limit hit, a triangle for over an alert, a dashed ring for no reading, a tick for all clear.
+const SHAPES = {
+ limit: [["path", { class: "fg", d: "M5 1h6l4 4v6l-4 4H5l-4-4V5z" }], ["rect", { class: "cut", x: 4, y: 7, width: 8, height: 2 }]],
+ over: [["path", { class: "fg", d: "M8 1.2 15.2 14H.8z" }], ["rect", { class: "cut", x: 7.1, y: 5.6, width: 1.8, height: 4.4 }], ["rect", { class: "cut", x: 7.1, y: 11, width: 1.8, height: 1.8 }]],
+ gap: [["circle", { class: "ring", cx: 8, cy: 8, r: 6.2 }]],
+ ok: [["circle", { class: "fg", cx: 8, cy: 8, r: 7 }], ["path", { class: "tick", d: "M4.6 8.2 7 10.6l4.4-4.8" }]],
+};
+const shape = (kind) => svg("svg", { class: "i", viewBox: "0 0 16 16", "aria-hidden": "true", focusable: "false" }, ...SHAPES[kind].map(([t, a]) => svg(t, a)));
+const arrow = (d) => svg("svg", { viewBox: "0 0 12 12", "aria-hidden": "true", focusable: "false" }, svg("path", { d }));
function nav(month, current) {
const link = (m, ...kids) => { const e = m > current ? el("span", "off") : Object.assign(el("a"), { href: `?month=${m}` }); e.append(...kids); return e; };
@@ -37,74 +47,285 @@ function nav(month, current) {
$("months").replaceChildren(link(prev, arrow("M10.5 6H1.5M5.5 2L1.5 6l4 4"), el("span", null, monthName(prev))), el("b", null, `${monthName(month)} ${month.slice(0, 4)}`), link(next, el("span", null, monthName(next)), arrow("M1.5 6h9M6.5 2l4 4-4 4")));
}
-// A number: its data-* attributes are the exact values its box shows.
+// The newest hour stored, and how long ago it ended once that is two hours or more.
+function freshness(newest, now) {
+ if (!newest) return void ($("asof").textContent = "Nothing stored yet");
+ const late = Math.floor((now - Date.parse(`${newest}:00:00Z`) - 3_600_000) / 3_600_000);
+ const words = el("span", null, `Newest hour ends ${asOf(newest)}${late >= 2 ? `, ${late} hours ago` : ""}`);
+ $("asof").replaceChildren(...(late >= 2 ? [shape("over"), words] : [words]));
+ if (late >= 2) $("fresh").classList.add("late");
+}
+
+// Needs a look: a sentence per problem, each a link to its seat; all clear; or why it can't check.
+function drawNeeds(v, now) {
+ const line = (kind, text, seat) => {
+ const li = el("li");
+ li.dataset.k = kind;
+ li.append(shape(kind === "wait" ? "gap" : kind), seat ? Object.assign(el("a", null, text), { href: `#seat-${seat}` }) : el("span", null, text));
+ return li;
+ };
+ const items = v.current ? needs(v.limits, v.keys, now) : null;
+ let lines;
+ if (!v.current) lines = [line("wait", "Limits are read live, so they show on the current month only.")];
+ else if (!items) lines = [line("wait", "Seat limits aren't sent to this page yet, so it can't check them. Usage is below.")];
+ else if (!items.length) lines = [line("ok", "Nothing needs a look")];
+ else lines = items.map((i) => line(i.kind, i.text, i.seat));
+ $("need").dataset.sev = !items ? "wait" : items[0]?.kind ?? "ok";
+ $("needs").replaceChildren(...lines);
+ $("need").hidden = false;
+}
+
+function tiles(v) {
+ const t = v.total.all;
+ $("sum").replaceChildren(...[
+ ["Fresh tokens", t?.text, v.current ? "this month so far" : `in ${v.name}`],
+ ["Cache reads", t?.cached, "counted apart"],
+ ["At API prices, about", t?.usd, "a size guide, not a bill"],
+ ["Busiest seat", v.busiest?.name, v.busiest && `${v.busiest.text} fresh tokens`],
+ ].map(([k, val, s]) => {
+ const li = el("li");
+ li.append(el("span", "k", k), el("span", val ? "v" : "v na", val ?? "–"), el("span", "s", val ? s : "no data"));
+ return li;
+ }));
+ $("sum").hidden = false;
+}
+
+// A limit meter: the figure and its word, the bar with the alert's tick, the reset and the reading.
+function meterBox(v, seat, name, label, now) {
+ const m = meter(v, seat, name, label, now), t = THRESHOLD[name];
+ const box = el("div", `meter ${name === "five_hour" ? "m5" : "mw"}`);
+ box.dataset.kind = v.kind;
+ if (v.level) box.dataset.level = v.level;
+ box.setAttribute("role", "group");
+ box.setAttribute("aria-label", m.label);
+ const head = el("div", "m-head"), flag = el("span", "m-flag"), track = el("div", "m-track"), scale = el("div", "m-scale"), meta = el("div", "m-meta");
+ if (m.pct != null) {
+ const pct = el("span", "m-pct", String(m.pct));
+ pct.append(el("small", null, "%"));
+ head.append(pct);
+ track.append(svg("svg", { class: "m-bar", viewBox: "0 0 100 10", preserveAspectRatio: "none", "aria-hidden": "true", focusable: "false" }, svg("rect", { class: "m-fill", width: Math.min(m.pct, 100), height: 10 })));
+ }
+ const kind = v.level === "limit" || v.level === "over" ? v.level : v.kind === "fresh" ? null : "gap";
+ if (kind) flag.append(shape(kind));
+ flag.append(el("span", null, m.flag));
+ head.append(flag);
+ track.append(el("span", `m-tick at${t}`));
+ scale.append(el("span", `m-tl at${t}`, `alert ${t}%`));
+ meta.append(...m.meta.map((x) => el("span", x.startsWith("rejected") ? "ev" : null, x)));
+ box.append(el("span", "cap", label === "5-hour" ? "5-hour" : "Weekly"), head, track, scale, meta);
+ return box;
+}
+
+// Codex has no Claude limits, never 0%; "other" has no seat; and with no limits sent, no figure at all.
+function noLimits(seat) {
+ const box = el("div", "nl nolimit");
+ box.append(shape("gap"), el("span", null, seat === "codex" ? "No Claude limits: Codex isn't a Claude seat" : hasLimits(seat) ? "No limit readings yet" : "No limits: no seat to read them from"));
+ return box;
+}
+
+// Today or the month: the fresh tokens big, the dollars and cache reads small; a dash for no data.
+function figure(cls, cap, c, sub) {
+ const box = el("div", cls);
+ box.append(el("span", "cap", cap));
+ if (!c) box.append(el("div", "fig na", "–"), el("span", "sub", "no data, not zero"));
+ else box.append(el("div", "fig", c.text), el("span", "sub", sub(c)));
+ return box;
+}
+
+// A seat's trend: its complete days as a line from zero, then today so far apart, dashed and hollow.
+const W = 150, H = 38, PAD = 5;
+function spark(points, today, label) {
+ const n = points.length + (today == null ? 0 : 1), step = (W - 2 * PAD) / Math.max(1, n - 1);
+ const top = Math.max(1, ...points.filter((p) => p != null), today ?? 0);
+ const x = (i) => +(PAD + i * step).toFixed(1), y = (p) => +(H - PAD - (p / top) * (H - 2 * PAD)).toFixed(1);
+ const pts = points.map((p, i) => p != null && [x(i), y(p)]).filter(Boolean);
+ const kids = [svg("line", { class: "base", x1: PAD, y1: H - PAD, x2: W - PAD, y2: H - PAD })];
+ if (pts.length) {
+ const line = pts.map(([a, b]) => `${a},${b}`).join(" ");
+ kids.push(svg("polygon", { class: "area", points: `${pts[0][0]},${H - PAD} ${line} ${pts.at(-1)[0]},${H - PAD}` }), svg("polyline", { class: "line", points: line }));
+ if (today != null) kids.push(svg("line", { class: "link", x1: pts.at(-1)[0], y1: pts.at(-1)[1], x2: x(n - 1), y2: y(today) }));
+ kids.push(svg("circle", { class: "end", cx: pts.at(-1)[0], cy: pts.at(-1)[1], r: 3.5 }));
+ }
+ if (today != null) kids.push(svg("circle", { class: "now", cx: x(n - 1), cy: y(today), r: 3.5 }));
+ return svg("svg", { class: "spark", viewBox: `0 0 ${W} ${H}`, role: "img", "aria-label": label }, ...kids);
+}
+
+let span = 7;
+const trendsDrawn = [];
+function drawTrends(v, days, first) {
+ const last = v.current ? shiftDay(v.rows[0]?.key ?? `${v.month}-01`, -1) : v.rows[0]?.key;
+ $("since").textContent = last
+ ? `Each line is a seat's fresh tokens a day over the ${span} days to ${dayName(last)}, from zero${v.current ? "; the hollow dot is today so far" : ""}.`
+ : "";
+ for (const { box, seat, i } of trendsDrawn) {
+ const t = trend(days, seat, last, span, first), words = changeWords(t.change, span);
+ const today = v.current ? v.today[i]?.n ?? 0 : null;
+ box.replaceChildren(el("span", "cap", `Trend, ${span} days`), spark(t.points, today, `${seatName(seat)}, fresh tokens a day: ${words}`), el("span", "chg", words));
+ }
+ if ($("trendcol")) $("trendcol").textContent = `Trend, ${span} days`;
+}
+
+function seatRows(v, now) {
+ const head = el("div", "cols");
+ head.setAttribute("aria-hidden", "true");
+ const trendCol = el("span", null, `Trend, ${span} days`);
+ trendCol.id = "trendcol";
+ head.append(...(v.current ? ["Seat", "5-hour", "Weekly", "Today", "This month"] : ["Seat", "Month"]).map((t) => el("span", null, t)), trendCol);
+ trendsDrawn.length = 0;
+ const rows = v.keys.map((seat, i) => {
+ const row = el("article", `seat k-${colour(seat)}`), id = el("div", "s-id"), h = el("h3");
+ row.id = `seat-${seat}`;
+ h.append(el("span", "chip"), el("span", null, seatName(seat)));
+ id.append(h);
+ if (who(seat)) id.append(el("span", "who", who(seat)));
+ row.append(id);
+ if (v.current) {
+ if (hasLimits(seat) && v.limits) {
+ const views = WINDOWS.map(([w]) => windowOf(v.limits, seat, w, now));
+ row.append(...WINDOWS.map(([w, label], j) => meterBox(views[j], seat, w, label, now)));
+ const alert = alertOf(views);
+ if (alert) row.dataset.alert = alert;
+ } else row.append(noLimits(seat));
+ row.append(figure("td-f", "Today", v.today[i], (c) => `so far · about ${c.usd}`));
+ }
+ row.append(figure("mo-f", v.current ? "This month" : "Month", v.total.cells[i], (c) => `${c.cached} cache reads · about ${c.usd}`));
+ const box = el("div", "trend");
+ trendsDrawn.push({ box, seat, i });
+ row.append(box);
+ return row;
+ });
+ $("rows").className = v.current ? "rows" : "rows past";
+ $("rows").replaceChildren(head, ...rows);
+ $("seats").hidden = false;
+}
+
+// A number in the table: its data-* attributes are the exact values its box shows.
function num(x, cls) {
- const td = el("td", `h ${cls}`);
+ const td = el("td", `h ${cls}`.trim());
td.tabIndex = 0;
Object.assign(td.dataset, { who: x.who, when: x.when, f: x.f, c: x.c, u: x.u });
td.setAttribute("aria-label", x.label);
return td;
}
-const dash = (cls = "") => el("td", `none ${cls}`, "–");
+const dash = (cls) => el("td", cls ? `none ${cls}` : "none", "–");
+const dbar = (pct) => svg("svg", { class: "dbar", viewBox: `0 0 ${BAR} 4`, preserveAspectRatio: "none", "aria-hidden": "true", focusable: "false" }, svg("rect", { width: pct, height: 4 }));
-function bar(px) {
- const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"), rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
- for (const [k, v] of Object.entries({ class: "bar", width: px, height: 4, "aria-hidden": "true" })) svg.setAttribute(k, v);
- for (const [k, v] of Object.entries({ width: px, height: 4, rx: 2 })) rect.setAttribute(k, v);
- svg.append(rect);
- return svg;
+// The sticky strip under each seat's name, once the table's head is stuck: both windows, briefly.
+function strip(v, seat, now) {
+ const box = el("div", "mini"), views = WINDOWS.map(([w]) => windowOf(v.limits, seat, w, now));
+ if (!hasLimits(seat)) box.append(el("span", null, "no Claude limits"));
+ else if (views.every((x) => x.kind === "none")) box.append(el("span", null, "not reporting"));
+ else for (const [j, [, label]] of WINDOWS.entries()) {
+ const x = views[j], cls = x.level === "limit" || x.level === "over" ? x.level : null, s = el("span", cls);
+ if (cls) s.append(shape(cls));
+ s.append(el("span", null, `${label === "5-hour" ? "5h" : "wk"} ${mini(x)}`));
+ box.append(s);
+ }
+ return box;
}
-function draw(v, newest) {
- $("title").textContent = `Tokens per seat, ${v.name}`;
- $("asof").textContent = newest ? `Newest hour ends ${asOf(newest)}` : "Nothing stored yet";
- const t = v.total.all;
- $("sum").replaceChildren(...[["Fresh tokens this month", t?.text], ["Cache reads", t?.cached], ["At API prices, about", t?.usd], ["Busiest seat", v.busiest]]
- .map(([k, val]) => { const li = el("li"); li.append(el("span", "k", k), el("span", "v", val ?? "–")); return li; }));
- if (v.empty) $("status").textContent = `Nothing is stored for ${v.name} yet.`;
- else $("status").hidden = true;
-
- const head = el("tr");
- head.append(...["Day", ...v.seats].map((s) => el("th", null, s)), el("th", "tot", "All seats"));
+function drawTable(v, now) {
+ const cols = el("colgroup"), head = el("tr");
+ cols.append(el("col", "d"), ...v.keys.map(() => el("col")), el("col", "a"));
+ head.append(el("th", null, "Day"), ...v.keys.map((seat) => {
+ const th = el("th", `sh k-${colour(seat)}`), nm = el("div", "nm");
+ nm.append(el("span", "chip"), el("span", null, seatName(seat)));
+ th.append(nm);
+ if (v.current && v.limits) th.append(strip(v, seat, now));
+ return th;
+ }), el("th", "all", "All seats"));
for (const th of head.children) th.setAttribute("scope", "col");
const body = el("tbody");
for (const r of v.rows) {
- const tr = el("tr", [r.weekend && "we", r.today && "today"].filter(Boolean).join(" "));
- const day = el("td", null, `${r.d} `);
- day.append(el("span", "wd", r.wd));
+ const tr = el("tr", [r.weekend && "we", r.today && "today"].filter(Boolean).join(" ")), day = el("th");
+ day.setAttribute("scope", "row");
+ day.append(el("span", "n", dayName(r.key)));
if (r.today) day.append(el("span", "tag", "so far"));
tr.append(day, ...r.cells.map((c) => {
if (!c) return dash();
const td = num(c, `t${c.heat}`);
- td.append(el("span", "m", c.text));
+ td.append(el("span", "n", c.text));
return td;
}));
if (r.all) {
- const td = num(r.all, "tot"), m = el("span", "m", `${r.all.text} `);
- m.append(el("span", "usd", r.all.usd));
- td.append(m);
- if (r.all.bar) td.append(bar(r.all.bar));
+ const td = num(r.all, "tot"), row = el("div", "row");
+ row.append(el("span", "n", r.all.text), dbar(r.all.bar), el("span", "n d", r.all.usd));
+ td.append(row);
tr.append(td);
} else tr.append(dash("tot"));
body.append(tr);
}
- const foot = el("tr");
- foot.append(el("td", null, v.name.split(" ")[0]), ...v.total.cells.map((c) => {
+ const foot = el("tr"), t = v.total.all, month = el("th", null, monthName(v.month));
+ month.setAttribute("scope", "row");
+ foot.append(month, ...v.total.cells.map((c) => {
if (!c) return dash();
const td = num(c, "");
- td.append(el("span", "m", c.text), el("span", "s", c.usd));
+ td.append(el("span", "n", c.text), el("span", "s", c.usd));
return td;
}));
if (t) {
const td = num(t, "tot");
- td.append(el("span", "m", t.text), el("span", "s", `${t.cached} cached`), el("span", "s", t.usd));
+ td.append(el("span", "n", t.text), el("span", "s", `${t.cached} cache reads`), el("span", "s", t.usd));
foot.append(td);
} else foot.append(dash("tot"));
const thead = el("thead"), tfoot = el("tfoot");
thead.append(head);
tfoot.append(foot);
- $("usage").replaceChildren(thead, body, tfoot);
- for (const id of ["sum", "scroll", ...(v.empty ? [] : ["hint"])]) $(id).hidden = false;
+ $("usage").replaceChildren(cols, thead, body, tfoot);
+}
+
+// Under 1180 px the table gives way to a per day, the newest open.
+function drawDays(v) {
+ const chev = () => svg("svg", { class: "chev", viewBox: "0 0 12 12", "aria-hidden": "true", focusable: "false" }, svg("path", { d: "M2.5 4.5 6 8l3.5-3.5" }));
+ $("daylist").replaceChildren(...v.rows.map((r, n) => {
+ const li = el("li", r.weekend ? "we" : null), details = el("details"), sum = el("summary"), dn = el("span", "dn", dayName(r.key)), list = el("ul");
+ details.open = n === 0;
+ if (r.today) dn.append(el("span", "tag", "so far"));
+ sum.append(dn, el("span", "dt n", r.all?.text ?? "–"), el("span", "dd n", r.all?.usd ?? ""), chev());
+ if (r.all?.bar) sum.append(dbar(r.all.bar));
+ list.append(...v.keys.map((seat, i) => {
+ const c = r.cells[i], item = el("li", c ? null : "nodata"), nm = el("span", `nm k-${colour(seat)}`);
+ nm.append(el("span", "dot"), el("span", null, seatName(seat)));
+ item.append(nm, el("span", c ? `heat n t${c.heat}` : "heat n", c?.text ?? "–"), el("span", "dl n", c?.usd ?? ""), el("span", "more", c ? `${c.cached} cache reads · ${c.req} requests` : "no data, not zero"));
+ return item;
+ }));
+ details.append(sum, list);
+ li.append(details);
+ return li;
+ }));
+}
+
+function draw(v, months, newest, now) {
+ $("title").textContent = `Usage per seat, ${v.name}`;
+ freshness(newest, now);
+ if (v.empty) $("status").textContent = `Nothing is stored for ${v.name} yet.`;
+ else $("status").hidden = true;
+ drawNeeds(v, now);
+ if (!v.empty) tiles(v);
+ if (v.keys.length) {
+ const days = Object.assign({}, ...months.map((d) => d.days)), first = firstDay(months);
+ seatRows(v, now);
+ drawTrends(v, days, first);
+ for (const n of [7, 30]) {
+ $(`span${n}`).addEventListener("click", () => {
+ span = n;
+ for (const m of [7, 30]) $(`span${m}`).setAttribute("aria-pressed", String(m === n));
+ drawTrends(v, days, first);
+ });
+ }
+ }
+ if (!v.empty) {
+ drawTable(v, now);
+ drawDays(v);
+ $("days").hidden = false;
+ }
+}
+
+// The table's head sticks to the top of the window; once it does, each seat's strip shows. The
+// observed area runs far below the window, so a jump past the table (End, a link) still crosses its edge.
+function stick() {
+ if (!("IntersectionObserver" in globalThis)) return;
+ new IntersectionObserver((seen) => $("usage").classList.toggle("stuck", !seen.at(-1).isIntersecting), { rootMargin: "0px 0px 100000px 0px" }).observe($("top"));
}
// The box, from the reference in setkernel-live#71: placed with the CSSOM, which the CSP allows.
@@ -138,27 +359,34 @@ function listen() {
if (td && !again) { pinned = td; td.classList.add("on"); show(td); }
});
document.addEventListener("keydown", (e) => { if (e.key === "Escape") hide(); });
- // the window's scroll and the table's own: move a pinned or focused box with its number (Tab
- // scrolls a number into view after focusin), drop a hovered one
+ // a scroll anywhere: move a pinned or focused box with its number (Tab scrolls a number into view
+ // after focusin), drop a hovered one
document.addEventListener("scroll", () => { const td = pinned ?? focused; td ? show(td) : hide(); }, { capture: true, passive: true });
}
+async function get(month) {
+ let res;
+ try {
+ res = await fetch(`/usage/data?month=${month}`, { cache: "no-store", redirect: "manual" });
+ if (res.ok) return { data: await res.json(), newest: res.headers.get("Usage-Newest-Hour") };
+ } catch {}
+ return { status: res?.status ?? 0 };
+}
+
async function load() {
- const today = homeDay(Date.now()), current = today.slice(0, 7);
+ const now = Date.now(), today = homeDay(now), current = today.slice(0, 7);
const asked = new URLSearchParams(location.search).get("month") ?? "";
const month = /^\d{4}-(0[1-9]|1[0-2])$/.test(asked) && asked <= current ? asked : current;
nav(month, current);
- let res, data;
- try {
- res = await fetch(`/usage/data?month=${month}`, { cache: "no-store", redirect: "manual" });
- if (res.ok) data = await res.json();
- } catch {}
- if (!data) {
- $("status").textContent = failure(res?.status ?? 0);
+ const got = await Promise.all([0, -1, -2].map((by) => get(shiftMonth(month, by))));
+ const bad = got.find((g) => !g.data);
+ if (bad) {
+ $("status").textContent = failure(bad.status);
$("asof").textContent = "Not loaded";
return;
}
- draw(buildMonth(data, today), res.headers.get("Usage-Newest-Hour"));
+ draw(buildMonth(got[0].data, today), got.map((g) => g.data), got[0].newest, now);
+ stick();
listen();
}
diff --git a/public/usage/table.js b/public/usage/table.js
index 167c88e..fc590df 100644
--- a/public/usage/table.js
+++ b/public/usage/table.js
@@ -1,18 +1,22 @@
-// live.setkernel.com/usage (setkernel-live#71): GET /usage/data's month -> the rows, cells and
-// summary the page shows, option B as Raghav picked it. Pure and tested (test/usage-page.test.mjs).
+// live.setkernel.com/usage (setkernel-live#71, v5 in #86): GET /usage/data's months -> the seats, the
+// month's totals, its seat-by-day rows and each seat's trend. Pure and tested (test/usage-page.test.mjs).
// Fresh tokens are input + output + cache writes; cache reads are shown apart.
-const SEATS = ["vega", "rigel", "lyra", "orion", "polaris"]; // then codex and other, when they have data
-const KEYS = ["input", "output", "cache_read", "cache_write", "usd_micros"];
+const ORDER = ["vega", "rigel", "lyra", "orion", "polaris", "codex", "other"]; // then any other seat, A to Z
+const COLOURS = ["vega", "rigel", "lyra", "orion", "polaris", "codex"]; // usage.css's .k-*; the rest are grey
+const WHO = { polaris: "Raghav's own sessions", codex: "not a Claude seat", other: "usage no seat claimed" };
+const KEYS = ["input", "output", "cache_read", "cache_write", "usd_micros", "requests"];
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
export const HEAT = 8; // shading steps, one CSS class each: the CSP allows no style attribute
-export const BAR = 96; // the busiest day's bar, in px
+export const BAR = 100; // the busiest day's bar, in percent of its column
export const exact = (n) => n.toLocaleString("en-US");
export const dollars = (micros) => `$${exact(Math.round(micros / 1e6))}`;
const fresh = (c) => c.input + c.output + c.cache_write;
-const add = (a, b) => Object.fromEntries(KEYS.map((k) => [k, (a?.[k] ?? 0) + b[k]]));
-const title = (s) => s[0].toUpperCase() + s.slice(1);
+const add = (a, b) => Object.fromEntries(KEYS.map((k) => [k, (a?.[k] ?? 0) + (b[k] ?? 0)]));
+export const seatName = (s) => s[0].toUpperCase() + s.slice(1);
+export const who = (s) => WHO[s] ?? "";
+export const colour = (s) => (COLOURS.includes(s) ? s : "x");
// 13,698,537 -> "14M", 2,372,363 -> "2.4M", 816,743 -> "817K", 15,045,054,434 -> "15.0B".
export function short(n) {
@@ -31,8 +35,15 @@ export function shiftMonth(month, by) {
return `${Math.floor(n / 12)}-${String((n % 12) + 1).padStart(2, "0")}`;
}
-// "2026-09" -> "September".
-export const monthName = (month) => MONTHS[Number(month.slice(5)) - 1];
+// "2026-10-28" moved by `by` days.
+export function shiftDay(day, by) {
+ const [y, m, d] = day.split("-").map(Number);
+ return new Date(Date.UTC(y, m - 1, d + by)).toISOString().slice(0, 10);
+}
+
+// "2026-09" -> "September"; "2026-10-27" -> "Tue 27 Oct".
+export const monthName = (month) => MONTHS[Number(month.slice(5, 7)) - 1];
+export const dayName = (day) => `${WEEKDAYS[new Date(`${day}T12:00:00Z`).getUTCDay()]} ${Number(day.slice(8))} ${monthName(day).slice(0, 3)}`;
// The newest hour stored ("2026-10-31T14", a UTC hour) -> when it ended, in Halifax: "31 Oct, 12:00 ADT".
const halifax = new Intl.DateTimeFormat("en-US", { timeZone: "America/Halifax", day: "numeric", month: "short", hour: "2-digit", minute: "2-digit", hourCycle: "h23", timeZoneName: "short" });
@@ -41,22 +52,31 @@ export function asOf(hour) {
return `${p.day} ${p.month}, ${p.hour}:${p.minute} ${p.timeZoneName}`;
}
-// One number: what its cell shows, and the exact values its box and aria-label give.
+// The seats a month names, in the team's order: those with usage and, on the current month, those the
+// seat limits name. Nothing else: a seat with neither isn't on the page.
+export function seatsOf(totals, limits) {
+ const rank = (s) => (ORDER.includes(s) ? ORDER.indexOf(s) : ORDER.length);
+ return [...new Set([...Object.keys(totals ?? {}), ...Object.keys(limits ?? {})])].sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
+}
+
+// One number: what it shows, and the exact values its box and aria-label give.
function cell(who, when, c) {
const f = exact(fresh(c)), r = exact(c.cache_read), u = dollars(c.usd_micros);
- return { who, when, n: fresh(c), text: short(fresh(c)), usd: u, cached: short(c.cache_read), f, c: r, u, label: `${who}, ${when}: ${f} fresh tokens, ${r} cache reads, about ${u}` };
+ return { who, when, n: fresh(c), text: short(fresh(c)), usd: u, cached: short(c.cache_read), f, c: r, u, req: exact(c.requests ?? 0), label: `${who}, ${when}: ${f} fresh tokens, ${r} cache reads, about ${u}` };
}
// The box: a heading and three label-value lines.
export const tip = (x) => ({ head: `${x.who} · ${x.when}`, rows: [["Fresh tokens", x.f], ["Cache reads", x.c], ["At API prices", `about ${x.u}`]] });
-// { month, days, totals } and today's Halifax date -> { name, seats, rows (newest day first, none
-// after today), total, empty }. A day or seat with no data is null: the page shows a dash.
+// { month, days, totals, limits? } and today's Halifax date -> { name, keys, seats, current, limits,
+// rows (newest day first, none after today), today, total, empty, busiest }. A seat-day with no data
+// is null: the page shows a dash. Limits count on the current month only: they are read live.
export function buildMonth(data, today) {
const [y, m] = data.month.split("-").map(Number);
- const name = MONTHS[m - 1];
- const keys = [...SEATS, ...["codex", "other"].filter((s) => data.totals[s])];
- const seats = keys.map(title);
+ const name = MONTHS[m - 1], current = today.startsWith(data.month);
+ const limits = current ? data.limits ?? null : null;
+ const keys = seatsOf(data.totals, limits);
+ const seats = keys.map(seatName);
const rows = [];
for (let d = new Date(Date.UTC(y, m, 0)).getUTCDate(); d >= 1; d--) {
const key = `${data.month}-${String(d).padStart(2, "0")}`;
@@ -65,7 +85,7 @@ export function buildMonth(data, today) {
const when = `${wd} ${d} ${name.slice(0, 3)}${key === today ? ", so far" : ""}`;
const day = data.days[key] ?? {};
const all = Object.values(day).reduce(add, null);
- rows.push({ d, wd, today: key === today, weekend: wd === "Sat" || wd === "Sun", cells: keys.map((s, i) => day[s] && cell(seats[i], when, day[s])), all: all && cell("All seats", when, all) });
+ rows.push({ key, d, wd, when, today: key === today, weekend: wd === "Sat" || wd === "Sun", cells: keys.map((s, i) => (day[s] ? cell(seats[i], when, day[s]) : null)), all: all && cell("All seats", when, all) });
}
// shading scales to the month's biggest seat-day, the bar to its busiest day
const hottest = Math.max(1, ...rows.flatMap((r) => r.cells.map((c) => c?.n ?? 0)));
@@ -77,7 +97,37 @@ export function buildMonth(data, today) {
const all = Object.values(data.totals).reduce(add, null);
const top = keys.reduce((a, s) => (data.totals[s] && (!a || fresh(data.totals[s]) > fresh(data.totals[a])) ? s : a), null);
return {
- name: `${name} ${y}`, seats, rows, empty: !all, busiest: top && title(top),
- total: { cells: keys.map((s, i) => data.totals[s] && cell(seats[i], name, data.totals[s])), all: all && cell("All seats", name, all) },
+ name: `${name} ${y}`, month: data.month, keys, seats, current, limits, rows, empty: !all,
+ today: current ? rows.find((r) => r.today)?.cells ?? keys.map(() => null) : null,
+ busiest: top && { name: seatName(top), text: short(fresh(data.totals[top])) },
+ total: { cells: keys.map((s, i) => (data.totals[s] ? cell(seats[i], name, data.totals[s]) : null)), all: all && cell("All seats", name, all) },
+ };
+}
+
+// The first day any of `months` (GET /usage/data answers) holds: the trend says nothing before it.
+export const firstDay = (months) => months.flatMap((d) => Object.keys(d.days).filter((k) => Object.keys(d.days[k]).length)).sort()[0] ?? null;
+
+// A seat's fresh tokens a day over the `span` days to `last`, oldest first (null before `first`, the
+// first day stored; a day stored without the seat is 0), and the change on the `span` days before as
+// a whole percent of their daily mean: null when fewer than half of them are stored or they sum to 0.
+export function trend(days, seat, last, span, first) {
+ const at = (back) => {
+ const key = shiftDay(last, -back);
+ if (!first || key < first) return null;
+ const c = days[key]?.[seat];
+ return c ? fresh(c) : 0;
};
+ const points = Array.from({ length: span }, (_, i) => at(span - 1 - i));
+ const before = Array.from({ length: span }, (_, i) => at(span + i)).filter((n) => n != null);
+ const now = points.filter((n) => n != null);
+ const mean = (a) => a.reduce((x, n) => x + n, 0) / a.length;
+ const change = now.length && before.length >= Math.ceil(span / 2) && mean(before) > 0 ? Math.round((mean(now) / mean(before) - 1) * 100) : null;
+ return { points, change };
+}
+
+// The change in words: "Up 12% on the previous 7 days".
+export function changeWords(change, span) {
+ if (change == null) return "No earlier days to compare with";
+ if (change === 0) return `No change on the previous ${span} days`;
+ return `${change > 0 ? "Up" : "Down"} ${Math.abs(change)}% on the previous ${span} days`;
}
diff --git a/public/usage/usage.css b/public/usage/usage.css
index 48752ef..c3fb834 100644
--- a/public/usage/usage.css
+++ b/public/usage/usage.css
@@ -1,76 +1,278 @@
-/* live.setkernel.com/usage (setkernel-live#78): option B from setkernel-live#71. The fonts, tokens,
- masthead and lead come from /style.css; this adds the dark theme (the wall's colours, so the
- contrast test in test/page.test.mjs covers them), the table, the shading and the box. */
-:root { --heat: 24, 24, 26; }
+/* live.setkernel.com/usage (setkernel-live#86): v5, Headroom's "Needs a look" and seat rows over
+ Ledger's totals and seat-by-day table (setkernel/hq#972's prototypes). Its own fonts and both
+ themes, so nothing here depends on the live page's style.css; test/usage-page.test.mjs checks the
+ contrast of every text colour on every ground, light and dark. Every colour and size the script
+ picks is a class: the CSP allows no inline style. */
+@font-face { font-family: "Manrope"; font-style: normal; font-weight: 400; font-display: swap; src: url("/usage/fonts/manrope-latin-400-normal.woff2") format("woff2");
+ unicode-range: U+0020-007E, U+00A0-00FF, U+0102, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2013-2014, U+2018-201A, U+201C-201E, U+2022, U+2026, U+2039-203A, U+2044, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215; }
+@font-face { font-family: "Manrope"; font-style: normal; font-weight: 600; font-display: swap; src: url("/usage/fonts/manrope-latin-600-normal.woff2") format("woff2");
+ unicode-range: U+0020-007E, U+00A0-00FF, U+0102, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2013-2014, U+2018-201A, U+201C-201E, U+2022, U+2026, U+2039-203A, U+2044, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215; }
+@font-face { font-family: "Manrope"; font-style: normal; font-weight: 800; font-display: swap; src: url("/usage/fonts/manrope-latin-800-normal.woff2") format("woff2");
+ unicode-range: U+0020-007E, U+00A0-00FF, U+0102, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2013-2014, U+2018-201A, U+201C-201E, U+2022, U+2026, U+2039-203A, U+2044, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215; }
+@font-face { font-family: "IBM Plex Mono"; font-style: normal; font-weight: 400; font-display: swap; src: url("/usage/fonts/ibm-plex-mono-latin-400-normal.woff2") format("woff2");
+ unicode-range: U+0020-007E, U+00A0-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+2013-2014, U+2018-201A, U+201C-201E, U+2022, U+2026, U+2032-2033, U+2039-203A, U+2044, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215; }
+@font-face { font-family: "IBM Plex Mono"; font-style: normal; font-weight: 500; font-display: swap; src: url("/usage/fonts/ibm-plex-mono-latin-500-normal.woff2") format("woff2");
+ unicode-range: U+0020-007E, U+00A0-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+2013-2014, U+2018-201A, U+201C-201E, U+2022, U+2026, U+2032-2033, U+2039-203A, U+2044, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215; }
+
+:root {
+ --sans: "Manrope", sans-serif;
+ --mono: "IBM Plex Mono", monospace;
+ --bg: #f6f5f1; --panel: #fdfcf9; --raise: #ecebe4; --ink: #18181a; --ink-2: #4a4945; --ink-3: #5f5d57;
+ --rule: #dcd9cf; --rule-2: #8a867c; --signal: #b42318; --ok: #1e6b33; --warn: #8a5a00; --focus: #1d4ed8;
+ --fill: #5f5d57;
+ /* a seat's colour marks who it is, always beside its name, never a level */
+ --c-vega: #2a78d6; --c-rigel: #d4561f; --c-lyra: #0f8a5f; --c-orion: #a87000; --c-polaris: #cc4a85; --c-codex: #3f7d00;
+ /* fresh tokens in a seat-day, 8 steps of one hue (table.js, HEAT) */
+ --h1: #f2f2fb; --h2: #e3e3f7; --h3: #d4d5f3; --h4: #c6c6ee; --h5: #b7b7e9; --h6: #a9a8e4; --h7: #9b99df; --h8: #8e8ad9;
+ color-scheme: light;
+}
@media (prefers-color-scheme: dark) {
:root {
- --bg: #111214; --surface: #1b1c20; --ink: #eeede9; --ink-2: #bdbbb5; --ink-3: #9a9892;
- --rule: #232427; --rule-2: #3d3e42; --band: #25262a; --bar: #77756f;
- --signal: #f2735f; --focus: #8fb0ff;
- --heat: 238, 237, 233; color-scheme: dark;
+ --bg: #111214; --panel: #18191c; --raise: #222327; --ink: #eeede9; --ink-2: #c4c2bc; --ink-3: #a3a19b;
+ --rule: #2c2d31; --rule-2: #6b6a66; --signal: #f2735f; --ok: #5fc77a; --warn: #e0a537; --focus: #8fb0ff;
+ --fill: #a3a19b;
+ --c-vega: #3987e5; --c-rigel: #d95926; --c-lyra: #199e70; --c-orion: #c98500; --c-polaris: #d55181; --c-codex: #008300;
+ --h1: #252435; --h2: #2d2c44; --h3: #353453; --h4: #3e3c63; --h5: #474474; --h6: #504d85; --h7: #595596; --h8: #635ea8;
+ color-scheme: dark;
}
}
-.lead { padding-bottom: var(--s3); }
-.months { display: flex; gap: var(--s4); align-items: baseline; font-size: var(--f2); line-height: var(--l2); color: var(--ink-2); padding-bottom: var(--s3); }
+.k-vega { --c: var(--c-vega); } .k-rigel { --c: var(--c-rigel); } .k-lyra { --c: var(--c-lyra); }
+.k-orion { --c: var(--c-orion); } .k-polaris { --c: var(--c-polaris); } .k-codex { --c: var(--c-codex); } .k-x { --c: var(--ink-3); }
+td.t1, span.t1, i.t1 { --c0: var(--h1); }
+td.t2, span.t2, i.t2 { --c0: var(--h2); }
+td.t3, span.t3, i.t3 { --c0: var(--h3); }
+td.t4, span.t4, i.t4 { --c0: var(--h4); }
+td.t5, span.t5, i.t5 { --c0: var(--h5); }
+td.t6, span.t6, i.t6 { --c0: var(--h6); }
+td.t7, span.t7, i.t7 { --c0: var(--h7); }
+td.t8, span.t8, i.t8 { --c0: var(--h8); }
+
+* { box-sizing: border-box; }
+[hidden] { display: none !important; }
+html { font-size: clamp(16px, 0.55vw + 8px, 22px); -webkit-text-size-adjust: 100%; }
+body { margin: 0; background: var(--bg); color: var(--ink); font: 400 1rem/1.5 var(--sans); }
+h1, h2, h3, p, ul { margin: 0; padding: 0; }
+ul { list-style: none; }
+a { color: inherit; text-decoration-thickness: 1px; text-underline-offset: .2em; }
+a:hover { text-decoration-thickness: 2px; }
+a:focus-visible, button:focus-visible, summary:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
+.n { font-family: var(--mono); font-variant-numeric: tabular-nums; }
+.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
+svg.i { width: 1rem; height: 1rem; flex: none; display: block; }
+svg.i .fg { fill: currentColor; }
+svg.i .cut { fill: var(--panel); }
+svg.i .ring { fill: none; stroke: currentColor; stroke-width: 1.8; stroke-dasharray: 2.6 2.2; }
+svg.i .tick { fill: none; stroke: var(--panel); stroke-width: 2; }
+.wrap { max-width: 150rem; margin: 0 auto; padding: 0 1rem; }
+@media (min-width: 720px) { .wrap { padding: 0 2rem; } }
+@media (min-width: 1180px) { .wrap { padding: 0 3rem; } }
+
+/* masthead: the newest hour stored, a warning pill once it is two hours old */
+.mast { border-bottom: 1px solid var(--rule); }
+.mast .wrap { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: .25rem 1.5rem; min-height: 3.5rem; }
+.brand { font-weight: 800; font-size: 1.05rem; letter-spacing: -.01em; }
+.brand a { text-decoration: none; }
+.brand span { font-weight: 400; color: var(--ink-2); }
+.fresh { display: flex; align-items: center; gap: .5rem; color: var(--ink-2); font-size: .875rem; }
+.fresh.late { color: var(--warn); font-weight: 600; border: 1px solid var(--warn); border-radius: 999px; padding: .15rem .7rem; }
+.fresh #asof { display: inline-flex; align-items: center; gap: .4rem; }
+.fresh svg.i { width: .9rem; height: .9rem; }
+.priv { color: var(--ink-3); font-weight: 400; }
+
+/* title and months */
+.intro { padding: 1.5rem 0 1rem; }
+h1 { font-size: clamp(1.75rem, 1.2rem + 1.6vw, 2.6rem); line-height: 1.1; font-weight: 800; letter-spacing: -.02em; }
+.months { display: flex; flex-wrap: wrap; align-items: center; gap: .25rem 1rem; margin-top: .6rem; font-size: .95rem; }
+.months a, .months .off { display: inline-flex; align-items: center; gap: .4rem; min-height: 1.75rem; }
.months .off { color: var(--ink-3); }
-.months .arrow:first-child { margin-right: var(--s1); }
-.months .arrow:last-child { margin-left: var(--s1); }
-a:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
-.status { margin: 0 0 var(--s4); color: var(--ink-2); }
-.sum { display: flex; flex-wrap: wrap; gap: var(--s3) var(--s5); margin: 0 0 var(--s4); padding: 0; list-style: none; }
-.sum li { display: flex; flex-direction: column; }
-.sum .k { font-size: var(--f1); line-height: var(--l1); color: var(--ink-3); }
-.sum .v { font-size: var(--f4); line-height: var(--l3); font-weight: 600; }
-.hint { margin: 0 0 var(--s2); font-size: var(--f1); line-height: var(--l1); color: var(--ink-3); }
-.note { margin: var(--s3) 0 0; font-size: var(--f1); line-height: var(--l1); color: var(--ink-3); max-width: 760px; }
+.months b { font-weight: 800; }
+.months svg { width: .85rem; height: .85rem; stroke: currentColor; fill: none; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
+.status { margin: 0 0 1rem; color: var(--ink-2); font-weight: 600; }
+
+/* Needs a look: a sentence per problem, worst first, each a link to its seat */
+.need { margin: 0 0 1.25rem; padding: .9rem 1.1rem 1rem; background: var(--panel); border: 1px solid var(--rule); border-left: 6px solid var(--rule-2); border-radius: 6px; }
+.need[data-sev="limit"] { border-left-color: var(--signal); }
+.need[data-sev="over"], .need[data-sev="gap"] { border-left-color: var(--warn); }
+.need[data-sev="ok"] { border-left-color: var(--ok); }
+.need h2, .cap, .cols span { font: 500 .8125rem/1.4 var(--mono); letter-spacing: .06em; text-transform: uppercase; color: var(--ink-3); }
+.need h2 { margin-bottom: .45rem; }
+.need ul { display: flex; flex-direction: column; gap: .45rem; }
+.need li { display: flex; gap: .55rem; align-items: flex-start; font-weight: 600; font-size: 1.1875rem; line-height: 1.35; }
+.need li svg { margin-top: .2rem; }
+.need li[data-k="limit"] { color: var(--signal); }
+.need li[data-k="over"], .need li[data-k="gap"] { color: var(--warn); }
+.need li[data-k="ok"] { color: var(--ok); }
+.need li[data-k="wait"] { color: var(--ink-3); }
+.need li a, .need li span { color: var(--ink); }
+.need li[data-k="wait"] span { color: var(--ink-2); }
+
+/* the month's four totals */
+.tiles { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .75rem 1.5rem; margin: 0 0 1.5rem; }
+@media (min-width: 720px) { .tiles { grid-template-columns: repeat(4, auto); justify-content: start; gap: .75rem 4rem; } }
+.tiles .k, .tiles .s { display: block; color: var(--ink-3); font-size: .8125rem; line-height: 1.3; }
+.tiles .v { display: block; font-size: 1.6rem; line-height: 1.2; font-weight: 800; letter-spacing: -.01em; }
+.tiles li:first-child .v { font-size: 2.2rem; line-height: 1.05; }
+.tiles .na { color: var(--ink-3); }
-/* the table: one row per Halifax day, newest first; only it scrolls sideways on a phone */
-.scroll { overflow-x: auto; border-top: 1px solid var(--rule-2); }
-table { border-collapse: collapse; width: 100%; font-size: var(--f2); line-height: var(--l2); }
-th, td { text-align: right; padding: var(--s2) var(--s3) var(--s2) 0; border-bottom: 1px solid var(--rule); vertical-align: top; white-space: nowrap; }
-thead th { font-weight: 600; color: var(--ink-2); position: sticky; top: 0; background: var(--bg); }
-th:first-child, td:first-child { text-align: left; position: sticky; left: 0; background: var(--bg); padding-left: 0; z-index: 1; }
-td:first-child { font: var(--f1)/var(--l2) var(--mono); color: var(--ink-2); }
-td:first-child .wd { color: var(--ink-3); }
-td .m, td .s { display: block; }
-td .m { color: var(--ink); }
-td .s { font-size: var(--f1); line-height: var(--l1); color: var(--ink-3); }
-td.none { color: var(--ink-3); padding-left: var(--s3); }
-th.tot, td.tot { border-left: 1px solid var(--rule-2); padding-left: var(--s3); }
-tr.we td:first-child { color: var(--ink-3); }
-tr.today td, tr.today td:first-child { background-color: var(--surface); }
-.tag { display: inline-block; margin-left: var(--s2); font: 600 var(--f1)/var(--l1) var(--sans); color: var(--signal); }
-tfoot td { border-top: 1px solid var(--rule-2); border-bottom: 0; padding-top: var(--s3); }
-tfoot td:first-child { font: 600 var(--f2)/var(--l2) var(--sans); color: var(--ink); }
-tfoot td .m, td.tot .m { font-weight: 600; }
-.usd { font-size: var(--f1); color: var(--ink-3); }
-.bar { display: block; margin: var(--s1) 0 0 auto; }
-.bar rect { fill: var(--bar); }
+/* section heads, and the trend span */
+.sec-row { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .5rem 2rem; margin: 0 0 .6rem; }
+h2.sec { font-weight: 800; font-size: 1.25rem; line-height: 1.2; }
+.seg { display: inline-flex; align-items: center; gap: .6rem; font-size: .875rem; color: var(--ink-2); }
+.seg [role="group"] { display: inline-flex; }
+.seg button { min-height: 2.25rem; min-width: 5rem; padding: 0 .9rem; font: 600 .875rem var(--sans); color: var(--ink); background: var(--panel); border: 1px solid var(--rule-2); cursor: pointer; }
+.seg button:first-child { border-radius: 6px 0 0 6px; }
+.seg button:last-child { border-radius: 0 6px 6px 0; margin-left: -1px; }
+.seg button[aria-pressed="true"] { background: var(--ink); color: var(--bg); border-color: var(--ink); }
+.since { margin: -.2rem 0 .7rem; color: var(--ink-2); font-size: .875rem; }
-/* a seat's day, shaded on 8 steps by its size against the month's biggest (table.js, HEAT): a
- class each, since the CSP allows no style attribute; laid over today's ground, not in place of it */
-td.h { padding-left: var(--s3); cursor: default; background-image: linear-gradient(var(--tint, transparent), var(--tint, transparent)); }
-td.t1 { --tint: rgba(var(--heat), .04); }
-td.t2 { --tint: rgba(var(--heat), .06); }
-td.t3 { --tint: rgba(var(--heat), .08); }
-td.t4 { --tint: rgba(var(--heat), .10); }
-td.t5 { --tint: rgba(var(--heat), .12); }
-td.t6 { --tint: rgba(var(--heat), .14); }
-td.t7 { --tint: rgba(var(--heat), .16); }
-td.t8 { --tint: rgba(var(--heat), .18); }
-td.h:focus { outline: none; }
-td.h:hover, td.h.on { outline: 2px solid var(--ink); outline-offset: -2px; }
-td.h:focus-visible { outline: 2px solid var(--focus); outline-offset: -2px; }
+/* the seats: a card each, then at 1180 px one row each */
+.rows { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 19rem), 1fr)); gap: .75rem; margin-bottom: 2rem; }
+.cols { display: none; }
+.seat { display: grid; grid-template-columns: 1fr 1fr; gap: .9rem 1.1rem; padding: 1rem 1rem 1.1rem; background: var(--panel); border: 1px solid var(--rule); border-left: 6px solid var(--rule); border-radius: 8px; scroll-margin-top: 4rem; }
+.seat[data-alert="limit"] { border-left-color: var(--signal); }
+.seat[data-alert="over"], .seat[data-alert="gap"] { border-left-color: var(--warn); }
+.seat > * { min-width: 0; }
+.s-id, .m5, .mw, .nl, .trend { grid-column: 1 / -1; }
+.s-id { display: flex; flex-wrap: wrap; gap: .1rem .6rem; align-items: baseline; }
+.s-id h3 { font-weight: 800; font-size: 1.375rem; line-height: 1.2; display: inline-flex; align-items: center; gap: .5rem; }
+.chip, .dot { flex: none; display: inline-block; width: .75rem; height: .75rem; border-radius: 2px; background: var(--c); }
+.dot { width: .65rem; height: .65rem; border-radius: 50%; }
+.who { font-size: .875rem; color: var(--ink-2); }
+.cap { display: block; margin-bottom: .2rem; }
+
+/* a limit meter: the big figure and its word, the bar with the alert ticked, the reset and the reading */
+.meter { display: flex; flex-direction: column; gap: .3rem; }
+.m-head { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: baseline; gap: 0 .75rem; }
+.m-pct { font-weight: 800; font-size: 2.25rem; line-height: 1.1; letter-spacing: -.02em; font-variant-numeric: tabular-nums; }
+.m-pct small { font-size: .55em; font-weight: 600; letter-spacing: 0; }
+.m-flag { display: inline-flex; gap: .4rem; align-items: center; font-weight: 600; font-size: .875rem; color: var(--ink-2); }
+.m-track { position: relative; height: .95rem; margin: .2rem 0 0; border: 1px solid var(--rule-2); border-radius: 3px; background: var(--raise); }
+.m-bar { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
+.m-fill { fill: var(--fill); }
+.m-tick { position: absolute; top: -.3rem; bottom: -.3rem; width: 2px; margin-left: -1px; background: var(--ink); }
+.m-scale { position: relative; height: 1.1rem; }
+.m-tl { position: absolute; top: .15rem; transform: translateX(-50%); font: 500 .75rem/1 var(--mono); color: var(--ink-3); white-space: nowrap; }
+.at80 { left: 80%; } .at70 { left: 70%; }
+.m-meta { font: 400 .8125rem/1.45 var(--mono); color: var(--ink-2); display: flex; flex-wrap: wrap; gap: 0 .9rem; }
+.meter[data-level="over"] .m-fill { fill: var(--warn); }
+.meter[data-level="over"] .m-pct, .meter[data-level="over"] .m-flag { color: var(--warn); }
+.meter[data-level="limit"] .m-fill { fill: var(--signal); }
+.meter[data-level="limit"] .m-track { border: 2px solid var(--signal); }
+.meter[data-level="limit"] .m-pct { color: var(--signal); }
+.meter[data-level="limit"] .m-flag { color: var(--signal); font-weight: 800; letter-spacing: .08em; }
+.meter[data-level="limit"] .m-meta .ev { color: var(--signal); font-weight: 600; }
+.meter[data-kind="stale"] .m-track, .meter[data-kind="none"] .m-track { background: transparent; border: 2px dashed var(--rule-2); }
+.meter[data-kind="stale"] .m-pct, .meter[data-kind="none"] .m-pct { color: var(--ink-3); }
+.meter[data-kind="stale"] .m-flag, .meter[data-kind="none"] .m-flag { color: var(--ink); }
+.nolimit { display: flex; gap: .55rem; align-items: flex-start; padding: .6rem .8rem; border: 1px dashed var(--rule-2); border-radius: 6px; font-weight: 600; color: var(--ink-2); font-size: .9375rem; }
+.nolimit svg { margin-top: .2rem; color: var(--ink-3); }
+
+/* today and this month */
+.fig { font-weight: 800; font-size: 1.5rem; line-height: 1.15; letter-spacing: -.01em; font-variant-numeric: tabular-nums; }
+.fig small { font-size: .8125rem; font-weight: 600; color: var(--ink-2); letter-spacing: 0; margin-left: .25rem; }
+.fig.na { color: var(--ink-3); }
+.sub { display: block; font-size: .8125rem; color: var(--ink-2); line-height: 1.45; font-variant-numeric: tabular-nums; }
+
+/* the trend: the span's complete days as a line, from zero; today apart, dashed, "so far" */
+.spark { display: block; width: 100%; max-width: 16rem; height: auto; overflow: visible; color: var(--c); margin: .15rem 0 .2rem; }
+.spark .base { stroke: var(--rule-2); stroke-width: 1; }
+.spark .area { fill: currentColor; opacity: .1; }
+.spark .line { fill: none; stroke: currentColor; stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; vector-effect: non-scaling-stroke; }
+.spark .end { fill: currentColor; stroke: var(--panel); stroke-width: 2; }
+.spark .now { fill: var(--panel); stroke: currentColor; stroke-width: 2; }
+.spark .link { fill: none; stroke: currentColor; stroke-width: 1.5; stroke-dasharray: 3 3; vector-effect: non-scaling-stroke; }
+.chg { font-weight: 600; font-size: .875rem; line-height: 1.35; }
+
+@media (min-width: 1180px) {
+ .rows { display: block; background: var(--panel); border: 1px solid var(--rule); border-radius: 8px; }
+ .cols { display: grid; padding: .6rem 1rem .6rem calc(1rem + 6px); border-bottom: 1px solid var(--rule); background: var(--raise); border-radius: 8px 8px 0 0; }
+ .cols span { color: var(--ink-2); }
+ .cols, .seat { grid-template-columns: 10rem minmax(0, 1.25fr) minmax(0, 1.25fr) 7rem 8.5rem minmax(0, 1.1fr); gap: 1.25rem; }
+ .rows.past .cols, .rows.past .seat { grid-template-columns: 10rem 10rem minmax(0, 1fr); }
+ .seat { align-items: start; border: 0; border-top: 1px solid var(--rule); border-left: 6px solid transparent; border-radius: 0; }
+ .cols + .seat { border-top: 0; }
+ .seat > .s-id, .seat > .m5, .seat > .mw, .seat > .trend { grid-column: auto; }
+ .seat > .nl { grid-column: span 2; }
+ .seat .cap { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
+ .s-id { flex-direction: column; gap: .1rem; align-items: flex-start; }
+ .m-pct { font-size: 2.5rem; }
+ .need li { font-size: 1.375rem; }
+ .need li svg { margin-top: .3rem; }
+ .fig { font-size: 1.375rem; }
+ .fig small { display: block; margin: 0; }
+}
+
+/* day by day: at 1180 px the seat-by-day table, under it a per day */
+.legend { display: inline-flex; flex-wrap: wrap; align-items: center; gap: .3rem .6rem; color: var(--ink-3); font-size: .8125rem; }
+.legend .ramp { display: flex; gap: 2px; }
+.legend .ramp i { width: 1.1rem; height: .8rem; border-radius: 2px; border: 1px solid var(--rule); background: var(--c0); }
+.hint { margin: 0 0 .5rem; color: var(--ink-3); font-size: .8125rem; }
+.frame { background: var(--panel); border: 1px solid var(--rule); border-radius: 8px; }
+.tbl, .hint { display: none; }
+@media (min-width: 1180px) { .tbl, .hint { display: block; } .days, .dayhead { display: none; } }
+table.ledger { width: 100%; table-layout: fixed; border-collapse: separate; border-spacing: 0; font-size: .875rem; }
+.ledger col.d { width: 8.2rem; }
+.ledger col.a { width: 17%; }
+.ledger th, .ledger td { padding: .4rem .7rem; text-align: left; vertical-align: middle; border-bottom: 1px solid var(--rule); font-weight: 400; }
+.ledger thead th { position: sticky; top: 0; z-index: 4; background: var(--panel); vertical-align: top; border-bottom: 1px solid var(--rule-2); padding-top: .6rem; padding-bottom: .5rem; }
+.ledger thead th:first-child { border-top-left-radius: 8px; font-size: .8125rem; font-weight: 600; color: var(--ink-2); }
+.ledger thead th:last-child { border-top-right-radius: 8px; }
+.ledger .nm { display: flex; align-items: center; gap: .5rem; font-weight: 800; font-size: 1.05rem; line-height: 1.2; }
+.mini { display: none; margin-top: .25rem; gap: .2rem .6rem; flex-wrap: wrap; font-size: .8125rem; color: var(--ink-2); }
+.stuck .mini { display: flex; }
+.mini span { display: inline-flex; align-items: center; gap: .25rem; }
+.mini .over { color: var(--warn); font-weight: 600; }
+.mini .limit { color: var(--signal); font-weight: 800; }
+.mini svg.i { width: .8rem; height: .8rem; }
+.ledger tbody th { white-space: nowrap; height: 2.5rem; padding: .2rem .7rem; }
+.ledger tbody th .n { font-size: .8125rem; }
+.ledger tr.we th { background: var(--raise); }
+.ledger tr.we th .n { color: var(--ink-3); }
+.tag { margin-left: .4rem; padding: 0 .4rem; border: 1px solid var(--rule-2); border-radius: 999px; font: 400 .75rem/1.4 var(--sans); color: var(--ink-2); white-space: nowrap; }
+.ledger td.h { height: 2.5rem; padding: 0 .8rem; text-align: right; border: 1px solid var(--panel); background: var(--c0, transparent); cursor: default; }
+.ledger td.h .n, .ledger td.tot .n { font-size: .875rem; font-weight: 500; }
+.ledger td.none { color: var(--ink-3); text-align: right; padding: 0 .8rem; }
+.ledger td.h:hover, .ledger td.h.on { outline: 2px solid var(--ink); outline-offset: -2px; }
+.ledger td.h:focus { outline: none; }
+.ledger td.h:focus-visible { outline: 2px solid var(--focus); outline-offset: -2px; }
+.ledger td.tot, .ledger th.all { border-left: 1px solid var(--rule-2); text-align: left; }
+.ledger td.tot .row { display: flex; align-items: center; gap: .6rem; }
+.dbar { display: block; flex: 1; min-width: 0; width: 100%; height: .5rem; }
+.dbar rect { fill: var(--ink-3); }
+.ledger td.tot .d { color: var(--ink-3); font-size: .8125rem; min-width: 3.6rem; text-align: right; }
+.ledger tfoot th, .ledger tfoot td { border-top: 1px solid var(--rule-2); border-bottom: 0; height: 3rem; }
+.ledger tfoot th { font-weight: 800; }
+.ledger tfoot td.h { background: var(--panel); }
+.ledger tfoot .s { display: block; color: var(--ink-3); font-size: .8125rem; font-weight: 400; }
+.dayhead { color: var(--ink-3); font-size: .8125rem; margin: 0 0 .5rem; }
+.days { background: var(--panel); border: 1px solid var(--rule); border-radius: 8px; }
+.days > li + li { border-top: 1px solid var(--rule); }
+.days summary { display: grid; grid-template-columns: 1fr auto auto 1.25rem; align-items: center; gap: .1rem .6rem; padding: .6rem .8rem; min-height: 3rem; cursor: pointer; list-style: none; }
+.days summary::-webkit-details-marker { display: none; }
+.days summary .dn { font-size: .875rem; }
+.days summary .dt { font-weight: 600; font-size: .95rem; }
+.days summary .dd { color: var(--ink-3); font-size: .8125rem; min-width: 3.2rem; text-align: right; }
+.days summary .chev { width: .9rem; height: .9rem; stroke: var(--ink-2); fill: none; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
+.days details[open] .chev { transform: rotate(180deg); }
+.days summary .dbar { grid-column: 1 / -1; height: .25rem; }
+.days summary .dbar rect { fill: var(--rule-2); }
+.days li.we summary .dn { color: var(--ink-3); }
+.days ul { padding: 0 .8rem .7rem; }
+.days ul li { display: grid; grid-template-columns: 1fr auto auto; align-items: center; gap: 0 .6rem; padding: .35rem 0; border-top: 1px solid var(--rule); }
+.days ul .nm { display: flex; align-items: center; gap: .5rem; font-weight: 600; font-size: .9rem; }
+.days ul .heat { min-width: 4rem; padding: .15rem .5rem; border-radius: 4px; background: var(--c0, transparent); text-align: right; font-size: .875rem; font-weight: 500; }
+.days ul .dl { min-width: 3.2rem; text-align: right; color: var(--ink-3); font-size: .8125rem; }
+.days ul .more { grid-column: 1 / -1; color: var(--ink-3); font-size: .8125rem; padding-left: 1.15rem; }
+.days ul li.nodata .nm { color: var(--ink-3); font-weight: 400; }
/* the box: a number's exact fresh tokens, cache reads and dollars */
-.tip { position: fixed; z-index: 5; min-width: 220px; padding: var(--s2) var(--s3); background: var(--ink); color: var(--bg); border-radius: 6px; font-size: var(--f2); line-height: var(--l2); pointer-events: none; box-shadow: 0 4px 16px rgba(0, 0, 0, .18); }
-.tip .t-h { font-weight: 600; margin-bottom: var(--s1); }
-.tip dl { display: grid; grid-template-columns: auto auto; gap: 0 var(--s3); margin: 0; }
-.tip dt { opacity: .72; }
+.tip { position: fixed; z-index: 20; min-width: 15rem; max-width: calc(100vw - 16px); padding: .6rem .8rem; background: var(--ink); color: var(--bg); border-radius: 6px; font-size: .875rem; line-height: 1.4; pointer-events: none; box-shadow: 0 4px 16px rgba(0, 0, 0, .25); }
+.tip[hidden] { display: none; }
+.tip .t-h { font-weight: 600; margin-bottom: .25rem; }
+.tip dl { display: grid; grid-template-columns: auto auto; gap: 0 1.2rem; margin: 0; }
+.tip dt { opacity: .8; }
.tip dd { margin: 0; text-align: right; font-weight: 600; }
-@media (max-width: 719px) {
- .sum .v { font-size: var(--f3); }
- .wide { display: none; }
- table { width: auto; }
-}
+.note { padding: 1.5rem 0 4rem; color: var(--ink-3); font-size: .8125rem; }
+.note p { margin: .2rem 0; max-width: 60rem; }
+@media (max-width: 719px) { .priv { display: none; } }
diff --git a/test/usage-page.test.mjs b/test/usage-page.test.mjs
index 45333a3..63e369b 100644
--- a/test/usage-page.test.mjs
+++ b/test/usage-page.test.mjs
@@ -1,11 +1,13 @@
-// The /usage page's month (setkernel-live#71): a fixture month through the real sumByDay and
-// buildMonth, with the November day the clocks go back; the box's text; and the Worker running
+// The /usage page's month (setkernel-live#71, v5 in #86): a fixture month through the real sumByDay
+// and buildMonth, with the November day the clocks go back; the box's text; the trend; the limit
+// windows' rules (the alert, a limit hit, a stale or missing reading, Codex); and the Worker running
// first for /usage. Run: npm test
import test from "node:test";
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
+import { existsSync, readFileSync } from "node:fs";
import { hourOf, sumByDay } from "../src/usage.js";
-import { asOf, buildMonth, monthName, shiftMonth, short, tip } from "../public/usage/table.js";
+import { asOf, buildMonth, changeWords, dayName, firstDay, monthName, seatsOf, shiftDay, shiftMonth, short, tip, trend } from "../public/usage/table.js";
+import { alertOf, meter, mini, needs, windowOf } from "../public/usage/limits.js";
const counts = (n) => ({ input: n, output: 2 * n, cache_read: 30 * n, cache_write: 7 * n, usd_micros: 1_000 * n, requests: 1 });
// Every hour from 03:00 UTC on 31 October to 02:00 UTC on 3 November: vega 100,000 an hour, rigel
@@ -19,27 +21,28 @@ rows.push({ hour: "2026-11-02T15", seat: "codex", ...counts(42) });
const data = { month: "2026-11", ...sumByDay(rows, "2026-11") };
const v = buildMonth(data, "2026-11-02");
-test("fixture month: a row per Halifax day up to today, newest first, a column per seat and codex when present", () => {
+test("fixture month: a row per Halifax day up to today, newest first, a column per seat with data", () => {
assert.equal(v.name, "November 2026");
- assert.deepEqual(v.seats, ["Vega", "Rigel", "Lyra", "Orion", "Polaris", "Codex"]);
+ assert.deepEqual(v.seats, ["Vega", "Rigel", "Codex"]);
assert.deepEqual(v.rows.map((r) => `${r.d} ${r.wd}`), ["2 Mon", "1 Sun"], "31 October is the day before, in Halifax");
assert.deepEqual(v.rows.map((r) => [r.today, r.weekend]), [[true, false], [false, true]]);
});
test("the day the clocks go back has 25 hours: 1 November's cells", () => {
- const [vega, rigel, lyra] = v.rows[1].cells;
+ const [vega, rigel, codex] = v.rows[1].cells;
assert.equal(vega.f, "25,000,000"); // 25 hours of 1,000,000 fresh (input, output, cache writes)
assert.equal(vega.text, "25M");
assert.equal(vega.heat, 8);
assert.equal(rigel.text, "1.3M"); // 25 x 50,000
assert.equal(rigel.heat, 1);
- assert.equal(lyra, undefined, "no data is a dash, not zero");
+ assert.equal(codex, null, "no data is a dash, not zero");
assert.equal(v.rows[1].all.text, "26M");
assert.equal(v.rows[1].all.usd, "$2,625");
- assert.equal(v.rows[1].all.bar, 96);
+ assert.equal(v.rows[1].all.bar, 100);
// today so far: 04:00 UTC on the 2nd to 02:00 UTC on the 3rd, 23 hours
assert.equal(v.rows[0].cells[0].f, "23,000,000");
- assert.equal(v.rows[0].cells[5].text, "420");
+ assert.equal(v.rows[0].cells[2].text, "420");
+ assert.deepEqual(v.today.map((c) => c?.text), ["23M", undefined, "420"]);
});
test("a number's box and aria-label carry its exact fresh tokens, cache reads and dollars", () => {
@@ -50,20 +53,117 @@ test("a number's box and aria-label carry its exact fresh tokens, cache reads an
});
test("the month row: fresh tokens and dollars per seat, and the cache reads for all seats", () => {
- assert.deepEqual(v.total.cells.map((c) => c && `${c.text} ${c.usd}`), ["48M $4,800", "1.3M $125", undefined, undefined, undefined, "420 $0"]);
+ assert.deepEqual(v.total.cells.map((c) => c && `${c.text} ${c.usd}`), ["48M $4,800", "1.3M $125", "420 $0"]);
assert.deepEqual([v.total.all.text, v.total.all.cached, v.total.all.usd], ["49M", "148M", "$4,925"]);
- assert.equal(v.busiest, "Vega");
+ assert.deepEqual(v.busiest, { name: "Vega", text: "48M" });
assert.equal(buildMonth({ month: "2026-10", days: {}, totals: {} }, "2026-11-01").empty, true);
});
-test("short numbers, months and the as-of time in Halifax", () => {
+test("the seats come from the data: usage, and the limits on the current month only, in the team's order", () => {
+ assert.deepEqual(seatsOf({ codex: {}, zeta: {}, vega: {}, other: {} }, { polaris: null, rigel: {} }), ["vega", "rigel", "polaris", "codex", "other", "zeta"]);
+ assert.deepEqual(buildMonth({ ...data, limits: { lyra: null } }, "2026-11-02").keys, ["vega", "rigel", "lyra", "codex"]);
+ const past = buildMonth({ ...data, limits: { lyra: null } }, "2026-12-01");
+ assert.deepEqual([past.keys, past.limits, past.current, past.today], [["vega", "rigel", "codex"], null, false, null], "limits are live: a past month has none");
+});
+
+test("short numbers, days, months and the as-of time in Halifax", () => {
assert.deepEqual([13_698_537, 2_372_363, 816_743, 15_045_054_434, 9_960_000, 999_700, 950].map(short), ["14M", "2.4M", "817K", "15.0B", "10M", "1.0M", "950"]);
assert.deepEqual([shiftMonth("2026-01", -1), shiftMonth("2026-12", 1), shiftMonth("2026-11", 0)], ["2025-12", "2027-01", "2026-11"]);
+ assert.deepEqual([shiftDay("2026-03-01", -1), shiftDay("2028-03-01", -1), shiftDay("2026-12-31", 1)], ["2026-02-28", "2028-02-29", "2027-01-01"]);
assert.deepEqual(["2025-12", "2027-01"].map(monthName), ["December", "January"]);
+ assert.deepEqual(["2026-10-27", "2026-11-01"].map(dayName), ["Tue 27 Oct", "Sun 1 Nov"]);
assert.equal(asOf("2026-10-31T14"), "31 Oct, 12:00 ADT");
assert.equal(asOf("2026-11-01T04"), "1 Nov, 01:00 AST"); // the hour the clocks went back
});
+// ---- the trend (Ledger): a day stored without the seat is 0, a day before the store began is nothing
+test("the trend: the span's days to the last, and the change on the span before, per day, over the days stored", () => {
+ const day = (n) => ({ vega: counts(n / 10) }); // n fresh tokens
+ const days = { "2026-10-20": day(100), "2026-10-21": day(100), "2026-10-22": {}, "2026-10-23": day(100), "2026-10-24": day(100), "2026-10-25": day(100), "2026-10-26": day(100), "2026-10-27": day(100), "2026-10-28": day(150), "2026-10-29": day(150), "2026-10-30": day(150), "2026-10-31": day(150), "2026-11-01": day(150), "2026-11-02": day(150), "2026-11-03": day(150) };
+ // 28 Oct to 3 Nov is 1,050; 21 to 27 Oct is 600 (22 Oct stored without vega is 0): per day 150 against 600 / 7
+ assert.deepEqual(trend(days, "vega", "2026-11-03", 7, "2026-10-20"), { points: [150, 150, 150, 150, 150, 150, 150], change: 75 });
+ // the store began on 23 October: four days before the span, at least half of seven, all 100
+ assert.equal(trend(days, "vega", "2026-11-03", 7, "2026-10-23").change, 50);
+ // it began on 25 October: three days before, fewer than half: nothing to compare
+ assert.equal(trend(days, "vega", "2026-11-03", 7, "2026-10-25").change, null);
+ assert.deepEqual(trend(days, "vega", "2026-10-26", 7, "2026-10-23").points, [null, null, null, 100, 100, 100, 100], "nothing before the store began");
+ assert.equal(trend(days, "rigel", "2026-11-03", 7, "2026-10-20").change, null, "the days before sum to nothing");
+ assert.equal(firstDay([{ days: { "2026-10-02": {}, "2026-10-05": { vega: {} } } }, { days: { "2026-09-30": { rigel: {} } } }]), "2026-09-30");
+ assert.equal(firstDay([{ days: {} }]), null);
+ assert.deepEqual([changeWords(75, 7), changeWords(-8, 30), changeWords(0, 7), changeWords(null, 7)], ["Up 75% on the previous 7 days", "Down 8% on the previous 30 days", "No change on the previous 7 days", "No earlier days to compare with"]);
+});
+
+// ---- the limit windows: the rules the wall uses (setkernel/hq observability/wall/limits.py)
+const NOW = Date.UTC(2026, 9, 28, 18, 4); // Wednesday 28 October, 15:04 ADT
+const at = (h, min, d = 28) => new Date(Date.UTC(2026, 9, d, h + 3, min)).toISOString(); // a Halifax clock time in October
+const w = (utilization, resets_at = at(16, 10), observed_at = at(14, 55)) => ({ utilization, resets_at, observed_at });
+const seat = (five_hour, seven_day = w(0.3, at(9, 0, 31)), event = null) => ({ five_hour, seven_day, event });
+const win = (limits, s = "rigel", name = "five_hour") => windowOf(limits, s, name, NOW);
+
+test("the alert is at the figure the page shows: 80% for 5 hours, 70% for the week, rounded down", () => {
+ assert.deepEqual([0.79, 0.7999, 0.8, 0.84, 0.999].map((u) => [win({ rigel: seat(w(u)) }).pct, win({ rigel: seat(w(u)) }).level]), [[79, "ok"], [79, "ok"], [80, "over"], [84, "over"], [99, "over"]]);
+ assert.deepEqual([0.69, 0.7].map((u) => win({ rigel: seat(w(0.1), w(u, at(9, 0, 31))) }, "rigel", "seven_day").level), ["ok", "over"]);
+ assert.deepEqual([win({ rigel: seat(w(1)) }).level, win({ rigel: seat(w(1.2)) }).pct], ["limit", 120]);
+});
+
+test("a limit hit: 100%, or a request rejected for this window since it last opened and not yet reset", () => {
+ const rejected = (type, received_at, resets_at = at(16, 10)) => ({ status: "rejected", rate_limit_type: type, resets_at, received_at });
+ assert.deepEqual([win({ rigel: seat(w(0.5), undefined, rejected("five_hour", at(14, 47))) }).level, win({ rigel: seat(w(0.5), undefined, rejected("five_hour", at(14, 47))) }).hit], ["limit", Date.parse(at(14, 47))]);
+ assert.equal(win({ rigel: seat(w(0.5), undefined, rejected("seven_day", at(14, 47))) }).level, "ok", "another window's rejection");
+ assert.equal(win({ rigel: seat(w(0.5), undefined, rejected("five_hour", at(11, 0))) }).level, "ok", "rejected in the window before (it opened at 11:10)");
+ assert.equal(win({ rigel: seat(w(0.5), undefined, rejected("five_hour", at(14, 47), at(15, 0))) }).level, "ok", "its own reset has passed");
+ assert.equal(win({ rigel: seat(w(0.5), undefined, { ...rejected("five_hour", at(14, 47)), status: "allowed" }) }).level, "ok");
+});
+
+test("a stale reading is one from before its window reset: no figure, and when it was read", () => {
+ const stale = win({ orion: seat(w(0.62, at(12, 30), at(10, 14))) }, "orion");
+ assert.deepEqual(stale, { kind: "stale", read: Date.parse(at(10, 14)) });
+ assert.equal(win({ orion: seat(w(0.62, at(15, 4), at(10, 14))) }, "orion").kind, "stale", "resetting now is reset");
+ // with no reset time, the window is taken to reset its length after the reading, as on the wall
+ assert.equal(win({ orion: seat(w(0.62, null, at(10, 4))) }, "orion").kind, "stale");
+ assert.deepEqual([win({ orion: seat(w(0.62, null, at(10, 5))) }, "orion").kind, win({ orion: seat(w(0.62, null, at(10, 5))) }, "orion").resets], ["fresh", Date.parse(at(15, 5))]);
+ assert.deepEqual(meter(stale, "orion", "five_hour", "5-hour", NOW), { flag: "no fresh reading since 10:14", meta: ["it reset since; the old figure is not shown"], label: "Orion 5-hour: no fresh reading since 10:14" });
+ assert.equal(mini(stale), "stale");
+});
+
+test("a missing or malformed reading is not reported, Codex has no Claude limits, and no limits at all is unread", () => {
+ for (const bad of [null, w(null), w(-0.1), w("0.5"), w(0.5, at(16, 10), null), w(0.5, at(16, 10), "yesterday")]) assert.equal(win({ rigel: seat(bad) }).kind, "none", JSON.stringify(bad));
+ assert.deepEqual([win({ rigel: null }).kind, win({}).kind], ["none", "none"]);
+ assert.deepEqual([win({ codex: seat(w(0)) }, "codex").kind, win({ other: seat(w(0)) }, "other").kind, win(null).kind, win(null, "codex").kind], ["nolimits", "nolimits", "unread", "nolimits"]);
+ assert.deepEqual(meter(win({ rigel: null }), "rigel", "seven_day", "weekly", NOW), { flag: "not reported", meta: ["no reading from this seat"], label: "Rigel weekly: not reported" });
+});
+
+test("what a meter says, and the worst of a seat's windows", () => {
+ const hit = { status: "rejected", rate_limit_type: "five_hour", resets_at: at(16, 10), received_at: at(14, 47) };
+ assert.deepEqual(meter(win({ rigel: seat(w(1), undefined, hit) }), "rigel", "five_hour", "5-hour", NOW), { pct: 100, flag: "LIMIT HIT", meta: ["resets 16:10", "read 14:55", "rejected 14:47"], label: "Rigel 5-hour: 100%, limit hit, resets 16:10, read 14:55, rejected 14:47" });
+ assert.deepEqual(meter(win({ rigel: seat(w(0.84)) }), "rigel", "five_hour", "5-hour", NOW).flag, "over 80%");
+ assert.deepEqual(meter(win({ rigel: seat(w(0.1), w(0.42, at(21, 0, 30))) }, "rigel", "seven_day"), "rigel", "seven_day", "weekly", NOW), { pct: 42, flag: "under 70%", meta: ["resets Fri 21:00", "read 14:55"], label: "Rigel weekly: 42%, under 70%, resets Fri 21:00, read 14:55" });
+ const views = (...k) => k.map((kind) => (kind === "limit" || kind === "over" || kind === "ok" ? { kind: "fresh", level: kind } : { kind }));
+ assert.deepEqual([alertOf(views("ok", "limit")), alertOf(views("over", "stale")), alertOf(views("ok", "none")), alertOf(views("ok", "ok"))], ["limit", "over", "gap", null]);
+});
+
+test("Needs a look: worst first, then the team's order; all clear is empty; no limits is null", () => {
+ const hit = { status: "rejected", rate_limit_type: "five_hour", resets_at: at(16, 10), received_at: at(14, 47) };
+ const limits = {
+ vega: seat(w(0.42)),
+ rigel: seat(w(1), undefined, hit),
+ lyra: seat(w(0.31), w(0.73, at(6, 0, 29))),
+ orion: seat(w(0.62, at(12, 30), at(10, 14)), w(0.91, at(13, 0, 30))),
+ polaris: null,
+ codex: seat(w(0.99)),
+ };
+ assert.deepEqual(needs(limits, ["vega", "rigel", "lyra", "orion", "polaris", "codex"], NOW).map((i) => [i.kind, i.seat, i.text]), [
+ ["limit", "rigel", "Rigel hit the 5-hour limit at 14:47, resets 16:10"],
+ ["over", "lyra", "Lyra's weekly is at 73%, resets Thu 06:00"],
+ ["over", "orion", "Orion's weekly is at 91%, resets Fri 13:00"],
+ ["gap", "orion", "Orion's 5-hour has no fresh reading since 10:14"],
+ ["gap", "polaris", "Polaris is not reporting"],
+ ]);
+ assert.deepEqual(needs({ vega: seat(w(0.5), null) }, ["vega"], NOW).map((i) => i.text), ["Vega's weekly is not reported"]);
+ assert.deepEqual(needs({ vega: seat(w(0.5)) }, ["vega", "codex"], NOW), []);
+ assert.equal(needs(null, ["vega"], NOW), null);
+});
+
// Without this the assets are served before the Worker runs, token or not (checked with wrangler
// dev: /usage/ answers 200); test/worker/ calls the Worker directly, so it can't see the difference.
test("wrangler.jsonc runs the Worker first for /usage and everything under it", () => {
@@ -71,7 +171,7 @@ test("wrangler.jsonc runs the Worker first for /usage and everything under it",
assert.deepEqual(JSON.parse(assets).run_worker_first, ["/usage", "/usage/*"]);
});
-// ---- the page script (setkernel-live#78), run in node against a stand-in document built from
+// ---- the page script (setkernel-live#78, #86), run in node against a stand-in document built from
// index.html's ids: just enough DOM for page.js, with fetch answering from the fixture month
class Node {
constructor(tag) { Object.assign(this, { tag, kids: [], attrs: {}, dataset: {}, style: {}, on: {}, hidden: false, className: "", text: "" }); }
@@ -91,42 +191,89 @@ class Node {
*all() { yield this; for (const k of this.kids) yield* k.all(); }
}
const html = readFileSync(new URL("../public/usage/index.html", import.meta.url), "utf8");
-async function runPage(answer) {
+async function runPage(answer, now = Date.UTC(2026, 10, 2, 16)) { // noon in Halifax
const doc = new Node("document"), ids = {};
for (const [, tag, id, rest] of html.matchAll(/<(\w+) [^>]*?id="([^"]+)"([^>]*)>/g)) doc.append(Object.assign(ids[id] = new Node(tag), { hidden: /\shidden\b/.test(rest) }));
Object.assign(doc, { documentElement: { clientWidth: 375 }, getElementById: (id) => ids[id], createElement: (t) => new Node(t), createElementNS: (_, t) => new Node(t) });
const fire = (type, target, more = {}) => { for (let n = target; n; n = n.parentNode) for (const f of n.on[type] ?? []) f({ type, target, ...more }); };
const asked = [];
- Object.assign(globalThis, { document: doc, location: { search: "?month=2026-11" }, fetch: async (url) => { asked.push(url); return answer(); } });
- test.mock.timers.enable({ apis: ["Date"], now: Date.UTC(2026, 10, 2, 16) }); // noon in Halifax
+ Object.assign(globalThis, { document: doc, location: { search: "?month=2026-11" }, fetch: async (url) => { asked.push(url); return answer(new URL(url, "https://x").searchParams.get("month")); } });
+ test.mock.timers.enable({ apis: ["Date"], now });
try {
await (await import(`../public/usage/page.js?${Math.random()}`)).ready;
} finally {
test.mock.timers.reset();
}
- return { ids, fire, asked, cells: [...ids.usage.all()].filter((n) => n.tag === "td") };
+ const find = (n, f) => [...n.all()].filter(f);
+ return { ids, fire, asked, find, cells: find(ids.usage, (n) => n.tag === "td") };
}
-const month = () => new Response(JSON.stringify(data), { headers: { "Usage-Newest-Hour": "2026-11-02T15" } });
+// November is the fixture; October and September are stored but empty
+const month = (extra = {}) => (m) => Response.json(m === "2026-11" ? { ...data, ...extra } : { month: m, days: {}, totals: {} }, { headers: m === "2026-11" ? { "Usage-Newest-Hour": "2026-11-02T15" } : {} });
-test("the page draws the fixture month: rows, a dash for no data, today so far, the months, the as-of time", async () => {
- const { ids, cells, asked } = await runPage(month);
- assert.deepEqual(asked, ["/usage/data?month=2026-11"]);
- assert.equal(ids.title.textContent, "Tokens per seat, November 2026");
+test("the page draws the fixture month: the totals, a row per seat, the table, the day list, the months", async () => {
+ const { ids, cells, asked, find, fire } = await runPage(month());
+ assert.deepEqual(asked, ["/usage/data?month=2026-11", "/usage/data?month=2026-10", "/usage/data?month=2026-09"]);
+ assert.equal(ids.title.textContent, "Usage per seat, November 2026");
assert.equal(ids.asof.textContent, "Newest hour ends 2 Nov, 12:00 AST");
- assert.deepEqual([ids.status.hidden, ids.scroll.hidden, ids.sum.hidden], [true, false, false]);
- assert.equal(ids.sum.textContent, "Fresh tokens this month49MCache reads148MAt API prices, about$4,925Busiest seatVega");
+ assert.doesNotMatch(ids.fresh.className, /late/);
+ assert.deepEqual([ids.status.hidden, ids.need.hidden, ids.sum.hidden, ids.seats.hidden, ids.days.hidden], [true, false, false, false, false]);
+ assert.deepEqual([ids.need.dataset.sev, ids.needs.textContent], ["wait", "Seat limits aren't sent to this page yet, so it can't check them. Usage is below."]);
+ assert.equal(ids.sum.textContent, "Fresh tokens49Mthis month so farCache reads148Mcounted apartAt API prices, about$4,925a size guide, not a billBusiest seatVega48M fresh tokens");
assert.deepEqual(ids.months.kids.map((k) => [k.tag, k.textContent, k.href]), [["a", "October", "?month=2026-10"], ["b", "November 2026", undefined], ["span", "December", undefined]]);
- const [head, body, foot] = ids.usage.kids;
- assert.equal(head.textContent, "DayVegaRigelLyraOrionPolarisCodexAll seats");
- assert.deepEqual(body.kids.map((r) => [r.className, r.kids[0].textContent]), [["today", "2 Monso far"], ["we", "1 Sun"]]);
- assert.deepEqual(body.kids[1].kids.map((td) => [td.className, td.textContent]), [["", "1 Sun"], ["h t8", "25M"], ["h t1", "1.3M"], ["none ", "–"], ["none ", "–"], ["none ", "–"], ["none ", "–"], ["h tot", "26M $2,625"]]);
- assert.deepEqual(body.kids[1].kids[7].kids[1].attrs, { class: "bar", width: "96", height: "4", "aria-hidden": "true" });
- assert.equal(foot.textContent, "November48M$4,8001.3M$125–––420$049M148M cached$4,925");
+
+ const [cols, vega, rigel, codex] = ids.rows.kids;
+ assert.equal(cols.textContent, "Seat5-hourWeeklyTodayThis monthTrend, 7 days");
+ assert.deepEqual([vega, rigel, codex].map((r) => [r.id, r.className]), [["seat-vega", "seat k-vega"], ["seat-rigel", "seat k-rigel"], ["seat-codex", "seat k-codex"]]);
+ assert.equal(vega.textContent, "VegaNo limit readings yetToday23Mso far · about $2,300This month48M144M cache reads · about $4,800Trend, 7 daysNo earlier days to compare with");
+ assert.match(rigel.textContent, /^RigelNo limit readings yetToday–no data, not zero/);
+ assert.match(codex.textContent, /^Codexnot a Claude seatNo Claude limits: Codex isn't a Claude seatToday420/);
+ assert.doesNotMatch(codex.textContent, /\d%/, "Codex never shows a percentage");
+ assert.equal(ids.since.textContent, "Each line is a seat's fresh tokens a day over the 7 days to Sun 1 Nov, from zero; the hollow dot is today so far.");
+ const spark = find(vega, (n) => n.tag === "svg" && n.attrs.class === "spark")[0];
+ assert.equal(spark.attrs["aria-label"], "Vega, fresh tokens a day: No earlier days to compare with");
+ assert.deepEqual(find(spark, (n) => n.tag === "circle").map((c) => [c.attrs.class, c.attrs.cx, c.attrs.cy]), [["end", "125", "5"], ["now", "145", "7.2"]], "1 November's 25M at the top, today's 23M so far apart");
+ fire("click", ids.span30);
+ assert.deepEqual([ids.span7.attrs["aria-pressed"], ids.span30.attrs["aria-pressed"], vega.kids.at(-1).kids[0].textContent], ["false", "true", "Trend, 30 days"]);
+
+ const [, head, body, foot] = ids.usage.kids;
+ assert.equal(head.textContent, "DayVegaRigelCodexAll seats");
+ assert.deepEqual(body.kids.map((r) => [r.className, r.kids[0].textContent]), [["today", "Mon 2 Novso far"], ["we", "Sun 1 Nov"]]);
+ assert.deepEqual(body.kids[1].kids.map((td) => [td.className, td.textContent]), [["", "Sun 1 Nov"], ["h t8", "25M"], ["h t1", "1.3M"], ["none", "–"], ["h tot", "26M$2,625"]]);
+ assert.deepEqual(find(body.kids[1].kids[4], (n) => n.tag === "rect")[0].attrs, { width: "100", height: "4" });
+ assert.equal(foot.textContent, "November48M$4,8001.3M$125420$049M148M cache reads$4,925");
assert.ok(cells.filter((td) => td.className.startsWith("h")).every((td) => td.tabIndex === 0 && td.attrs["aria-label"]));
+
+ const [today, sunday] = ids.daylist.kids.map((li) => li.kids[0]);
+ assert.deepEqual([today.open, sunday.open], [true, false], "the newest day is open");
+ assert.equal(sunday.kids[1].textContent, "Vega25M$2,50075M cache reads · 25 requestsRigel1.3M$1253.8M cache reads · 25 requestsCodex–no data, not zero");
+});
+
+test("with limits: Needs a look links each line to its seat, the meters say the level, the strip names both", async () => {
+ const limits = {
+ vega: { five_hour: { utilization: 0.84, resets_at: "2026-11-02T17:30:00Z", observed_at: "2026-11-02T15:55:00Z" }, seven_day: { utilization: 0.2, resets_at: "2026-11-05T13:00:00Z", observed_at: "2026-11-02T15:55:00Z" }, event: null },
+ rigel: null,
+ };
+ const { ids, find } = await runPage(month({ limits }));
+ assert.equal(ids.need.dataset.sev, "over");
+ assert.deepEqual(ids.needs.kids.map((li) => [li.dataset.k, li.kids[1].tag, li.kids[1].href, li.kids[1].textContent]), [
+ ["over", "a", "#seat-vega", "Vega's 5-hour is at 84%, resets 13:30"],
+ ["gap", "a", "#seat-rigel", "Rigel is not reporting"],
+ ]);
+ const [, vega, rigel, codex] = ids.rows.kids;
+ assert.deepEqual([vega.dataset.alert, rigel.dataset.alert, codex.dataset.alert], ["over", "gap", undefined]);
+ const meters = find(vega, (n) => n.className.startsWith("meter"));
+ assert.deepEqual(meters.map((m) => [m.className, m.dataset.kind, m.dataset.level, m.textContent]), [
+ ["meter m5", "fresh", "over", "5-hour84%over 80%alert 80%resets 13:30read 11:55"],
+ ["meter mw", "fresh", "ok", "Weekly20%under 70%alert 70%resets Thu 09:00read 11:55"],
+ ]);
+ assert.deepEqual(find(rigel, (n) => n.className.startsWith("meter")).map((m) => [m.dataset.kind, m.textContent]), [["none", "5-hournot reportedalert 80%no reading from this seat"], ["none", "Weeklynot reportedalert 70%no reading from this seat"]]);
+ assert.equal(find(meters[0], (n) => n.attrs.class === "m-fill")[0].attrs.width, "84");
+ assert.deepEqual(find(meters[0], (n) => /^m-(tick|tl)/.test(n.className)).map((n) => n.className), ["m-tick at80", "m-tl at80"]);
+ assert.equal(ids.usage.kids[1].textContent, "DayVega5h 84%wk 20%Rigelnot reportingCodexno Claude limitsAll seats");
});
test("a number's box: hover, focus or tap shows its exact values; Esc or a tap elsewhere closes it", async () => {
- const { ids, fire, cells } = await runPage(month);
+ const { ids, fire, cells } = await runPage(month());
const vega = cells.find((td) => td.dataset.who === "Vega" && td.dataset.when === "Sun 1 Nov"), box = ids.tip;
assert.equal(box.hidden, true);
fire("focusin", vega.kids[0]);
@@ -150,37 +297,91 @@ test("a number's box: hover, focus or tap shows its exact values; Esc or a tap e
assert.equal(box.hidden, true);
});
+test("a past month: no meters and no today, Needs a look says limits are read live, and a late store says so", async () => {
+ const { ids, find } = await runPage(month({ limits: { vega: null } }), Date.UTC(2026, 11, 2, 16));
+ assert.equal(ids.rows.className, "rows past");
+ assert.deepEqual([ids.need.dataset.sev, ids.needs.textContent], ["wait", "Limits are read live, so they show on the current month only."]);
+ const [cols, vega, rigel, codex] = ids.rows.kids;
+ assert.equal(cols.textContent, "SeatMonthTrend, 7 days");
+ assert.equal(find(ids.rows, (n) => n.className.startsWith("meter")).length, 0);
+ assert.equal(vega.textContent, "VegaMonth48M144M cache reads · about $4,800Trend, 7 daysNo earlier days to compare with");
+ assert.deepEqual([rigel.id, codex.id], ["seat-rigel", "seat-codex"], "no limits: no seat added from them");
+ assert.match(ids.usage.kids[1].textContent, /^DayVegaRigelCodexAll seats$/, "no strip");
+ assert.equal(ids.asof.textContent, "Newest hour ends 2 Nov, 12:00 AST, 720 hours ago");
+ assert.match(ids.fresh.className, /late/);
+});
+
test("a refused, failed or empty month shows a plain message, not a blank page", async () => {
for (const [answer, words] of [
[() => new Response("Forbidden", { status: 403 }), /can't read usage/],
[() => new Response("Usage is not configured", { status: 503 }), /isn't set up/],
[() => Promise.reject(new TypeError("Failed to fetch")), /no answer/],
[() => new Response(null, { status: 500 }), /HTTP 500/],
+ [(m) => (m === "2026-11" ? month()(m) : new Response(null, { status: 500 })), /HTTP 500/],
]) {
const { ids } = await runPage(answer);
assert.match(ids.status.textContent, words);
- assert.deepEqual([ids.status.hidden, ids.scroll.hidden, ids.sum.hidden], [false, true, true]);
+ assert.deepEqual([ids.status.hidden, ids.need.hidden, ids.sum.hidden, ids.seats.hidden, ids.days.hidden, ids.asof.textContent], [false, true, true, true, true, "Not loaded"]);
}
- const { ids, cells } = await runPage(() => Response.json({ month: "2026-11", days: {}, totals: {} }));
+ const { ids } = await runPage((m) => Response.json({ month: m, days: {}, totals: {} }));
assert.equal(ids.status.textContent, "Nothing is stored for November 2026 yet.");
- assert.deepEqual([ids.asof.textContent, ids.hint.hidden], ["Nothing stored yet", true]);
- assert.ok(cells.length > 2 && cells.filter((td) => td.className.startsWith("none")).length === cells.length - 3, "every number is a dash");
+ assert.deepEqual([ids.asof.textContent, ids.need.hidden, ids.sum.hidden, ids.seats.hidden, ids.days.hidden], ["Nothing stored yet", false, true, true, true]);
});
-test("the page follows the CSP and the site's rules: no inline style or script, no markup from data, site fonts only", () => {
+test("the page follows the CSP and the site's rules: no inline style or script, no markup from data, its own fonts", () => {
assert.doesNotMatch(html, /