From 0c2dd5915e5d3cbc548f488841fbb013acdf5615 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 6 Oct 2026 10:50:05 +0800 Subject: [PATCH] =?UTF-8?q?gui:=20an=20answer=20read=20while=20the=20accou?= =?UTF-8?q?nts=20are=20read=20again=20is=20followed=20by=20the=20new=20one?= =?UTF-8?q?=20(#959)=20=E2=80=94=20usage/quotas=20answers=20at=20once=20wi?= =?UTF-8?q?th=20the=20kept=20copy=20and=20reads=20the=20accounts=20again?= =?UTF-8?q?=20behind=20it,=20so=20the=20tray=20panel,=20opened,=20showed?= =?UTF-8?q?=20the=20old=20usage=20(40%)=20while=20the=20window's=20next=20?= =?UTF-8?q?timed=20read=20had=20the=20new=20(used=20up),=20until=20refresh?= =?UTF-8?q?ed=20by=20hand=20(Magixyne).=20Such=20an=20answer=20now=20says?= =?UTF-8?q?=20so=20(X-Magpie-Reading:=201,=20provider.SubscriptionUsageRea?= =?UTF-8?q?ding),=20and=20loadQuotas=20asks=20again=20every=201.5s,=20twen?= =?UTF-8?q?ty=20times=20at=20most,=20until=20it=20has=20landed;=20an=20ans?= =?UTF-8?q?wer=20the=20same=20as=20the=20last=20isn't=20drawn=20again.=20q?= =?UTF-8?q?uota-reading-again=20(panel=20and=20window,=20en=20and=20zh,=20?= =?UTF-8?q?Chromium=20and=20WebKit;=20a=20read=20that=20never=20lands=20st?= =?UTF-8?q?ops=20after=20twenty)=20passes=20and=20fails=20without=20the=20?= =?UTF-8?q?fix;=20TestSubscriptionUsageReadingWhileStale=20passes=20with?= =?UTF-8?q?=20-race=20-count=3D5.=20claude-usage-asked,=20panel-usage,=20t?= =?UTF-8?q?ray-usages,=20usage-card-refresh,=20usage-stale-answer,=20quota?= =?UTF-8?q?-curve=20and=20usage-fold=20pass;=20go=20test=20./internal/prov?= =?UTF-8?q?ider/=20./internal/gui/=20and=20vet=20pass.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gui/assets/app.js | 28 ++++-- .../gui/tests/quota-reading-again.test.cjs | 92 +++++++++++++++++++ internal/gui/usage.go | 8 +- .../provider/subscription_reading_test.go | 60 ++++++++++++ internal/provider/subscription_usage.go | 11 +++ 5 files changed, 192 insertions(+), 7 deletions(-) create mode 100644 internal/gui/tests/quota-reading-again.test.cjs create mode 100644 internal/provider/subscription_reading_test.go diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 569b65de9..2e6a93401 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -63,13 +63,15 @@ const modelFavorites = new Set(Array.isArray(savedModelFavorites) ? savedModelFa const favoriteKey = (o) => o.ref || o.value; const isFavorite = (o) => modelFavorites.has(favoriteKey(o)) || modelFavorites.has(o.value); -async function api(path, body) { +// heads, when given, is shown the answer's headers (loadQuotas' X-Magpie-Reading) +async function api(path, body, heads) { if (web && path === "open") { window.open(body.url, "_blank", "noopener"); return null; } const res = await fetch("/api/" + path, { method: body === undefined ? "GET" : "POST", headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), }); + heads?.(res.headers); if (res.status === 204) return null; // a body that isn't JSON (a proxy's or a plain http.Error) is the error // itself, not WebKit's "did not match the expected pattern" @@ -11923,13 +11925,27 @@ async function loadUsage(asked) { // An asked load is never swallowed by one already on its way that wasn't: // it goes after it. -let quotasLoading = null; -function loadQuotas(asked) { +// An answer said to be read while the accounts' usage is being read again +// (X-Magpie-Reading) can be the stale copy that read replaces: it is asked +// for again, every 1.5s for half a minute at most, until the new one has +// landed, so the tray panel, opened, shows what the window does without a +// refresh by hand (#959). An answer the same as the last isn't drawn again. +let quotasLoading = null, quotasLater = 0, quotasTries = 0; +function loadQuotas(asked, again) { if (quotasLoading && (!asked || quotasLoading.asked)) return quotasLoading; + if (!again) quotasTries = 0; + let reading = false, same = false; const p = Promise.resolve(quotasLoading).catch(() => {}) - .then(() => Promise.all([api("usage/quotas" + (asked ? "?asked=1" : "")), api("usage/quotas/history?days=35").catch(() => null)])) - .then(([q, h]) => { quotas = q || []; quotasAt = Date.now(); if (h) quotaHist = h; }, () => { quotas = quotas || []; }) - .finally(() => { if (quotasLoading === p) quotasLoading = null; renderQuotas(); }); + .then(() => Promise.all([api("usage/quotas" + (asked ? "?asked=1" : ""), undefined, (h) => { reading = h.get("X-Magpie-Reading") === "1"; }), api("usage/quotas/history?days=35").catch(() => null)])) + .then(([q, h]) => { + 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; + }, () => { quotas = quotas || []; reading = false; }) + .finally(() => { + if (quotasLoading === p) quotasLoading = null; + if (!same) renderQuotas(); + if (reading && !quotasLater && ++quotasTries <= 20) quotasLater = setTimeout(() => { quotasLater = 0; loadQuotas(false, true); }, 1500); + }); p.asked = !!asked; quotasLoading = p; return p; diff --git a/internal/gui/tests/quota-reading-again.test.cjs b/internal/gui/tests/quota-reading-again.test.cjs new file mode 100644 index 000000000..be8b000a3 --- /dev/null +++ b/internal/gui/tests/quota-reading-again.test.cjs @@ -0,0 +1,92 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// #959: the tray panel, opened, showed an account's old usage while the +// window had the new, until refreshed by hand. magpie answers usage/quotas +// at once with what it kept and reads the accounts again behind it; such an +// answer says so (X-Magpie-Reading: 1), and the page asks again until the +// new reading has landed. The panel and the window both show it without a +// click; the follow-up asks stop once the read is done, and a run that never +// lands stops asking after half a minute's worth. English and Chinese, +// Chromium and WebKit; no backend, the API is faked here. +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(__dirname, "../assets"); + +// the read behind: the first `stale` answers are the kept copy, said to be +// read while a new one is on its way; then the new one, read +function serve(lang, read) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data, headers) => route.fulfill({ json: data, headers }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${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") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/usage/quotas") { + read.asks++; + const stale = read.asks <= read.stale; + const used = stale ? 40 : 100; + return json([{ provider: "codex", name: "Codex", user: "a@example.com", plan: "plus", + windows: [{ name: "5 hours", used, resetsAt: new Date(Date.now() + 36e5).toISOString() }] }], + stale ? { "X-Magpie-Reading": "1" } : {}); + } + if (url.pathname === "/api/usage/quotas/history") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true } }); + 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: "" }); } + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + for (const surface of ["panel", "window"]) { + test(`${engine} ${lang} ${surface}: an answer read while the accounts are read again is followed by the new one`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await browser.newPage({ viewport: { width: surface === "panel" ? 440 : 900, height: 760 }, reducedMotion: "reduce" }); + page.setDefaultTimeout(8000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const read = { asks: 0, stale: 2 }; + await page.route("**/*", serve(lang, read)); + await page.goto(surface === "panel" ? "http://magpie.test/?mode=panel" : "http://magpie.test/?view=usage"); + if (surface === "panel") await page.locator('button[data-ptab="usage"]').click(); + const card = surface === "panel" ? ".pq-card" : ".subscription-card"; + await page.waitForFunction((s) => document.querySelector(s)?.textContent.includes("40%"), card); + // no click, no focus: the new reading comes by itself + await page.waitForFunction((s) => document.querySelector(s)?.textContent.includes("100%"), card); + const after = read.asks; + await page.waitForTimeout(2500); + assert.equal(read.asks, after, "once the new reading is in, nothing more is asked"); + assert.deepEqual(errors, []); + }); + } + test(`${engine} ${lang}: a read that never lands is asked after for half a minute at most`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await browser.newPage({ viewport: { width: 440, height: 760 }, reducedMotion: "reduce" }); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.clock.install(); + const read = { asks: 0, stale: Infinity }; + await page.route("**/*", serve(lang, read)); + await page.goto("http://magpie.test/?mode=panel"); + await page.locator('button[data-ptab="usage"]').click(); + await page.waitForFunction(() => document.querySelector(".pq-card")?.textContent.includes("40%")); + const first = read.asks; + for (let i = 0; i < 40; i++) { await page.clock.runFor(1500); await page.waitForTimeout(30); } + const asked = read.asks - first; + assert(asked >= 15 && asked <= 21, `about 20 follow-ups, not more: ${asked}`); + const n = read.asks; + for (let i = 0; i < 10; i++) { await page.clock.runFor(1500); await page.waitForTimeout(30); } + assert.equal(read.asks, n, "then it stops"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/usage.go b/internal/gui/usage.go index f96bf29b6..de2455e7d 100644 --- a/internal/gui/usage.go +++ b/internal/gui/usage.go @@ -441,7 +441,13 @@ func usageRoutes(mux *http.ServeMux, w Windows) { defer cancel() // a WorkBuddy (China) account's card says how its daily check-in // went (#694) - writeJSON(rw, provider.WithCheckins(provider.Quotas(ctx))) + qs := provider.WithCheckins(provider.Quotas(ctx)) + // an account's card may be the stale copy a read under way will + // replace: the page asks again until it has landed (#959) + if provider.SubscriptionUsageReading() { + rw.Header().Set("X-Magpie-Reading", "1") + } + writeJSON(rw, qs) }) // One card read again, from its refresh button (#840): ?provider= and, // of a card with several accounts, &user=; the others are left as they diff --git a/internal/provider/subscription_reading_test.go b/internal/provider/subscription_reading_test.go new file mode 100644 index 000000000..1eeb2c783 --- /dev/null +++ b/internal/provider/subscription_reading_test.go @@ -0,0 +1,60 @@ +package provider + +import ( + "context" + "testing" + "time" +) + +// #959: an answer given from the kept copy while the accounts are read +// again says so, for the page to ask again once the new reading lands; the +// read done, it no longer does. +func TestSubscriptionUsageReadingWhileStale(t *testing.T) { + claudeHome(t) + c := &subscriptionUsageCache + c.Lock() + oldAt, oldData, oldAsked, oldPending := c.at, c.data, c.asked, c.pending + c.at, c.asked, c.pending = time.Now(), false, nil + c.data = []SubscriptionQuota{{Provider: "codex", User: "a@example.com", Windows: []QuotaWindow{{Name: "5 hours", Used: 40}}}} + c.Unlock() + t.Cleanup(func() { + c.Lock() + c.at, c.data, c.asked, c.pending = oldAt, oldData, oldAsked, oldPending + c.Unlock() + }) + + SubscriptionUsage(context.Background()) + if SubscriptionUsageReading() { + t.Fatal("a fresh copy, with nothing read again, said to be reading") + } + + held := make(chan struct{}) + c.Lock() + c.pending = held + c.Unlock() + if !SubscriptionUsageReading() { + t.Fatal("a read under way not told") + } + c.Lock() + c.pending = nil + c.Unlock() + + // stale: the kept copy comes back at once and a read starts behind it, + // told until it has landed + c.Lock() + c.at = time.Now().Add(-2 * time.Minute) + c.Unlock() + got := SubscriptionUsage(context.Background()) + if len(got) != 1 || got[0].Windows[0].Used != 40 { + t.Fatalf("the kept copy not answered at once: %+v", got) + } + c.Lock() + p := c.pending + c.Unlock() + if p != nil { + <-p + } + if SubscriptionUsageReading() { + t.Fatal("still said to be reading after the read landed") + } +} diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index 25216a268..28899f4dd 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -191,6 +191,17 @@ func SubscriptionUsage(ctx context.Context) []SubscriptionQuota { return withDailyCredits(out, time.Now()) } +// SubscriptionUsageReading says a read of the accounts' usage is under way: +// what SubscriptionUsage just gave may be the stale copy it replaces, for a +// page to ask again once it lands (#959: the panel, opened, kept the old +// copy until refreshed by hand, while the window's next read had the new). +func SubscriptionUsageReading() bool { + c := &subscriptionUsageCache + c.Lock() + defer c.Unlock() + return c.pending != nil +} + // visibleQuotas drops accounts removed from magpie since the last refresh. func visibleQuotas(all []SubscriptionQuota) []SubscriptionQuota { hidden := map[string]bool{}