Files
magpie/internal/gui/tests/usage-ledger-detail.test.cjs
T
yetone 8fba65d0bc gateway: what masking took a request is kept, and shown as Masking in its time
fremontdango on Discord asked, after the request that sat as "routing…"
while it was masked, how long masking took. Now each request keeps it.

noteRedacting adds up the time from the first masking at once to the
last's end (redaction.spent); maskingMs gives it in ms, at least 1 when
there was any, never more than Own, magpie's own time before the request
went out (splitSent), since masking happens inside it. It goes on the
route (Route.Masking, /api/gateway/trace) and in the usage record
(Record.Masking, masking_ms; packedRow's int32 fits in its padding, so
TestRowsOfOneSessionShareAShape's 216 bytes are unchanged, and the
process-private snapshot carries it). It is a duration, no text.

The Routing page shows it as magpie's "Masking" part, first in where the
first try's time went (timeParts, renderSteps); the Usage page's detail
splits it out of "In magpie" (page.js). Both use the core "Masking"
string every language already has (脱敏, 脫敏, マスク, Maskierung).

Why masking can be slow, measured on this machine (go1.27, M-series):
the rules are linear, ~0.25 ms/KB. redact.MaskJSON over a Claude Code
shaped body: 283 KB 35 ms (secrets) / 63 ms (+ personal data); 511 KB
70 / 122 ms; a dense 402 KB with 7,821 hits 173 ms with personal data,
144 ms with the user's words too. Through the gateway (redactedHits,
secrets + personal, 402 KB dense) 145 ms the first time, 123 ms again;
noteMasked ~2.6 ms. Doubling the body doubles the time; nothing
quadratic or repeated per hit. So a request held "routing…" for 15 s or
more (unroutedShow) while masked is the local model (Settings → Privacy
→ Find with a local model, internal/pii): it reads each text it hasn't
seen (a new turn's tool results are the misses), one model turn at a
time, so requests queue behind each other (#3682: 480 KB took 90 s on an
RX 470/580). No change to masking's speed here; the phase and the time
now say which it was.

Run at this head, on origin/main 9ae791221 (Go, M-series macOS):
- go test -timeout 45m ./internal/gateway ./internal/gui ./internal/redact
  ./internal/usage: ok (gateway 425s, gui 99s); ./internal/masking and
  ./internal/pii ok at the pre-rebase head 3a4a13d04
- gofmt -l internal: clean; go vet ./..., GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean; go build: ok
- go test -race -count=3 TestMaskingIsAPhaseWithItsTime,
  TestNoMaskingNoMaskingTime: ok
- GUI, chromium and webkit: routing-masking (every language) 10/10,
  usage-ledger-detail 6/6, i18n-keys and routing-levels green. The whole
  routing-*, panel-routing*, usage-ledger* and i18n-keys set: 1,824
  tests, 96 red at load ~47, in 15 files. The first run's i18n-keys red
  was this change's (a Go comment quoting the core word), fixed in the
  commit before. The other 14 files, rerun two at a time at this head
  and at origin/main 9ae791221: the same files red on both (89 here, 86
  there; routing-rule-remove alone 5 red here, 7 on main). Each has an
  issue: #2115, #3410, #3411, #1905, #3593, #3408, #3096, #3094, #3001,
  #3104, #3786.

Broken by hand, each red: spent not added (route and record Masking 0),
no t.Masking on the route, no Masking in the usage record, the snapshot's
put/take of Masking (TestRowsOfOneSessionShareAShape), timeParts without
Masking or renderSteps without the first try's masking
(routing-masking), the Usage page without the Masking line
(usage-ledger-detail, 3 red).

Not tried: a real local model (Settings → Privacy → Find with a local
model) on the reporter's Windows box or any GPU, so a long masking was
only held by a fake masker; the Codex backend's usage record has no
Masking yet; the Windows test box wasn't used.

Reported by fremontdango on Discord.
2026-10-27 08:08:23 +08:00

222 lines
17 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// The Usage page's Requests says how a request went and what is known of it:
// a failure the gateway logged shows its status and the vendor's error type in
// the row, and what the vendor said when the row is opened, with the request's
// id and endpoint, and what a call that isn't a turn of the conversation
// was for (a subagent's, #714); a call read from an agent's session file is marked "session
// log", says only that it went well ("Succeeded") or the error that ended it,
// and says in its details that the file records no status. A click on a row
// opens and closes its details without moving the page, the keyboard does the
// same, text selected in them is not a click, and a row stays open when the list
// refreshes. English and Chinese; 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 ROWS = [
// the gateway's: a failure the vendor explained
{ t: new Date(now - 60e3).toISOString(), agent: "codex", agentName: "Codex", icon: "codex-color", provider: "relay", providerName: "Relay", host: "team", req: "sol", model: "gpt-6-sol", in: 0, out: 0, ms: 610, status: 429, err: "Relay: slow down, please", err_type: "rate_limit_error", rid: "req_011abc", ep: "/v1/responses", session: "019a2b", cost: 0, priced: false },
// the gateway's: answered, with the id and the protocol it was turned into
{ t: new Date(now - 120e3).toISOString(), agent: "claude", agentName: "Claude Code", icon: "claudecode-color", provider: "relay", providerName: "Relay", host: "team", req: "sonnet", model: "sonnet", served: "sonnet", in: 300, out: 40, ms: 2380, ttft_ms: 700, sent_ms: 40, status: 200, kind: "collab_spawn", rid: "chatcmpl-77", ep: "/v1/messages → /v1/chat/completions", cost: 0.01, priced: true },
// a session file's: nothing went wrong
{ t: new Date(now - 180e3).toISOString(), agent: "claude-desktop", agentName: "Claude Desktop", icon: "claude-color", provider: "claude", providerName: "Claude", req: "claude-opus-5[1m]", model: "claude-opus-5", served: "claude-opus-5", effort: "xhigh", ms: 4200, in: 1000, out: 200, cache_read: 4000, cache_write: 500, status: 0, rid: "req_log", session: "s2", session_account: "claude@example.com", source: "log", cost: 0.02, priced: true },
// a session file's: the error that ended the call
{ t: new Date(now - 240e3).toISOString(), agent: "claude-desktop", agentName: "Claude Desktop", icon: "claude-color", provider: "claude", providerName: "Claude", model: "", in: 0, out: 0, status: 0, err: "You've hit your limit · resets 3am", err_type: "rate_limit", rid: "req_lim", session: "s3", source: "log", cost: 0, priced: false },
// the gateway's, answered on its second try (#1532): the vendor held the
// first ~103 s before its 503, which isn't magpie's time
{ t: new Date(now - 300e3).toISOString(), agent: "codex", agentName: "Codex", icon: "codex-color", provider: "opencode-go", providerName: "OpenCode Go", host: "opencode.ai", req: "opencode-go/deepseek-flash", model: "deepseek-flash", served: "deepseek-flash", effort: "max", in: 7064, out: 5373, cache_read: 314624, reasoning: 4946, ms: 160000, ttft_ms: 141000, sent_ms: 104000, own_ms: 180, masking_ms: 150, retried_ms: 103000, tries: 2, status: 200, ep: "/backend-api/codex/responses", session: "01a12671", cost: 0.005, priced: true },
];
function page(q) {
let rows = ROWS;
if (q.get("failed") === "1") rows = rows.filter((r) => r.status >= 400 || r.err);
return {
period: q.get("period"), rows, offset: 0, total: rows.length, calls: rows.length, errors: 2,
input: 1300, output: 240, cache_read: 4000, cache_write: 500, reasoning: 0, cost: 0.03, unpriced: 0,
agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }, { id: "claude-desktop", name: "Claude Desktop", icon: "claude-color" }, { id: "codex", name: "Codex", icon: "codex-color" }],
};
}
function server(lang, refreshed) {
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") { refreshed.n++; return json(page(url.searchParams)); }
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/usage") return json({ calls: 4, errors: 2, input: 1300, output: 240, cache_read: 4000, cache_write: 500, 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: {
statuses: ["429 · rate_limit_error", "200", "Succeeded", "rate_limit", "200 · 2 tries"], badge: "Local session",
split: [["Masking", "150 ms"], ["In magpie", "30 ms"], ["Tries that failed first", "103 s"], ["Connecting and sending", "820 ms"], ["Vendor's first token", "37 s"]],
speed: "24 tok/s", tokens: "300 in · 40 out · 0 cache read · 0 cache creation", labels: { fail: ["Status", "Error type", "Upstream said", "Duration", "Request ID", "Endpoint", "Protocol", "Session ID"], ok: ["Status", "Duration", "Tokens", "Speed", "Request ID", "Endpoint", "Protocol", "Called for", "First token", "In magpie", "Vendor's first token"], log: ["Request ID", "Session ID", "Data source"], logFail: ["Status", "Error type", "Error", "Request ID", "Session ID", "Data source"] },
subagent: "Subagent",
noStatus: "Read from the agent's session file. The account is shown only when local metadata identifies it; no service provider is inferred.",
},
zh: {
statuses: ["429 · rate_limit_error", "200", "成功", "rate_limit", "200 · 2 次尝试"], badge: "本地会话",
split: [["脱敏", "150 毫秒"], ["magpie 内耗时", "30 毫秒"], ["之前失败的尝试", "103 秒"], ["连接并发送请求", "820 毫秒"], ["厂商首字等待", "37 秒"]],
speed: "24 token/秒", tokens: "输入 300 · 输出 40 · 缓存读取 0 · 缓存创建 0", labels: { fail: ["状态", "错误类型", "上游返回", "耗时", "请求 ID", "终结点", "协议", "会话 ID"], ok: ["状态", "耗时", "Token", "速度", "请求 ID", "终结点", "协议", "用途", "首字耗时", "magpie 内耗时", "厂商首字等待"], log: ["请求 ID", "会话 ID", "数据来源"], logFail: ["状态", "错误类型", "错误", "请求 ID", "会话 ID", "数据来源"] },
subagent: "子代理",
noStatus: "读自 Agent 的会话文件;仅在本地元数据能够明确识别时显示账号,不推断供应商。",
},
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": the Requests tab's details", 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"]) {
const w = L[lang];
await t.test(lang, async () => {
const errors = [], refreshed = { n: 0 };
const p = await (await browser.newContext({ viewport: { width: 1180, height: 640 }, reducedMotion: "reduce" })).newPage();
p.setDefaultTimeout(5000);
p.on("pageerror", (e) => errors.push(e.message));
await p.route("**/*", server(lang, refreshed));
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").first().waitFor();
const rows = p.locator(".led tbody tr.led-row");
assert.equal(await rows.count(), 5);
// how each went, in its row: the gateway's status and the vendor's error
// type; a session file's plain "Succeeded" or the error that ended it
const status = await rows.evaluateAll((trs) => trs.map((tr) => tr.querySelector(".st").textContent.trim()));
assert.deepEqual(status, w.statuses);
assert.deepEqual(await rows.evaluateAll((trs) => trs.map((tr) => tr.classList.contains("bad"))), [true, false, false, true, false]);
// a session file's time for a call is about (told from its lines' stamps); with none, a dash, not 0 ms
const cell = (n) => rows.nth(n).locator("td.duration").textContent();
assert.equal(await cell(2), lang === "zh" ? "≈4.2 秒" : "≈4.2 s", "about, from the file's times");
assert.equal(await cell(3), "—", "a call with no time is a dash");
assert.notEqual(await cell(0), "—");
assert(!(await cell(0)).startsWith("≈"), "the gateway's time is its own");
// the models and the effort: a session file names the model the API
// answered with (Claude Code's) in Served, has none of the gateway's
// "sent", and says the thinking effort; the gateway's row has its own
const cells = async (n) => rows.nth(n).locator("td").evaluateAll((tds) => tds.map((td) => td.textContent.trim()));
const logged = await cells(2), gateway = await cells(0);
assert.deepEqual([logged[2], logged[4], logged[5], logged[6]], ["claude-opus-5[1m]", "claude-opus-5", "claude-opus-5", "xhigh"], "a session file's models and effort");
assert.deepEqual([gateway[2], gateway[4]], ["sol", "gpt-6-sol"], "the gateway's model asked for and sent");
// only the session file's rows are marked as such; the gateway's say
// the protocol they were sent upstream in (a session file keeps no path)
const badge = (sel) => rows.evaluateAll((trs, sel) => trs.map((tr) => tr.querySelector(sel)?.textContent || ""), sel);
assert.deepEqual(await badge(".src.local"), ["", "", w.badge, "", ""]);
assert.deepEqual(await badge(".src.proto"), ["Responses", "Anthropic → Chat", "", "", "Responses"]);
assert.equal(await p.locator(".led tbody tr.led-detail").count(), 0, "closed to begin with");
const labels = async () => p.locator(".led tbody tr.led-detail dt:not(.lc-opt)").allTextContents();
const values = async () => p.locator(".led tbody tr.led-detail dd:not(.lc-opt)").allTextContents();
const top = async () => p.locator("#view-usage").evaluate((v) => v.scrollTop);
// scrolled by the wheel, as a reader does: the page puts back any scroll
// that no wheel, key or drag asked for
await p.mouse.move(600, 400);
await p.mouse.wheel(0, 30);
for (let i = 0; i < 40 && (await top()) < 30; i++) await p.waitForTimeout(25);
await p.waitForTimeout(300);
// the first row wholly in sight (a row with badges is two lines tall),
// so the click's own bringing it there isn't counted as the page moving
await reader.inView(p, rows.nth(0));
const before = await top();
assert(before > 0, "the page is long enough to scroll");
// a failure the gateway logged: what the vendor said, in the details
await reader.click(p, rows.nth(0));
assert.deepEqual(await labels(), w.labels.fail);
const v = await values();
assert.equal(v[0], "429");
assert.equal(v[1], "rate_limit_error");
assert.equal(v[2], "Relay: slow down, please");
assert.equal(v[4], "req_011abc");
assert.equal(v[5], "/v1/responses");
assert.equal(v[6], "Responses", "the protocol it was sent upstream in");
assert.equal(await rows.nth(0).getAttribute("aria-expanded"), "true");
assert.equal(await top(), before, "the click moved the page");
// the details sit under their row, and no row is pushed out of the table
assert.equal(await p.locator(".led tbody tr").nth(1).getAttribute("class"), "led-detail");
const box = await p.locator(".led-box").boundingBox(), wrap = await p.locator("#ledWrap").boundingBox();
assert(box.x >= wrap.x - 1 && box.x + box.width <= wrap.x + wrap.width + 1, "the details are within the table's box");
// the others: the id and the endpoint it was turned into; a session file's
await reader.click(p, rows.nth(0));
assert.equal(await p.locator(".led tbody tr.led-detail").count(), 0, "a second click closes it");
assert.equal(await top(), before);
await reader.click(p, rows.nth(1));
assert.deepEqual(await labels(), w.labels.ok);
// how it went and how long, which the row says only in its last columns (#799)
assert.deepEqual((await values()).slice(0, 2).map((v) => v.replace(/[^\d.]/g, "")), ["200", "2.4"]);
// how fast it wrote (#860)
// its tokens, the cache's beside in and out, though none was read (#1839)
assert.equal((await values())[2], w.tokens);
assert.equal((await values())[3], w.speed);
assert.deepEqual((await values()).slice(4, 8), ["chatcmpl-77", "/v1/messages → /v1/chat/completions", "Anthropic → Chat", w.subagent]);
// the first token split: magpie's own 40 ms, the vendor's 660 ms
assert.deepEqual((await values()).slice(9, 11).map((v) => v.match(/^\d+/)?.[0]), ["40", "660"]);
await reader.click(p, rows.nth(2));
assert.deepEqual(await p.locator(".led tbody tr.led-detail").count(), 2);
assert(!(await p.locator(".led-detail").nth(1).locator("dd.bad").count()), "a session file's success has nothing in red");
assert.equal((await p.locator(".led-detail").nth(1).locator("dd").last().textContent()), w.noStatus);
await reader.click(p, rows.nth(3));
assert.deepEqual(await p.locator(".led-detail").nth(2).locator("dt:not(.lc-opt)").allTextContents(), w.labels.logFail);
assert.equal(await p.locator(".led-detail").nth(2).locator("dd").nth(2).textContent(), "You've hit your limit · resets 3am");
// #1532: of the 104 s before the vendor had the request, magpie's own
// 180 ms, the try that failed first 103 s, connecting and sending the
// rest; the 40 ms of a record from before the split was kept stays
// "In magpie" (above). Of magpie's own, the 150 ms masking it took
// is told apart (fremontdango on Discord)
await reader.click(p, rows.nth(4));
const pairs = await p.locator(".led-detail").nth(3).evaluate((d) => [...d.querySelectorAll("dt")].map((dt) => [dt.textContent, dt.nextElementSibling.textContent]));
const at = pairs.findIndex(([k]) => k === w.split[0][0]);
assert.deepEqual(pairs.slice(at, at + w.split.length), w.split);
await reader.click(p, rows.nth(4));
// a refresh of the list keeps the rows open
const n = refreshed.n;
await reader.click(p, p.locator("#ledStatus .opt").nth(1)); // Failed: asks the server
for (let i = 0; i < 60 && refreshed.n === n; i++) await p.waitForTimeout(40);
await reader.click(p, p.locator("#ledStatus .opt").nth(0));
for (let i = 0; i < 60 && refreshed.n < n + 2; i++) await p.waitForTimeout(40);
await p.waitForTimeout(150);
assert.equal(await p.locator(".led tbody tr.led-detail").count(), 3, "the rows stayed open");
// the keyboard: focus a row, Enter closes it and Space opens it
await rows.nth(1).focus();
await p.keyboard.press("Enter");
assert.equal(await rows.nth(1).getAttribute("aria-expanded"), "false");
await p.keyboard.press("Space");
assert.equal(await rows.nth(1).getAttribute("aria-expanded"), "true");
// text selected in the details is the reader copying: not a click
await reader.inView(p,p.locator(".led-detail").first().locator("dd").first());
await p.locator(".led-detail").first().locator("dd").first().dblclick();
assert.equal(await p.locator(".led tbody tr.led-detail").count(), 3, "selecting text closed a row");
// no left-border stripe on a failed row
assert.equal(await rows.nth(0).locator("td").first().evaluate((td) => getComputedStyle(td).borderLeftWidth), "0px");
assert.deepEqual(errors, []);
});
}
});
}