Files
magpie/internal/gui/tests/usage-ledger-mcp.test.cjs
T
yetone 1bbaded622 usage: an agent's call to magpie's own MCP tools is a row of Requests
ferock (Discord) asked to see calls to magpie's MCP tools, such as
magpie-image's generate_image, generate_video and generation_result, in
Routing > Requests.

Each tools/call to magpie's own MCP servers (image, vision, web search,
tools and the Library hub) is now a row of the request log. The row has
Source and Kind "mcp", the tool as its model, the server as its host,
how long the call took, and its error if it failed. The provider and
model it shows are those of the model requests the call made, collected
through the request's context in appendUsage. generation_result names
the model of the job it answers. The stdio Magpie Image server reports
each call it answered to the gateway as "magpie/toolCalled". That report
carries the tool, ms, model and error, never the prompt.

The arguments are never stored at all, so there is nothing to mask. The
rows go down the probe lane: they are listed, but no total, host list,
budget or key limit counts them. The model requests a call made are rows
of their own.

In the GUI the row reuses the Requests list. It gets a muted "MCP" badge
with a tooltip, the server beside the provider, and a Succeeded/Failed
status. The Purpose filter gains "MCP tool" in every language. There is
no new page, no <select> and no left border.

The core scripts went over their budget with the new purpose.
genpurposes now writes purposes.js as compact JSON, which makes the core
448 bytes smaller than main in all, and coreScriptBudget is lowered to
the new total, 1,538,975. No room is added.

Run on mote, at the rebased head:
- gofmt -l: clean. go vet -tags nogui ./... with GOOS darwin, linux
  and windows: ok.
- go test -tags nogui -timeout 45m: ./internal/usage, ./internal/imagemcp,
  ./internal/usageapi and ./internal/gui ok. internal/budget has no test
  files. ./internal/gateway (805s): every test ok except five Antigravity
  and Codex/Grok tests. They fail the same on a clean origin/main
  3bebc3839 and are filed as #4362.
