Files
magpie/internal/gui/tests/cache-hit-pct.test.cjs
T
yetone 67f24d7422 usage: every cache hit rate to two decimals, its exact share on hover; a speed's dash says why
shangyuan0818 on X: in Usage › Requests the ranking's model hit rates
had no decimals or one ("98%" beside "99.6%"), the request table mixed
them too, and hovering showed no exact value.

- hitPct gives every hit rate two decimals (98.00%, 99.60%), the same
  in the ranking, the request table and its details, the Cache hit
  rate card, the cache-read tiles, the model and agent rows, Sessions,
  the tray panel, Routing's rows, figures and group averages, and the
  context window's Prompt cache. It still never says 100.00% or 0.00%
  of a prompt not all or none cached (99.99%, 0.01%).
- Each of them has the exact share on hover, in its title (hitTip):
  "9,800 of 10,000 prompt tokens read from the cache: 98%", the share
  to six places with no trailing zeros. One new string, translated in
  zh, zh-TW, ja and de.

ohblue on X: 速度 shows "—" for many 200 requests (491 in, 93 out,
first token 6.3s, total 6.4s), "≥133 token/秒" for others.

- That speed can't honestly be counted: 93 tokens in the 120ms after a
  6.3s wait would read ~775 tok/s, which is a reply written during the
  wait and let go at once (ledHeldShort_). The dash already had its
  reason as a title, but nothing showed it was there. It now has the
  help cursor (the cache column's dash too), the Speed column's head
  says what a speed is on hover, and a request's details say "— " and
  the reason in words, for a reader who can't hover.

Budget: app.js and the core grew by my hitTip, cacheHitTip and the
titles. To stay inside both budgets with no raise, setQuotaRange moved
to plugins/usage/page.js and PLACEHOLDER to plugins/redact/page.js (each
read by that page alone), cacheHitOf and cacheHitTip share cachePrompt,
and hitPct is one expression. Core 1,272,578 of 1,272,581; app.js
1,087,887 of 1,088,248.

Run on mote/mica, this change on origin/main, both engines, every
language, at the widths each file covers:
- usage-hit-exact.test.cjs (new): green. Red with the old hitPct
  ('hit rate 98%') and red with the help cursor and the details' line
  taken out ('pointer' !== 'help').
- 85 GUI files (every test that reads a hit rate, quota range or
  masking, Usage, Routing, i18n-keys, gui-ja/de/zh-tw): 1318 pass, 30
  fail. All 30 are red alike without this change, and all are filed:
  agent-menu-label webkit panel (#6371), zcode-models webkit de
  (#6566), quota-credits (#6807), quota-curve (#6789), usage-fold's
  17 subscriptions (#3415, #6003), usage-ledger (#4078, #3104, #4626),
  usage-ledger-chart (#6790). usage-fold's 'several accounts' went red
  only under the 85-file run and passes alone on this tree (#3415,
  commented).
- go test ./internal/gui on mica: ok (TestCoreScriptBudget included).
- Red alike on a HEAD checkout without this change, already filed:
  usage-ledger "newest live route needs no return-to-live button"
  (#4078, #3104, #4626), usage-ledger-chart "the metric is remembered"
  (#6790).

Not run before the push: the whole GUI suite and go test ./... (both
machines had other sessions' full suites running); they run after it
and their result goes on record. Not tried: Windows WebView2, the
reporters' own ledgers, the real app.
2026-11-18 16:14:52 +08:00

77 lines
5.1 KiB
JavaScript

// A cache hit rate never reads 100% unless every prompt token came from the
// cache (ZhangXiaof48473 on X: Codex gpt-6.1-sol requests of 77.5K tokens
// read "缓存 100%" on Routing's request list beside "缓存 99%"). Where
// rounding would say 100.00% or 0.00% of a prompt not all or none cached,
// the rate reads 99.99% or 0.01%. Every rate has two decimals, alike down a
// list (shangyuan0818 on X: "98%" beside "99.6%"), and its exact share on
// hover. One formatter (hitPct) says every hit rate. No backend: the API
// is faked here.
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 assets = path.resolve(__dirname, "../assets");
const now = new Date();
const seat = { id: "codex", provider: "codex", name: "Codex", who: "test@example.com", kind: "account", model: "gpt-6.1-sol" };
function req(id, input, read) {
const time = new Date(now.getTime() - (20 - id) * 60e3).toISOString();
return { id, seq: id, time, agent: "codex", session: "cache-pct", model: "codex/gpt-6.1-sol", provider: "codex",
order: [seat], tries: [{ id: seat.id, model: seat.model, start: time, done: true, status: 200, ms: 11000, ttft: 7000 }],
done: true, status: 200, ms: 11000, ttft: 7000, tokens: input + read + 400, out: 400,
usage: [{ provider: seat.provider, model: seat.model, in: input, out: 400, cache_read: read, cache_write: 0 }], priced: true, cost: 0.01 };
}
// newest first: 77,200 of 77,500 read (99.61%), all read, 77,035 of 77,500 (99.4%)
const fixtures = [req(3, 300, 77200), req(2, 0, 77500), req(1, 465, 77035)];
function serve(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:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", fields: [] }], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.has("wait")) return new Promise(() => {});
return json({ mine: true, now: now.toISOString(), seq: 3, totals: { requests: fixtures.length, rerouted: 0, errors: 0 }, routes: fixtures });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, window: true } });
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404 }); }
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
test(`${engine} ${lang}: a cache hit rate reads 100% only when all of the prompt was cached`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, reducedMotion: "reduce" });
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang));
await page.goto("http://magpie.test/?view=routing");
const rows = page.locator(".rt-req");
await rows.nth(fixtures.length - 1).waitFor();
assert.deepEqual(await rows.locator(".cache-hit .v").allTextContents(), ["99.61%", "100.00%", "99.40%"]);
await rows.nth(0).click();
assert.match(await page.locator(".rt-steps").textContent(), lang === "zh" ? /请求缓存命中率 99\.61%/ : /request cache hit rate 99\.61%/);
// every caller's shared formatter, at its edges
const got = await page.evaluate(() => [1, 0, 0.6, 0.994, 0.9995, 0.99999, 0.003, 0.0004, 1e-7, 0.873, 0.99996].map((h) => hitPct(h)));
assert.deepEqual(got, ["100.00%", "0.00%", "60.00%", "99.40%", "99.95%", "99.99%", "0.30%", "0.04%", "0.01%", "87.30%", "99.99%"]);
// the exact share on hover
const title = await rows.nth(0).locator(".cache-hit").getAttribute("title");
const tip = await page.evaluate(() => t("{a} of {b} prompt tokens read from the cache: {p}", { a: ledNum(77200), b: ledNum(77500), p: +(100 * 77200 / 77500).toFixed(6) + "%" }));
assert(title.startsWith(tip), title);
assert.deepEqual(errors, []);
});
}
}