gui: a filter a click set on Usage's Requests goes when they are left (TJHHHH on Discord)

TJHHHH: after a jump to Codex's requests on the Usage page, every later
visit listed only Codex's. The Requests' filters are module state in
plugins/usage/page.js and nothing ever reset them, so a click on Codex in
the ranking split by agent stuck for the app's lifetime.

Now a filter a click lent the Requests (a ranking click on an agent,
provider, model or gateway key, a chart day, the address's ?agent= and
the like, a route from Routing) is remembered in ledLent and given back
by ledLeave when the reader leaves the Requests: for another Usage tab
(renderUsageTab), or another page through a new page hook, `leave`, that
show() calls on the page it leaves. A filter picked in its own menu or
typed in the search stays, as a menu choice does in a Mac app. A route's
saved filters keep their lent marks, and leaving with a route on gives
back the route too. Docs: plugin-runtime.md's Usage hooks.

Siblings judged and left: the tray panel's Usage tab ranking (its own
view, not the page's Requests), the Sessions reveal (per agent, no "all"), the KPI
failed/retried jumps (shown in the status segment, read as own picks).

Test: tests/usage-ledger-leave.test.cjs, chromium and webkit, en zh
zh-TW ja de: ranking click leaves for a page and for a tab, menu pick
stays, ?agent= goes, a route goes. On the old app.js/page.js/client.js
it is red, 20 of 25 in chromium ("back from another page: last asked
period=today&agent=codex"); only the menu-pick case passes there.
Green with the fix, in both engines.

Run at 5b267fbd8 (load 200-400):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok.
- go test -timeout 45m ./...: 60 ok; internal/agent, gateway, library
  past 45m (#2544, #2870, #2853), internal/gui
  TestSetAnswersWhileDevinAndProvidersHang 13s (#1375). All filed, none
  touch these files.
- Whole GUI suite (node --test --test-concurrency=4, both engines):
  i18n-keys was red on my comment saying "View usage" (routing's word);
  reworded, i18n-keys green. codex-auto-reset, codex-auto-reset-settings
  and codex-predictions red in the full run; rerun alone: codex-auto-reset 20/20 and codex-auto-reset-settings 22/22
  green (load); codex-predictions 7 of 20 red at 420px, the same as
  #2624 on main. usage-ledger-leave 52/52 alone. The whole suite was
  still running at commit time (load ~400); its reds so far are these.
This commit is contained in:
yetone
2026-10-19 21:59:40 +08:00
parent be6a74f13e
commit f73378365f
5 changed files with 229 additions and 16 deletions
+6 -1
View File
@@ -150,7 +150,12 @@ says one of its words, which goes back to i18n.js.
it, `refresh(again)` is `load()`'s read of it (coming back to the
Overview is opening the allowances, #1588), `reload` is Refresh now,
`costs` draws the costs again when Settings' currency changes, and
`tab` says which tab it is on, for `focusQuotaCard`. Still in app.js,
`tab` says which tab it is on, for `focusQuotaCard`, and `leave`, which
`show()` calls on the page it leaves, gives back what a click lent the
Requests (`ledLeave`, TJHHHH on Discord): a filter a ranking or chart
click set, or one brought in by the address or Routing's View usage,
goes when the reader leaves the Requests for another page or tab. One
picked in its own menu or typed stays. Still in app.js,
since the tray panel draws them too: the allowance cards,
`quotasOpened`, `panelQuotaFocus` and `panelUseFocus`. With the plugin
off, its nav tab goes, and so do the ways to the page
+3
View File
@@ -22633,6 +22633,9 @@ async function show(v) {
if (!(await confirmDiscard())) return false;
magpie.call("library", "discard");
}
// the page left lets go of what was only for this visit (the Usage
// page's Requests, what a click filtered them by)
magpie.call(view, "leave");
}
view = v;
// the page the reader leaves is the one the window opens on next (keptView)
@@ -137,5 +137,8 @@ magpie.plugin("usage", (ctx) => {
reload() { return refreshUsage(true); },
costs() { renderCosts(); },
tab() { return usageTab; },
// the reader goes to another page: the Requests give back what a
// click lent them (ledLeave)
leave() { if (usageTab === "requests") ledLeave(); },
});
});
+65 -15
View File
@@ -631,19 +631,65 @@ try {
if (["tokens", "cost", "calls", "speed"].includes(m)) ledMetric = m;
} catch {}
// The filters a click set for the reader rather than one they picked in a
// filter's menu: someone in the chart's ranking or a day of its columns
// ("a click lists only theirs"), or a way in from elsewhere (the tray
// panel's Open Usage, a route Routing sent here). They last while the
// Requests are looked at, and go when the reader leaves them, for another
// tab or page (TJHHHH on Discord: a click on Codex in the ranking had
// every later visit list only Codex's requests). A filter picked in its
// menu stays, as one picked in a Mac app's does.
const ledLent = new Set();
const LED_UNLEND = {
agent: () => { ledAgent = ""; },
provider: () => { ledProvider = ""; },
model: () => { ledModel = ""; ledQuery = ""; $("#ledQ").value = ""; },
callerKey: () => { ledCallerKey = ""; },
day: () => { ledDay = ""; },
purpose: () => { ledPurpose = ""; },
computer: () => { ledComputer = ""; },
via: () => { ledVia = ""; },
};
// the reader picked this filter themselves: it stays
const ledOwn = (k) => ledLent.delete(k);
let ledRouteInfo = null, ledBeforeRoute = null;
window.openUsageRoute = (route) => {
if (!ledBeforeRoute) ledBeforeRoute = { period, ledOffset, ledPurpose, ledAgent, ledProvider, ledAccount, ledCallerKey, ledFailed, ledRetried, ledQuery, ledModel, ledComputer, ledDay, ledVia };
if (!ledBeforeRoute) ledBeforeRoute = { period, ledOffset, ledPurpose, ledAgent, ledProvider, ledAccount, ledCallerKey, ledFailed, ledRetried, ledQuery, ledModel, ledComputer, ledDay, ledVia, lent: [...ledLent] };
ledRoute = route.id;
ledRouteInfo = route;
ledOffset = 0; ledPurpose = ""; ledAgent = ""; ledProvider = ""; ledAccount = ""; ledCallerKey = ""; ledFailed = false; ledRetried = false; ledQuery = ""; ledModel = ""; ledComputer = ""; ledVia = "";
ledDay = "";
ledLent.clear();
$("#ledQ").value = "";
period = "all";
usageTab = "requests";
ledger = null;
show("usage");
};
// the one request a route from Routing listed gives way to the list as it
// was before it
function ledRouteOff() {
ledRoute = 0; ledRouteInfo = null;
if (ledBeforeRoute) {
({ period, ledOffset, ledPurpose = "", ledAgent, ledProvider, ledAccount = "", ledCallerKey, ledFailed, ledRetried = false, ledQuery, ledModel, ledComputer = "", ledDay = "", ledVia = "" } = ledBeforeRoute);
ledLent.clear();
for (const k of ledBeforeRoute.lent || []) ledLent.add(k);
}
ledBeforeRoute = null;
$("#ledQ").value = ledQuery;
}
// ledLeave: the reader leaves the Requests; what a click lent them goes
// (the rows drawn for them aren't shown again on the way back)
function ledLeave() {
const routed = !!ledRoute;
if (routed) ledRouteOff();
if (!ledLent.size && !routed) return;
for (const k of ledLent) LED_UNLEND[k]();
ledLent.clear();
ledOffset = 0;
ledger = null;
}
function ledParams(extra) {
const q = new URLSearchParams({ period });
@@ -1094,6 +1140,7 @@ function drawLedTrend() {
const chart = $("#ledChart"), rank = $("#ledRank");
drawLedColumns(chart, l, ledSplit, ledMetric, false, (day) => {
ledDay = ledDay === day ? "" : day;
ledLent.add("day");
ledOffset = 0;
loadLedger().catch((e) => status(e.message, "err"));
});
@@ -1109,10 +1156,11 @@ function drawLedTrend() {
ledProvider = off ? "" : x.id.slice(0, cut);
ledModel = off ? "" : x.id.slice(cut + 1);
ledQuery = ledModel; q.value = ledQuery;
} else if (ledSplit === "provider") ledProvider = ledProvider === x.id ? "" : x.id;
else if (ledSplit === "agent") ledAgent = ledAgent === x.id ? "" : x.id;
else if (ledSplit === "callerKey") ledCallerKey = ledCallerKey === x.id ? "" : x.id;
else { const q = $("#ledQ"); ledModel = ledModel === x.id ? "" : x.id; ledQuery = ledModel; q.value = ledQuery; }
ledLent.add("provider").add("model");
} else if (ledSplit === "provider") { ledProvider = ledProvider === x.id ? "" : x.id; ledLent.add("provider"); }
else if (ledSplit === "agent") { ledAgent = ledAgent === x.id ? "" : x.id; ledLent.add("agent"); }
else if (ledSplit === "callerKey") { ledCallerKey = ledCallerKey === x.id ? "" : x.id; ledLent.add("callerKey"); }
else { const q = $("#ledQ"); ledModel = ledModel === x.id ? "" : x.id; ledQuery = ledModel; q.value = ledQuery; ledLent.add("model"); }
ledOffset = 0;
loadLedger().catch((e) => status(e.message, "err"));
}, false);
@@ -1463,15 +1511,15 @@ function renderLedger() {
costHead(fmtCost(l), l.unpriced ? unpricedCalls(l.unpriced) : "", unpricedCallsWhy(l.unpriced));
// the filters: choices seen in the period, and failures alone
sessPick($("#ledPurpose"), "All purposes", ledPurpose, purposeOptions(l.purposes || [], ledPurpose), "Purpose", (v) => { ledPurpose = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
sessPick($("#ledPurpose"), "All purposes", ledPurpose, purposeOptions(l.purposes || [], ledPurpose), "Purpose", (v) => { ledPurpose = v; ledOwn("purpose"); ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
$("#ledPurpose").title = t("Purpose");
sessPick($("#ledComputer"), "All computers", ledComputer, computers, "Computer", (v) => { ledComputer = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
sessPick($("#ledAgent"), "All agents", ledAgent, l.agents.map((a) => ({ v: a.id, name: a.name, note: "" })), "Agent", (v) => { ledAgent = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
sessPick($("#ledProvider"), "All providers", ledProvider, providers.map((p) => ({ v: p.id, name: t(p.name), note: "" })), "Provider", (v) => { ledProvider = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
sessPick($("#ledComputer"), "All computers", ledComputer, computers, "Computer", (v) => { ledComputer = v; ledOwn("computer"); ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
sessPick($("#ledAgent"), "All agents", ledAgent, l.agents.map((a) => ({ v: a.id, name: a.name, note: "" })), "Agent", (v) => { ledAgent = v; ledOwn("agent"); ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
sessPick($("#ledProvider"), "All providers", ledProvider, providers.map((p) => ({ v: p.id, name: t(p.name), note: "" })), "Provider", (v) => { ledProvider = v; ledOwn("provider"); ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
sessPick($("#ledAccount"), "All accounts", ledAccount, accounts.map((a) => ({ v: a.id, name: a.id, note: (a.providers || []).map((p) => t(p)).join(" · ") })), "Account", (v) => { ledAccount = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
sessPick($("#ledKey"), "All gateway keys", ledCallerKey, callers.map((k) => ({
v: k.id, name: k.name, note: "",
})).concat(noKey ? [{ v: "none", name: t("No gateway key"), note: "" }] : []), "Gateway keys", (v) => { ledCallerKey = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
})).concat(noKey ? [{ v: "none", name: t("No gateway key"), note: "" }] : []), "Gateway keys", (v) => { ledCallerKey = v; ledOwn("callerKey"); ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); });
const seg = $("#ledStatus");
seg.replaceChildren();
// every request, those the agent got an error for, and those answered
@@ -1529,6 +1577,7 @@ function renderLedger() {
const next = ledVia === pick ? "" : pick;
if (next === ledVia) return;
ledVia = next;
ledOwn("via");
ledOffset = 0;
loadLedger().catch((e) => status(e.message, "err"));
};
@@ -1561,10 +1610,7 @@ function renderLedger() {
$("#ledRouteClear").title = t("Clear filter");
$("#ledRouteClear").setAttribute("aria-label", t("Clear filter"));
$("#ledRouteClear").onclick = () => {
ledRoute = 0; ledRouteInfo = null;
if (ledBeforeRoute) ({ period, ledOffset, ledPurpose = "", ledAgent, ledProvider, ledAccount = "", ledCallerKey, ledFailed, ledRetried = false, ledQuery, ledModel, ledComputer = "", ledDay = "", ledVia = "" } = ledBeforeRoute);
ledBeforeRoute = null;
$("#ledQ").value = ledQuery;
ledRouteOff();
loadLedger().catch((e) => status(e.message, "err"));
};
renderLedgerDash(l);
@@ -1754,11 +1800,12 @@ function renderLedger() {
$("#ledQ").oninput = (e) => {
ledQuery = e.target.value;
ledModel = "";
ledOwn("model");
clearTimeout(typing);
typing = setTimeout(() => { ledOffset = 0; loadLedger().catch((err) => status(err.message, "err")); }, 250);
};
$("#ledQ").onkeydown = (e) => {
if (e.key === "Escape" && e.target.value) { e.stopPropagation(); e.target.value = ""; ledQuery = ""; ledModel = ""; ledOffset = 0; loadLedger().catch((err) => status(err.message, "err")); }
if (e.key === "Escape" && e.target.value) { e.stopPropagation(); e.target.value = ""; ledQuery = ""; ledModel = ""; ledOwn("model"); ledOffset = 0; loadLedger().catch((err) => status(err.message, "err")); }
};
$("#ledExport").onclick = async () => {
const b = $("#ledExport");
@@ -1846,6 +1893,7 @@ function renderUsageTab() {
const b = el("button", "opt" + (id === usageTab ? " on" : ""), t(name));
b.onclick = () => {
if (id === usageTab) return;
if (usageTab === "requests") ledLeave();
usageTab = id;
try { localStorage.setItem("magpie.usageTab", id); } catch {}
$("#usageCost").replaceChildren();
@@ -3218,6 +3266,8 @@ if (mode === "window" && params.get("view") === "usage") {
ledComputer = params.get("computer") || "";
const v = params.get("via") || "";
ledVia = v === "through" || v === "direct" || v === "reported" ? v : "";
// a way in, not the reader's pick: they go once the Requests are left
for (const [k, x] of [["provider", ledProvider], ["agent", ledAgent], ["purpose", ledPurpose], ["computer", ledComputer], ["via", ledVia]]) if (x) ledLent.add(k);
const u = new URL(location.href);
for (const k of ["tab", "provider", "agent", "computer", "card", "purpose", "via", "period"]) u.searchParams.delete(k);
history.replaceState(null, "", u);
@@ -0,0 +1,152 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// What a click filtered the Requests by goes when the reader leaves them
// (TJHHHH on Discord): a click on Codex in the ranking split by agent, a
// click on a chart's day, a filter brought from elsewhere (the URL, a
// route from Routing) is for that visit. Off to another page or another
// Usage tab and back, the Requests are of all agents again. An agent picked
// in its own menu stays, as a choice made in a menu does. In every
// language, Chromium and WebKit; 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 { click } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const now = Date.now();
const ROW = { t: new Date(now).toISOString(), agent: "codex", agentName: "Codex", icon: "codex-color", provider: "openai", providerName: "OpenAI", req: "gpt-5.5", model: "gpt-5.5", in: 2, out: 600, cache_write: 0, cache_read: 0, ms: 2380, status: 200, cost: 0.08, priced: true };
const ROWS = [ROW, { ...ROW, t: new Date(now - 60000).toISOString(), agent: "claude", agentName: "Claude Code", icon: "claudecode-color", req: "claude-sonnet-5", model: "claude-sonnet-5" }];
const AGENTS = [{ id: "codex", name: "Codex", icon: "codex-color" }, { id: "claude", name: "Claude Code", icon: "claudecode-color" }];
const by = (k) => ({ id: k.id, name: k.name, icon: k.icon, calls: 1, input: 2, output: 600, cache_read: 0, cache_write: 0, cost: 0.08 });
function server(lang, 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:"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") {
asked.push(url.searchParams);
const agent = url.searchParams.get("agent") || "";
const rows = ROWS.filter((r) => !agent || r.agent === agent);
return json({
period: "today", rows, offset: 0, total: rows.length, calls: rows.length, errors: 0, input: 4, output: 1200, cache_write: 0, cache_read: 0, cost: 0.16, reasoning: 0, unpriced: 0,
bucket: "hour", series: [], by: { provider: [], agent: AGENTS.map(by), model: [] },
agents: AGENTS, providers: [{ id: "openai", name: "OpenAI", icon: "openai" }],
});
}
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 newest ask for the Requests satisfies want
async function lastAsked(p, asked, want, what) {
for (let i = 0; i < 100; i++) {
const q = asked[asked.length - 1];
if (q && want(q)) return;
await p.waitForTimeout(50);
}
assert.fail(what + ": last asked " + String(asked[asked.length - 1]));
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a filter a click set on the Requests goes when they are left", 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", "zh-TW", "ja", "de"]) {
const open = async (q = "") => {
const asked = [], errors = [];
const context = await browser.newContext({ viewport: { width: 1100, 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, asked));
await p.goto("http://magpie.test/?view=usage&tab=requests" + q);
await p.locator("table.led tbody tr.led-row").first().waitFor();
return { p, asked, errors };
};
// the Usage tabs are in the sidebar under the page's name, or on the
// page itself where the sidebar has none
const tabAt = (p, id) => p.evaluate((id) => USAGE_TABS.findIndex(([x]) => x === id), id).then((i) => p.locator(":is(#usageTab .opt, .nav-s):visible").nth(i));
// away to the Agents page and back to the Usage page's Requests
const awayByPage = async (p) => {
await p.locator('#nav button[data-view="agents"]').click();
await p.locator("#view-agents").waitFor();
await p.locator('#nav button[data-view="usage"]').click();
};
// away to the Overview tab and back
const awayByTab = async (p) => {
await (await tabAt(p, "usage")).click();
await (await tabAt(p, "requests")).click();
};
const allAgents = async (p, asked, what) => {
await lastAsked(p, asked, (q) => !q.has("agent") && !q.has("route"), what);
await p.locator("table.led tbody tr.led-row").nth(1).waitFor();
assert.equal(await p.locator("#ledAgent").evaluate((b) => b.classList.contains("set")), false, what + ": the agent menu says all agents");
};
for (const [how, away] of [["another page", awayByPage], ["another tab", awayByTab]]) {
await t.test(`${lang}: a ranking click on Codex goes on leaving for ${how}`, async () => {
const { p, asked, errors } = await open();
await click(p, p.locator("#ledSplit .opt").nth(3));
await click(p, p.locator("#ledRank .rk", { hasText: "Codex" }));
await lastAsked(p, asked, (q) => q.get("agent") === "codex", "the click lists Codex's requests");
await away(p);
await allAgents(p, asked, "back from " + how);
assert.equal(await p.locator("#view-usage select").count(), 0);
assert.deepEqual(errors, []);
});
}
await t.test(`${lang}: Codex picked in the agent menu stays`, async () => {
const { p, asked, errors } = await open();
await click(p, p.locator("#ledAgent"));
await p.locator(".sess-menu .pm-item", { hasText: "Codex" }).click();
await lastAsked(p, asked, (q) => q.get("agent") === "codex", "the pick lists Codex's requests");
await awayByPage(p);
await lastAsked(p, asked, (q) => q.get("agent") === "codex", "the pick is still there back on the page");
await awayByTab(p);
await lastAsked(p, asked, (q) => q.get("agent") === "codex", "the pick is still there back on the tab");
assert.equal(await p.locator("#ledAgent").evaluate((b) => b.classList.contains("set")), true);
// a ranking click on the one picked doesn't make the pick a loan
await click(p, p.locator("#ledSplit .opt").nth(3));
await awayByPage(p);
await lastAsked(p, asked, (q) => q.get("agent") === "codex", "the pick outlives a change of split");
assert.deepEqual(errors, []);
});
await t.test(`${lang}: an agent brought in the address goes on leaving`, async () => {
const { p, asked, errors } = await open("&agent=codex");
await lastAsked(p, asked, (q) => q.get("agent") === "codex", "the address lists Codex's requests");
await awayByPage(p);
await allAgents(p, asked, "back from another page");
assert.deepEqual(errors, []);
});
await t.test(`${lang}: a route from Routing goes on leaving, and what it set aside with it`, async () => {
const { p, asked, errors } = await open();
await click(p, p.locator("#ledSplit .opt").nth(3));
await click(p, p.locator("#ledRank .rk", { hasText: "Codex" }));
await lastAsked(p, asked, (q) => q.get("agent") === "codex", "the click lists Codex's requests");
await p.evaluate(() => window.openUsageRoute({ id: 123, time: new Date().toISOString(), model: "gpt-5.5" }));
await lastAsked(p, asked, (q) => q.get("route") === "123", "the route is listed");
await awayByPage(p);
await allAgents(p, asked, "back from another page");
assert.equal(await p.locator("#ledRouteClear").isVisible().catch(() => false), false, "no route is left to clear");
assert.deepEqual(errors, []);
});
}
});
}