diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 693eebe90..1ebffca04 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -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 diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 3d45bdb87..362ab5071 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -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"); diff --git a/internal/gui/tests/quota-refresh-order.test.cjs b/internal/gui/tests/quota-refresh-order.test.cjs index 4d3ac482e..b5e6ec7ed 100644 --- a/internal/gui/tests/quota-refresh-order.test.cjs +++ b/internal/gui/tests/quota-refresh-order.test.cjs @@ -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"); +}); diff --git a/internal/gui/tests/usage-card-refresh.test.cjs b/internal/gui/tests/usage-card-refresh.test.cjs index 0e2ce21bb..ad5b8e285 100644 --- a/internal/gui/tests/usage-card-refresh.test.cjs +++ b/internal/gui/tests/usage-card-refresh.test.cjs @@ -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, []); }); }