- GUI, the usage-ledger*, routing-request*, purpose*, i18n* and
  gui-zh/ja/de files (25). On mote, Chromium: 32 of 32 ok; WebKit
  could not launch (10 other sessions' suites on mote). On Linux
  (wsl-run), both engines: 335 of 355 ok. The 20 reds are
  routing-request-model, usage-ledger, -ttft, -chart and
  -open-settled, which fail the same at the parent 1534474c8 (#4120).
  usage-ledger-mcp, purpose-filter and i18n-keys are ok in both.
  The whole GUI suite runs after the push, and each red it finds gets
  an issue.
- At the pushed head, rebased on 0804f2d97: ./internal/gui (the
  budget and purpose asset tests among them), ./internal/usage,
  ./internal/imagemcp and ./internal/usageapi ok, and ./internal/gateway
  -run "MCP|Purpose|Probe" ok.
- usage-ledger-mcp.test.cjs covers 5 languages, widths 1180 and 420,
  light and dark, with no sideways scroll.

Broken by hand. Each break went red:
- sawHost's MCP skip removed: TestMCPCallRowsListedNotCounted (the hosts
  list had magpie-image).
- Row/Record.IsProbe's MCP case removed: the same test (3 calls counted),
  and TestMCPCallCountsInNoKeyLimit (Calls: 1).
- The callMCPTool hook removed: TestMCPToolCallIsARequestRow and its
  siblings (no rows).
- The appendUsage hook removed: the row had no provider or model.
- imagemcp's report removed: TestToolCallsAreReported.
- The gateway's magpie/toolCalled case removed:
  TestMCPCalledFromStdioIsARow.
budget's in-memory counts() now skips these rows too. Breaking only that
stays green, because budget.Of reads the file through usage.Visit, which
already skips probes, and limits count tokens and cost.

Not tried:
- no real agent calling a real vendor's drawing;
- no test run on Windows or Linux;
- the page not checked in the real app or in WebKitGTK.
A generate call that answers while its drawing still runs has no model on
its row. The generation_result row that follows names it.
2026-10-30 15:00:16 +08:00

124 lines
8.0 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// An agent's call to a tool of magpie's own MCP servers (ferock on
// Discord) is a row of the Requests tab: an "MCP" badge, the tool's name
// as the model asked for, the server it is of beside the provider, the
// model it used, how long it took and whether it worked; its tooltip says
// its arguments are not kept and it counts nowhere. The Purpose filter
// names it. In every language, Chromium and WebKit, wide and narrow,
// light and dark; 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 assets = path.resolve(__dirname, "../assets");
const tot = (calls, tokens, cost) => ({ calls, errors: 0, input: tokens * 0.2, output: tokens * 0.1, cache_write: 0, cache_read: tokens * 0.7, cost });
const ROW = { t: new Date().toISOString(), agent: "claude", agentName: "Claude Code", icon: "claudecode-color", provider: "anthropic", providerName: "Claude", model: "claude-sonnet-5", in: 2, out: 600, cache_write: 0, cache_read: 3900, ms: 2380, status: 200, cost: 0.08, priced: true };
const MCP = { ...ROW, provider: "art", providerName: "Art", model: "gpt-image-1", req: "generate_image", host: "magpie-image", in: 0, out: 0, cache_read: 0, ms: 8400, status: 0, cost: 0, priced: false, source: "mcp", kind: "mcp", endpoint: "/v1/magpie/mcp/image" };
const FAILED = { ...MCP, t: new Date(Date.now() - 60000).toISOString(), provider: "", providerName: "", model: "", req: "github__create_issue", host: "github", ms: 40, err: "github is down" };
function page(q, called) {
const rows = [ROW, ...(called ? [MCP, FAILED] : [])];
return {
period: "today", rows, offset: 0, total: rows.length, ...tot(1, 4500, 0.08), reasoning: 0, unpriced: 0,
bucket: "hour", series: [], by: { provider: [], agent: [], model: [] },
agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }], providers: [{ id: "anthropic", name: "Claude", icon: "claudecode-color" }],
through: tot(1, 4500, 0.08), direct: tot(0, 0, 0), purposes: called ? ["kind:mcp", "unmarked"] : ["unmarked"],
};
}
function server(lang, theme, called, asked) {
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:"${theme}",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 }, fx: { rate: 7.2, at: new Date().toISOString() } });
if (url.pathname === "/api/usage/requests") { asked.push(url.searchParams); return json(page(url.searchParams, called)); }
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/usage") return json({ calls: 1, errors: 0, input: 1, output: 1, cache_read: 0, cache_write: 0, reasoning: 0, unpriced: 0, cost: 1, 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 });
};
}
// the purpose's name, a word of the tooltip that says it counts nowhere,
// and the status words
const L = {
en: { purpose: "MCP tool", why: "not counted in any total", ok: "Succeeded", bad: "Failed" },
zh: { purpose: "MCP 工具", why: "不计入任何汇总", ok: "成功", bad: "失败" },
"zh-TW": { purpose: "MCP 工具", why: "不計入任何彙總", ok: "成功", bad: "失敗" },
ja: { purpose: "MCP ツール", why: "どの合計にも数えません", ok: "成功", bad: "失敗" },
de: { purpose: "MCP-Tool", why: "zählt in keiner Summe", ok: "Erfolgreich", bad: "Fehlgeschlagen" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": an MCP tool call is a row of its own", 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());
const shots = process.env.ARTIFACT_DIR;
if (shots) await fs.mkdir(shots, { recursive: true });
const open = async (lang, { theme = "light", width = 1180, called = true } = {}) => {
const errors = [], asked = [];
const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" });
t.after(() => context.close());
const p = await context.newPage();
p.setDefaultTimeout(5000);
p.on("pageerror", (e) => errors.push(e.message));
await p.route("**/*", server(lang, theme, called, asked));
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("#ledVia .blk").first().waitFor();
return { p, errors };
};
for (const lang of Object.keys(L)) {
const w = L[lang];
for (const width of [1180, 420]) {
await t.test(`${lang} at ${width}`, async () => {
const { p, errors } = await open(lang, { width, theme: width < 600 ? "dark" : "light" });
const badge = p.locator(".led .src.mcp");
await badge.first().waitFor();
assert.equal(await badge.count(), 2);
assert.equal(await badge.first().textContent(), "MCP");
const why = await badge.first().getAttribute("title");
assert(why.includes(w.why) && why.includes("generate_image") && why.includes("magpie-image") && why.includes("Claude Code"), why);
// the model row has none, and neither is a probe
assert.equal(await p.locator(".led .src.probe").count(), 0);
const drawn = p.locator(".led tr.led-row", { has: p.locator(".src.mcp") }).first();
const text = await drawn.textContent();
assert(text.includes("generate_image") && text.includes("gpt-image-1") && text.includes("magpie-image"), text);
const failed = p.locator(".led tr.led-row", { hasText: "github__create_issue" });
{
assert((await drawn.locator(".st").textContent()).startsWith(w.ok));
assert((await failed.locator(".st").textContent()).startsWith(w.bad));
}
// the purpose picker names it in the page's language
assert.equal(await p.evaluate(() => purposeOptions(["kind:mcp"], "")[0].name), w.purpose);
// no coloured stripe down its side, and the page doesn't scroll sideways
assert(parseFloat(await badge.first().evaluate((b) => getComputedStyle(b).borderLeftWidth)) <= 1);
assert(await p.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), "no sideways scroll");
if (shots) await p.screenshot({ path: path.join(shots, `mcp-${engine}-${lang}-${width}.png`) });
assert.deepEqual(errors, []);
});
}
}
await t.test("no MCP call: no badge", async () => {
const { p, errors } = await open("en", { called: false });
await p.locator(".led tr", { hasText: "claude-sonnet-5" }).first().waitFor();
assert.equal(await p.locator(".led .src.mcp").count(), 0);
assert.deepEqual(errors, []);
});
});
}