Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

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

yetone7dd965ed22e6
diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js
index 1d6fdbddb..180bcf60f 100644
--- a/internal/gui/assets/app.js
+++ b/internal/gui/assets/app.js
@@ -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"]');
diff --git a/internal/gui/tests/panel-quota-lazy.test.cjs b/internal/gui/tests/panel-quota-lazy.test.cjs
new file mode 100644
index 000000000..1fa3a8da9
--- /dev/null
+++ b/internal/gui/tests/panel-quota-lazy.test.cjs
@@ -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: "[email protected]", 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|[email protected]"]';
+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, []);
+ });
+ }
+ }
+}
diff --git a/internal/gui/tests/tray-cell-click.test.cjs b/internal/gui/tests/tray-cell-click.test.cjs
index 156e36e38..e01e7e4af 100644
--- a/internal/gui/tests/tray-cell-click.test.cjs
+++ b/internal/gui/tests/tray-cell-click.test.cjs
@@ -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|[email protected]"]') !== 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|[email protected]"]').evaluate((e) => e.classList.contains("flash")), "first-open focus refresh must preserve the highlight");
assert(await panel.locator('#panelQuota [data-card="codex|[email protected]"]').evaluate((e) => e.getAnimations().find((a) => a.animationName === "flash")?.currentTime >= 600), "refresh must continue the animation rather than restart it");