providers: a key's balance shows on its row, as Usage last read it

lyj1115 on X: magpie found the relay's balance (the probe), but the
Providers row showed only the API key; the figure was on Usage alone.

The row's quiet facts line (host · models) now ends in " · $10472.14",
in the line's own colour and size, with "Balance $…" as its tooltip.
Several keys' balances are added up as the Usage card's head adds them
(shared balances counted once), else the key in use's. A failed read, a
signed-in account (its windows are on Usage) and Usage turned off show
none. Opening Providers asks for Usage's own read (never ?asked=1, so
"read only when asked" holds) when it is over a minute old, as Routing
does (#1833); rows are marked after the list is drawn and after a read.

rowBalance, markBalances and keysSum/keysSumTip live in
plugins/usage/page.js (keysSum moved out of app.js) so app.js stays
under its code budget without a raise; app.js calls markBalances?.().
No new words, no CSS.

Run (mote, at this tree rebased on origin/main 6cc7402bd):
- provider-row-balance.test.cjs: 24/24 green, chromium and webkit,
  en zh zh-TW ja de at 900 and 420px, and Usage off.
- Broken by hand: against origin/main's assets (MAGPIE_ASSETS) it is
  22 of 24 red (no .pv-bal); only the Usage-off cases pass.
- go test ./internal/gui -run 'TestCoreScriptBudget|I18n|Words|Asset|Budget': ok.
- i18n-keys, i18n-en-no-cjk and 12 provider-*.test.cjs files: 329 pass,
  1 red: i18n-keys "a plugin's words are its own" (routing's ", with an
  image"), red the same on origin/main 6cc7402bd, filed as #6877.
- A 218-file GUI batch (provider, routing, balance, usage-keys,
  usage-shared-balance, i18n) was still running on mote at push time;
  new reds against origin/main get issues when it ends.
Not tried: the real app with a real relay's probed balance.
This commit is contained in:
yetone
2026-11-16 23:11:36 +08:00
parent 6cc7402bd3
commit b0674b9ec4
3 changed files with 160 additions and 15 deletions
+4 -15
View File
@@ -6270,6 +6270,7 @@ function renderProviders(quiet) {
if (importingApps) dialog = renderImportApps(importingApps);
keptIcons = null;
markUpstream();
globalThis.markBalances?.(); // plugins/usage/page.js
view.scrollTop = top; // first: a closing dialog folds into its row where it is
if (dialog) openModal(dialog, quiet); else closeModal();
}
@@ -16073,6 +16074,7 @@ function loadQuotas(asked, again) {
if (quotasLoading === p) quotasLoading = null;
if (!same) renderQuotas(true);
if (view === "usage") loadUpstream();
globalThis.markBalances?.();
if (reading && !quotasLater && ++quotasTries <= 20) quotasLater = setTimeout(() => { quotasLater = 0; loadQuotas(false, true); }, 1500);
if (mode === "panel" && state?.agents && !panelAccts) panelAccounts();
});
@@ -16488,20 +16490,6 @@ function acctsMore(provider, n) {
};
return b;
}
// keysSum: the keys' balances added up, written as theirs are ("$12.50"),
// when each is one amount in the same currency; "" otherwise
function keysSum(subs) {
let total = 0, unit = null;
for (const q of subs) {
const m = !q.error && !q.balanceParts?.length && (q.balance || "").match(/^([^\d-]*)(-?\d[\d,]*(?:\.\d+)?)(\D*)$/);
if (!m) return "";
const u = m[1] + "|" + m[3];
if (unit != null && u !== unit) return "";
unit = u;
total += Number(m[2].replace(/,/g, ""));
}
return balanceAmount(subs[0], total);
}
// the card's button: the accounts in brief (or, in the panel, left out) in
// full, its count the ones it opens; or, every one in full, the ones it
// opened back in brief (none of them: every one but the one in sight). An
@@ -23364,7 +23352,8 @@ async function show(v) {
if (v === "providers" && providersBehind) renderProviders();
if (v === "providers" || rtView(v) || providersPage(v)) loadProviders().then(back, statusErr);
// Routing's accounts' windows as Usage read them (#1833), never an asked read
if (rtView(v) && (!quotas || Date.now() - quotasAt > 60e3)) loadQuotas();
// and Providers' balances (rowBalance, plugins/usage/page.js)
if ((rtView(v) || v === "providers" && !featuresOff.has("usage")) && (!quotas || Date.now() - quotasAt > 60e3)) loadQuotas();
if (v === "settings") (settingsLoad = loadSettings()).then(back, statusErr);
if (v === "plugins") window.loadPlugins?.()?.then(back);
syncTitle();
+42
View File
@@ -608,6 +608,48 @@ function sharedKeysNote(q) {
s.title = t("One balance for the account these keys share: {keys}", { keys: q.sharedKeys.join(", ") });
return s;
}
// keysSum: the keys' balances added up, written as theirs are ("$12.50"),
// when each is one amount in the same currency; "" otherwise
function keysSum(subs) {
let total = 0, unit = null;
for (const q of subs) {
const m = !q.error && !q.balanceParts?.length && (q.balance || "").match(/^([^\d-]*)(-?\d[\d,]*(?:\.\d+)?)(\D*)$/);
if (!m) return "";
const u = m[1] + "|" + m[3];
if (unit != null && u !== unit) return "";
unit = u;
total += Number(m[2].replace(/,/g, ""));
}
return balanceAmount(subs[0], total);
}
// A key's balance, as Usage last read it, beside the row's models (lyj1115
// on X: found, but shown on Usage only); several keys' added up as Usage's
// card adds them, else the key in use's.
function rowBalance(p) {
if (p.account || featuresOff.has("usage")) return "";
const cards = sharedBalances((quotas || []).filter((q) => q.provider === p.id && !q.from && q.balance && !q.error));
if (cards.length < 2) return cards[0]?.balance || "";
const on = p.keyList?.find((k) => k.active), own = on && cards.find((q) => q.user === (on.name || on.masked));
return keysSum(cards) || own?.balance || "";
}
// markBalances puts it on the rows drawn, after the list or a read of
// Usage's (app.js)
function markBalances() {
const byId = new Map((providers?.providers || []).map((p) => [p.id, p]));
for (const row of document.querySelectorAll("#providers .row.provider[data-id], #offProviders .row.provider[data-id]")) {
const sub = row.querySelector(".who > .sub"), p = byId.get(row.dataset.id);
if (!sub || !p) continue;
const amount = rowBalance(p), had = sub.querySelector(":scope > .pv-bal");
if (had?.dataset.amount === amount) continue;
had?.remove();
if (!amount) continue;
const b = el("span", "pv-bal", " · " + amount);
b.title = t("Balance") + " " + amount;
b.dataset.amount = amount;
sub.append(b);
}
}
// the keys' sum's tooltip: an account several keys share counted once
function keysSumTip(subs) {
return subs.some((q) => q.sharedKeys) ? t("The balances added up, each account's once") : t("The {n} keys' balances added up", { n: subs.length });
@@ -0,0 +1,114 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A provider's balance, as the Usage page reads it, is a quiet figure on its
// row in Providers too (lyj1115 on X: magpie found the relay's balance, and
// the row showed only the API key). Several keys' balances are added up as
// the Usage card adds them; a failed read, a signed-in account and the Usage
// page turned off show none. The read is Usage's own, never an asked one.
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 base = {
icon: "generic", chat: "", responses: "", anthropic: "", catalog: "",
models: [{ id: "model-a", name: "Model A", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…one" }, keyList: [{ id: "a", masked: "sk-…one", active: true, on: true }],
balanceURL: "", balancePath: "", balanceToken: { takes: false, set: false },
};
const relay = { ...base, id: "relay", name: "Relay", host: "relay.example.com", chat: "https://relay.example.com/v1", balanceProbe: true, balanceFound: "https://relay.example.com/v1/usage", balanceFoundField: "$remaining" };
const many = { ...base, id: "many", name: "Many", host: "many.example.com", key: { set: true, masked: "sk-…aaa" },
keyList: [{ id: "a", name: "work", masked: "sk-…aaa", active: true, on: true }, { id: "b", masked: "sk-…bbb", on: true }] };
const broke = { ...base, id: "broke", name: "Broke", host: "broke.example.com" };
const none = { ...base, id: "none", name: "Nothing", host: "none.example.com" };
const acct = { ...base, id: "acct", name: "Acct", host: "acct.example.com", key: { set: false, masked: "" }, keyList: [], account: { user: "me@example.com", agentName: "Codex", plan: "Plus", logins: [] } };
const quotas = [
{ provider: "relay", name: "Relay", icon: "generic", windows: [], balance: "$10472.14" },
{ provider: "many", name: "Many", icon: "generic", user: "work", windows: [], balance: "$12.50" },
{ provider: "many", name: "Many", icon: "generic", user: "sk-…bbb", windows: [], balance: "$7.50" },
{ provider: "broke", name: "Broke", icon: "generic", windows: [], error: "401 invalid key", balance: "$1.00" },
{ provider: "acct", name: "Acct", icon: "generic", windows: [], balance: "$3.00" },
];
function server(lang, featuresOff, asked) {
const providers = { providers: [relay, many, broke, none, acct], presets: [], excluded: [], gateway: { running: true, window: true } };
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = ${JSON.stringify({ lang, theme: "light", web: true, featuresOff })};` });
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/providers") return json(providers);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/usage/quotas") { asked.push(url.search); return json(quotas); }
if (url.pathname.startsWith("/api/usage/quotas/history")) return json([]);
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 });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a provider's balance shows on its row in Providers", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const width of [900, 420]) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
await t.test(`${width}px ${lang}`, async () => {
const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const asked = [];
await page.route("**/*", server(lang, [], asked));
await page.goto("http://magpie.test/?view=providers");
const row = (id) => page.locator(`#providers .row.provider[data-id="${id}"]`);
const bal = (id) => row(id).locator(".who > .sub > .pv-bal");
await bal("relay").waitFor();
const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]);
// the relay's found balance, quietly after its models
assert.equal(await bal("relay").textContent(), " · $10472.14");
assert.equal(await bal("relay").getAttribute("title"), (await tr("Balance")) + " $10472.14");
assert.match(await row("relay").locator(".who > .sub").textContent(), /^relay\.example\.com · .+ · \$10472\.14$/);
// two keys: added up, as the Usage card's head does
const sum = await page.evaluate(() => balanceAmount({ balance: "$12.50" }, 20)); // "$20,00" in German
assert.match(sum, /^\$20[.,]00$/);
assert.equal(await bal("many").textContent(), " · " + sum);
// a read that failed, no card, a signed-in account: nothing
for (const id of ["broke", "none", "acct"]) assert.equal(await bal(id).count(), 0, id);
// Usage's own read, not an asked one
assert(asked.length >= 1 && asked.every((s) => !s.includes("asked")), "asked: " + asked.join(","));
// a quiet figure: the row's facts' colour and size, on one line
const look = await row("relay").evaluate((r) => {
const sub = r.querySelector(".who > .sub"), b = sub.querySelector(".pv-bal"), s = getComputedStyle(sub), c = getComputedStyle(b);
return { color: s.color === c.color, size: s.fontSize === c.fontSize, oneLine: sub.scrollHeight <= parseFloat(s.lineHeight || "16") * 1.6 + 2 || sub.getClientRects().length === 1, fits: sub.getBoundingClientRect().right <= r.getBoundingClientRect().right + 1 };
});
assert.deepEqual(look, { color: true, size: true, oneLine: true, fits: true });
// drawn again with the list, never twice
await page.evaluate(() => renderProviders());
assert.equal(await row("relay").locator(".pv-bal").count(), 1);
assert.deepEqual(errors, []);
await context.close();
});
}
}
await t.test("Usage turned off: no balance, nothing read", async () => {
const context = await browser.newContext({ viewport: { width: 900, height: 760 } });
const page = await context.newPage();
const asked = [];
await page.route("**/*", server("en", ["usage"], asked));
await page.goto("http://magpie.test/?view=providers");
await page.locator('#providers .row.provider[data-id="relay"]').waitFor();
// show() asks for Usage's read before the list is drawn, so none was asked
assert.equal(await page.evaluate(() => quotas === null && !quotasLoading), true);
assert.equal(await page.locator("#providers .pv-bal").count(), 0);
assert.deepEqual(asked, []);
await context.close();
});
});
}