gui: keep refreshed cards when their account identity changes (#1630)

The ce5d9f9d4 review correctly restored replies whose account was first
named by a refresh. Its full-list fallback bypassed the ordering guard:
an older GET could restore the unnamed card, or the fallback could undo
another card's completed refresh.

Apply the fallback to its provider's cards (a remote summary's namespaced
children included), keep other providers, and preserve card refreshes that
completed since the request began. Mark the replaced keys as well as the
new cards, so an old response cannot resurrect the unnamed summary. Only
a serialized whole-page read retires the markers it no longer needs.
No changes to account reading, authentication, throttling or auto-refresh.

Verification on macOS arm64, Go 1.27.2, Bun 1.4.3, isolated homes/APIs:
- On ce5d9f9d4, four new ordering cases fail: renamed account vs old GET,
  crossed card replies, a pending GET after another provider's completed
  refresh, and a remote summary becoming child cards. All nine now pass.
- The real browser page on ce5d9f9d4 reverts 61% to 28% after the late
  response. Named and unnamed cards now pass in both engines/all five
  languages. 21 related frontend files pass 184/184; the whole GUI suite
  was not run. The remote-card suite caught a missing namespace case in
  the first draft; corrected and the 21-file run repeated successfully.
- Three-platform vet and darwin/linux-nogui/windows builds pass. Final
  internal/gui Go tests pass after the namespace correction. Diff clean.
- Full go test -tags nogui ./... completed. The first isolation wrapper
  made TMPDIR too long for the omarchy Unix sockets; shortening TMPDIR
  makes that package pass. The unresolved failure is the already recorded
  TestPluginSOCKSProxy HTTPS/dead-SOCKS response-vs-error mismatch. No Go
  source or proxy paths changed; no full-suite-green claim.

Not tried: the native app or real account identity changes. These are
controlled response-order regressions, not the cause of the user's clicks
on the noninteractive reset-date glyph.

Review record (magpie maintainer session, on origin/main 429698f96, then
rebased onto fad96ea0f; sandbox HOME, private GOCACHE):
- gofmt -l clean; go vet darwin/linux/windows and the three builds pass.
- go test -tags nogui ./...: 52 packages ok at once. agent and gateway hit
  the 10m default under load ~190, middleware's TestFailOpen was slow and
  omarchy's sockets hit a long TMPDIR; rerun with a short TMPDIR and
  -timeout 40m all four are ok. internal/gui ok again after the rebase.
- quota-refresh-order: on main's app.js cases 6-9 fail; patched 9/9.
  Broken by hand, each red: no marker on replaced keys (6,8,9); an older
  reply may restore a removed key (6,8,9); fallback skipping
  keepRefreshedQuotas (7); remote children not matched (9); markers
  retired inside keepRefreshedQuotas (8); belongs() always true (8).
