Files
magpie/internal/gui/tests/usage-reads-note.test.cjs
T
yetone 5cf1d3846a sessions: an agent left off in the first "allow selected" is asked about once more, on Sessions and Usage › Requests
baysonfox on X: with magpie installed after Antigravity 2.0, the app's
sessions and calls made without magpie never showed in Usage, while agy
CLI's did. The first consent named the app off beside agy, and a named
agent was never "new" again, so nothing asked about it and nothing on
Usage said why. The reader is fine: the app's calls come from its own
SQLite steps (antigravityRead), read once allowed.

Nothing is turned on by magpie: the gate is the user's privacy choice.
Instead:
- settings.SessionReads gets Kept: agents turned off on their own (a
  sessions/reads post without `all`: Keep off, a Settings › Privacy row,
  `magpie sessions read off <agent>`). A post setting it on takes it out.
- readsNow's New: off, found here and not Kept (was: never named). So an
  agent left off in the first choice's list is asked about once more,
  as one found later already was.
- Usage › Requests shows a line above its rows for those agents
  (readsLater in the usage plugin): Count {names} / Don't count, the
  same {agents} posts as the Sessions page's laterCard. Gone after
  either answer; sessions/reads read at most once a minute.
- Old data: an agent turned off in Settings before Kept existed has no
  entry and is asked once more, for every user with such an agent.

Tests:
- TestSessionReadsUncheckedAgentAskedAgain (count, keep off): sandbox
  HOME with testdata/agy-sessions and the real Antigravity 2.30
  conversation (antigravity-2.30-tools); after the first choice the app
  is off and New, has no rows in /api/usage/requests; Count brings its
  rows in, Keep off keeps none, and neither is asked again. Red on the
  old code (New false after the first choice).
- TestSessionReadsTurnedOffNotAskedAgain: off on its own, under all true
  and all false, is neither on nor New.
