diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js
index 83350084d..85938b90d 100644
--- a/internal/gui/assets/plugins/usage/i18n.js
+++ b/internal/gui/assets/plugins/usage/i18n.js
@@ -2,6 +2,15 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
+ "What the bytes sent upstream were made of": "发往上游的字节由什么组成",
+ "≈ {size} a request": "每个请求约 {size}",
+ "Each request sends the whole conversation again, with the system prompt and the tools' definitions, so a request's bytes grow with its context.": "每个请求都会把整段对话连同系统提示词和工具定义重新发送一遍,所以一个请求的字节数随上下文增长。",
+ "Tool definitions": "工具定义",
+ "Not measured": "未测量",
+ "Requests whose body magpie didn't read: a Responses WebSocket's turns, and bodies it couldn't take apart": "magpie 没有读取请求体的请求:Responses WebSocket 的轮次,以及无法拆解的请求体",
+ "Bytes sent": "已发送",
+ "Per request": "每个请求",
+ "Made of": "组成",
"Order by": "排序方式",
"Order this list": "给这个列表排序",
"Model speed": "模型速度",
@@ -282,6 +291,15 @@ magpie.strings({
"Sent upstream as {to}, as the agent spoke it": "以 {to} 协议发往上游,与 agent 所用协议相同",
},
"zh-TW": {
+ "What the bytes sent upstream were made of": "傳往上游的位元組由什麼組成",
+ "≈ {size} a request": "每個請求約 {size}",
+ "Each request sends the whole conversation again, with the system prompt and the tools' definitions, so a request's bytes grow with its context.": "每個請求都會把整段對話連同系統提示詞和工具定義重新傳送一遍,所以一個請求的位元組數隨上下文增長。",
+ "Tool definitions": "工具定義",
+ "Not measured": "未測量",
+ "Requests whose body magpie didn't read: a Responses WebSocket's turns, and bodies it couldn't take apart": "magpie 沒有讀取請求內容的請求:Responses WebSocket 的輪次,以及無法拆解的請求內容",
+ "Bytes sent": "已傳送",
+ "Per request": "每個請求",
+ "Made of": "組成",
"Order by": "排序方式",
"Order this list": "排序這個列表",
"Model speed": "模型速度",
@@ -562,6 +580,15 @@ magpie.strings({
"Sent upstream as {to}, as the agent spoke it": "以 {to} 協議發往上游,與 agent 所用協議相同",
},
ja: {
+ "What the bytes sent upstream were made of": "上流へ送ったバイトの内訳",
+ "≈ {size} a request": "1 リクエストあたり約 {size}",
+ "Each request sends the whole conversation again, with the system prompt and the tools' definitions, so a request's bytes grow with its context.": "各リクエストは会話全体をシステムプロンプトとツール定義ごと送り直すため、リクエストのバイト数はコンテキストとともに増えます。",
+ "Tool definitions": "ツール定義",
+ "Not measured": "未計測",
+ "Requests whose body magpie didn't read: a Responses WebSocket's turns, and bodies it couldn't take apart": "magpie が本文を読まなかったリクエスト:Responses WebSocket のターンと、分解できなかった本文",
+ "Bytes sent": "送信量",
+ "Per request": "1 リクエストあたり",
+ "Made of": "内訳",
"Order by": "並べ替え",
"Order this list": "この一覧を並べ替える",
"Model speed": "モデルの速度",
@@ -842,6 +869,15 @@ magpie.strings({
"Sent upstream as {to}, as the agent spoke it": "エージェントと同じ {to} で上流へ送信",
},
de: {
+ "What the bytes sent upstream were made of": "Woraus die an den Upstream gesendeten Bytes bestehen",
+ "≈ {size} a request": "≈ {size} pro Anfrage",
+ "Each request sends the whole conversation again, with the system prompt and the tools' definitions, so a request's bytes grow with its context.": "Jede Anfrage sendet die ganze Unterhaltung erneut, samt Systemprompt und Tool-Definitionen, daher wachsen die Bytes einer Anfrage mit ihrem Kontext.",
+ "Tool definitions": "Tool-Definitionen",
+ "Not measured": "Nicht gemessen",
+ "Requests whose body magpie didn't read: a Responses WebSocket's turns, and bodies it couldn't take apart": "Anfragen, deren Inhalt magpie nicht gelesen hat: Züge über einen Responses-WebSocket und Inhalte, die es nicht zerlegen konnte",
+ "Bytes sent": "Gesendet",
+ "Per request": "Pro Anfrage",
+ "Made of": "Zusammensetzung",
"Order by": "Sortieren nach",
"Order this list": "Diese Liste sortieren",
"Model speed": "Modelltempo",
diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js
index ac5355a2a..823760269 100644
--- a/internal/gui/assets/plugins/usage/page.js
+++ b/internal/gui/assets/plugins/usage/page.js
@@ -2067,6 +2067,11 @@ function ledDetail(r) {
// DeepSeek's image files kept out of it (#5407); a row from before has
// none of them, and says nothing
if (r.up_bytes > 0) add("Sent upstream", fmtBytes(r.up_bytes));
+ // and what it was made of, for a row whose body magpie read
+ if (r.up_bytes > 0 && r.up_parts) {
+ const p = ledUpParts({ up_bytes: r.up_bytes, up_measured: r.up_bytes, up_system: r.up_parts.system, up_tools: r.up_parts.tools, up_images: r.up_parts.images });
+ add("Made of", LED_UP_PARTS.filter(([k]) => p[k] > 0).map(([k, label]) => t(label) + " " + fmtBytes(p[k])).join(" · "));
+ }
if (r.down_bytes > 0) add("Received", fmtBytes(r.down_bytes));
// and how many images they were, for a row that kept it (matrix0487)
if (r.image_files_saved > 0) add("Saved by image files", r.image_files > 0 ? t(r.image_files === 1 ? "{size} ({n} image)" : "{size} ({n} images)", { size: fmtBytes(r.image_files_saved), n: ledNum(r.image_files) }) : fmtBytes(r.image_files_saved));
@@ -2329,11 +2334,114 @@ function drawLedSpeed(l) {
box.append(head, scroll);
}
+// ---- what the bytes sent upstream were made of (theforeveriris on X:
+// "8.6 GB up from plain-text projects?"). Every request sends the whole
+// conversation again, so a request's bytes are about its context; the
+// card says so, splits the bytes of the requests whose body magpie read
+// into the system prompt, the tools' definitions, images and the
+// conversation, and lists them by agent and by model, each with its bytes
+// a request. Opened from the ↑ on the Requests card, kept open as left.
+let ledUpOpen = false;
+try { ledUpOpen = localStorage.getItem("magpie.ledUp") === "1"; } catch {}
+const LED_UP_PARTS = [
+ ["conv", "Conversation", "c1"],
+ ["tools", "Tool definitions", "c2"],
+ ["system", "System prompt", "c3"],
+ ["images", "Images", "c4"],
+ ["rest", "Not measured", ""],
+];
+function ledUpParts(x) {
+ const sys = x.up_system || 0, tools = x.up_tools || 0, images = x.up_images || 0;
+ const measured = Math.min(x.up_measured || 0, x.up_bytes || 0);
+ return { conv: Math.max(0, measured - sys - tools - images), tools, system: sys, images, rest: Math.max(0, (x.up_bytes || 0) - measured) };
+}
+const ledUpEach = (x) => (x.up_calls > 0 ? (x.up_bytes || 0) / x.up_calls : 0);
+function drawLedUp(l, entering) {
+ const box = $("#ledUp");
+ box.hidden = !ledUpOpen || !(l.up_bytes > 0);
+ box.replaceChildren();
+ if (box.hidden) return;
+ const head = el("div", "led-bar");
+ head.append(el("b", "led-spd-t", t("Sent upstream")), el("span", "grow"));
+ const each = ledUpEach(l);
+ if (each) head.append(el("span", "led-up-each", t("≈ {size} a request", { size: fmtBytes(each) })));
+ const close = el("button", "text led-up-x", "×");
+ close.type = "button";
+ close.setAttribute("aria-label", t("Close"));
+ close.onclick = () => ledUpToggle(false);
+ head.append(close);
+ const note = el("p", "led-up-note", t("Each request sends the whole conversation again, with the system prompt and the tools' definitions, so a request's bytes grow with its context."));
+ const parts = ledUpParts(l);
+ const bar = el("div", "led-up-bar");
+ bar.setAttribute("role", "img");
+ const legend = el("div", "led-up-legend");
+ const said = [];
+ for (const [key, label, c] of LED_UP_PARTS) {
+ const n = parts[key];
+ if (!(n > 0)) continue;
+ const share = n / l.up_bytes;
+ const seg = el("i", "led-up-seg " + key);
+ if (c) seg.style.background = "var(--" + c + ")";
+ seg.style.flexGrow = String(share);
+ seg.title = t(label) + ": " + fmtBytes(n) + " (" + (100 * share).toFixed(1) + "%)";
+ bar.append(seg);
+ const item = el("span", "led-up-key " + key);
+ const dot = el("i", "dot");
+ if (c) dot.style.background = "var(--" + c + ")";
+ item.append(dot, el("span", "", t(label)), el("b", "", fmtBytes(n)), el("span", "pc", (100 * share < 1 ? "<1" : Math.round(100 * share)) + "%"));
+ if (key === "rest") item.title = t("Requests whose body magpie didn't read: a Responses WebSocket's turns, and bodies it couldn't take apart");
+ legend.append(item);
+ said.push(t(label) + " " + fmtBytes(n));
+ }
+ bar.setAttribute("aria-label", said.join(", "));
+ const lists = el("div", "led-up-lists");
+ for (const [dim, title] of [["agent", "Agent"], ["model", "Model"]]) {
+ const rows = (l.by?.[dim] || []).filter((s) => s.up_bytes > 0).sort((a, b) => b.up_bytes - a.up_bytes);
+ if (!rows.length) continue;
+ const table = el("table", "led-spd led-up-by");
+ const hr = el("tr");
+ hr.append(el("th", "nm", t(title)), el("th", "n", t("Bytes sent")), el("th", "n", t("Per request")));
+ const thead = el("thead");
+ thead.append(hr);
+ const body = el("tbody");
+ const top = rows[0].up_bytes;
+ for (const s of rows.slice(0, 8)) {
+ const tr = el("tr");
+ const nm = el("td", "nm");
+ const name = s.name || s.id || "—";
+ nm.append(el("span", "", dim === "agent" ? t(name) : name));
+ nm.title = name;
+ const meter = el("i", "led-up-meter");
+ meter.style.width = (100 * s.up_bytes / top).toFixed(1) + "%";
+ nm.append(meter);
+ tr.append(nm, el("td", "", fmtBytes(s.up_bytes)), el("td", ledUpEach(s) ? "" : "faint", ledUpEach(s) ? fmtBytes(ledUpEach(s)) : "—"));
+ body.append(tr);
+ }
+ table.append(thead, body);
+ lists.append(table);
+ }
+ box.append(head, note, bar, legend, lists);
+ if (entering && box.animate) {
+ const still = calm();
+ box.animate([{ opacity: 0, transform: still ? "none" : "translateY(-4px)" }, { opacity: 1, transform: "none" }], { duration: 200, easing: "cubic-bezier(.23, 1, .32, 1)" });
+ }
+}
+let ledUpLast = null;
+function ledUpToggle(open) {
+ ledUpOpen = open;
+ try { localStorage.setItem("magpie.ledUp", open ? "1" : "0"); } catch {}
+ for (const b of document.querySelectorAll("#ledKpi .led-up-open")) b.setAttribute("aria-expanded", String(open));
+ if (ledUpLast) drawLedUp(ledUpLast, open);
+ if (!open) $("#ledKpi .led-up-open")?.focus({ preventScroll: true });
+}
+
function renderLedgerDash(l) {
const dash = $("#ledDash");
dash.hidden = !l.total && !l.day;
if (dash.hidden) return;
drawLedSpeed(l);
+ ledUpLast = l;
+ drawLedUp(l);
const total = allTokens(l);
// of the calls whose vendor counted the cache: none when no call's was (#3464)
const rate = cacheHitOf(l);
@@ -2391,6 +2499,17 @@ function renderLedgerDash(l) {
const io = line(...usageParts(["↑ " + fmtBytes(l.up_bytes || 0), "↓ " + fmtBytes(l.down_bytes || 0), ...(l.image_files_saved > 0 ? [t("{n} saved by image files", { n: fmtBytes(l.image_files_saved) })] : [])]));
io.classList.add("parts", "led-io");
io.title = t("Sent upstream") + ": " + ledNum(l.up_bytes || 0) + " B\n" + t("Received") + ": " + ledNum(l.down_bytes || 0) + " B";
+ // the ↑ opens what those bytes were made of (drawLedUp)
+ if (l.up_bytes > 0) {
+ const up = io.firstElementChild;
+ const b = el("button", "led-jump led-up-open", up.textContent);
+ b.type = "button";
+ b.title = t("What the bytes sent upstream were made of");
+ b.setAttribute("aria-controls", "ledUp");
+ b.setAttribute("aria-expanded", String(ledUpOpen));
+ b.onclick = () => ledUpToggle(!ledUpOpen);
+ up.replaceChildren(b);
+ }
strip.lastChild.append(io);
}
// and how fast it flows now, while requests are in flight (ledFlow)
diff --git a/internal/gui/tests/usage-upload.test.cjs b/internal/gui/tests/usage-upload.test.cjs
new file mode 100644
index 000000000..f47a59aa4
--- /dev/null
+++ b/internal/gui/tests/usage-upload.test.cjs
@@ -0,0 +1,161 @@
+// Run with Node's test runner and Playwright on the module path; see README.md.
+// What the bytes sent upstream were made of (theforeveriris on X: 8169
+// requests, "↑ 8.6 GB" from plain-text projects). The Requests card's ↑ is
+// a button that opens a card under the strip: the bytes a request, a line
+// saying each request sends the whole conversation again, a bar and its
+// legend of the conversation, the tools' definitions, the system prompt,
+// images and what wasn't measured, and the bytes of each agent and each model,
+// largest first. It stays open as left across a reload and closes from its
+// ×. A request's details say what its bytes were made of; one that kept no
+// parts says nothing. A period with nothing sent has no button. At 1180 and
+// 420 wide nothing scrolls sideways. Chromium and WebKit, every language;
+// no backend, the API is faked.
+const assert = require("node:assert/strict");
+const fs = require("node:fs/promises");
+const path = require("node:path");
+const { test } = require("node:test");
+const { chromium, webkit } = require("playwright");
+const reader = require("./reader.cjs");
+
+const assets = path.resolve(__dirname, "../assets");
+const now = Date.now();
+
+const row = (rid, more) => ({ t: new Date(now - 60e3).toISOString(), agent: "codex", agentName: "Codex", icon: "codex-color", provider: "openai", providerName: "OpenAI", req: "gpt-5", model: "gpt-5", served: "gpt-5", in: 300, out: 40, ms: 2380, status: 200, rid, ep: "/v1/chat/completions", cost: 0.01, priced: true, ...more });
+const ROWS = [
+ row("req_parts", { up_bytes: 1_000_000, down_bytes: 3_000, up_parts: { system: 200_000, tools: 50_000 } }),
+ row("req_plain", { up_bytes: 40_000, down_bytes: 900 }),
+];
+const UP = { up_bytes: 8_600_000_000, up_calls: 8169, up_measured: 8_000_000_000, up_system: 1_000_000_000, up_tools: 500_000_000, up_images: 100_000_000, down_bytes: 1_000_000_000 };
+const share = (id, name, up, calls) => ({ id, name, calls, input: 1, output: 1, up_bytes: up, up_calls: calls });
+const BY = {
+ agent: [share("claude", "Claude Code", 2_100_000_000, 4000), share("codex", "Codex", 6_500_000_000, 4169), share("gemini", "Gemini CLI", 0, 0)],
+ model: [share("gpt-5", "gpt-5", 6_500_000_000, 4169), share("claude-sonnet", "claude-sonnet", 2_100_000_000, 4000)],
+};
+
+function page(q, sent) {
+ return {
+ period: q.get("period"), rows: ROWS, offset: 0, total: ROWS.length, calls: 8169, errors: 0,
+ input: 700, output: 80, cache_read: 0, cache_write: 0, reasoning: 0, cost: 0.03, unpriced: 0,
+ ...(sent ? UP : {}), by: sent ? BY : {},
+ agents: [{ id: "codex", name: "Codex", icon: "codex-color" }],
+ };
+}
+
+function server(lang, sent) {
+ return async (route) => {
+ const req = route.request(), url = new URL(req.url());
+ const json = (data) => route.fulfill({ json: data });
+ if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
+ if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, fx: { rate: 7.2, at: new Date().toISOString() } });
+ if (url.pathname === "/api/usage/requests") return json(page(url.searchParams, sent));
+ if (url.pathname === "/api/usage/quotas") return json([]);
+ if (url.pathname === "/api/usage") return json({ calls: 3, errors: 0, input: 700, output: 80, cache_read: 0, cache_write: 0, reasoning: 0, unpriced: 0, cost: 0.03, bucket: "day", series: [], agents: [], models: [], path: "~/.config/magpie/usage.jsonl" });
+ if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] });
+ if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} });
+ if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
+ if (url.pathname.startsWith("/api/")) return json({});
+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
+ await route.fulfill({ body: await fs.readFile(file), contentType });
+ };
+}
+
+const L = {
+ en: { each: "≈ 1.1 MB a request", conv: "Conversation", tools: "Tool definitions", system: "System prompt", images: "Images", rest: "Not measured", agent: "Agent", model: "Model", made: "Made of", note: /whole conversation again/ },
+ zh: { each: "每个请求约 1.1 MB", conv: "会话内容", tools: "工具定义", system: "系统提示词", images: "图像", rest: "未测量", agent: "Agent", model: "模型", made: "组成", note: /整段对话/ },
+ "zh-TW": { each: "每個請求約 1.1 MB", conv: "會話內容", tools: "工具定義", system: "系統提示詞", images: "影像", rest: "未測量", agent: "Agent", model: "模型", made: "組成", note: /整段對話/ },
+ ja: { each: "1 リクエストあたり約 1.1 MB", conv: "会話", tools: "ツール定義", system: "システムプロンプト", images: "画像", rest: "未計測", agent: "エージェント", model: "モデル", made: "内訳", note: /会話全体/ },
+ de: { each: "≈ 1.1 MB pro Anfrage", conv: "Unterhaltung", tools: "Tool-Definitionen", system: "Systemprompt", images: "Bilder", rest: "Nicht gemessen", agent: "Agent", model: "Modell", made: "Zusammensetzung", note: /ganze Unterhaltung/ },
+};
+
+async function open(browser, lang, width, sent, storage) {
+ const ctx = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce", ...(storage ? { storageState: storage } : {}) });
+ const p = await ctx.newPage();
+ p.setDefaultTimeout(5000);
+ p.setDefaultNavigationTimeout(60000);
+ const errors = [];
+ p.on("pageerror", (e) => errors.push(e.message));
+ await p.route("**/*", server(lang, sent));
+ await p.goto("http://magpie.test/");
+ await p.locator('[data-view="usage"]').first().click();
+ await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click();
+ await p.locator("#ledWrap .led tbody tr.led-row").first().waitFor();
+ await p.locator("#ledKpi .blk").first().waitFor();
+ return { ctx, p, errors };
+}
+
+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
+ test(engine + ": what the bytes sent upstream were made of", async (t) => {
+ assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
+ t.after(() => browser.close());
+ for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
+ const w = L[lang];
+ for (const width of [1180, 420]) {
+ await t.test(lang + " " + width, async () => {
+ const { ctx, p, errors } = await open(browser, lang, width, true);
+ const btn = p.locator("#ledKpi .led-io .led-up-open");
+ assert.equal(await btn.count(), 1);
+ assert.equal((await btn.textContent()).trim(), "↑ 8.6 GB");
+ assert.equal(await btn.getAttribute("aria-expanded"), "false");
+ assert.equal(await p.locator("#ledUp").isVisible(), false);
+ await btn.click();
+ const box = p.locator("#ledUp");
+ await box.waitFor();
+ assert.equal(await btn.getAttribute("aria-expanded"), "true");
+ assert.equal((await box.locator(".led-up-each").textContent()).trim(), w.each);
+ assert.match(await box.locator(".led-up-note").textContent(), w.note);
+ // the legend: each part, its bytes, its share, in this order
+ const keys = await box.locator(".led-up-key").evaluateAll((ks) => ks.map((k) => [...k.querySelectorAll("span, b")].map((s) => s.textContent)));
+ assert.deepEqual(keys, [
+ [w.conv, "6.4 GB", "74%"], [w.tools, "500 MB", "6%"], [w.system, "1.0 GB", "12%"], [w.images, "100 MB", "1%"], [w.rest, "600 MB", "7%"],
+ ]);
+ // the bar's segments are as wide as their shares
+ const segs = await box.locator(".led-up-bar").evaluate((b) => [b.getBoundingClientRect().width, ...[...b.children].map((s) => s.getBoundingClientRect().width)]);
+ assert.equal(segs.length, 6);
+ assert(segs[1] > segs[3] && segs[3] > segs[2] && segs[2] > segs[4], `segments ${segs}`);
+ // by agent and by model, largest first, with the bytes a request; none for an agent that sent nothing
+ const tables = await box.locator(".led-up-by").evaluateAll((ts) => ts.map((tb) => [...tb.querySelectorAll("tr")].map((tr) => [...tr.children].map((c) => c.textContent.trim()))));
+ assert.deepEqual(tables, [
+ [[w.agent, tables[0][0][1], tables[0][0][2]], ["Codex", "6.5 GB", "1.6 MB"], ["Claude Code", "2.1 GB", "525 KB"]],
+ [[w.model, tables[1][0][1], tables[1][0][2]], ["gpt-5", "6.5 GB", "1.6 MB"], ["claude-sonnet", "2.1 GB", "525 KB"]],
+ ]);
+ const sideways = await p.evaluate(() => [document.documentElement.scrollWidth - innerWidth, ...[...document.querySelectorAll("#ledKpi .blk, #ledUp")].map((b) => b.scrollWidth - b.clientWidth)]);
+ assert(sideways.every((n) => n <= 1), `scrolls sideways: ${sideways}`);
+
+ // a request's details: what its bytes were made of; one without parts, nothing
+ const rows = p.locator(".led tbody tr.led-row");
+ const pairs = () => p.locator("#ledReqPane .led-detail").evaluate((d) => Object.fromEntries([...d.querySelectorAll("dt")].map((dt) => [dt.textContent, dt.nextElementSibling.textContent])));
+ await reader.click(p, rows.nth(0));
+ await p.locator("#ledReqPane .led-detail").waitFor();
+ assert.equal((await pairs())[w.made], `${w.conv} 750 KB · ${w.tools} 50 KB · ${w.system} 200 KB`);
+ await reader.closeRequest(p);
+ await reader.click(p, rows.nth(1));
+ await p.locator("#ledReqPane .led-detail").waitFor();
+ assert(!(w.made in (await pairs())), "a row with no parts says what it was made of");
+ await reader.closeRequest(p);
+
+ // kept open across a reload, closed from its ×
+ const state = await ctx.storageState();
+ const again = await open(browser, lang, width, true, state);
+ await again.p.locator("#ledUp").waitFor();
+ assert.equal(await again.p.locator("#ledKpi .led-up-open").getAttribute("aria-expanded"), "true");
+ await again.p.locator("#ledUp .led-up-x").click();
+ assert.equal(await again.p.locator("#ledUp").isVisible(), false);
+ assert.equal(await again.p.locator("#ledKpi .led-up-open").getAttribute("aria-expanded"), "false");
+ assert.deepEqual([...errors, ...again.errors], []);
+ await again.ctx.close();
+ await ctx.close();
+ });
+ }
+ await t.test(lang + " nothing sent", async () => {
+ const { ctx, p, errors } = await open(browser, lang, 1180, false);
+ assert.equal(await p.locator("#ledKpi .led-up-open").count(), 0);
+ assert.equal(await p.locator("#ledUp").isVisible(), false);
+ assert.deepEqual(errors, []);
+ await ctx.close();
+ });
+ }
+ });
+}
diff --git a/internal/usage/heat_disk.go b/internal/usage/heat_disk.go
index c77d5f81b..3c85fc90f 100644
--- a/internal/usage/heat_disk.go
+++ b/internal/usage/heat_disk.go
@@ -34,7 +34,7 @@ import (
// history again on its first start, the cold start's peak (#2278). Raise
// it with any change to what a row counts as; TestSettledCountedAsVersioned
// fails until it is raised.
-const settledCountVersion = "4"
+const settledCountVersion = "5"
func heatDiskPath() string {
return filepath.Join(filepath.Dir(sessions.CachePath()), "heat-v1.json")
@@ -249,10 +249,14 @@ func hashRows(h hash.Hash, c *rowChunk) {
b = binary.AppendVarint(b, p.RouteID)
b = binary.AppendUvarint(b, math.Float64bits(p.Cost))
b = binary.AppendUvarint(b, math.Float64bits(p.Credits))
- for _, v := range [...]int32{p.Millis, p.TTFT, p.FirstText, p.Sent, p.Flow, p.FirstReasoning, p.Own, p.Retried, p.Queued, p.Masking, p.Status, int32(p.Tries), p.UpBytes, p.DownBytes, p.FilesSaved} {
+ for _, v := range [...]int32{p.Millis, p.TTFT, p.FirstText, p.Sent, p.Flow, p.FirstReasoning, p.Own, p.Retried, p.Queued, p.Masking, int32(p.Status), int32(p.Tries), p.UpBytes, p.DownBytes, p.FilesSaved} {
b = binary.AppendVarint(b, int64(v))
}
b = binary.AppendUvarint(b, uint64(p.Flags))
+ if p.Flags&rowUpParts != 0 {
+ // only where kept, so a row from before hashes as it did
+ b = append(b, p.upMix[:]...)
+ }
if len(b) > 30<<10 {
h.Write(b)
b = b[:0]
diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go
index f336b4ee4..1d15281fd 100644
--- a/internal/usage/ledger.go
+++ b/internal/usage/ledger.go
@@ -956,9 +956,7 @@ func (t *Totals) plus(d *Totals) {
t.FloorOut += d.FloorOut
t.FloorMs += d.FloorMs
t.FloorN += d.FloorN
- t.UpBytes += d.UpBytes
- t.DownBytes += d.DownBytes
- t.ImageFilesSaved += d.ImageFilesSaved
+ t.plusBytes(d)
}
// FloorAgents are the agents whose session files time a call from what
diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go
index ac9b76ae0..9eef4e991 100644
--- a/internal/usage/request_page.go
+++ b/internal/usage/request_page.go
@@ -93,16 +93,20 @@ type packedRow struct {
Sent, Flow, FirstReasoning int32
Own, Retried, Queued int32
Masking int32 // ms (Record.Masking)
- Status int32
- // Tries and ImageFiles in 16 bits, so the row is no larger than its
- // 152 bytes before the count was kept: neither comes near 32767
- // (smallOf)
- Tries, ImageFiles int16
// the bytes up and down (Record.UpBytes, DownBytes, ImageFilesSaved),
// in 32 bits as Masking: 2GiB is past any request a vendor takes
UpBytes, DownBytes, FilesSaved int32
- Flags uint16
- zone uint16
+ // Status and ImageFiles in 16 bits, and Tries in 8, so the row is no
+ // larger than its 152 bytes before the counts and upMix were kept:
+ // no status passes 32767, no request 32767 images or 255 tries
+ // (smallOf, tinyOf)
+ Status, ImageFiles int16
+ Flags uint16
+ zone uint16
+ Tries uint8
+ // upMix is Record.UpParts, each part's share of UpBytes in 255ths
+ // (upMixOf), where Flags has rowUpParts
+ upMix [3]uint8
}
// rowZones are the zones rows' times are in, by a row's zone; 0 is the
@@ -227,6 +231,26 @@ const rowCacheUnknown = 8192
// rowSocket is the Flags bit of Record.Socket.
const rowSocket = 16384
+// rowUpParts marks a row that kept what its bytes up were made of
+// (Record.UpParts, packedRow.upMix).
+const rowUpParts = 32768
+
+// upMixOf is u's parts as shares of up in 255ths, for a packed row: a
+// part rounds to the nearest 255th of the request, so the sums of many
+// rows stay within a fraction of a percent.
+func upMixOf(u *UpParts, up int) (m [3]uint8) {
+ for i, n := range [3]int{u.System, u.Tools, u.Images} {
+ m[i] = uint8(min(max((n*255+up/2)/up, 0), 255))
+ }
+ return m
+}
+
+// upPartsOf is what upMixOf kept, as bytes of up.
+func upPartsOf(m [3]uint8, up int) *UpParts {
+ part := func(i int) int { return up * int(m[i]) / 255 }
+ return &UpParts{System: part(0), Tools: part(1), Images: part(2)}
+}
+
type rowChunk struct {
Archive []byte
Locations []*time.Location
@@ -356,7 +380,7 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
c.Bytes += int64(len(s) + 48)
return id
}
- p := packedRow{Tokens: [6]int32{tokensOf(int64(r.Input)), tokensOf(int64(r.Output)), tokensOf(int64(r.CacheRead)), tokensOf(int64(r.CacheWrite)), tokensOf(int64(r.Reasoning)), tokensOf(int64(r.CacheWrite1h))}, Millis: msOf(r.Millis), TTFT: msOf(r.TTFT), FirstText: msOf(r.FirstText), FirstReasoning: msOf(r.FirstReasoning), Sent: msOf(r.Sent), Flow: msOf(r.Flow), Own: msOf(r.Own), Masking: int32(min(r.Masking, math.MaxInt32)), Retried: msOf(r.Retried), Queued: msOf(r.Queued), Order: order, RouteID: r.RouteID, Cost: r.Cost, Status: int32(r.Status), Tries: smallOf(r.Tries), ImageFiles: smallOf(r.ImageFiles), UpBytes: bytesOf(r.UpBytes), DownBytes: bytesOf(r.DownBytes), FilesSaved: bytesOf(r.ImageFilesSaved)}
+ p := packedRow{Tokens: [6]int32{tokensOf(int64(r.Input)), tokensOf(int64(r.Output)), tokensOf(int64(r.CacheRead)), tokensOf(int64(r.CacheWrite)), tokensOf(int64(r.Reasoning)), tokensOf(int64(r.CacheWrite1h))}, Millis: msOf(r.Millis), TTFT: msOf(r.TTFT), FirstText: msOf(r.FirstText), FirstReasoning: msOf(r.FirstReasoning), Sent: msOf(r.Sent), Flow: msOf(r.Flow), Own: msOf(r.Own), Masking: int32(min(r.Masking, math.MaxInt32)), Retried: msOf(r.Retried), Queued: msOf(r.Queued), Order: order, RouteID: r.RouteID, Cost: r.Cost, Status: smallOf(r.Status), Tries: tinyOf(r.Tries), ImageFiles: smallOf(r.ImageFiles), UpBytes: bytesOf(r.UpBytes), DownBytes: bytesOf(r.DownBytes), FilesSaved: bytesOf(r.ImageFilesSaved)}
p.setTime(r.Time)
var t [rowTexts]uint32
for i, s := range rowText(&r) {
@@ -388,6 +412,10 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
if r.Socket {
p.Flags |= rowSocket
}
+ if r.UpParts != nil && p.UpBytes > 0 {
+ p.Flags |= rowUpParts
+ p.upMix = upMixOf(r.UpParts, int(p.UpBytes))
+ }
if failed {
p.Flags |= 16
}
@@ -435,6 +463,11 @@ func smallOf(n int) int16 {
return int16(max(min(n, math.MaxInt16), 0))
}
+// tinyOf is a count of tries in a packed row's 8 bits, as smallOf.
+func tinyOf(n int) uint8 {
+ return uint8(max(min(n, math.MaxUint8), 0))
+}
+
func (c *rowChunk) row(i int) Row {
p := &c.Rows[i]
r := Row{Record: Record{RouteID: p.RouteID, Time: p.Time(), Input: int(p.Tokens[0]), Output: int(p.Tokens[1]), CacheRead: int(p.Tokens[2]), CacheWrite: int(p.Tokens[3]), CacheWrite1h: int(p.Tokens[5]), Reasoning: int(p.Tokens[4]), Millis: int64(p.Millis), TTFT: int64(p.TTFT), FirstText: int64(p.FirstText), FirstReasoning: int64(p.FirstReasoning), ReasoningHidden: p.Flags&rowReasoningHidden != 0, CacheUnknown: p.Flags&rowCacheUnknown != 0, Socket: p.Flags&rowSocket != 0, Sent: int64(p.Sent), Flow: int64(p.Flow), Own: int64(p.Own), Masking: int64(p.Masking), Retried: int64(p.Retried), Queued: int64(p.Queued), Status: int(p.Status), Tries: int(p.Tries), UpBytes: int(p.UpBytes), DownBytes: int(p.DownBytes), ImageFilesSaved: int(p.FilesSaved), ImageFiles: int(p.ImageFiles), HandedOn: p.Flags&rowHandedOn != 0, Rejected: p.Flags&4 != 0, SessionOfficialLogin: p.Flags&8 != 0}, Cost: p.Cost, Priced: p.Flags&1 != 0, Swapped: p.Flags&2 != 0, Routed: p.Flags&32 != 0}
@@ -442,6 +475,9 @@ func (c *rowChunk) row(i int) Row {
credits := p.Credits
r.Credits = &credits
}
+ if p.Flags&rowUpParts != 0 && p.UpBytes > 0 {
+ r.UpParts = upPartsOf(p.upMix, int(p.UpBytes))
+ }
if p.Flags&rowCompactionKnown != 0 {
compacted := p.Flags&rowCompaction != 0
r.Compaction = &compacted
diff --git a/internal/usage/request_snapshot.go b/internal/usage/request_snapshot.go
index 3235c3f03..90a239e34 100644
--- a/internal/usage/request_snapshot.go
+++ b/internal/usage/request_snapshot.go
@@ -101,6 +101,9 @@ func (c *rowChunk) encode(keep func([]byte) bool) ([]byte, []*time.Location) {
put(uint64(p.DownBytes))
put(uint64(int64(p.FilesSaved)))
put(uint64(p.ImageFiles))
+ if p.Flags&rowUpParts != 0 {
+ put(uint64(p.upMix[0]) | uint64(p.upMix[1])<<8 | uint64(p.upMix[2])<<16)
+ }
if p.Flags&rowCredits != 0 {
put(math.Float64bits(p.Credits))
}
@@ -301,11 +304,16 @@ func (c *rowChunk) unpackReusing(dst *rowChunk, into []packedRow, strs []string,
p.Sent, p.Flow = msOf(int64(take())), msOf(int64(take()))
p.Own, p.Retried, p.Queued = msOf(int64(take())), msOf(int64(take())), msOf(int64(take()))
p.FirstReasoning = msOf(int64(take()))
- p.Cost, p.Status, p.Flags = math.Float64frombits(take()), int32(take()), uint16(take())
- p.Tries = int16(take())
+ p.Cost, p.Status, p.Flags = math.Float64frombits(take()), int16(take()), uint16(take())
+ p.Tries = uint8(take())
p.Masking = int32(take())
p.UpBytes, p.DownBytes, p.FilesSaved = int32(take()), int32(take()), int32(take())
p.ImageFiles = int16(take())
+ p.upMix = [3]uint8{}
+ if p.Flags&rowUpParts != 0 {
+ m := take()
+ p.upMix = [3]uint8{uint8(m), uint8(m >> 8), uint8(m >> 16)}
+ }
p.Credits = 0
if p.Flags&rowCredits != 0 {
p.Credits = math.Float64frombits(take())
diff --git a/internal/usage/row_shape_test.go b/internal/usage/row_shape_test.go
index 2074c3ba0..054b552ea 100644
--- a/internal/usage/row_shape_test.go
+++ b/internal/usage/row_shape_test.go
@@ -151,7 +151,7 @@ func TestRowImageFilesKept(t *testing.T) {
if a.ImageFiles != 3 || a.ImageFilesSaved != 10_000_000 || a.Tries != 2 {
t.Fatalf("%d: read back %d images, saved %d, %d tries", i, a.ImageFiles, a.ImageFilesSaved, a.Tries)
}
- if b.ImageFiles != math.MaxInt16 || b.Tries != math.MaxInt16 {
+ if b.ImageFiles != math.MaxInt16 || b.Tries != math.MaxUint8 {
t.Fatalf("%d: past the most read back %d images, %d tries", i, b.ImageFiles, b.Tries)
}
if old.ImageFiles != 0 {
diff --git a/internal/usage/settled_version_test.go b/internal/usage/settled_version_test.go
index e179f5e67..dae7d63b9 100644
--- a/internal/usage/settled_version_test.go
+++ b/internal/usage/settled_version_test.go
@@ -18,7 +18,7 @@ import (
// settled days, under settledCountVersion. A change that counts them
// otherwise changes it: raise settledCountVersion and set this to the new
// hash in the same commit.
-const settledCounted = "8715ad3d4bdd7a48a9d882be5a089b17231152b10abc3d278e17070e879f107c"
+const settledCounted = "e27e12fd0fb0b8589936f2a562ae602f0cc2f1368d2e7a8f4668cdff6afe5952"
// The settled days, a page's cells and Codex's effort are kept on disk
// under settledCountVersion, not under this package's source: an upgrade
diff --git a/internal/usage/up_parts_test.go b/internal/usage/up_parts_test.go
new file mode 100644
index 000000000..5b1357b7b
--- /dev/null
+++ b/internal/usage/up_parts_test.go
@@ -0,0 +1,99 @@
+package usage
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+ "time"
+ "unsafe"
+)
+
+// A row keeps what its bytes up were made of (Record.UpParts) in 255ths
+// of them, packed and read back, so each part is within a 255th of the
+// request; a row that kept none reads back none, and keeping it made no
+// row larger. usage.jsonl has the parts as they were.
+func TestRowUpPartsKept(t *testing.T) {
+ at := time.Date(2026, 11, 14, 12, 0, 0, 0, time.UTC)
+ parts := UpParts{System: 120_000, Tools: 40_000, Images: 1_000}
+ c := &rowChunk{}
+ c.add(Row{Record: Record{Time: at, UpBytes: 1_000_000, UpParts: &parts, Tries: 3, Status: 529}}, "", 0, false)
+ c.add(Row{Record: Record{Time: at, UpBytes: 1_000_000}}, "", 1, false)
+ c.add(Row{Record: Record{Time: at, UpParts: &parts}}, "", 2, false) // nothing went up: no parts to be shares of
+ for i, c := range []*rowChunk{c, c.pack().unpack()} {
+ a, old, none := c.row(0), c.row(1), c.row(2)
+ u := a.UpParts
+ if u == nil {
+ t.Fatalf("%d: the parts weren't kept", i)
+ }
+ for _, p := range [][2]int{{u.System, parts.System}, {u.Tools, parts.Tools}, {u.Images, parts.Images}} {
+ if d := p[0] - p[1]; d < -1_000_000/255 || d > 1_000_000/255 {
+ t.Fatalf("%d: read back %+v, was %+v", i, *u, parts)
+ }
+ }
+ if a.Tries != 3 || a.Status != 529 {
+ t.Fatalf("%d: beside them, %d tries and status %d", i, a.Tries, a.Status)
+ }
+ if old.UpParts != nil || none.UpParts != nil {
+ t.Fatalf("%d: a row without parts reads back %+v, %+v", i, old.UpParts, none.UpParts)
+ }
+ }
+ if n := unsafe.Sizeof(packedRow{}); n != 152 {
+ t.Fatalf("a packed row is %d bytes, was 152", n)
+ }
+ line, _ := json.Marshal(Record{Time: at, UpBytes: 9, UpParts: &UpParts{System: 4}})
+ var back Record
+ if err := json.Unmarshal(line, &back); err != nil || back.UpParts == nil || back.UpParts.System != 4 || !strings.Contains(string(line), `"up_parts":{"system":4}`) {
+ t.Fatalf("usage.jsonl's line %s read back %+v (%v)", line, back.UpParts, err)
+ }
+ if line, _ := json.Marshal(Record{Time: at, UpBytes: 9}); strings.Contains(string(line), "up_parts") {
+ t.Fatalf("a row with no parts says some: %s", line)
+ }
+}
+
+// A period's totals, and each agent's, say what their bytes up were made
+// of: how many requests sent any (for the bytes a request), the bytes of
+// those whose parts were read, and the parts summed. From the rows and
+// from the request page's cells alike, and from records.
+func TestTotalsSumUpParts(t *testing.T) {
+ pageHome(t)
+ now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local))
+ records := []Record{
+ {Time: now, Provider: "a", Agent: "codex", Model: "m", Input: 10, UpBytes: 2550, UpParts: &UpParts{System: 510, Tools: 1020}, Status: 200},
+ {Time: now, Provider: "a", Agent: "codex", Model: "m", Input: 10, UpBytes: 5100, UpParts: &UpParts{Images: 2600}, Status: 200},
+ {Time: now, Provider: "b", Agent: "claude", Model: "n", Input: 10, UpBytes: 700, Status: 200}, // not read
+ {Time: now, Provider: "b", Agent: "claude", Model: "n", Input: 10, Status: 200}, // nothing went
+ }
+ gateway := &rowChunk{}
+ all := Ledgered{}
+ for i, r := range records {
+ row := Row{Record: r}
+ gateway.add(row, "", int64(i), false)
+ all.Rows = append(all.Rows, row)
+ }
+ page := buildRequestPage(Today, Filter{}, 0, 100, gateway, nil)
+ var recs, rows, sum Totals
+ for _, r := range records {
+ recs.add(r, nil)
+ }
+ for _, r := range all.Rows {
+ rows.addRow(r)
+ }
+ sum.plus(&rows)
+ for name, s := range map[string]Totals{"page": page.Sum, "records": recs, "rows": rows, "plus": sum} {
+ t.Run(name, func(t *testing.T) {
+ if s.UpBytes != 8350 || s.UpCalls != 3 || s.UpMeasured != 7650 || s.UpSystem != 510 || s.UpTools != 1020 || s.UpImages != 2600 {
+ t.Fatalf("the period: %+v", s)
+ }
+ })
+ }
+ agents := map[string]Totals{}
+ for _, sh := range page.By["agent"] {
+ agents[sh.ID] = sh.Totals
+ }
+ if c := agents["codex"]; c.UpCalls != 2 || c.UpMeasured != 7650 || c.UpImages != 2600 {
+ t.Fatalf("codex: %+v", c)
+ }
+ if c := agents["claude"]; c.UpCalls != 1 || c.UpMeasured != 0 || c.UpBytes != 700 {
+ t.Fatalf("claude: %+v", c)
+ }
+}
diff --git a/internal/usage/usage.go b/internal/usage/usage.go
index ea7c978d4..ed81c1df6 100644
--- a/internal/usage/usage.go
+++ b/internal/usage/usage.go
@@ -229,6 +229,11 @@ type Record struct {
// what ImageFilesSaved was saved on (matrix0487 on Discord). None in a
// row from before it was kept.
ImageFiles int `json:"image_files,omitempty"`
+ // UpParts is what UpBytes was made of, where the body was read to
+ // know (UpParts); nil where it wasn't: a socket's delta, a request
+ // whose images went by file, a row from before it was kept
+ // (theforeveriris on X: 8.6 GB up from plain-text projects).
+ UpParts *UpParts `json:"up_parts,omitempty"`
// Socket says the request went over the Responses WebSocket, its
// last try (provider.Socket, matrix0487 on Discord): UpBytes is then
// what the socket was sent, a delta on a kept socket.
@@ -612,6 +617,27 @@ type Totals struct {
UpBytes int64 `json:"up_bytes,omitempty"`
DownBytes int64 `json:"down_bytes,omitempty"`
ImageFilesSaved int64 `json:"image_files_saved,omitempty"`
+ // UpCalls is how many rows sent any bytes up, what UpBytes is spread
+ // over; UpMeasured the bytes of those whose parts were read
+ // (Record.UpParts), and UpSystem, UpTools and UpImages those parts
+ // summed: the conversation is UpMeasured less the three
+ UpCalls int `json:"up_calls,omitempty"`
+ UpMeasured int64 `json:"up_measured,omitempty"`
+ UpSystem int64 `json:"up_system,omitempty"`
+ UpTools int64 `json:"up_tools,omitempty"`
+ UpImages int64 `json:"up_images,omitempty"`
+}
+
+// UpParts is a request's bytes up by what they were: the agent's own
+// prompt and instructions (system prompt, skills, memory), the tools'
+// definitions, and the images and documents it sent inline, each scaled
+// to the bytes that went up (Record.UpBytes). The rest is the
+// conversation: the messages, the tool calls and their results, which an
+// agent sends again whole on every request.
+type UpParts struct {
+ System int `json:"system,omitempty"`
+ Tools int `json:"tools,omitempty"`
+ Images int `json:"images,omitempty"`
}
// addBytes adds r's bytes on the wire (Totals.UpBytes …).
@@ -619,6 +645,27 @@ func (t *Totals) addBytes(r *Record) {
t.UpBytes += int64(r.UpBytes)
t.DownBytes += int64(r.DownBytes)
t.ImageFilesSaved += int64(r.ImageFilesSaved)
+ if r.UpBytes > 0 {
+ t.UpCalls++
+ if u := r.UpParts; u != nil {
+ t.UpMeasured += int64(r.UpBytes)
+ t.UpSystem += int64(u.System)
+ t.UpTools += int64(u.Tools)
+ t.UpImages += int64(u.Images)
+ }
+ }
+}
+
+// plusBytes adds what addBytes counted of another sum.
+func (t *Totals) plusBytes(d *Totals) {
+ t.UpBytes += d.UpBytes
+ t.DownBytes += d.DownBytes
+ t.ImageFilesSaved += d.ImageFilesSaved
+ t.UpCalls += d.UpCalls
+ t.UpMeasured += d.UpMeasured
+ t.UpSystem += d.UpSystem
+ t.UpTools += d.UpTools
+ t.UpImages += d.UpImages
}
// Tokens is what went in and out, excluding cache traffic.