fn load_usage_html() -> String {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/assets/usage/index.html");
std::fs::read_to_string(path).unwrap_or_else(|e| panic!("failed to read {path}: {e}"))
}
fn extract_inline_script(html: &str) -> &str {
let start = html
.find("<script>")
.expect("usage page must contain <script>")
+ "<script>".len();
let end = html[start..]
.find("</script>")
.expect("usage page must contain </script>")
+ start;
&html[start..end]
}
fn run_usage_script(harness: &str) {
let html = load_usage_html();
let script = extract_inline_script(&html);
let combined = format!("{script}\n{harness}\n");
use std::io::Write;
let mut child = std::process::Command::new("node")
.arg("-")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("node must be available to run usage script tests");
let mut stdin = child.stdin.take().expect("node stdin");
let writer = std::thread::spawn(move || stdin.write_all(combined.as_bytes()));
let output = child.wait_with_output().expect("wait for node");
writer
.join()
.expect("stdin writer thread")
.expect("write the script to node");
assert!(
output.status.success(),
"node test failed:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
#[test]
fn usage_page_contains_required_layout_and_no_external_urls() {
let html = load_usage_html();
assert!(
html.contains("<title>Usage - blyte</title>"),
"usage page must have title Usage - blyte"
);
assert!(
html.contains("<a id=\"usage-back\" href=\"/\">Back to the surface</a>"),
"usage page must contain the back link to /"
);
for id in [
"usage-back",
"usage-range",
"usage-status",
"usage-totals",
"usage-notes",
"usage-days",
"usage-by-surface",
"usage-by-kind",
"usage-by-repo",
"usage-by-model",
] {
let needle = format!("id=\"{id}\"");
assert!(
html.contains(&needle),
"usage page must contain element with {needle}"
);
}
for range in ["7d", "30d", "all"] {
let needle = format!("data-range=\"{range}\"");
assert!(
html.contains(&needle),
"usage page must contain range control {needle}"
);
}
assert!(
html.contains("Days are UTC days"),
"usage page must state that days are UTC days"
);
let lower = html.to_ascii_lowercase();
assert!(
!lower.contains("http://"),
"usage page must not contain any http:// URL"
);
assert!(
!lower.contains("https://"),
"usage page must not contain any https:// URL"
);
assert_eq!(
html.matches("<script>").count(),
1,
"usage page must have exactly one inline script"
);
}
#[test]
fn pure_functions_match_contract() {
let harness = r#"
const assert = require("node:assert");
assert.strictEqual(formatUsd(0), "USD 0.00");
assert.strictEqual(formatUsd(12.5), "USD 12.50");
assert.strictEqual(formatUsd(2847.27), "USD 2,847.27");
for (const bad of [NaN, Infinity, -Infinity, null, undefined, "12.50", {}]) {
assert.throws(
() => formatUsd(bad),
(err) => err instanceof Error && err.message === "not a cost: " + bad
);
}
assert.strictEqual(formatCount(0), "0");
assert.strictEqual(formatCount(999), "999");
assert.strictEqual(formatCount(19780), "19,780");
assert.strictEqual(rangeSince("7d", 1795990000), 1795990000 - 7 * 86400);
assert.strictEqual(rangeSince("30d", 1795990000), 1795990000 - 30 * 86400);
assert.strictEqual(rangeSince("all", 1795990000), null);
for (const bad of ["14d", "", "week", null, undefined]) {
assert.throws(
() => rangeSince(bad, 1795990000),
(err) => err instanceof Error && err.message === "unknown range: " + bad
);
}
assert.strictEqual(usageUrl(null), "/api/usage");
assert.strictEqual(usageUrl(1795000000), "/api/usage?since=1795000000");
assert.strictEqual(usageUrl(0), "/api/usage?since=0");
assert.strictEqual(surfaceLabel({ surface: "s0123456789abcdef", name: "alpha" }), "alpha");
assert.strictEqual(surfaceLabel({ surface: "s0123456789abcdef", name: null }), "s0123456789abcdef");
assert.strictEqual(surfaceLabel({ surface: "s0123456789abcdef", name: "" }), "s0123456789abcdef");
assert.strictEqual(surfaceLabel({ surface: null, name: null }), "Not from a surface");
assert.strictEqual(surfaceLabel({}), "Not from a surface");
assert.deepStrictEqual(
usageNotes({
log: "/home/u/.local/state/blyte/usage.jsonl",
log_exists: true,
unreadable_lines: 0,
totals: { unpriced: 0 },
}),
[]
);
assert.deepStrictEqual(
usageNotes({
log: "/home/u/.local/state/blyte/usage.jsonl",
log_exists: true,
unreadable_lines: 0,
totals: { unpriced: 2 },
}),
["2 lines have no price and are not in the cost"]
);
assert.deepStrictEqual(
usageNotes({
log: "/home/u/.local/state/blyte/usage.jsonl",
log_exists: true,
unreadable_lines: 3,
totals: { unpriced: 0 },
}),
["3 lines in the log could not be read"]
);
assert.deepStrictEqual(
usageNotes({
log: "/home/u/.local/state/blyte/usage.jsonl",
log_exists: false,
unreadable_lines: 0,
totals: { unpriced: 0 },
}),
["No usage recorded yet at /home/u/.local/state/blyte/usage.jsonl"]
);
assert.deepStrictEqual(
usageNotes({
log: "/tmp/usage.jsonl",
log_exists: false,
unreadable_lines: 4,
totals: { unpriced: 1 },
}),
[
"1 lines have no price and are not in the cost",
"4 lines in the log could not be read",
"No usage recorded yet at /tmp/usage.jsonl",
]
);
assert.deepStrictEqual(barHeights([], 120), []);
assert.deepStrictEqual(
barHeights(
[
{ day: "2026-11-28", cost_usd: 0 },
{ day: "2026-11-29", cost_usd: 0 },
],
120
),
[0, 0]
);
assert.deepStrictEqual(
barHeights(
[
{ day: "2026-11-27", cost_usd: 1 },
{ day: "2026-11-28", cost_usd: 3 },
{ day: "2026-11-29", cost_usd: 1.5 },
],
100
),
[33, 100, 50]
);
"#;
run_usage_script(harness);
}
#[test]
fn page_behaviour_handles_token_errors_and_range_reload() {
let harness = r#"
const assert = require("node:assert");
function makeEl(tag) {
const attrs = Object.create(null);
const listeners = Object.create(null);
const el = {
tagName: tag.toUpperCase(),
className: "",
textContent: "",
title: "",
hidden: false,
colSpan: 1,
style: {},
children: [],
parentNode: null,
get firstChild() {
return this.children.length > 0 ? this.children[0] : null;
},
appendChild(child) {
child.parentNode = this;
this.children.push(child);
return child;
},
removeChild(child) {
const idx = this.children.indexOf(child);
if (idx >= 0) {
this.children.splice(idx, 1);
child.parentNode = null;
}
return child;
},
setAttribute(name, val) {
attrs[name] = String(val);
},
getAttribute(name) {
return Object.prototype.hasOwnProperty.call(attrs, name) ? attrs[name] : null;
},
querySelector(sel) {
for (const child of this.children) {
if (child.tagName.toLowerCase() === sel.toLowerCase()) {
return child;
}
const nested = child.querySelector(sel);
if (nested) return nested;
}
return null;
},
querySelectorAll(sel) {
const out = [];
for (const child of this.children) {
if (sel === "[data-range]" && child.getAttribute("data-range") !== null) {
out.push(child);
}
out.push(...child.querySelectorAll(sel));
}
return out;
},
closest(sel) {
let cur = this;
while (cur) {
if (sel === "[data-range]" && cur.getAttribute("data-range") !== null) {
return cur;
}
cur = cur.parentNode;
}
return null;
},
addEventListener(type, fn) {
listeners[type] = listeners[type] || [];
listeners[type].push(fn);
},
dispatchClick(target) {
for (const fn of listeners.click || []) {
fn({ target });
}
},
};
return el;
}
function collectText(el) {
if (el.children.length === 0) return el.textContent;
return el.children.map(collectText).join(" | ");
}
const byId = Object.create(null);
for (const id of [
"usage-status",
"usage-totals",
"usage-notes",
"usage-days-bars",
"usage-days-axis",
]) {
byId[id] = makeEl("div");
}
const rangeEl = makeEl("div");
const rangeButtons = {};
for (const r of ["7d", "30d", "all"]) {
const b = makeEl("button");
b.setAttribute("data-range", r);
b.setAttribute("aria-pressed", r === "30d" ? "true" : "false");
rangeEl.appendChild(b);
rangeButtons[r] = b;
}
byId["usage-range"] = rangeEl;
for (const id of ["usage-by-surface", "usage-by-kind", "usage-by-repo", "usage-by-model"]) {
const table = makeEl("table");
const tbody = makeEl("tbody");
table.appendChild(tbody);
byId[id] = table;
}
global.document = {
getElementById(id) {
return byId[id] || null;
},
createElement(tag) {
return makeEl(tag);
},
};
const storage = Object.create(null);
global.window = {
sessionStorage: {
getItem(k) {
return Object.prototype.hasOwnProperty.call(storage, k) ? storage[k] : null;
},
setItem(k, v) {
storage[k] = String(v);
},
removeItem(k) {
delete storage[k];
},
},
};
const fetchCalls = [];
let nextResponse = null;
global.fetch = async (url, options) => {
fetchCalls.push({ url, options });
return nextResponse;
};
async function run() {
await loadUsage();
assert.strictEqual(fetchCalls.length, 0);
assert.strictEqual(byId["usage-status"].hidden, false);
assert.strictEqual(
byId["usage-status"].textContent,
"Open this page from a surface: its token is missing"
);
storage["blyte.surface.token"] = "tok-alpha";
const sampleReport = {
generated_at: 1795990000,
since: 1793398000,
log: "/home/u/.local/state/blyte/usage.jsonl",
log_exists: true,
unreadable_lines: 1,
totals: {
cost_usd: 12.5,
unpriced: 2,
lines: 40,
runs: 6,
input: 1000,
cached: 800,
output: 200,
thinking: 50,
},
by_day: [
{
day: "2026-11-28",
cost_usd: 2.5,
unpriced: 0,
lines: 10,
runs: 2,
input: 200,
cached: 100,
output: 50,
thinking: 10,
},
{
day: "2026-11-29",
cost_usd: 10.0,
unpriced: 2,
lines: 30,
runs: 4,
input: 800,
cached: 700,
output: 150,
thinking: 40,
},
],
by_kind: [
{
kind: "conversation",
cost_usd: 12.5,
unpriced: 2,
lines: 40,
runs: 6,
input: 1000,
cached: 800,
output: 200,
thinking: 50,
},
],
by_surface: [
{
surface: "s0123456789abcdef",
name: "alpha",
last_ts: 1795980000,
cost_usd: 10.0,
unpriced: 0,
lines: 30,
runs: 5,
input: 800,
cached: 600,
output: 150,
thinking: 40,
},
{
surface: null,
name: null,
last_ts: 1795000000,
cost_usd: 2.5,
unpriced: 2,
lines: 10,
runs: 1,
input: 200,
cached: 200,
output: 50,
thinking: 10,
},
],
by_repo: [
{
repo: "/work/notes",
cost_usd: 12.5,
unpriced: 2,
lines: 40,
runs: 6,
input: 1000,
cached: 800,
output: 200,
thinking: 50,
},
],
by_model: [
{
model: "m1",
cost_usd: 12.5,
unpriced: 2,
lines: 40,
runs: 6,
input: 1000,
cached: 800,
output: 200,
thinking: 50,
},
],
};
nextResponse = {
status: 200,
async json() {
return sampleReport;
},
};
await loadUsage();
assert.strictEqual(fetchCalls.length, 1);
assert.ok(fetchCalls[0].url.startsWith("/api/usage?since="));
assert.strictEqual(fetchCalls[0].options.headers["X-Blyte-Token"], "tok-alpha");
assert.strictEqual(byId["usage-status"].hidden, true);
const totalsText = collectText(byId["usage-totals"]);
assert.ok(totalsText.includes("USD 12.50"));
assert.ok(totalsText.includes("1,250"));
assert.ok(totalsText.includes("800 cached"));
assert.strictEqual(byId["usage-notes"].hidden, false);
assert.strictEqual(byId["usage-notes"].children.length, 2);
assert.strictEqual(byId["usage-days-bars"].children.length, 2);
assert.strictEqual(
byId["usage-days-bars"].children[0].children[0].title,
"2026-11-28: USD 2.50"
);
assert.strictEqual(
byId["usage-days-bars"].children[1].children[0].title,
"2026-11-29: USD 10.00"
);
assert.strictEqual(byId["usage-by-surface"].querySelector("tbody").children.length, 2);
assert.ok(collectText(byId["usage-by-surface"]).includes("alpha"));
assert.ok(collectText(byId["usage-by-surface"]).includes("Not from a surface"));
nextResponse = {
status: 404,
async text() {
return JSON.stringify({ error: "the usage log is switched off (BLYTE_USAGE_LOG=off)" });
},
};
await loadUsage();
assert.strictEqual(byId["usage-status"].hidden, false);
assert.strictEqual(
byId["usage-status"].textContent,
"Could not load usage: 404 the usage log is switched off (BLYTE_USAGE_LOG=off)"
);
assert.strictEqual(byId["usage-totals"].children.length, 0);
assert.strictEqual(byId["usage-notes"].hidden, true);
assert.strictEqual(byId["usage-days-bars"].children.length, 0);
assert.strictEqual(byId["usage-by-surface"].querySelector("tbody").children.length, 0);
assert.strictEqual(byId["usage-by-kind"].querySelector("tbody").children.length, 0);
assert.strictEqual(byId["usage-by-repo"].querySelector("tbody").children.length, 0);
assert.strictEqual(byId["usage-by-model"].querySelector("tbody").children.length, 0);
bindEvents();
nextResponse = {
status: 200,
async json() {
return sampleReport;
},
};
rangeEl.dispatchClick(rangeButtons["all"]);
await new Promise((r) => setTimeout(r, 10));
assert.strictEqual(rangeButtons["all"].getAttribute("aria-pressed"), "true");
assert.strictEqual(rangeButtons["30d"].getAttribute("aria-pressed"), "false");
assert.strictEqual(rangeButtons["7d"].getAttribute("aria-pressed"), "false");
assert.strictEqual(fetchCalls[fetchCalls.length - 1].url, "/api/usage");
}
run().catch((err) => {
console.error(err);
process.exit(1);
});
"#;
run_usage_script(harness);
}