gui: a client in the Usage page's Agents list can be hidden from it, and shown again from the line under it (ikunbots on X)

ikunbots asked to hide curl, Go-http-client, python-httpx and other clients
from the Agents list beside the agents they actually use.

What changed:
- Each Agents row has a "…" button that shows on hover (always on touch) and
  opens the app's row menu (openRowMenu) with "Hide from this list".
  Right-clicking the row opens the same menu. No native select.
- The hidden ids are saved by client id in settings.UsageAgentsHidden,
  trimmed and deduped. They go through POST /api/usage/arrange
  (agentsHidden), which changes only that field, and the Settings save
  carries the field over.
- Hiding is display only. The ledger keeps the calls, and the totals, the
  chart and every share still count them.
- When anything is hidden, a quiet "3 hidden" / "已隐藏 3 个" line sits under
  the list. It opens the hidden rows, dimmed, each with "Unhide" / "取消隐藏".
  No click scrolls the page: the scroll guard holds the clicked line in place.
- Where a pointer hovers, the "…" takes no room. Its margins give back its
  width and gap, so a row at rest is laid out as on main (mobile-web's
  desktop comparison is the same). It shows over the end of the share bar.
  On phones (body.web) it has its own grid column.
- Translated into zh, zh-TW, ja and de. docs/subsystems/gui-shell.md
  describes it.

What was run, in a worktree off origin/main:
- gofmt -l: clean.
- go build ./... and go vet ./...: pass.
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: pass.
- HOME=<scratch> go test -tags nogui ./...: 49 packages ok. Includes the new
  TestUsageArrangeAgentsHidden, which covers saving, surviving a settings
  save, narrowing and emptying.
- New usage-agents-hide.test.cjs: 32/32 in Chromium and WebKit. It covers
  en, zh, zh-TW, ja and de at 1200, 560 and 390 (web). It hides by "…" and
  by right-click, checks the POST body, unchanged totals and an unmoved
  page, then unhides, reloads and checks the hidden rows persist.
- All 48 usage, panel-arrange and click-scroll GUI files: 503/503.
  old-webkit and mobile-web: pass.
- Full GUI suite (6489 tests, concurrency 5): the reds outside this change
  fail the same when run alone on origin/main 3deb85685, in WebKit only.
  They are filed in #1672 and #1609, and in #1745 (new: group-member-info,
  searcher-pick).
- Broken by hand:
  - Without the hidden filter in renderUsage, the new GUI test fails 16/16
    in Chromium (the shown rows still list curl).
  - Without the arrange handler, TestUsageArrangeAgentsHidden fails at
    line 82.
  - Without the Settings-save carry-over, it fails at line 84.
