gui: an answer read while the accounts are read again is followed by the new one (#959) — usage/quotas answers at once with the kept copy and reads the accounts again behind it, so the tray panel, opened, showed the old usage (40%) while the window's next timed read had the new (used up), until refreshed by hand (Magixyne). Such an answer now says so (X-Magpie-Reading: 1, provider.SubscriptionUsageReading), and loadQuotas asks again every 1.5s, twenty times at most, until it has landed; an answer the same as the last isn't drawn again. quota-reading-again (panel and window, en and zh, Chromium and WebKit; a read that never lands stops after twenty) passes and fails without the fix; TestSubscriptionUsageReadingWhileStale passes with -race -count=5. claude-usage-asked, panel-usage, tray-usages, usage-card-refresh, usage-stale-answer, quota-curve and usage-fold pass; go test ./internal/provider/ ./internal/gui/ and vet pass.

This commit is contained in:
yetone
2026-10-06 10:58:10 +08:00
parent e564e5a309
commit 0c2dd5915e
5 changed files with 192 additions and 7 deletions
+22 -6
View File
@@ -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;
@@ -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, []);
});
}
}
+7 -1
View File
@@ -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
@@ -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")
}
}
+11
View File
@@ -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{}