diff --git a/docs/reference.md b/docs/reference.md index ce159f4c2..993e78457 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -308,9 +308,19 @@ its token count, and Codex can write the output of a tool that call itself asked for before the count, so its time can begin inside the call and a floor from it could read high; it shows none. A call whose session file timed it (a Codex -turn of one call) shows its own speed as before. The floor is the row's -alone: the period's output speed, the Speed trend and `magpie usage` count -timed calls only. +turn of one call) shows its own speed as before. A floor never mixes into a +measured speed: the Speed trend and `magpie usage` count timed calls only. + +A group's speed (a row of the Usage page's ranking, by model, provider or +agent, its Output speed card, and the overview's lists) says how many +replies it is of, by one rule: with replies whose speed was measured, their +speed and how many they are (`125 tok/s (1)`, though the group has 260 +requests, most of them Codex calls in a turn of several); with none, but +rows that tell a floor, the least those wrote at, their tokens over their +whole times, and how many (`≥100 tok/s (30)`); with neither, nothing. Its +tooltip says which. A ranking by speed orders a floor-only group by its +floor (`usage.Totals` `decode_n`, `floor_out`, `floor_ms`, `floor_n`; +`usage.Row.Floor`). It lists **accounts** too: each Codex, Claude or other subscription account's tokens and cost, by the account that actually answered — the one that took diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 5e20f67b2..9e6faba02 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -15985,8 +15985,9 @@ function renderUsage() { // wrote after (#196) if (g.timed) { sub.push(t("TTFT {ms}", { ms: ledTook(Math.round(g.ttft_ms / g.timed)) })); - if (g.decode_ms > 0) sub.push(t("{n} tok/s", { n: Math.round(g.decode_out / (g.decode_ms / 1000)) })); } + const gs = ledGroupSpeed(g); + if (gs) sub.push(gs.text); who.append(el("div", "sub", sub.join(" · "))); r.append(who); const share = el("div", "share"); @@ -16402,10 +16403,32 @@ function cacheTTLs(x, fmt) { // how fast the timed replies of a point, a share or a part wrote, in tokens // a second after their first (usage.Totals.Speed): 0 for none timed const ledSpeed = (x) => x?.decode_ms > 0 ? (1000 * x.decode_out) / x.decode_ms : 0; +// the least the replies of a group that has no first token wrote at +// (usage.Totals.Floor, ledFloorSpeed's for each): 0 for none +const ledFloor = (x) => x?.floor_ms > 0 ? (1000 * x.floor_out) / x.floor_ms : 0; +// a group's speed as every ranking and the Output speed card say it, by one +// rule (Fallmonkey on Discord): with replies whose speed was measured, their +// speed and how many they are, "125 tok/s (1)", not beside "260 requests" +// alone; with none, but replies read from a session file that tell the +// least they wrote at, that floor and how many, "≥100 tok/s (30)"; else +// nothing. The Requests tab says the same of each row: "125 tok/s" or +// "≥100 tok/s". v is the figure a speed ranking orders by and bars. +function ledGroupSpeed(x) { + const v = ledSpeed(x), f = v ? 0 : ledFloor(x), k = v ? x.decode_n || 0 : x?.floor_n || 0; + if (!v && !f) return null; + const n = ledNum(Math.round(v || f)); + const text = (f ? "≥" : "") + (k ? t("{n} tok/s ({k})", { n, k: ledNum(k) }) : t("{n} tok/s", { n })); + const title = !k ? "" : v ? t(k === 1 ? "Measured on {k} reply, from its first token to its end; the others tell no speed" : "Measured on {k} replies, from their first token to their end; the others tell no speed", { k: ledNum(k) }) + : t(k === 1 ? "At least: {k} reply read from a session file, which has no first token, so the wait for it is counted too" : "At least: {k} replies read from session files, which have no first token, so the wait for it is counted too", { k: ledNum(k) }); + return { v: v || f, text, title }; +} // their mean wait for the first token, 0 for none const ledTTFT = (x) => x?.timed > 0 ? x.ttft_ms / x.timed : 0; // a metric's value of a point or a share, as the chart counts it const ledValue = (m, x) => m === "speed" ? ledSpeed(x) : m === "cost" ? +x.cost || 0 : m === "calls" ? +x.calls || 0 : allTokens(x); +// of a share in the ranking: a speed is what its row says, the floor of a +// group none of whose replies was measured (ledGroupSpeed) +const ledRankValue = (m, x) => m === "speed" ? ledGroupSpeed(x)?.v || 0 : ledValue(m, x); // of a point's part, which has its calls, tokens, cost and speed const ledPart = (m, x) => m === "speed" ? ledSpeed(x) : m === "cost" ? +x.cost || 0 : m === "calls" ? +x.calls || 0 : +x.tokens || 0; // a metric as its axis and its values say it @@ -16423,7 +16446,7 @@ function ledAxis(max) { // what a chart tells apart, most first, and the colour of each: those of the // ranking's top, and the rest together as "Other" function ledCategories(l, split, metric) { - const list = (l.by?.[split] || []).slice().sort((a, b) => ledValue(metric, b) - ledValue(metric, a) || allTokens(b) - allTokens(a)); + const list = (l.by?.[split] || []).slice().sort((a, b) => ledRankValue(metric, b) - ledRankValue(metric, a) || allTokens(b) - allTokens(a)); const top = list.slice(0, LED_SHOWN).map((x, i) => ({ ...x, color: `var(--c${i + 1})` })); return { top, rest: list.slice(LED_SHOWN), list }; } @@ -16627,11 +16650,11 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) { } if (!list.length) return; const sum = list.reduce((a, x) => a + ledValue(metric, x), 0) || 1; - const leader = Math.max(1, ledValue(metric, top[0])); + const leader = Math.max(1, ledRankValue(metric, top[0])); const one = (x, color, plain) => { const b = el("button", "rk" + (plain ? " plain" : "") + (picked && picked === x.id ? " on" : "")); b.type = "button"; - const v = ledValue(metric, x); + const v = ledRankValue(metric, x), gs = ledGroupSpeed(x); const l1 = el("div", "rk-a"); const sw = el("i", "rk-sw"); sw.style.background = color; @@ -16639,7 +16662,9 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) { if (x.icon && split !== "model") l1.append(icon(x.icon)); const nm = el("span", "rk-nm", t(x.name || x.id || "—")); nm.title = t(x.name || x.id || ""); - l1.append(nm, el("span", "rk-val", ledFormatLong(metric, v))); + const val = el("span", "rk-val", metric === "speed" ? gs?.text || "—" : ledFormatLong(metric, v)); + if (metric === "speed" && gs?.title) val.title = gs.title; + l1.append(nm, val); const bar = el("div", "rk-bar"), fill = el("i"); fill.style.width = Math.max(1.5, (100 * v) / leader).toFixed(1) + "%"; fill.style.background = color; @@ -16649,14 +16674,14 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) { if (metric !== "tokens") more.push(t("{n} tokens", { n: fmtN(allTokens(x)) })); if (metric !== "cost" && x.cost) more.push("≈" + fmtCost(x)); // how fast its replies came, beside what they cost (#860) - if (metric !== "speed" && ledSpeed(x)) more.push(t("{n} tok/s", { n: ledNum(Math.round(ledSpeed(x))) })); + if (metric !== "speed" && gs) more.push(Object.assign(el("span", "rk-speed", gs.text), { title: gs.title })); if (ledTTFT(x)) more.push(t("TTFT {ms}", { ms: ledTook(ledTTFT(x)) })); const prompt = x.input + x.cache_write + x.cache_read; if (prompt && !compact) more.push(t("hit rate {p}", { p: Math.round((100 * x.cache_read) / prompt) + "%" })); // a speed is no one's share of all if (metric !== "speed") more.push(Math.round((100 * v) / sum) + "%"); const l2 = el("div", "rk-b"); - l2.append(more.join(" · ")); + more.forEach((m, i) => l2.append(...(i ? [" · ", m] : [m]))); if (x.errors) l2.append(" · ", Object.assign(el("span", "rk-bad"), { textContent: t("{n} failed", { n: x.errors }) })); b.append(l1, bar, l2); if (!plain) b.onclick = () => choose(x); @@ -16667,7 +16692,7 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) { for (const x of top) box.append(one(x, x.color)); if (rest.length) { const tot = rest.reduce((acc, x) => { - for (const k of ["calls", "errors", "input", "output", "cache_read", "cache_write", "cost", "timed", "ttft_ms", "decode_ms", "decode_out"]) acc[k] = (acc[k] || 0) + (x[k] || 0); + for (const k of ["calls", "errors", "input", "output", "cache_read", "cache_write", "cost", "timed", "ttft_ms", "decode_ms", "decode_out", "decode_n", "floor_out", "floor_ms", "floor_n"]) acc[k] = (acc[k] || 0) + (x[k] || 0); return acc; }, { id: "\0other", name: t("Other ({n})", { n: rest.length }) }); box.append(one(tot, "var(--faint)", true)); @@ -16746,10 +16771,10 @@ function renderLedgerDash(l) { meter.append(fill); hit.append(meter); // how fast the streamed replies wrote, and how long they took to begin (#860) - const speed = ledSpeed(l); - block("Output speed", speed ? t("{n} tok/s", { n: ledNum(Math.round(speed)) }) : "—", + const gs = ledGroupSpeed(l); + block("Output speed", gs ? gs.text : "—", line(ledTTFT(l) ? t("first token in {ms} on average", { ms: ledTook(ledTTFT(l)) }) : t("no streamed replies timed")), - "", t("Output tokens a second after the first, over the streamed replies") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it")); + "", [gs?.title, t("Output tokens a second after the first, over the streamed replies") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it")].filter(Boolean).join("\n")); drawLedTrend(); } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 2ecf6746b..4a4b9bf40 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3475,6 +3475,11 @@ const I18N = { "first token in {ms}": "{ms} 后首响", "first text in {ms}": "{ms} 后出现正文", "{n} tok/s": "{n} token/秒", + "{n} tok/s ({k})": "{n} token/秒({k} 次)", + "Measured on {k} reply, from its first token to its end; the others tell no speed": "实测 {k} 次回复:从首字到结束;其余请求测不出速度", + "Measured on {k} replies, from their first token to their end; the others tell no speed": "实测 {k} 次回复:从首字到结束;其余请求测不出速度", + "At least: {k} reply read from a session file, which has no first token, so the wait for it is counted too": "下限:{k} 次读自会话文件的回复。会话文件没有首字时间,等首字的时间也算在里面", + "At least: {k} replies read from session files, which have no first token, so the wait for it is counted too": "下限:{k} 次读自会话文件的回复。会话文件没有首字时间,等首字的时间也算在里面", "requested {sent} · served {served}": "请求 {sent} · 实际 {served}", "served {served}": "实际 {served}", "Upstream: {upstream}": "上游:{upstream}", @@ -7685,6 +7690,11 @@ const I18N = { "first token in {ms}": "{ms} 後首響", "first text in {ms}": "{ms} 後出現正文", "{n} tok/s": "{n} token/秒", + "{n} tok/s ({k})": "{n} token/秒({k} 次)", + "Measured on {k} reply, from its first token to its end; the others tell no speed": "實測 {k} 次回覆:從首字到結束;其餘請求測不出速度", + "Measured on {k} replies, from their first token to their end; the others tell no speed": "實測 {k} 次回覆:從首字到結束;其餘請求測不出速度", + "At least: {k} reply read from a session file, which has no first token, so the wait for it is counted too": "下限:{k} 次讀自會話檔案的回覆。會話檔案沒有首字時間,等首字的時間也算在裡面", + "At least: {k} replies read from session files, which have no first token, so the wait for it is counted too": "下限:{k} 次讀自會話檔案的回覆。會話檔案沒有首字時間,等首字的時間也算在裡面", "requested {sent} · served {served}": "請求 {sent} · 實際 {served}", "served {served}": "實際 {served}", "Upstream: {upstream}": "上游:{upstream}", @@ -11909,6 +11919,11 @@ const I18N = { "first token in {ms}": "最初のトークンまで {ms}", "first text in {ms}": "最初のテキストまで {ms}", "{n} tok/s": "{n} トークン/秒", + "{n} tok/s ({k})": "{n} トークン/秒({k} 件)", + "Measured on {k} reply, from its first token to its end; the others tell no speed": "{k} 件の応答で実測:最初のトークンから終わりまで。ほかのリクエストは速度を計れません", + "Measured on {k} replies, from their first token to their end; the others tell no speed": "{k} 件の応答で実測:最初のトークンから終わりまで。ほかのリクエストは速度を計れません", + "At least: {k} reply read from a session file, which has no first token, so the wait for it is counted too": "下限:セッションファイルから読んだ {k} 件の応答。最初のトークンの時刻がないため、それを待つ時間も含まれます", + "At least: {k} replies read from session files, which have no first token, so the wait for it is counted too": "下限:セッションファイルから読んだ {k} 件の応答。最初のトークンの時刻がないため、それを待つ時間も含まれます", "requested {sent} · served {served}": "リクエスト {sent} · 応答 {served}", "served {served}": "応答 {served}", "Upstream: {upstream}": "上流:{upstream}", @@ -16136,6 +16151,11 @@ const I18N = { "first token in {ms}": "erstes Token nach {ms}", "first text in {ms}": "erster Text nach {ms}", "{n} tok/s": "{n} Token/s", + "{n} tok/s ({k})": "{n} Token/s ({k})", + "Measured on {k} reply, from its first token to its end; the others tell no speed": "Gemessen an {k} Antwort, vom ersten Token bis zum Ende; die übrigen Anfragen zeigen kein Tempo", + "Measured on {k} replies, from their first token to their end; the others tell no speed": "Gemessen an {k} Antworten, vom ersten Token bis zum Ende; die übrigen Anfragen zeigen kein Tempo", + "At least: {k} reply read from a session file, which has no first token, so the wait for it is counted too": "Mindestens: {k} Antwort aus einer Sitzungsdatei. Sie hat kein erstes Token, also zählt das Warten darauf mit", + "At least: {k} replies read from session files, which have no first token, so the wait for it is counted too": "Mindestens: {k} Antworten aus Sitzungsdateien. Sie haben kein erstes Token, also zählt das Warten darauf mit", "requested {sent} · served {served}": "angefragt {sent} · geliefert {served}", "served {served}": "geliefert {served}", "Upstream: {upstream}": "Upstream: {upstream}", diff --git a/internal/gui/tests/usage-speed-count.test.cjs b/internal/gui/tests/usage-speed-count.test.cjs new file mode 100644 index 000000000..8c801e1d2 --- /dev/null +++ b/internal/gui/tests/usage-speed-count.test.cjs @@ -0,0 +1,185 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// One rule for a group's speed, in the Usage page's ranking, its Output speed +// card and the overview's lists (Fallmonkey on Discord): gpt-6.1-sol showed a +// tok/s that was the one reply of its 260 calls that used no tool (the only +// Codex turn its session file times) beside "260 requests", while Claude +// Code, whose rows on the Requests tab say "≥100 tok/s" by the dozen, showed +// none. A group with replies whose speed was measured now says that speed and +// how many replies it is of, "125 tok/s (1)"; one with none, but floors, the +// least they wrote at, "≥100 tok/s (30)"; one with neither, nothing. The +// rows of the Requests tab say each one's the same way. Every language, a +// wide window and a narrow one; 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 at = (i) => new Date(now - (i + 1) * 60e3).toISOString(); + +const LOG = { in: 9000, cache_read: 0, cache_write: 0, status: 0, cost: 0, priced: false, source: "log", provider: "session-unknown", providerName: "Local session" }; +const SOL = { ...LOG, agent: "codex", agentName: "Codex", icon: "codex-color", model: "gpt-6.1-sol", req: "gpt-6.1-sol", served: "gpt-6.1-sol" }; +const CC = { ...LOG, agent: "claude", agentName: "Claude Code", icon: "claudecode-color", model: "claude-opus-5-5", req: "claude-opus-5-5", served: "claude-opus-5-5" }; +const ROWS = [ + // the one sol reply its session file timed: 500 tokens in the 4 s after its first + { ...SOL, t: at(0), out: 500, ms: 5000, ttft_ms: 1000 }, + // a sol call in a turn of several: no speed + { ...SOL, t: at(1), out: 1500, ms: 30000 }, + // a Claude Code reply: at least 2000 tokens in 20 s + { ...CC, t: at(2), out: 2000, ms: 20000 }, + // a short one tells nothing + { ...CC, t: at(3), out: 300, ms: 20000 }, +]; +// the groups as usage.Breakdown sums them (TestGroupSpeedSaysHowManyRepliesItIsOf) +const G = { + sol: { id: "gpt-6.1-sol", calls: 260, input: 2340000, output: 389000, cache_read: 0, cache_write: 0, cost: 0, timed: 1, ttft_ms: 1000, decode_ms: 4000, decode_out: 500, decode_n: 1 }, + cc: { id: "claude-opus-5-5", calls: 42, input: 210000, output: 64000, cache_read: 0, cache_write: 0, cost: 0, floor_out: 60000, floor_ms: 600000, floor_n: 30 }, + none: { id: "glm-5", calls: 12, input: 1000, output: 100, cache_read: 0, cache_write: 0, cost: 0 }, +}; +const SUM = ["calls", "input", "output", "timed", "ttft_ms", "decode_ms", "decode_out", "decode_n", "floor_out", "floor_ms", "floor_n"]; + +function ledger(period, model) { + const groups = model ? [G[Object.keys(G).find((k) => G[k].id === model)]] : [G.sol, G.cc, G.none]; + const tot = {}; + for (const k of SUM) tot[k] = groups.reduce((a, x) => a + (x[k] || 0), 0); + const rows = model ? ROWS.filter((r) => r.model === model) : ROWS; + return { + period, rows, offset: 0, total: rows.length, errors: 0, cache_read: 0, cache_write: 0, cost: 0, unpriced: 0, ...tot, + by: { model: groups }, bucket: "hour", series: [], + agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }, { id: "codex", name: "Codex", icon: "codex-color" }], + }; +} + +const USAGE = { + calls: 262, errors: 0, input: 1, output: 1, reasoning: 0, unpriced: 0, cost: 0, bucket: "day", series: [], path: "", + agents: [{ ...G.sol, id: "codex", name: "Codex", icon: "codex-color" }, { ...G.none, id: "opencode", name: "OpenCode" }], + models: [G.sol, G.none], +}; + +const STATE = (lang) => ({ + agents: [ + { id: "claude", name: "Claude Code", path: "/t/c.json", icon: "claudecode-color", wired: true, fields: [] }, + { id: "codex", name: "Codex", path: "/t/c.toml", icon: "codex-color", wired: true, fields: [] }, + ], + profiles: [], settings: { lang, theme: "light" }, fx: { rate: 7.2, at: new Date().toISOString() }, +}); + +function server(lang) { + return async (route) => { + const url = new URL(route.request().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(STATE(lang)); + if (url.pathname === "/api/usage/requests") return json(ledger(url.searchParams.get("period"), url.searchParams.get("model"))); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/usage") return json(USAGE); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], models: [], gateway: { running: false } }); + 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: { speed: "Speed", kpi: "Output speed", sol: "125 tok/s (1)", cc: "≥100 tok/s (30)", row: "125 tok/s", rowFloor: "≥100 tok/s", + solTip: "Measured on 1 reply, from its first token to its end; the others tell no speed", + ccTip: "At least: 30 replies read from session files, which have no first token, so the wait for it is counted too" }, + zh: { speed: "速度", kpi: "输出速度", sol: "125 token/秒(1 次)", cc: "≥100 token/秒(30 次)", row: "125 token/秒", rowFloor: "≥100 token/秒", + solTip: "实测 1 次回复:从首字到结束;其余请求测不出速度", + ccTip: "下限:30 次读自会话文件的回复。会话文件没有首字时间,等首字的时间也算在里面" }, + "zh-TW": { speed: "速度", kpi: null, sol: "125 token/秒(1 次)", cc: "≥100 token/秒(30 次)", row: "125 token/秒", rowFloor: "≥100 token/秒", + solTip: "實測 1 次回覆:從首字到結束;其餘請求測不出速度", + ccTip: "下限:30 次讀自會話檔案的回覆。會話檔案沒有首字時間,等首字的時間也算在裡面" }, + ja: { speed: null, kpi: null, sol: "125 トークン/秒(1 件)", cc: "≥100 トークン/秒(30 件)", row: "125 トークン/秒", rowFloor: "≥100 トークン/秒", + solTip: "1 件の応答で実測:最初のトークンから終わりまで。ほかのリクエストは速度を計れません", + ccTip: "下限:セッションファイルから読んだ 30 件の応答。最初のトークンの時刻がないため、それを待つ時間も含まれます" }, + de: { speed: null, kpi: null, sol: "125 Token/s (1)", cc: "≥100 Token/s (30)", row: "125 Token/s", rowFloor: "≥100 Token/s", + solTip: "Gemessen an 1 Antwort, vom ersten Token bis zum Ende; die übrigen Anfragen zeigen kein Tempo", + ccTip: "Mindestens: 30 Antworten aus Sitzungsdateien. Sie haben kein erstes Token, also zählt das Warten darauf mit" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a group's speed says how many replies it is of, and a floor says ≥", 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 Object.keys(L)) { + for (const width of [1400, 560]) { + const w = L[lang]; + await t.test(lang + " " + width, async () => { + const errors = []; + const ctx = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" }); + const p = await ctx.newPage(); + p.setDefaultTimeout(5000); + p.on("pageerror", (e) => errors.push(e.message)); + await p.route("**/*", server(lang)); + await p.goto("http://magpie.test/"); + await p.locator('[data-view="usage"]').first().click(); + + // the overview's lists: the measured speed and how many it is of + const codex = p.locator("#usageAgents .row.stat").first().locator(".sub"); + await codex.waitFor(); + assert((await codex.textContent()).includes(w.sol), "overview: " + (await codex.textContent())); + assert(!(await p.locator("#usageAgents .row.stat").nth(1).locator(".sub").textContent()).includes("/"), "a group with no speed says none"); + + await p.locator("#usageTab .opt").nth(1).click(); + await p.locator("#ledWrap .led tbody tr").first().waitFor(); + await p.waitForTimeout(200); + + // the rows say each one's: measured, and at least + const cell = (i) => p.locator(".led tbody tr.led-row").nth(i).locator("td.speed"); + assert.equal((await cell(0).textContent()).trim(), w.row); + assert.equal((await cell(1).textContent()).trim(), "—"); + assert.equal((await cell(2).textContent()).trim(), w.rowFloor); + + // the ranking, by tokens: each group's speed beside its requests + const rk = (id) => p.locator("#ledRank .rk").filter({ has: p.locator(".rk-nm", { hasText: id }) }); + const speedOf = async (id) => (await rk(id).locator(".rk-speed").count()) ? (await rk(id).locator(".rk-speed").textContent()).trim() : ""; + assert.equal(await speedOf("gpt-6.1-sol"), w.sol); + assert.equal(await rk("gpt-6.1-sol").locator(".rk-speed").getAttribute("title"), w.solTip); + assert.equal(await speedOf("claude-opus-5-5"), w.cc); + assert.equal(await rk("claude-opus-5-5").locator(".rk-speed").getAttribute("title"), w.ccTip); + assert.equal(await speedOf("glm-5"), "", "no speed, nothing said"); + + // the period's speed: sol's measured one, with its count + const kpi = p.locator("#ledKpi .blk").nth(4); + assert.equal((await kpi.locator(".v").textContent()).trim(), w.sol); + assert((await kpi.getAttribute("title")).startsWith(w.solTip), "the card says what it is of"); + if (w.kpi) assert.equal((await kpi.locator(".k").textContent()).trim(), w.kpi); + assert(await kpi.locator(".v").evaluate((v) => v.scrollWidth <= v.clientWidth + 1), "the card's figure is read whole"); + + // the ranking by speed: what each row says, ordered by it, the floor's bar its floor + await reader.click(p, p.locator("#ledMetric .opt").nth(3)); + await p.waitForTimeout(150); + const vals = await p.locator("#ledRank .rk").evaluateAll((bs) => bs.map((b) => [b.querySelector(".rk-nm").textContent, b.querySelector(".rk-val").textContent.trim(), b.querySelector(".rk-val").title])); + assert.deepEqual(vals, [["gpt-6.1-sol", w.sol, w.solTip], ["claude-opus-5-5", w.cc, w.ccTip], ["glm-5", "—", ""]]); + const bar = async (i) => p.locator("#ledRank .rk").nth(i).locator(".rk-bar i").evaluate((e) => parseFloat(e.style.width)); + assert.equal(await bar(0), 100); + assert.equal(await bar(1), 80, "≥100 against 125"); + const clipped = await p.locator("#ledRank .rk-val").evaluateAll((vs) => vs.filter((v) => v.scrollWidth > v.clientWidth + 1).length); + assert.equal(clipped, 0, "every figure is read whole"); + + // Claude Code's model alone: only floors, so the period's speed is at least + await reader.click(p, rk("claude-opus-5-5")); + await p.waitForFunction(() => document.querySelectorAll(".led tbody tr.led-row").length === 2); + await p.waitForTimeout(150); + assert.equal((await p.locator("#ledKpi .blk").nth(4).locator(".v").textContent()).trim(), w.cc); + assert((await p.locator("#ledKpi .blk").nth(4).getAttribute("title")).startsWith(w.ccTip)); + + // no sideways scroll of the page + assert(await p.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), "no sideways scroll"); + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + } + }); +} diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go index a2ec853a7..d5c442c4f 100644 --- a/internal/usage/ledger.go +++ b/internal/usage/ledger.go @@ -606,8 +606,14 @@ func (t *Totals) addRow(r Row) { if n, w := r.Decode(); w > 0 { t.DecodeMs += w t.DecodeOut += n + t.DecodeN++ } } + if n, ms := r.Floor(); ms > 0 { + t.FloorOut += n + t.FloorMs += ms + t.FloorN++ + } t.Calls++ if r.Failed() { t.Errors++ @@ -626,6 +632,33 @@ func (t *Totals) addRow(r Row) { } } +// FloorAgents are the agents whose session files time a call from the line +// that asked for it, written before it was sent, to its reply's last +// (Claude Code's, Claude Desktop's): their calls' tokens over that time are +// a floor of how fast the reply wrote. A Codex call in a turn of several can +// be timed from inside the call, and OpenCode's isn't checked against real +// sessions, so they tell none. app.js's LED_FLOOR_AGENTS has the same. +var FloorAgents = map[string]bool{"claude": true, "claude-desktop": true} + +// Floor is the tokens and ms a row read from a session file tells the least +// its reply wrote at by, when its speed wasn't measured: its output over its +// whole time, the wait for the first token in it, for a reply of 1,000 +// tokens or more over a second or more (a shorter one's wait is too much of +// it to tell anything) and no faster than MaxDecodeSpeed. 0, 0 when it +// tells none. app.js's ledFloorSpeed is the same rule for one row. +func (r Row) Floor() (tokens int, ms int64) { + if r.Source != "log" || !FloorAgents[r.Agent] || r.Failed() { + return 0, 0 + } + if _, w := r.Decode(); w > 0 { + return 0, 0 + } + if r.Output < 1000 || r.Millis < 1000 || int64(r.Output)*1000 > MaxDecodeSpeed*r.Millis { + return 0, 0 + } + return r.Output, r.Millis +} + // Dimensions are what calls are told apart by: the provider they went to, // the agent that made them, the model, and the model at the provider it // went to ("modelAt"), so one model's speed at each provider can be compared diff --git a/internal/usage/speed_count_test.go b/internal/usage/speed_count_test.go new file mode 100644 index 000000000..905c2c561 --- /dev/null +++ b/internal/usage/speed_count_test.go @@ -0,0 +1,74 @@ +package usage + +import ( + "testing" + "time" +) + +// A group's speed says how many replies it is of, and a group none of whose +// replies was measured says the least they wrote at (Fallmonkey on Discord: +// gpt-6.1-sol showed a tok/s from the one reply of 260 that called no tool, +// beside "260 requests", while Claude Code, with dozens of floors on the +// Requests tab, showed none). Breakdown and the sums count the measured +// replies (DecodeN) and the floors (FloorOut over FloorMs, FloorN) apart. +func TestGroupSpeedSaysHowManyRepliesItIsOf(t *testing.T) { + at := time.Date(2026, 10, 11, 9, 0, 0, 0, time.UTC) + var rows []Row + // sol: 260 Codex calls read from its session files; only a turn of one + // call is timed, 500 tokens over the 4 s after the first, 125 tok/s + for i := 0; i < 260; i++ { + r := Row{Source: "log", Record: Record{Time: at, Agent: "codex", Model: "gpt-6.1-sol", Input: 9000, Output: 1500, Millis: 30000}} + if i == 0 { + r.Output, r.Millis, r.TTFT = 500, 5000, 1000 + } + rows = append(rows, r) + } + // Claude Code: 40 calls from its session file, none timed; 30 wrote + // 2,000 tokens over 20 s (a floor of 100 tok/s), 10 are too short to tell + for i := 0; i < 40; i++ { + r := Row{Source: "log", Record: Record{Time: at, Agent: "claude", Model: "claude-opus-5-5", Input: 5000, Output: 2000, Millis: 20000}} + if i >= 30 { + r.Output = 300 + } + rows = append(rows, r) + } + // a failed Claude Code call and one through the gateway tell no floor + rows = append(rows, + Row{Source: "log", Record: Record{Time: at, Agent: "claude", Model: "claude-opus-5-5", Output: 2000, Millis: 20000, Error: "overloaded"}}, + Row{Record: Record{Time: at, Agent: "claude", Model: "claude-opus-5-5", Output: 2000, Millis: 20000, Status: 200}}, + ) + by := map[string]Share{} + for _, s := range Breakdown(rows, "agent") { + by[s.ID] = s + } + sol := by["codex"] + if sol.Calls != 260 || sol.DecodeN != 1 || sol.Speed() != 125 || sol.FloorN != 0 || sol.Floor() != 0 { + t.Fatalf("sol: %d calls, %d measured at %v tok/s, %d floors at %v; want 260, 1 at 125, none", sol.Calls, sol.DecodeN, sol.Speed(), sol.FloorN, sol.Floor()) + } + cc := by["claude"] + if cc.Calls != 42 || cc.DecodeN != 0 || cc.Speed() != 0 || cc.FloorN != 30 || cc.FloorOut != 60000 || cc.FloorMs != 600000 || cc.Floor() != 100 { + t.Fatalf("Claude Code: %d calls, %d measured at %v, %d floors %d/%d ms at %v; want 42, none, 30 at 100", cc.Calls, cc.DecodeN, cc.Speed(), cc.FloorN, cc.FloorOut, cc.FloorMs, cc.Floor()) + } + // the page's own sums count both the same way + var sum Totals + for _, r := range rows { + sum.addRow(r) + } + if sum.DecodeN != 1 || sum.FloorN != 30 || sum.Speed() != 125 { + t.Fatalf("sum: %+v", sum) + } + // a timed Claude Code row tells its own speed, not a floor + timed := Row{Source: "log", Record: Record{Agent: "claude", Output: 2000, Millis: 20000, TTFT: 4000}} + if n, ms := timed.Floor(); ms != 0 || n != 0 { + t.Fatalf("timed row's floor %d/%d", n, ms) + } + // records through the gateway count their measured replies too + recs := []Record{ + {Time: at, Provider: "openai", Model: "gpt-6.1-sol", Output: 1200, Millis: 15000, TTFT: 3000, Status: 200}, + {Time: at, Provider: "openai", Model: "gpt-6.1-sol", Output: 1200, Millis: 15000, Status: 200}, + } + m := summarize(Today, at.Add(time.Hour), recs).Models[0] + if m.Calls != 2 || m.DecodeN != 1 || m.Speed() != 100 { + t.Fatalf("summarized: %+v", m.Totals) + } +} diff --git a/internal/usage/usage.go b/internal/usage/usage.go index 1169b1344..27a444079 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -321,6 +321,17 @@ type Totals struct { TTFT int64 `json:"ttft_ms,omitempty"` DecodeMs int64 `json:"decode_ms,omitempty"` DecodeOut int `json:"decode_out,omitempty"` + // DecodeN is how many replies DecodeMs and DecodeOut are of: the ones + // whose speed was measured, which a speed is shown with, so a group of + // 260 calls whose speed is one reply's says so (Fallmonkey on Discord) + DecodeN int `json:"decode_n,omitempty"` + // FloorOut tokens over FloorMs are the least FloorN replies read from a + // session file wrote at, those with no first token (Row.Floor): what a + // group none of whose replies was measured shows, as "≥", beside how + // many it is of. They are never in Speed. + FloorOut int `json:"floor_out,omitempty"` + FloorMs int64 `json:"floor_ms,omitempty"` + FloorN int `json:"floor_n,omitempty"` } // Tokens is what went in and out, excluding cache traffic. @@ -343,6 +354,15 @@ func (t Totals) Speed() float64 { return float64(t.DecodeOut) / (float64(t.DecodeMs) / 1000) } +// Floor is the least the replies with no first token wrote at, in tokens a +// second over their whole time (Row.Floor): 0 for none. +func (t Totals) Floor() float64 { + if t.FloorMs <= 0 { + return 0 + } + return float64(t.FloorOut) / (float64(t.FloorMs) / 1000) +} + // A reply's speed is its output tokens over its decode window, the ms // from its first content to its end (#196; one that reasoned, DecodeOf); a window counts only when it // timed the writing (#731). One that is shorter than MinDecodeMs, or over @@ -478,6 +498,7 @@ func (t *Totals) add(r Record, price *catalog.Price) { if n, w := r.Decode(); w > 0 { t.DecodeMs += w t.DecodeOut += n + t.DecodeN++ } } if r.Input+r.Output == 0 {