This commit is contained in:
yetone
2026-10-12 14:56:28 +08:00
parent 6a8b2c6831
commit e21ea07e47
10 changed files with 386 additions and 8 deletions
+1
View File
@@ -154,6 +154,7 @@ retry after a failed read. See `TestRecentCallBodiesOnDemand` and
- A click never moves the page. Code scrolls a view only with the reader's event in hand (`scrollOnPurpose`); `click-scroll.test.cjs` guards this. A click is taken where the reader left the view: a scroll not theirs made just before it, whose scroll event the browser sends only at the next frame, after the click, is put back first (`backToReader` in the click guard, #1554).
- There are no native `<select>` elements and no colored left-border stripes. State is shown with a dot or a swatch.
- The Usage page's cards and the tray panel's Allowances tab share one order, `settings.UsageOrder` (`byUsageOrder`). In the panel a balance-only card stands where that order puts it, and balances next to each other share one *Balances* grid (`panelBalances`, #1510); none is gathered after the plans. The panel's *Arrange* (`panelArrange`) moves rows in it and hides subscriptions from that tab alone (`settings.PanelUsageHidden`); both save through `POST /api/usage/arrange`, which changes only the field it is sent, and the Settings save keeps both. Hiding is display only: a menu bar cell's card shows though hidden (`panelPeek`). See `TestUsageArrangePanelHidden`, `panel-arrange.test.cjs` and `panel-balance-order.test.cjs`.
- A client in the Usage page's Agents list can be hidden from that list (ikunbots on X): its row's "…" button or right-click opens the row menu with *Hide from this list*, saved by client id in `settings.UsageAgentsHidden` through the same `POST /api/usage/arrange` (`agentsHidden`), and kept by the Settings save. The ledger, the totals and the chart still count a hidden client. A quiet "{n} hidden" line under the list opens them, each with *Unhide* (`hideUsageAgent`). See `TestUsageArrangeAgentsHidden` and `usage-agents-hide.test.cjs`.
- Opening the allowances is asking to see them (#1588, `quotasOpened` in `app.js`): the Usage page from the nav or its Overview tab picked, the window brought back to the front on the Overview, the tray panel's Allowances tab picked or the panel brought up on it, and a menu bar cell clicked each load `usage/quotas?asked=1`, as Refresh now does. An asked read makes the backend read every account again (`AskClaudeUsage`), so an opening within 30s (`QUOTAS_OPEN_GAP`) of the last asked read sends an ordinary read instead, which joins one on its way; Refresh now always asks. A panel page loaded while it is put away (hidden, or without focus) doesn't ask. The timed refresh is unchanged and never asks. See `allowance-open-read.test.cjs`.
- The Usage page's cards are packed into columns, never all stretched to a row's height (`packUsage`, #860): each card in that order goes to the leftmost column that ends highest, on 1px grid rows, so short cards stack beside a tall one. The last card in each column then reaches down to where the tallest column ends (a `min-height`, cleared before the cards are measured again), so cards side by side in one row are as tall as each other and a stack ends with the tall card beside it (ikunbots on X); content stays at each card's top. The page's order (DOM, dragging, Alt+arrows) stays `UsageOrder`. The column count is the most 260px columns that fit, or one fewer when that leaves much less empty room; it is chosen again only when the cards change or the width fits another number of columns, so a card opened or folded stays where it is, even as the scrollbar comes in. See `usage-pack.test.cjs`.
- The Providers page has a search box over its list (#1614, `findProviders` in [`app.js`](../../internal/gui/assets/app.js)): the words typed keep the rows, on and off, whose text or data say them all: name, id, preset, addresses, every model's id and name, the account's user and plan and each login's, account names and key names. The Turned off fold stays open while searching; Escape or clearing the box shows every row and the fold as it was. A row that is on reorders by dragging its logo, Alt+↑/↓, Alt+Shift+↑/↓ (top, bottom) or its right-click menu (`openProviderMenu`: Move to top, Move up, Move down, Move to bottom). While searching, a step or a drop moves it among the rows shown (it takes the place of the row it passes, `stepProvider`, `shownToOn`) and the hidden ones keep their order; Move to top and Move to bottom go to the ends of the whole list. Every move saves the whole order through `POST /api/providers/arrange`. See `provider-find.test.cjs` and `provider-order.test.cjs`.
+10 -4
View File
@@ -1076,6 +1076,8 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
in.UsageOrder = cur.UsageOrder // the Usage page's, dragged there
// and what the tray panel's Allowances tab leaves out, set there
in.PanelUsageHidden = cur.PanelUsageHidden
// and the clients the Usage page's Agents list leaves out, set there
in.UsageAgentsHidden = cur.UsageAgentsHidden
// how agents' lists name models, set on its own for the agents to be told
in.PlainNames, in.PlainOwnNames = cur.PlainNames, cur.PlainOwnNames
in.CodexAgentsV1 = cur.CodexAgentsV1
@@ -1546,12 +1548,13 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
writeJSON(rw, settingsState())
})
// the Usage page's order of its cards, which the tray panel's Allowances
// tab follows, and what that tab leaves out, in magpie's settings; one
// not sent stays as it is
// tab follows, what that tab leaves out, and the clients the page's
// Agents list leaves out, in magpie's settings; one not sent stays as it is
mux.HandleFunc("POST /api/usage/arrange", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
Order *[]string
PanelHidden *[]string
Order *[]string
PanelHidden *[]string
AgentsHidden *[]string
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
@@ -1564,6 +1567,9 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
if in.PanelHidden != nil {
s.PanelUsageHidden = *in.PanelHidden
}
if in.AgentsHidden != nil {
s.UsageAgentsHidden = *in.AgentsHidden
}
if err := settings.Save(s); err != nil {
fail(rw, err)
return
+30
View File
@@ -964,6 +964,33 @@ body.window .field.solo { grid-column: auto; }
.row.stat .num b { font-weight: 600; }
.row.stat .num small { font-size: 10.5px; color: var(--muted); white-space: nowrap; }
.row.stat .cost { flex: none; min-width: 58px; text-align: right; color: var(--green); font-variant-numeric: tabular-nums; font-size: 12px; }
/* an Agents row's actions: shown as the row is hovered, as a Finder row's are,
and always where nothing hovers */
.row.stat .us-more { flex: none; width: 22px; height: 22px; opacity: 0; transition: opacity .12s, background .12s, color .12s; }
/* where a pointer hovers it takes no room: its margins give back its width
and the gap before it, so the row at rest is laid out as it was, and it
shows over the end of the share bar, on the card's own colour */
@media (hover: hover) {
.row.stat .us-more { position: relative; margin: 0 -9px 0 -22px; background: var(--card); }
.row.stat .us-more:hover { background: var(--pill); }
}
.row.stat:hover .us-more { opacity: 1; }
.row.stat .us-more:focus-visible { opacity: 1; }
.row.stat .us-more.open { opacity: 1; background: var(--pill); color: var(--fg); }
@media (hover: none) { .row.stat .us-more { opacity: 1; margin: 0 -4px 0 -2px; } }
.row.stat .us-unhide { flex: none; margin-right: -4px; }
/* the action's room comes out of the name's, which ends in "…" */
.row.stat.acts .who { flex-shrink: 1; }
/* the hidden ones: a quiet line under the list, opening them dimmed */
.us-hid { display: flex; flex-direction: column; flex: none; }
.us-hid[hidden] { display: none; }
.us-hid .us-hidline { align-self: flex-start; display: inline-flex; align-items: center; gap: 4px; margin: 4px 0 0 2px; font-size: 11.5px; color: var(--faint); }
.us-hid .us-hidline:hover { color: var(--fg-2); }
.us-hid .us-hidline svg { transition: transform .15s; }
.us-hid .us-hidline[aria-expanded="true"] svg { transform: rotate(180deg); }
.us-hid .list { margin-top: 4px; }
.us-hid .list[hidden] { display: none; }
.row.stat.hid > :not(.us-unhide) { opacity: .55; }
.usage-note { padding: 10px 4px 2px; font-size: 11px; color: var(--faint); user-select: text; -webkit-user-select: text; }
.usage-pane { display: flex; flex-direction: column; flex: none; }
.usage-pane[hidden] { display: none; }
@@ -3169,6 +3196,9 @@ body.panel .modal { padding: 16px 12px; }
body.web .row.stat .num { grid-column: 2 / 4; grid-row: 2; min-width: 0; align-items: flex-start; }
body.web .row.stat .num small { max-width: 100%; white-space: normal; }
body.web .row.stat .share { grid-column: 2 / 4; grid-row: 3; margin: 0; }
body.web .row.stat.acts { grid-template-columns: 20px minmax(0, 1fr) auto auto; }
body.web .row.stat.acts .num, body.web .row.stat.acts .share { grid-column: 2 / 5; }
body.web .row.stat .us-more, body.web .row.stat .us-unhide { grid-column: 4; grid-row: 1; margin: 0; }
body.web .connect { grid-template-columns: minmax(0, 1fr); gap: 6px; }
body.web .connect label { text-align: left; margin-top: 6px; }
body.web .connect .segs { flex-wrap: wrap; }
+74 -4
View File
@@ -35,6 +35,7 @@ let view = "agents";
let showAllAgents = false; // the agents no one has set anything on, folded away
let period = "today"; // usage window
let usage = null; // last usage summary
let usageHidOpen = false; // the Usage page's hidden agents shown under their line
let pick = null; // { agent, field, options, items, cursor, anchor }
let editing = null; // provider id being edited; { preset } or { custom: true } for a new one
let draft = null; // the editor's working copy
@@ -177,6 +178,8 @@ function svg(d, size = 12, stroke = 1.6) {
return s;
}
const CHEV = "m5.5 6.5 2.5 2.5 2.5-2.5";
// three dots, a row's actions (drawn with a thick round stroke)
const DOTS = "M3.5 8h.01M8 8h.01M12.5 8h.01";
const CHEV_R = "m6.5 4.5 3 3.5-3 3.5";
const CHECK = "m3.5 8.5 3 3 6-7";
const CROSS = "M4.5 4.5l7 7M11.5 4.5l-7 7";
@@ -14161,7 +14164,7 @@ function renderUsageLoading() {
stats.append(tile);
}
$("#chart").hidden = true;
for (const id of ["usageAgents", "usageModels", "usageKeys"]) $("#" + id).hidden = true;
for (const id of ["usageAgents", "usageAgentsHid", "usageModels", "usageKeys"]) $("#" + id).hidden = true;
// the allowances' head is renderQuotas' alone: the quotas it heads are
// still there while the period loads (#809, Hu9956: 用量界面红框这行会延迟几秒才会出现)
for (const h of $$("#view-usage .row-head:not(#quotaHead)")) h.hidden = true;
@@ -16489,6 +16492,7 @@ function renderUsage() {
const empty = !u.calls;
$("#chart").hidden = empty;
for (const id of ["usageAgents", "usageModels"]) $("#" + id).hidden = empty;
if (empty) $("#usageAgentsHid").hidden = true;
for (const h of $$("#view-usage .row-head:not(#quotaHead)")) h.hidden = empty;
$("#usageKeysHead").hidden = $("#usageKeys").hidden = empty || !u.callerKeys?.length;
// each subscription account's share, by the account that answered (#557)
@@ -16547,11 +16551,12 @@ function renderUsage() {
fitChartLabels();
const total = Math.max(1, tokensOf(u));
const list = (id, groups) => {
const box = $("#" + id);
const list = (id, groups, act) => {
const box = typeof id === "string" ? $("#" + id) : id;
box.replaceChildren();
for (const g of groups) {
const r = el("div", "row stat");
r.dataset.id = g.id || "";
r.append(icon(g.icon || "generic"));
const who = el("div", "who");
who.append(el("div", "name" + (g.name ? "" : " faint"), g.name || t("account not recorded")));
@@ -16583,16 +16588,81 @@ function renderUsage() {
num.append(el("b", "", fmtN(tokensOf(g))), el("small", "", t("{a} in · {b} out", { a: fmtN(g.input), b: fmtN(g.output) }) + (g.cache_read ? " · " + t("{n} cached", { n: fmtN(g.cache_read) }) : "") + hit));
r.append(num);
r.append(el("div", "cost", fmtCost(g) ? "≈" + fmtCost(g) : ""));
if (act) act(r, g);
box.append(r);
}
};
list("usageAgents", u.agents);
// a client hidden from the Agents list (ikunbots on X: curl,
// Go-http-client, python-httpx beside the agents in use) is left out of
// it, and only of it: the totals, the chart and every share above still
// count its calls. One line under the list says how many, and opens them.
const hid = new Set(state.settings?.usageAgentsHidden || []);
const hidden = u.agents.filter((g) => hid.has(g.id));
list("usageAgents", u.agents.filter((g) => !hid.has(g.id)), (r, g) => {
r.classList.add("acts");
const b = el("button", "icon us-more");
b.type = "button";
b.setAttribute("aria-haspopup", "menu");
b.setAttribute("aria-label", t("Actions for {name}", { name: g.name || g.id }));
b.append(svg(DOTS, 14, 2.2));
const menu = () => {
const again = agentMenu?.anchor === b;
closeAgentMenu();
if (again) return;
openRowMenu(b, [{ name: "Hide from this list", icon: EYE_OFF, run: () => hideUsageAgent(g.id, true) }]);
};
b.onclick = (e) => { e.stopPropagation(); menu(); };
r.oncontextmenu = (e) => { e.preventDefault(); menu(); };
r.querySelector(".share").after(b);
});
const hb = $("#usageAgentsHid");
hb.hidden = !hidden.length;
if (!hidden.length) usageHidOpen = false;
const line = hb.querySelector(".us-hidline"), hl = hb.querySelector(".list");
line.replaceChildren(el("span", "", t("{n} hidden", { n: hidden.length })), svg(CHEV, 11, 1.6));
line.title = t("Hidden from this list only: their calls still count in the totals and the chart. Click to see them.");
line.setAttribute("aria-expanded", String(usageHidOpen));
line.onclick = () => { usageHidOpen = !usageHidOpen; renderUsage(); };
hl.hidden = !usageHidOpen;
list(hl, usageHidOpen ? hidden : [], (r, g) => {
r.classList.add("hid", "acts");
const b = el("button", "text us-unhide", t("Unhide"));
b.type = "button";
b.onclick = (e) => { e.stopPropagation(); hideUsageAgent(g.id, false); };
r.append(b);
});
list("usageModels", u.models);
list("usageAccounts", u.accounts || []);
list("usageKeys", u.callerKeys || []);
$("#usageNote").textContent = t("Counted from the providers' own usage reports on every call through the gateway · {path}", { path: u.path });
}
// hideUsageAgent takes a client out of the Usage page's Agents list, or
// puts it back: drawn at once, put back if the save fails. Its calls stay
// in the ledger and in every total.
async function hideUsageAgent(id, hide) {
const prev = state.settings || {};
const cur = (prev.usageAgentsHidden || []).filter((k) => k !== id);
const agentsHidden = hide ? [...cur, id] : cur;
state.settings = { ...prev, usageAgentsHidden: agentsHidden };
const again = () => {
if (!usage) return;
renderUsage();
// the focus stays on the list: the row put back, else the hidden line
const to = hide ? $("#usageAgentsHid .us-hidline") : $(`#usageAgents .row.stat[data-id="${CSS.escape(id)}"] .us-more`);
(to && !to.closest("[hidden]") ? to : null)?.focus({ preventScroll: true });
};
again();
try {
const s = await api("usage/arrange", { agentsHidden });
state.settings = { ...state.settings, usageAgentsHidden: s.usageAgentsHidden || [] };
} catch (e) {
state.settings = prev;
again();
status(e.message, "err");
}
}
// ---------- requests ----------
//
// The ledger: every request of the period, one row each, newest first —
+16
View File
@@ -2991,6 +2991,10 @@ const I18N = {
"Found groups are on": "已开启自动创建路由组",
"Found groups are off: only yours are listed and served": "已关闭自动创建路由组:只保留你自己的组",
"Bring it back": "恢复",
"Hide from this list": "从列表中隐藏",
"Actions for {name}": "{name} 的操作",
"Unhide": "取消隐藏",
"Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "只是不在此列表中显示,它们的调用仍计入总数和图表。点击查看。",
"{name} is back": "{name} 已恢复",
"found by magpie": "magpie 自动发现",
"no member ready": "没有可用成员",
@@ -7320,6 +7324,10 @@ const I18N = {
"Found groups are on": "已開啟自動建立路由組",
"Found groups are off: only yours are listed and served": "已關閉自動建立路由組:只保留你自己的組",
"Bring it back": "恢復",
"Hide from this list": "從列表中隱藏",
"Actions for {name}": "{name} 的操作",
"Unhide": "取消隱藏",
"Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "只是不在此列表中顯示,它們的呼叫仍計入總數和圖表。點按查看。",
"{name} is back": "{name} 已恢復",
"found by magpie": "magpie 自動發現",
"no member ready": "沒有可用成員",
@@ -11661,6 +11669,10 @@ const I18N = {
"Found groups are on": "グループの自動作成はオンです",
"Found groups are off: only yours are listed and served": "グループの自動作成はオフです:自分のグループだけを一覧・提供します",
"Bring it back": "元に戻す",
"Hide from this list": "この一覧から隠す",
"Actions for {name}": "{name} の操作",
"Unhide": "再表示",
"Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "この一覧に表示しないだけで、呼び出しは合計とグラフに含まれます。クリックで表示します。",
"{name} is back": "{name} を元に戻しました",
"found by magpie": "magpie が自動作成",
"no member ready": "準備できたメンバーがありません",
@@ -16001,6 +16013,10 @@ const I18N = {
"Found groups are on": "Gefundene Gruppen sind eingeschaltet",
"Found groups are off: only yours are listed and served": "Gefundene Gruppen sind ausgeschaltet: nur Ihre werden aufgelistet und bereitgestellt",
"Bring it back": "Wiederherstellen",
"Hide from this list": "In dieser Liste ausblenden",
"Actions for {name}": "Aktionen für {name}",
"Unhide": "Einblenden",
"Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "Nur in dieser Liste ausgeblendet: Ihre Aufrufe zählen weiter in den Summen und im Diagramm. Klicken, um sie zu sehen.",
"{name} is back": "{name} ist wieder da",
"found by magpie": "von magpie gefunden",
"no member ready": "kein Mitglied bereit",
+1
View File
@@ -173,6 +173,7 @@
<section class="chart" id="chart"></section>
<div class="row-head"><span class="label" data-t>Agents</span></div>
<div class="list" id="usageAgents"></div>
<div class="us-hid" id="usageAgentsHid" hidden><button class="text us-hidline" type="button" aria-expanded="false"></button><div class="list" hidden></div></div>
<div class="row-head"><span class="label" data-t>Models</span></div>
<div class="list" id="usageModels"></div>
<div class="row-head" id="usageAccountsHead" hidden><span class="label" data-t>Accounts</span></div>
+1
View File
@@ -141,6 +141,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
QuotaLeft: true,
UsageOrder: []string{"kimi", "codex"},
PanelUsageHidden: []string{"deepseek"},
UsageAgentsHidden: []string{"curl"},
PlainNames: true,
PlainOwnNames: true,
CodexAgentsV1: true,
@@ -0,0 +1,209 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The Usage page's Agents list hides the clients a reader doesn't care
// about (ikunbots on X: Go-http-client, AsyncOpenAI, curl, python-httpx and
// magpie beside Pi and their own agent). A row's actions (its "…" button,
// or a right-click) hide it from the list; the totals and the chart still
// count it. A quiet line under the list says how many are hidden and opens
// them, each with Unhide. What is hidden is saved (POST /api/usage/arrange,
// agentsHidden) and stays hidden when the page is opened again. No click
// moves the page. Every language, a wide window, a narrow one and magpie
// web on a phone; 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 G = (id, name, tokens, icon) => ({ id, name, icon: icon || "generic", calls: 10, input: tokens - 100, output: 100, cache_read: 0, cache_write: 0, cost: 0 });
const AGENTS = [
G("pi", "Pi", 900000, "pi"),
G("novelcraft", "novelcraft", 500000),
G("curl", "curl", 40000),
G("Go-http-client", "Go-http-client", 30000),
G("python-httpx", "python-httpx", 20000),
G("AsyncOpenAI", "AsyncOpenAI", 10000),
];
const TOTAL = AGENTS.reduce((n, g) => n + g.input + g.output, 0);
const USAGE = {
calls: 60, errors: 0, input: TOTAL - 600, output: 600, reasoning: 0, cache_read: 0, cache_write: 0, unpriced: 0, cost: 0, bucket: "day",
series: [],
path: "~/.config/magpie/usage.jsonl",
agents: AGENTS,
models: [{ ...G("m", "glm-5", TOTAL), model: "glm-5" }],
};
function server(lang, web, saved, posts) {
return async (route) => {
const req = route.request();
const url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
const settings = () => ({ lang, theme: "light", usageAgentsHidden: saved.hidden });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web}};` });
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: settings(), fx: { rate: 7.2, at: new Date().toISOString() } });
if (url.pathname === "/api/usage/arrange") {
const body = JSON.parse(req.postData() || "{}");
posts.push(body);
if (body.agentsHidden) saved.hidden = body.agentsHidden;
return json(settings());
}
if (url.pathname === "/api/settings") return json(settings());
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/usage") return json(USAGE);
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], models: [], gateway: { running: false } });
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: { hide: "Hide from this list", n: (n) => `${n} hidden`, unhide: "Unhide" },
zh: { hide: "从列表中隐藏", n: (n) => `已隐藏 ${n} 个`, unhide: "取消隐藏" },
"zh-TW": { hide: "從列表中隱藏", n: (n) => `已隱藏 ${n} 個`, unhide: "取消隱藏" },
ja: { hide: "この一覧から隠す", n: (n) => `${n} 件非表示`, unhide: "再表示" },
de: { hide: "In dieser Liste ausblenden", n: (n) => `${n} ausgeblendet`, unhide: "Einblenden" },
};
const SIZES = [{ width: 1200, web: false }, { width: 560, web: false }, { width: 390, web: true }];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": the Usage page's Agents list hides a client, and brings it back", 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 Object.keys(L)) {
for (const { width, web } of SIZES) {
const w = L[lang];
await t.test(`${lang} ${width}${web ? " web" : ""}`, async () => {
const errors = [];
// python-httpx was hidden before: it stays hidden
const saved = { hidden: ["python-httpx"] }, posts = [];
const ctx = await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce", hasTouch: web, isMobile: web && engine === "chromium" });
const open = async () => {
const p = await ctx.newPage();
p.setDefaultTimeout(5000);
p.on("pageerror", (e) => errors.push(e.message));
await p.route("**/*", server(lang, web, saved, posts));
await p.goto("http://magpie.test/");
const nav = p.locator('[data-view="usage"]:visible').first();
if (await nav.count()) await nav.click();
else await p.evaluate(() => show("usage"));
await p.locator("#usageAgents .row.stat").first().waitFor();
return p;
};
const ids = (p, sel) => p.locator(sel + " .row.stat").evaluateAll((rs) => rs.map((r) => r.dataset.id));
const tokens = (p) => p.locator("#stats .kpi b").first().textContent();
const top = (p) => p.locator("#view-usage").evaluate((v) => v.scrollTop);
let p = await open();
const allTokens = await tokens(p);
assert.deepEqual(await ids(p, "#usageAgents"), ["pi", "novelcraft", "curl", "Go-http-client", "AsyncOpenAI"]);
const line = p.locator("#usageAgentsHid .us-hidline");
assert.equal((await line.textContent()).trim(), w.n(1));
assert.equal(await p.locator("#usageAgentsHid .list").isHidden(), true, "the hidden ones wait under their line");
// a row's "…" opens its menu; Hide takes it out of the list
const row = (id) => p.locator(`#usageAgents .row.stat[data-id="${id}"]`);
// brought into sight by the reader's wheel, then hovered: its "…" shows
await reader.inView(p, row("curl"));
if (!web) await row("curl").hover();
const more = row("curl").locator(".us-more");
// shown once the hover's fade is done
await more.evaluate((b) => new Promise((ok, no) => { const end = Date.now() + 2000; (function f() { getComputedStyle(b).opacity === "1" ? ok() : Date.now() > end ? no(new Error("the hovered row's actions don't show")) : requestAnimationFrame(f); })(); }));
let at = await top(p);
await more.click();
const item = p.locator(".row-menu .rm-item");
assert.deepEqual(await item.allTextContents(), [w.hide]);
await item.click();
await p.waitForFunction(() => !document.querySelector('#usageAgents .row.stat[data-id="curl"]'));
assert.deepEqual(posts.at(-1), { agentsHidden: ["python-httpx", "curl"] });
assert.equal((await line.textContent()).trim(), w.n(2));
assert.equal(await top(p), at, "hiding a row doesn't move the page");
// and a right-click opens the same menu
if (!web) {
await reader.inView(p, row("Go-http-client"));
at = await top(p);
await row("Go-http-client").click({ button: "right" });
await p.locator(".row-menu .rm-item").click();
await p.waitForFunction(() => !document.querySelector('#usageAgents .row.stat[data-id="Go-http-client"]'));
} else {
await reader.inView(p, row("Go-http-client"));
at = await top(p);
await row("Go-http-client").locator(".us-more").click();
await p.locator(".row-menu .rm-item").click();
await p.waitForFunction(() => !document.querySelector('#usageAgents .row.stat[data-id="Go-http-client"]'));
}
assert.deepEqual(saved.hidden, ["python-httpx", "curl", "Go-http-client"]);
assert.equal((await line.textContent()).trim(), w.n(3));
assert.equal(await top(p), at, "hiding a row doesn't move the page");
assert.equal(await tokens(p), allTokens, "the totals still count the hidden ones");
assert.deepEqual(await ids(p, "#usageAgents"), ["pi", "novelcraft", "AsyncOpenAI"]);
// the line opens them, the page left where it is
await reader.inView(p, line);
at = await top(p);
await line.click();
assert.equal(await line.getAttribute("aria-expanded"), "true");
assert.deepEqual(await ids(p, "#usageAgentsHid"), ["curl", "Go-http-client", "python-httpx"]);
assert.deepEqual((await p.locator("#usageAgentsHid .us-unhide").allTextContents()).map((s) => s.trim()), [w.unhide, w.unhide, w.unhide]);
assert.equal(await top(p), at, "opening the hidden ones doesn't move the page");
// Unhide puts one back where it was in the list; the line clicked
// under stays where it was on the screen as the row goes in above
const back = p.locator('#usageAgentsHid .row.stat[data-id="curl"] .us-unhide');
await reader.inView(p, back);
const lineAt = () => line.evaluate((e) => e.getBoundingClientRect().top);
const was = await lineAt();
await back.click();
await p.waitForFunction(() => !!document.querySelector('#usageAgents .row.stat[data-id="curl"]'));
await p.waitForTimeout(150);
assert.deepEqual(posts.at(-1), { agentsHidden: ["python-httpx", "Go-http-client"] });
assert.deepEqual(await ids(p, "#usageAgents"), ["pi", "novelcraft", "curl", "AsyncOpenAI"]);
assert.deepEqual(await ids(p, "#usageAgentsHid"), ["Go-http-client", "python-httpx"]);
assert.equal((await line.textContent()).trim(), w.n(2));
// within the pixel the page's hold leaves it
const now = await lineAt();
assert(Math.abs(now - was) < 1.5, `unhiding a row leaves the hidden line where it was: ${was} → ${now}`);
// nothing is wider than the page
const wide = await p.evaluate(() => { const v = document.querySelector("#view-usage"); return [v.scrollWidth, v.clientWidth, document.documentElement.scrollWidth, window.innerWidth]; });
assert(wide[0] <= wide[1] + 1 && wide[2] <= wide[3] + 1, "no sideways scroll: " + wide);
const out = await p.evaluate(() => [...document.querySelectorAll("#usageAgents .row.stat, #usageAgentsHid .row.stat")].filter((r) => {
const box = r.getBoundingClientRect();
return [...r.querySelectorAll(".us-more, .us-unhide")].some((b) => { const x = b.getBoundingClientRect(); return x.right > box.right + 0.5 || x.left < box.left - 0.5; });
}).map((r) => r.dataset.id));
assert.deepEqual(out, [], "every row's action stays inside its row");
// opened again, the hidden ones are still hidden
await p.close();
p = await open();
assert.deepEqual(await ids(p, "#usageAgents"), ["pi", "novelcraft", "curl", "AsyncOpenAI"]);
assert.equal((await p.locator("#usageAgentsHid .us-hidline").textContent()).trim(), w.n(2));
assert.equal(await tokens(p), allTokens);
// all of them back, the line goes
await reader.click(p, p.locator("#usageAgentsHid .us-hidline"));
for (const id of ["Go-http-client", "python-httpx"]) {
const b = p.locator(`#usageAgentsHid .row.stat[data-id="${id}"] .us-unhide`);
await reader.inView(p, b);
await b.click();
await p.waitForFunction((id) => !!document.querySelector(`#usageAgents .row.stat[data-id="${id}"]`), id);
}
assert.deepEqual(saved.hidden, []);
assert.equal(await p.locator("#usageAgentsHid").isHidden(), true);
assert.equal(await p.locator("#usageAgents .row.stat").count(), AGENTS.length);
assert.deepEqual(errors, []);
await ctx.close();
});
}
}
});
}
+38
View File
@@ -49,3 +49,41 @@ func TestUsageArrangePanelHidden(t *testing.T) {
post("/api/usage/arrange", `{"panelHidden":[]}`)
want([]string{"codex", "kimi"}, nil)
}
// The Usage page's Agents list leaves out the clients hidden there
// (ikunbots on X: curl, Go-http-client, python-httpx beside the agents in
// use): saved on its own, beside the panel's, and kept through a save of
// the Settings page.
func TestUsageArrangeAgentsHidden(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Setenv("APPDATA", filepath.Join(h, "AppData", "Roaming"))
t.Setenv("LOCALAPPDATA", filepath.Join(h, "AppData", "Local"))
post := func(path, body string) {
t.Helper()
rec := httptest.NewRecorder()
Handler(nil, nil).ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))
if rec.Code != http.StatusOK {
t.Fatalf("%s: %d %s", path, rec.Code, rec.Body)
}
}
want := func(agents, panel []string) {
t.Helper()
s := settings.Load()
if !slices.Equal(s.UsageAgentsHidden, agents) || !slices.Equal(s.PanelUsageHidden, panel) {
t.Fatalf("agents hidden %v panel hidden %v, want %v %v", s.UsageAgentsHidden, s.PanelUsageHidden, agents, panel)
}
}
post("/api/usage/arrange", `{"panelHidden":["deepseek"]}`)
post("/api/usage/arrange", `{"agentsHidden":["curl","Go-http-client"," curl"]}`)
want([]string{"curl", "Go-http-client"}, []string{"deepseek"})
post("/api/settings", `{"theme":"dark"}`)
want([]string{"curl", "Go-http-client"}, []string{"deepseek"})
post("/api/usage/arrange", `{"agentsHidden":["Go-http-client"]}`)
want([]string{"Go-http-client"}, []string{"deepseek"})
post("/api/usage/arrange", `{"agentsHidden":[]}`)
want(nil, []string{"deepseek"})
}
+6
View File
@@ -399,6 +399,11 @@ type Settings struct {
// panel shows, nothing more: routing, caps, the Usage page and the menu
// bar's cells still have them. The panel's order is UsageOrder.
PanelUsageHidden []string `json:"panelUsageHidden,omitempty"`
// UsageAgentsHidden are the clients, by the id the ledger records them
// under ("curl", "Go-http-client", an agent's id), that the Usage page's
// Agents list leaves out (ikunbots on X). It is that list's only: the
// ledger keeps their calls, and the totals and the chart count them.
UsageAgentsHidden []string `json:"usageAgentsHidden,omitempty"`
// Visible narrows the models an agent is shown, by agent id: the
// families (the tag a provider or group is given), provider ids and
// group ids its lists hold. An agent it doesn't name is shown them all.
@@ -1065,6 +1070,7 @@ func save(s Settings, recording bool) error {
s.AgentOrder, s.AgentsHidden, s.AgentsShown = ids(s.AgentOrder), ids(s.AgentsHidden), ids(s.AgentsShown)
s.UsageOrder = ids(s.UsageOrder)
s.PanelUsageHidden = ids(s.PanelUsageHidden)
s.UsageAgentsHidden = ids(s.UsageAgentsHidden)
s.TrayUsages = ids(s.TrayUsages)
for i, u := range s.CodexAutoReset {
s.CodexAutoReset[i] = strings.ToLower(u)