- Full GUI suite in chromium and webkit, 5 languages, 1100/420. Reds also
  red on main alone: usage-agents-hide and usage-fold (#2211, #2163),
  usage-sum-whole ja/de 780px (#1864: main 1/3, patched 2/3; that test
  serves no quotas). quota-name-translated and quota-pace goto timeouts
  under load passed rerun. After the rebase quota-refresh-order and
  usage-card-refresh pass 21/21 in both engines.
- Not tried: the native app or a real account whose identity changes.
This commit is contained in:
hhh2210
2026-10-15 00:44:51 +08:00
committed by yetone
parent 62fc1b4b57
commit 2a99e7a429
4 changed files with 86 additions and 10 deletions
+7
View File
@@ -40,6 +40,13 @@ card list. A whole-page read begun before that refresh completed keeps
the newer card when its older response arrives; other cards still update,
and a later whole-page read can replace or remove the card. This also
keeps two different card refreshes from undoing each other's results.
If a refresh first supplies the account's name, its provider's cards are
replaced while newer card refreshes and other providers stay. The replaced
keys are protected too: an older whole-page response cannot restore an
unnamed card or erase its newly named replacement. Only a completed
whole-page read retires the ordering markers it no longer needs.
A remote magpie's summary can likewise become its namespaced child cards;
refreshing it preserves local providers and other remote magpies.
`keepRefreshedQuotas` and `quotaRefresh` in
[`app.js`](../../internal/gui/assets/app.js) own this publication order;
`quota-refresh-order.test.cjs` covers held responses and failures, and
+24 -7
View File
@@ -14430,6 +14430,9 @@ function loadQuotas(asked, again) {
// was read before stays, as it does when the read is refused
if (q != null && !Array.isArray(q)) { quotas = quotas || []; reading = false; return; }
q = keepRefreshedQuotas(q || [], began);
// 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;
}, () => { quotas = quotas || []; reading = false; })
@@ -14448,12 +14451,13 @@ function loadQuotas(asked, again) {
// 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.
function keepRefreshedQuotas(next, began) {
for (const [key, version] of quotaRefreshVersions) if (version <= began) quotaRefreshVersions.delete(key);
const kept = new Map((quotas || []).filter(q => quotaRefreshVersions.has(usageAcctKey(q))).map(q => [usageAcctKey(q), q]));
const out = next.map(q => {
const kept = new Map((quotas || []).filter(q => quotaRefreshVersions.get(usageAcctKey(q)) > began).map(q => [usageAcctKey(q), q]));
const out = next.flatMap(q => {
const key = usageAcctKey(q), newer = kept.get(key);
kept.delete(key);
return newer || q;
// A protected key with no current card was removed or replaced by a
// newly named account. An older response cannot bring it back.
return newer ? [newer] : quotaRefreshVersions.get(key) > began ? [] : [q];
});
return out.concat([...kept.values()]);
}
@@ -17164,6 +17168,7 @@ function quotaRefresh(q) {
if (quotaRefreshing.has(key)) return;
quotaRefreshing.add(key);
b.classList.add("busy");
const began = quotaRefreshVersion;
try {
const qs = await api("usage/quotas/refresh?provider=" + encodeURIComponent(q.provider) + (q.user ? "&user=" + encodeURIComponent(q.user) : ""), {});
const fresh = Array.isArray(qs) && qs.find(x => usageAcctKey(x) === key);
@@ -17175,9 +17180,21 @@ function quotaRefresh(q) {
quotas = kept.some(x => usageAcctKey(x) === key) ? kept.map(x => usageAcctKey(x) === key ? fresh : x) : [...kept, fresh];
quotasAt = Date.now();
} else if (Array.isArray(qs)) {
// The card came back under another key (an account first read
// under its name): the reply's list is taken as it was before.
quotas = qs; quotasAt = Date.now();
// The account was first named by this read. Replace its provider's
// cards, preserving other providers and newer completed refreshes.
const belongs = x => x.provider === q.provider || q.from && x.provider.startsWith(q.provider + "/");
const before = quotas || [], replacement = qs.filter(belongs), next = [];
let placed = false;
for (const x of before) {
if (!belongs(x)) next.push(x);
else if (!placed) { next.push(...replacement); placed = true; }
}
if (!placed) next.push(...replacement);
quotas = keepRefreshedQuotas(next, began); quotasAt = Date.now();
// Protect the new identities and the old keys they replaced, so a
// pending GET can neither erase the new cards nor restore the old.
const version = ++quotaRefreshVersion;
for (const x of [q, ...before, ...quotas]) if (belongs(x)) quotaRefreshVersions.set(usageAcctKey(x), version);
}
} catch (err) {
status(err.message, "err");
@@ -98,3 +98,53 @@ test("a card that comes back under another key still shows the reply", async ()
p.answer(0, [card("a@x.com", 32)]); await refresh;
assert.deepEqual(plain(p.cards()).map(q => [q.user, q.windows[0].used]), [["a@x.com", 32]], "the refreshed card's reply was dropped");
});
test("an account first named by refresh survives an older whole-page reply", async () => {
const p = page(), unnamed = card("", 0);
p.seed([unnamed]);
const loading = p.load(); await tick();
const refresh = p.refresh(unnamed);
p.answer(1, [card("a@x.com", 32)]); await refresh;
p.answer(0, [unnamed]); await loading;
assert.deepEqual(plain(p.cards()).map(q => [q.user, q.windows[0].used]), [["a@x.com", 32]], "an old reply restored the unnamed card over its refresh");
});
test("an account first named by refresh keeps another card's completed refresh", async () => {
const p = page(), unnamed = card("", 0), b = card("b@x.com", 0);
p.seed([unnamed,b]);
const first = p.refresh(unnamed), second = p.refresh(b);
p.answer(1,[unnamed,card("b@x.com",61)]); await second;
p.answer(0,[card("a@x.com",32),b]); await first;
assert.deepEqual(plain(p.cards()).map(q => [q.user,q.windows[0].used]), [["a@x.com",32],["b@x.com",61]], "the renamed card's reply undid another card's completed refresh");
});
test("a renamed card cannot retire another provider's protection against a pending GET", async () => {
const p = page(), unnamed = card("", 0), b = { ...card("b@x.com", 0), provider: "codex" };
const freshB = { ...card("b@x.com", 61), provider: "codex" };
p.seed([unnamed, b]);
const loading = p.load(); await tick();
const second = p.refresh(b);
p.answer(1, [unnamed, freshB]); await second;
const first = p.refresh(unnamed);
p.answer(2, [card("a@x.com", 32), b]); await first;
const readings = () => Object.fromEntries(plain(p.cards()).map(q => [q.user, q.windows[0].used]));
assert.deepEqual(readings(), { "a@x.com": 32, "b@x.com": 61 }, "the provider refresh replaced another provider's newer card");
p.answer(0, [unnamed, b]); await loading;
assert.deepEqual(readings(), { "a@x.com": 32, "b@x.com": 61 }, "the card reply retired protection needed by the older GET");
});
test("a remote summary becomes its child cards without undoing a local refresh", async () => {
const p = page(), summary = { ...card("", 0), provider: "home", from: "Home" };
const child = { ...card("a@x.com", 32), provider: "home/claude", from: "Home" };
const local = { ...card("b@x.com", 0), provider: "codex" };
const freshLocal = { ...local, windows: [{ name: "7 days", used: 61 }] };
p.seed([summary, local]);
const loading = p.load(); await tick();
const remote = p.refresh(summary), own = p.refresh(local);
p.answer(2, [summary, freshLocal]); await own;
p.answer(1, [child, local]); await remote;
const readings = () => Object.fromEntries(plain(p.cards()).map(q => [q.provider, q.windows[0].used]));
assert.deepEqual(readings(), { "home/claude": 32, codex: 61 });
p.answer(0, [summary, local]); await loading;
assert.deepEqual(readings(), { "home/claude": 32, codex: 61 }, "the late GET restored the remote summary or an old local reading");
});
@@ -53,6 +53,7 @@ function serve(lang, state) {
if (q?.windows?.length) { q.windows[0].used = 61; q.readAt = iso(Date.now()); }
if (q?.error) { delete q.error; q.windows = [{ name: "Week", used: 10 }]; q.readAt = iso(Date.now()); }
if (q) { delete q.asOf; delete q.readDeferred; }
if (q && state.nameOnRefresh && !q.user) q.user = "a@x.com";
return json(state.quotas);
}
if (url.pathname === "/api/usage/quotas/history") return json([]);
@@ -75,14 +76,15 @@ const deferredWords = {
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(deferredWords)) {
test(`${engine} ${lang}: a deferred card is not a failure, and a late background reply cannot undo its refresh`, async (t) => {
for (const named of [true, false]) test(`${engine} ${lang}: a deferred ${named ? "named" : "unnamed"} card is not a failure, and a late background reply cannot undo its refresh`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await browser.newPage({ viewport: { width: 900, height: 700 }, reducedMotion: "reduce" });
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", e => errors.push(e.message));
const state = { quotas: fixtures(Date.now()), gets: 0, refreshes: [] };
const state = { quotas: fixtures(Date.now()), gets: 0, refreshes: [], nameOnRefresh: !named };
if (!named) state.quotas[0].user = "";
state.quotas[0].asOf = state.quotas[0].readAt;
state.quotas[0].readDeferred = true;
await page.route("**/*", serve(lang, state));
@@ -107,7 +109,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await page.evaluate(() => quotasLoading);
assert.match(await claude.locator(".quota-n").textContent(), /61%/, "an older reply undid the click");
assert.equal(await read.evaluate(e => e.classList.contains("stale")), false);
assert.deepEqual(state.refreshes, ["?provider=claude&user=a%40x.com"]);
assert.deepEqual(state.refreshes, [named ? "?provider=claude&user=a%40x.com" : "?provider=claude"]);
assert.deepEqual(errors, []);
});
}