- usage-reads-note.test.cjs: the Requests line in Chromium and WebKit,
  en/zh/zh-TW/ja/de at 900/420/390px, both answers, buttons inside the
  line, no sideways scroll; red on the old code (no #ledReads).

Run on mica (mote was full: load 40+, another GUI suite on it), rebased
on 389169f76:
- gofmt -l clean
- go vet on gui, sessions, settings, cli and tui; GOOS=linux -tags nogui
  and GOOS=windows vet on gui, sessions, settings and cli; go build ./...
- go test -count=1 -timeout 45m on internal/gui, sessions, settings, cli
  and tui: all ok except gui's TestGatewayModeListsNoOwnSessions, red
  the same on an untouched 389169f76 copy (#7064)
- GUI, both engines: usage-reads-note, sessions-reads, i18n-keys,
  i18n-en-no-cjk, usage-ledger, usage-request-page, usage-no-reading,
  usage-ledger-fit, ledger-hscroll, usage-phone-head, sessions-usage-off.
  Only usage-ledger's "newest live route needs no return-to-live button"
  was red (en, zh, both engines), red the same on the untouched
  389169f76 copy (#3104). i18n-keys first caught "Leave off" as otel's
  word; renamed to "Don't count".
- After rebasing on dc507aefd: gofmt, vet, the TestSessionReads tests
  and usage-reads-note, i18n-keys, i18n-en-no-cjk and sessions-reads
  again: all ok, 98 of 98 GUI tests.

Broken by hand: recording Kept on every off post (all sent too) turns
TestSessionReadsNewAgent, ...UncheckedAgentAskedAgain and
...TurnedOffNotAskedAgain red.

Not tried: the whole GUI suite (both machines had another GUI suite
running), the full go test ./..., and a real Antigravity 2.0 install
in the GUI; the live Antigravity data was not touched.
2026-11-18 20:59:55 +08:00

173 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Run with Node's test runner and Playwright on the module path; see README.md.
// simonzyzy on X: with no provider set up, Claude Code's and Codex's own
// sessions, tokens and speed seemed impossible. magpie reads no agent's
// session files until they are allowed (sessions/reads asked false), and an
// empty Usage page only told people to route an agent through the gateway.
// Now the Overview and the Requests page say the files aren't read yet and
// offer the one button that allows the agents found; once allowed (asked
// true) the note is gone. Chromium and WebKit, every language; API 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 found = () => [
{ agent: "claude", name: "Claude Code", icon: "claudecode-color", on: false },
{ agent: "codex", name: "Codex", icon: "codex-color", on: false },
];
const empty = { calls: 0, errors: 0, input: 0, output: 0, cache_read: 0, cache_write: 0, reasoning: 0, cost: 0, unpriced: 0, path: "/test/usage.jsonl", bucket: "day", series: [], agents: [], models: [] };
function serve(lang, store, posts) {
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: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: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/groups") return json({ groups: [], pools: [], models: [] });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, calls: [], groups: [] } });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/sessions/reads") {
if (req.method() === "POST") {
const b = req.postDataJSON();
posts.push(b);
store.asked = true;
if (store.later && "antigravity" in b.agents) store.app = b.agents.antigravity;
}
// later: asked, agy CLI read and the Antigravity app left off in
// that first choice, so it is new until answered (baysonfox on X)
if (store.later) return json({ asked: true, all: false, found: [
{ agent: "agy", name: "Antigravity CLI", icon: "antigravity-color", on: true },
{ agent: "antigravity", name: "Antigravity", icon: "antigravity-color", on: store.app === true, new: store.app === undefined },
] });
return json({ asked: store.asked, all: false, found: found() });
}
if (url.pathname === "/api/speeds") return json([]);
if (url.pathname === "/api/sessions/manage") {
const at = new Date(Date.now() - 300e3).toISOString();
return json({ agents: [{ agent: "claude", count: 1, deletable: true, name: "Claude Code", icon: "claudecode-color" }], agent: "claude", sessions: [{ agent: "claude", id: "c-1", cwd: "/work/app", title: "a chat", start: at, last: at, models: [], resume: "", path: "/x/c", size: 10, messages: 2, files: 1, deletable: true }], terminal: false, trash: [], trashDir: "", reads: { asked: true, all: true, found: found() } });
}
if (url.pathname === "/api/usage/requests") return json({ ...empty, rows: [], offset: 0, total: 0, by: { provider: [], agent: [], model: [] } });
if (url.pathname === "/api/usage") return json(empty);
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] });
if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} });
if (url.pathname.startsWith("/api/window/")) return route.fulfill({ status: 204 });
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 }); }
};
}
const ASK = "magpie reads no agent's session files until you allow it, so {names} calls aren't counted here yet.";
const LANGS = [["en", 900], ["zh", 420], ["zh-TW", 420], ["ja", 420], ["de", 390]];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const [lang, width] of LANGS) {
test(`${engine} ${lang} ${width}px: an empty Usage page says session files aren't read yet, and allows them`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(8000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const store = { asked: false }, posts = [];
await page.route("**/*", serve(lang, store, posts));
await page.goto("http://magpie.test/?view=usage");
const names = "Claude Code, Codex";
const ask = await page.evaluate(([s, n]) => t(s, { names: n }), [ASK, names.replace(", ", await page.evaluate(() => t(", ")))]);
if (lang !== "en") assert.notEqual(ask, ASK.replace("{names}", names), "translated");
// the Overview
const note = page.locator("#stats .reads-note");
await note.waitFor();
assert.equal(await note.locator("p").textContent(), ask);
// not worded as if a provider were needed
assert.ok(!/catalog model/i.test(await page.locator("#stats").textContent()));
const over = await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth);
assert.equal(over, false, "no sideways scroll");
// the Requests tab says the same
await page.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click();
await page.locator("#ledWrap .reads-note").waitFor();
assert.equal(await page.locator("#ledWrap .reads-note p").textContent(), ask);
assert.equal(posts.length, 0, "nothing allowed before the button");
await page.locator("#ledWrap .reads-note button").click();
await page.locator("#ledWrap .reads-note").waitFor({ state: "detached" });
assert.deepEqual(posts, [{ all: false, agents: { claude: true, codex: true } }]);
assert.deepEqual(errors, []);
});
}
}
// baysonfox on X: the Antigravity app was left off in the first choice
// beside agy CLI, and its calls made without magpie were counted nowhere,
// with nothing on Usage saying why. Requests says so above its rows and asks
// once: Count reads it, Don't count keeps it off; either way the line goes.
const LATER = "magpie doesn't read the session files of {names}, so their calls that didn't go through magpie aren't counted here.";
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const [lang, width] of LANGS) {
for (const on of [true, false]) {
test(`${engine} ${lang} ${width}px: Requests asks about an agent left off in the first choice (${on ? "Count" : "Don't count"})`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(8000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const store = { asked: true, later: true }, posts = [];
await page.route("**/*", serve(lang, store, posts));
await page.goto("http://magpie.test/?view=usage");
await page.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click();
const line = page.locator("#ledReads");
await line.locator("p").waitFor();
const want = await page.evaluate(([s]) => t(s, { names: "Antigravity" }), [LATER]);
if (lang !== "en") assert.notEqual(want, LATER.replace("{names}", "Antigravity"), "translated");
assert.equal(await line.locator("p").textContent(), want);
assert.equal(await line.getAttribute("role"), "group");
// the not-yet-asked note is not shown beside it
assert.equal(await page.locator("#ledWrap .reads-note").count(), 0);
// both buttons inside the line, nothing sideways
const box = await line.boundingBox();
for (const b of await line.locator("button").all()) {
const r = await b.boundingBox();
assert.ok(r.x >= box.x - 0.5 && r.x + r.width <= box.x + box.width + 0.5, "button inside the line");
}
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth), false, "no sideways scroll");
assert.equal(posts.length, 0, "nothing changed before an answer");
await line.locator("button").nth(on ? 1 : 0).click();
await line.waitFor({ state: "hidden" });
assert.deepEqual(posts, [{ agents: { antigravity: on } }]);
assert.deepEqual(errors, []);
});
}
}
}
const SPEED = "Live output speed is measured on requests that go through magpie's gateway. For agents that don't, each call's tokens and time are in Usage › Requests, read from their session files.";
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const [lang, width] of LANGS) {
test(`${engine} ${lang} ${width}px: Sessions say where the output speed is when none was measured`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(8000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, { asked: true }, []));
await page.goto("http://magpie.test/?view=sessions");
const note = page.locator("#view-sessions .sm-speed-note");
await note.waitFor();
const want = await page.evaluate((s) => t(s), SPEED);
if (lang !== "en") assert.notEqual(want, SPEED, "translated");
assert.equal(await note.textContent(), want);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth), false);
assert.deepEqual(errors, []);
});
}
}