routing: a folded fold of accounts on one plan says what they have left together

chen2652 (Discord #help): a provider with several accounts on one plan
should show, when its group is folded, one bar and what is left in all;
opened, each account's own quota as now.

A Routing account fold (3+ adjacent accounts of one provider and model),
when folded, now writes its tightest shared window before its status
("5 hours 40% used · …") and a bar under it, from quotaall.js's
mergeQuotas over the accounts' Usage cards. Its tip lists every window,
how they were put together (the mean of n accounts on one plan, added up,
or unlimited on each) and when the first of them starts again. Only when
every account has a card, all on one plan, none free; with different
plans, a card missing, the fold open, or the day view, nothing changes.
An open fold shows only each account's own row, as before. No new words:
every string is already in i18n.js in every language. routing.css is
unchanged (the account rows' bar grid). foldQuota in plugins/routing/
client.js; documented in docs/subsystems/gui-shell.md.

Run:
- routing-fold-accounts-together.test.cjs (new): 5 languages x 1100/420px
  x Chromium/WebKit, 22/22 on mote. Folded: figure, 40% fill, tip in each
  language, no email in the figure; mixed plans: no bar; open: no bar;
  nothing overflows.
- At this tree (rebased on origin/main 999ba6a00), on mote: the new test,
  routing-fold-all, routing-folder and i18n-keys: 66 tests, 65 pass. The
  one red is i18n-keys "a plugin's words are its own" (plugins/library and
  plugins/routing "No session ID"), filed as #5327/#5332/#5426/#5482, not
  a string of this change.
- Earlier, on WSL at d7b298dec vs base 56f095604: every routing GUI file
  plus i18n-keys, provider-at-once and quota-all, 2942 tests; the same
  WebKit/load reds at the base (36 there, 38 here). The one head-only red,
  provider-at-once "webkit en: accounts at once are typed and saved" (a
  Providers editor timeout), passed 60/60 with the new test on a rerun.
- Screenshots of every language at both widths (WebKit) looked at.

Broken by hand, each red in the new test:
- the old client.js;
- combining while the fold is open (no !f.open): "an open fold has no
  bar of its own";
- no one-plan check: the mixed-plan fold drew a bar.

Not tried: the whole GUI suite and the Go suite before the tag (run after
it); the real app with the reporter's real accounts on one plan.

Reported-by: chen2652
This commit is contained in:
yetone
2026-11-07 22:03:32 +08:00
parent 999ba6a00e
commit ea1a8ae809
3 changed files with 192 additions and 6 deletions
+11
View File
@@ -199,6 +199,17 @@ lit and what it is doing, how many are available and how many rest
from the fold. Accounts and keys folds a provider's keys, and its accounts,
into one `.rt-keys` row each with their summed tally.
A folded fold of accounts, live, also says what they have left together,
first in its line, with a bar under it like an account row's (`foldQuota`,
chen2652 on Discord): the Usage page's readings of its accounts (`cardOf`)
put together by quotaall.js's `mergeQuotas`, the same as the Usage page's
"All N accounts" strip, its tightest window that says a share as the figure
and the bar, every window and when the first of them resets on hover. Only
when every account in it was read, none is free, and all are on one plan;
otherwise, and while the fold is open or a kept day is shown, it says
nothing of it and each account's row has its own. See
`routing-fold-accounts-together.test.cjs`.
A group in the group's heading (`li.rt-sub`, `subNode`) folds the same way
(`toggleSub`): folded, it says how many it routes to and what they do
together, a request to any seat under it flies to the heading
+43 -6
View File
@@ -2390,14 +2390,16 @@ function routingPage(part) {
let f = folds.get(key);
if (!f) {
const li = el("li", "rt-fold"), b = el("b"), st = el("em"), tg = el("span", "tag");
const n = el("span", "n"), chev = el("span", "chev");
const n = el("span", "n"), chev = el("span", "chev"), bar = el("div", "bar"), bi = el("i");
chev.append(svg(CHEV, 12, 1.7));
li.append(el("i", "dot"), b, st, chev, tg);
bar.append(bi);
li.append(el("i", "dot"), b, st, chev, bar, tg);
li.classList.add("nobar");
li.tabIndex = 0;
li.setAttribute("role", "button");
li.onclick = () => toggleFold(f);
li.onkeydown = (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toggleFold(f); } };
f = { li, b, st, tg, n, wire: path(), key };
f = { li, b, st, tg, n, bi, wire: path(), key };
folds.set(key, f);
}
f.w = w;
@@ -2921,18 +2923,19 @@ function routingPage(part) {
// a fold tells of its keys together: the one answering or that
// answered, by name, then how many are there to route to and how many
// rest
const together = (f, ms) => {
const together = (f, ms, sum) => {
const has = (m, c) => m.li.classList.contains(c);
const on = ms.find((m) => has(m, "now")) || ms.find((m) => has(m, "on")), resting = ms.filter((m) => has(m, "rest")).length;
const held = ms.filter((m) => !has(m, "rest") && has(m, "left")).length; // at a cap, or used up (#2129)
const parts = [];
if (sum) parts.push(sum.text);
if (on) parts.push(`${who(on.w)}: ${on.st.textContent}`);
if (resting + held < ms.length) parts.push(t("{n} available", { n: ms.length - resting - held }));
if (resting) parts.push(t("{n} resting", { n: resting }));
if (held) parts.push(t("{n} held", { n: held }));
setText(f.st, parts.join(" · "));
// a title or an intent the row cut short is read whole over the fold too
const tip = on?.st.title ? f.st.textContent : "";
const tip = tipLines(on?.st.title ? f.st.textContent : "", sum?.tip);
if (f.st.title !== tip) { if (tip) f.st.title = tip; else f.st.removeAttribute("title"); }
lightRow(f.li, f.wire, !!on, ms.some((m) => has(m, "now")));
tint(f.wire, on?.wire);
@@ -2941,7 +2944,14 @@ function routingPage(part) {
for (const f of folds.values()) {
const ms = (f.ids || []).map((id) => rows.get(id)).filter(Boolean);
setText(f.n, t(f.w.kind === "account" ? "{n} accounts" : "{n} keys", { n: ms.length }));
const all = together(f, ms);
// folded, a fold of accounts on one plan says what they have left
// together, and its bar shows it (chen2652 on Discord); open, each
// account's own row does, and the fold says nothing of it
const sum = f.w.kind === "account" && !f.open && !day ? foldQuota(ms) : null;
f.li.classList.toggle("nobar", !sum?.bar);
const fill = sum?.bar ? quotaFill(sum.bar) + "%" : "0";
if (f.bi.style.width !== fill) f.bi.style.width = fill;
const all = together(f, ms, sum);
f.li.classList.toggle("rest", all);
f.wire.classList.toggle("rest", all);
}
@@ -4439,6 +4449,33 @@ function routingPage(part) {
const q = mine.find((q) => (q.user || "").trim().toLowerCase() === user) || (mine.length === 1 && !mine[0].user ? mine[0] : null);
return q && !q.error && q.windows?.length ? q : null;
}
// foldQuota: what a fold's accounts have left together, from the Usage
// page's readings (mergeQuotas), as its strip of all of a provider's
// accounts says it: only when every account in it was read, and all are
// on one plan, so their windows are alike; a window only some of them
// have is left out (mergeQuotas). The tightest window that says a share
// is the figure and the bar; the rest, and when the first of them
// starts again, are on hover. Null when nothing adds up.
function foldQuota(ms) {
if (ms.length < 2 || ms.some((m) => m.w.free)) return null;
const cards = ms.map((m) => cardOf(m.w));
if (cards.some((q) => !q) || new Set(cards).size !== cards.length) return null;
if (new Set(cards.map((q) => q.plan || "")).size > 1) return null;
if (!window.mergeQuotas) { quotaAllJS().then(renderAll); return null; }
const ws = familyWindows(mergeQuotas(cards).windows) || [];
if (!ws.length) return null;
const shares = ws.filter((w) => !w.unlimited && !quotaNoShare(w));
const bar = shares.length ? shares.reduce((a, b) => (b.used > a.used ? b : a)) : null;
const top = bar || ws[0];
const line = (w) => t(w.name) + " " + quotaText(w);
const soon = ws.map((w) => w.firstReset).filter(Boolean).sort()[0];
return {
text: line(top), bar,
tip: tipLines(...ws.map(line),
t(top.how === "p" ? "The mean of {n} accounts on one plan" : top.how === "u" ? "Unlimited on each of {n} accounts" : "Added up over {n} accounts", { n: top.accounts }),
soon && t("The first of them starts again {when}", { when: resetClock(new Date(soon)) })),
};
}
// winsOf: each of an account's windows, as the Usage page's card names
// it: "5 hours 40% used · resets in 2h"
function winsOf(w) {
@@ -0,0 +1,138 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// chen2652 on Discord: a fold of one provider's accounts on one plan, folded,
// says what they have left together, as the Usage page's strip of all of a
// provider's accounts does, and its bar shows it: the tightest window, a
// share the mean of the accounts (5 hours 40% used of 20, 40 and 60). Open,
// each account's row says its own and the fold says nothing of it.
// Accounts on different plans are not put together: their fold is as it
// was. In every language, at a window's width and at 420px, in both
// engines. ARTIFACT_DIR keeps a screenshot of each folded stage.
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(process.env.MAGPIE_ASSETS || path.join(__dirname, "../assets"));
const now = Date.now();
const iso = (ms) => new Date(ms).toISOString();
const acct = (provider, who, plan) => ({ id: `${provider}@${who}`, provider, name: provider === "same" ? "Same Plan" : "Mixed Plans", who, kind: "account", model: "m-1", known: true, used: 10, plan });
const accts = [
acct("same", "a@example.com", "Pro"), acct("same", "b@example.com", "Pro"), acct("same", "c@example.com", "Pro"),
acct("mixed", "d@example.com", "Pro"), acct("mixed", "e@example.com", "Max"), acct("mixed", "f@example.com", "Pro"),
];
const route = {
id: 7, seq: 7, time: iso(now - 2000), agent: "claude", model: "m-1", provider: "same", done: true, status: 200, ms: 900, tokens: 1500,
order: accts, tries: [{ id: accts[0].id, model: "m-1", start: iso(now - 2000), done: true, ms: 800, status: 200 }],
};
const card = (provider, user, plan, five, seven, reset) => ({ provider, name: provider, kind: "subscription", user, plan, windows: [
{ name: "5 hours", used: five, resetsAt: iso(now + reset * 60e3) },
{ name: "7 days", used: seven, resetsAt: iso(now + 73 * 3600e3) },
] });
const cards = [
card("same", "a@example.com", "Pro", 20, 10, 130), card("same", "b@example.com", "Pro", 40, 30, 200), card("same", "c@example.com", "Pro", 60, 20, 250),
card("mixed", "d@example.com", "Pro", 20, 10, 130), card("mixed", "e@example.com", "Max", 40, 30, 200), card("mixed", "f@example.com", "Pro", 60, 20, 250),
];
function serve(lang) {
const state = { agents: [{ id: "claude", name: "Claude Code", path: "/test/claude", fields: [] }], profiles: [], settings: { lang, theme: "light", quotaLeft: false } };
return async (r) => {
const url = new URL(r.request().url());
const json = (data) => r.fulfill({ json: data });
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
return json({ mine: true, now: new Date().toISOString(), seq: 7, totals: { requests: 1, rerouted: 0, errors: 0 }, routes: [route] });
}
if (url.pathname === "/api/usage/quotas") return json(cards);
if (url.pathname === "/api/usage/quotas/history") return json([]);
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
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 r.fulfill({ body: await fs.readFile(file), contentType });
};
}
// the fold's figure: the 5 hours window, the mean of 20, 40 and 60
const words = {
en: ["5 hours 40% used", "The mean of 3 accounts on one plan"],
zh: ["5 小时 已用 40%", "同一套餐 3 个账号的平均值"],
"zh-TW": ["5 小時 已用 40%", "同一方案 3 個帳號的平均值"],
ja: ["5 時間 使用済み 40%", "同じプランの 3 アカウントの平均"],
de: ["5 Stunden 40% verbraucht", "Mittelwert von 3 Konten mit demselben Tarif"],
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: a folded fold of accounts on one plan says what they have left together`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of Object.keys(words)) {
for (const width of [1100, 420]) {
await t.test(`${lang} at ${width}px`, async () => {
const ctx = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
try {
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang));
await page.goto("http://magpie.test/?view=routing");
const fold = (name) => page.locator(".rt-accts > li.rt-fold", { has: page.locator(".who", { hasText: new RegExp(`^${name}$`) }) });
const same = fold("Same Plan"), mixed = fold("Mixed Plans");
await same.waitFor();
await mixed.waitFor();
await page.waitForFunction("typeof quotas !== \"undefined\" && Array.isArray(quotas) && quotas.length > 0");
const look = (li) => li.evaluate((e) => ({
open: e.classList.contains("open"), bar: !e.classList.contains("nobar") && getComputedStyle(e.querySelector(".bar")).display !== "none",
fill: e.querySelector(".bar i").style.width, text: e.querySelector("em").textContent, tip: e.querySelector("em").title,
}));
// three accounts fold open: each says its own, the fold nothing of theirs
let s = await look(same);
assert.ok(s.open, "three accounts open by default");
assert.ok(!s.bar, "an open fold has no bar of its own");
assert.ok(!s.text.includes(words[lang][0]), `open: ${s.text}`);
// folded: the figure first, and the bar at it
await same.click();
await page.waitForFunction(([w]) => [...document.querySelectorAll(".rt-accts > li.rt-fold:not(.open) em")].some((e) => e.textContent.startsWith(w)), [words[lang][0]]);
s = await look(same);
assert.ok(!s.open && s.bar, JSON.stringify(s));
assert.equal(s.fill, "40%");
assert.ok(s.text.startsWith(words[lang][0] + " · "), s.text);
if (words[lang][1]) assert.ok(s.tip.includes(words[lang][1]), s.tip);
assert.ok(s.tip.split("\n").length >= 3, "each window and how it was put together, on hover: " + s.tip);
// no account is named in it
assert.ok(!/@example\.com/.test(s.text.split(" · ")[0]), s.text);
// different plans: folded, as it was
await mixed.click();
await page.locator(".rt-accts > li.rt-fold:not(.open)").nth(1).waitFor();
const m = await look(mixed);
assert.ok(!m.open && !m.bar, JSON.stringify(m));
assert.ok(!m.text.includes(words[lang][0]), m.text);
// nothing runs past the list
const over = await same.evaluate((e) => Math.max(e.scrollWidth - e.clientWidth, document.documentElement.scrollWidth - innerWidth));
assert.ok(over <= 1, `${lang} at ${width}: ${over}px past`);
// open again: the figure and the bar go
await same.click();
await page.waitForFunction(() => document.querySelectorAll(".rt-accts > li.rt-fold.open").length === 1);
s = await look(same);
assert.ok(s.open && !s.bar && !s.text.includes(words[lang][0]), JSON.stringify(s));
if (process.env.ARTIFACT_DIR) {
await same.click();
await page.waitForFunction(() => document.querySelectorAll(".rt-accts > li.rt-fold:not(.open)").length === 2);
await page.locator(".rt-accts").screenshot({ path: path.join(process.env.ARTIFACT_DIR, `fold-together-${engine}-${lang}-${width}.png`) });
}
assert.deepEqual(errors, []);
} finally {
await ctx.close();
}
});
}
}
});
}