gui: the tray's allowances show without their history, and stay as drawn when nothing changed (#3192)

parkavenue9639 found three things on the tray panel's Allowances tab:

- loadQuotas waited for /api/usage/quotas/history (45 days, and a
  remote magpie's too) in one Promise.all with the allowances, so the
  skeleton stayed until the curves' history came. The history is now
  read on its own (loadQuotaHist); the cards are drawn as soon as the
  allowances are in, and drawn again when a history that differs lands.
  Of two history reads on their way, the later asked stands.
- The window coming back (focus, visibility) ran renderPanelQuota from
  load() and again when the quotas came, each a rebuild of cards that
  had not changed (and, while loading, a restart of the skeleton's
  shimmer). Those two calls are now lazy: the panel is drawn only when
  something it draws from changed (the allowances, a new history, used
  or left, the curves' range, folded options, the settings, language,
  tab, peek, arranging, or the minute, for its clock deadlines). Every
  other caller draws as before.
- renderQuotas went on to build the Usage page's cards, trend and
  curves in the panel, which never shows that page. It now stops after
  the panel's own draw there.

renderQuotas' local `const mode` (the Used/Left picker) shadowed the
page's mode, so the new panel check hit its temporal dead zone; it is
`pick` now. The fold check `mode !== "panel"` beside it compared that
element, so it was always true; it is dropped, which changes nothing.

Tests: panel-quota-lazy.test.cjs, every language, 440 and 360 wide,
Chromium and WebKit: with the history held the card is drawn and no
skeleton is left; the panel draws no #subscriptionUsage cards; loadBack
with the same answers keeps the card and group nodes; a changed
allowance is drawn.

tray-cell-click waited for the card to be replaced after the window's
focus; with the same allowances it is kept now, so it waits for the
refresh to finish and checks the highlight on the card as drawn. Red
4 of 4 at the old wait, green with the new one.

Run:
- panel-quota-lazy at the old app.js: red in every case; at this change
  20 of 20.
- The whole GUI suite (826 files, --test-concurrency=3, load 40 to 90)
  at e0abb65ff on b1a2eec2c: 11641 tests, 46 failed in 14 files. Each
  of them was run alone at this change:
  - green alone: fonts, library-row-remove, market-have, model-copy-id,
    panel-profiles, remote-group-served, tray-usages, usage-pack.
  - red alone, the same count at the old app.js, filed: quota-count-wrap
    and quota-name-translated (#2228), s3-sync (#2448),
    usage-agents-hide 22 (#2276), usage-checkin 2 (#2549, #3091),
    usage-fold 2 (#2163), usage-ledger 6 (#3104).
- After rebasing onto b0d46ca7f: panel-quota-lazy, tray-cell-click,
  i18n-keys, panel-profiles and tray-usages, 53 of 53; go test
  ./internal/gui (core script budget) ok 4 runs of 5. The first run
  printed FAIL and its log was cut by a tail, so which test failed is
  not known; the next four were ok.
- Full Go suite at 36890807e (on b0d46ca7f): go test -timeout 45m
  ./..., 68 packages ok (gateway 550s, agent 442s, gui 205s); gofmt -l
  clean.
This commit is contained in:
yetone
2026-10-22 06:21:54 +08:00
parent b0d46ca7fe
commit 7dd965ed22
3 changed files with 140 additions and 17 deletions
+45 -16
View File
@@ -3996,7 +3996,7 @@ async function load(again) {
if (mode !== "panel" && !(view === "providers" || providersPage(view))) prefetchProviders();
// the panel brought up on its Allowances tab is the reader opening
// them (#1588); the page loaded while the panel is still put away is not
if (mode === "panel") { renderPanelQuota(); panelTab === "usage" && !document.hidden && (again || document.hasFocus()) ? quotasOpened() : loadQuotas(); }
if (mode === "panel") { renderPanelQuota(true); panelTab === "usage" && !document.hidden && (again || document.hasFocus()) ? quotasOpened() : loadQuotas(); }
// an open provider editor is someone typing: coming back to the window
// must not rebuild it under them
if ((view === "providers" || providersPage(view)) && !(editing || adding)) await loadProviders();
@@ -15282,9 +15282,12 @@ function loadQuotas(asked, again) {
const p = Promise.resolve(quotasLoading).catch(() => {})
.then(() => {
began = quotaRefreshVersion;
return Promise.all([api("usage/quotas" + (asked ? "?asked=1" : ""), undefined, (h) => { reading = h.get("X-Magpie-Reading") === "1"; }), api("usage/quotas/history?days=45").catch(() => null)]);
// the curves come on their own: the allowances now never wait for
// them (a remote magpie's history can take seconds; #3192)
loadQuotaHist();
return api("usage/quotas" + (asked ? "?asked=1" : ""), undefined, (h) => { reading = h.get("X-Magpie-Reading") === "1"; });
})
.then(([q, h]) => {
.then((q) => {
// an answer that isn't a list of cards is a read that failed: what
// was read before stays, as it does when the read is refused
if (q != null && !Array.isArray(q)) { quotas = quotas || []; reading = false; return; }
@@ -15292,12 +15295,12 @@ function loadQuotas(asked, again) {
// Whole-page reads are serialized; no older one still needs these
// markers. A card reply must not retire them while a GET is pending.
for (const [key, version] of quotaRefreshVersions) if (version <= began) quotaRefreshVersions.delete(key);
same =!!again && !!quotas && JSON.stringify(q || []) === JSON.stringify(quotas) && (!h || JSON.stringify(h) === JSON.stringify(quotaHist));
quotas = q || []; quotasAt = Date.now(); if (h) quotaHist = h;
same = !!again && !!quotas && JSON.stringify(q || []) === JSON.stringify(quotas);
quotas = q || []; quotasAt = Date.now();
}, () => { quotas = quotas || []; reading = false; })
.finally(() => {
if (quotasLoading === p) quotasLoading = null;
if (!same) renderQuotas();
if (!same) renderQuotas(true);
if (view === "usage") loadUpstream();
if (reading && !quotasLater && ++quotasTries <= 20) quotasLater = setTimeout(() => { quotasLater = 0; loadQuotas(false, true); }, 1500);
});
@@ -15306,6 +15309,19 @@ function loadQuotas(asked, again) {
return p;
}
// loadQuotaHist reads the allowances' history for the curves, and draws
// them again only when it differs from what is drawn. Of two reads on
// their way, the later asked is the one that stands.
let quotaHistSeq = 0, quotaHistV = 0;
function loadQuotaHist() {
const seq = ++quotaHistSeq;
return api("usage/quotas/history?days=45").then((h) => {
if (seq !== quotaHistSeq || !h || JSON.stringify(h) === JSON.stringify(quotaHist)) return;
quotaHist = h; quotaHistV++;
if (quotas) renderQuotas(true);
}, () => {});
}
// A whole-page reply can have left the backend before a card's refresh
// completed. Keep each card refreshed since this read began, including a
// card the older reply did not yet contain. A later read may replace it.
@@ -15392,8 +15408,13 @@ function ownLine(sub) {
return line;
}
function renderQuotas() {
renderPanelQuota();
// lazy: drawn only if something the panel shows changed (a load's answer,
// the window coming back), not each time it is asked (#3192)
function renderQuotas(lazy) {
renderPanelQuota(lazy);
// the tray panel never shows the Usage page: its cards and curves are
// not drawn there unseen (#3192)
if (mode === "panel") return;
const subscriptions = $("#subscriptionUsage");
const restoreFlash = keepQuotaFlash(subscriptions);
const restoreRefresh = keepQuotaRefresh(subscriptions);
@@ -15402,17 +15423,17 @@ function renderQuotas() {
// left turns their meters, and is only there when some card has one (a
// balance is only ever what is left)
$("#quotaHead").hidden = !!quotas && !quotas.length;
const mode = $("#quotaMode");
mode.hidden = !quotas?.some((q) => !q.error && q.windows?.length);
if (!mode.hidden) {
mode.replaceChildren();
const pick = $("#quotaMode");
pick.hidden = !quotas?.some((q) => !q.error && q.windows?.length);
if (!pick.hidden) {
pick.replaceChildren();
for (const [left, name] of [[false, "Used"], [true, "Left"]]) {
const b = el("button", "opt" + (left === quotaLeft ? " on" : ""), t(name));
b.title = t(left ? "Show how much of each window is left" : "Show how much of each window is used");
b.onclick = () => { if (left !== quotaLeft) setQuotaLeft(left); };
mode.append(b);
pick.append(b);
}
slide(mode, "quotaMode");
slide(pick, "quotaMode");
}
renderQuotaTrend();
if (!quotas) {
@@ -15463,7 +15484,7 @@ function renderQuotas() {
}
// many accounts (Linx on X: twenty-odd on one plugin, 顶成擎天柱):
// the same, each still a row of its own
const accts = !keys && several && mode !== "panel" && subs.length > ACCTS_FOLD;
const accts = !keys && several && subs.length > ACCTS_FOLD;
const folded = keys ? keysFolded(subs) : accts ? acctsFolded(subs) : new Set();
for (const sub of subs) {
if (folded.has(sub)) continue;
@@ -16860,9 +16881,17 @@ function renderPanelUse() {
// account; balances as figures. All in the Usage page's order, a balance
// where it was put there, not after the plans (#1510, JokerQyou); balances
// side by side share one grid.
function renderPanelQuota() {
//
// lazy: kept as it is when nothing it draws from has changed, so the
// window's focus and visibility coming back neither rebuild the cards nor
// start the skeleton's shimmer again (#3192). The minute is in it, for
// the deadlines it words by the clock.
function renderPanelQuota(lazy) {
const box = $("#panelQuota");
if (mode !== "panel" || !box) return;
const drawn = JSON.stringify([quotas, quotaHistV, quotaLeft, quotaRange, [...panelOptsFolded], state?.settings, locale, panelTab, panelPeek, panelArranging, usageArranging, Math.floor(Date.now() / 60e3)]);
if (lazy && renderPanelQuota.drawn === drawn) return;
renderPanelQuota.drawn = drawn;
const subs = byUsageOrder(keyCards(quotas || []).filter((q) => q.balance || q.error || q.windows?.length));
const none = !!quotas && !subs.length;
const usageTab = $('#ptabs [data-ptab="usage"]');
@@ -0,0 +1,91 @@
// #3192 (parkavenue9639): the tray panel's Allowances tab showed its
// skeleton until the allowances' 45-day history came, though the cards
// need only the allowances; the window coming back rebuilt cards that had
// not changed (and restarted the skeleton's shimmer while loading); and
// each draw also built the Usage page's cards and curves, which the panel
// never shows. Real page, isolated responses: no vendor, account or
// installed app is used. MAGPIE_QUOTA_ASSETS points at older assets to see
// it fail.
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 = process.env.MAGPIE_QUOTA_ASSETS || path.resolve(__dirname, "../assets");
const iso = n => new Date(n).toISOString();
function fixtures() {
const now = Date.now(), readAt = iso(now - 60000), resetsAt = iso(now + 2 * 3600000);
return [
{ provider: "codex", name: "Codex", icon: "openai", user: "b@example.com", plan: "Pro", readAt, windows: [{ name: "5 hours", used: 50, resetsAt }] },
{ provider: "relay", name: "Relay", balance: "$2.00", readAt, windows: [] },
];
}
function serve(lang, data) {
const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd" };
return async route => {
const url = new URL(route.request().url()), json = body => route.fulfill({ json: body });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = ${JSON.stringify({ 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") { data.states++; return json({ agents: [], profiles: [], settings }); }
if (url.pathname === "/api/settings") return json(settings);
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/usage/quotas") { data.gets++; return json(data.quotas); }
if (url.pathname === "/api/usage/quotas/history") { await data.history; return json([]); }
if (url.pathname === "/api/usage") return json({ calls: 0, cost: 0, days: [], agents: [], models: [], keys: [] });
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
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, body: "" }); }
};
}
async function open(t, engine, lang, width) {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await browser.newPage({ viewport: { width, height: 640 }, reducedMotion: "reduce" });
page.setDefaultTimeout(5000);
let release;
const data = { quotas: fixtures(), gets: 0, states: 0, history: new Promise(r => { release = r; }) };
const errors = [];
page.on("pageerror", e => errors.push(e.message));
await page.route("**/*", serve(lang, data));
await page.goto("http://magpie.test/?mode=panel");
await page.locator('#ptabs [data-ptab="usage"]').click();
return { page, data, errors, release };
}
const card = '#panelQuota .pq-card[data-card="codex|b@example.com"]';
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [440, 360]) {
test(`${engine} ${lang} ${width}px: the panel's allowances show without their history, and stay as drawn when nothing changed`, async (t) => {
const { page, data, errors, release } = await open(t, engine, lang, width);
// the history held: the allowances are drawn all the same
await page.locator(card).waitFor();
assert.equal(await page.locator("#panelQuota .skeleton").count(), 0, "no skeleton left once the allowances came");
release();
await page.evaluate(() => quotasLoading);
// the Usage page is never drawn in the panel
assert.equal(await page.locator("#subscriptionUsage > *").count(), 0, "the panel draws no Usage page cards");
// the window coming back with the same answers keeps the cards
await page.evaluate(() => { document.querySelector("#panelQuota .pq-card").kept = true; document.querySelector("#panelQuota .pq-group").kept = true; });
const states = data.states;
await page.evaluate(() => loadBack());
await page.evaluate(() => quotasLoading);
await page.evaluate(() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))));
assert.ok(data.states > states, "the state was read again");
assert.equal(await page.locator(card).evaluate(c => document.querySelector("#panelQuota .pq-card").kept === true && c.isConnected), true, "the card is the one drawn before");
assert.equal(await page.evaluate(() => document.querySelector("#panelQuota .pq-group").kept), true, "the group is the one drawn before");
// a change is drawn
data.quotas[0].windows[0].used = 75;
await page.evaluate(() => loadQuotas(true));
await page.locator(`${card} .pq-dial b`, { hasText: "75%" }).waitFor();
assert.deepEqual(errors, []);
});
}
}
}
+4 -1
View File
@@ -106,7 +106,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
window.__beforeFocusRefresh.getAnimations().find((a) => a.animationName === "flash").currentTime = 600;
window.dispatchEvent(new Event("focus"));
});
await panel.waitForFunction(() => document.querySelector('#panelQuota [data-card="codex|x@y.z"]') !== window.__beforeFocusRefresh);
// the refresh read the same allowances, so the card is kept as drawn
// (#3192); one drawn again would have to keep the highlight too
await panel.waitForFunction(() => !loadBack.flight && !quotasLoading);
await panel.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
assert(await panel.locator('#panelQuota [data-card="codex|x@y.z"]').evaluate((e) => e.classList.contains("flash")), "first-open focus refresh must preserve the highlight");
assert(await panel.locator('#panelQuota [data-card="codex|x@y.z"]').evaluate((e) => e.getAnimations().find((a) => a.animationName === "flash")?.currentTime >= 600), "refresh must continue the animation rather than restart it");