Skip to content

Commit c82dded

Browse files
agentHitsclaude
andcommitted
fix(gui): a superseded quota refresh joins only a newer successful outcome
`useProviderAccountPools` stamped `freshLandedRef[key] = generation` for every HTTP 200 quota payload and only then returned false for a structured `quotaUnavailable` row. A refresh A that had been superseded by B consulted that stamp and reported success, so the operator saw "Quota check completed" for a read whose newest result was a failure. A landed quota observation and a successful refresh are now separate facts. The hook keeps the latest quota outcome next to its generation (`quotaOutcomeRef: { generation, ok }`), written for a structured-unavailable payload, a thrown quota read and a failed roster read alike. A superseded request joins the newer request only when that outcome is newer and ok. The newer request's membership, selection, last-good readings and unavailable flags are applied exactly as before; only the boolean a stale caller receives changes. Overlap controls in provider-account-quota-loading.test.tsx, each asserting the returned value, the active account, the roster membership and the last-good/unavailable flags: - newer HTTP failure -> superseded A returns false - newer HTTP 200 / unavailable -> superseded A returns false - newer successful enrichment -> superseded A returns true - a later failure after an earlier success -> false (latest outcome wins) Against the previous hook the unavailable and latest-outcome cases fail and the HTTP-failure and success controls pass, which is the reproduction in review 5481554870. Also in this change, because it is the same overlap seen from the poller: the visibility poll skips a provider whose forced quota read is still in flight instead of starting a cached read that would supersede it. The removal-confirmation scope binding that landed with the merge gets its regression test here: the dialog does not follow the panel to another provider or another API base, and confirming back in the original scope removes from that scope only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 2ba8d36 commit c82dded

3 files changed

Lines changed: 174 additions & 11 deletions

File tree

‎gui/src/hooks/useProviderAccountPools.ts‎

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -179,15 +179,22 @@ export function useProviderAccountPools(deps: {
179179
requests.clear();
180180
};
181181
}, [apiBase]);
182-
// Newest generation whose QUOTA data was actually applied, per provider key. A
183-
// request superseded mid-flight by a newer one reports success only when fresher
184-
// quota already landed, so a manual refresh racing the visibility poll does not
185-
// surface a "refresh failed" state for data that is already on screen — and a
186-
// failed newer quota request still surfaces as failure.
187-
const freshLandedRef = useRef<Record<string, number>>({});
182+
// Latest settled QUOTA outcome per provider key, with the request generation that
183+
// owns it. A landed observation is not a successful refresh: an HTTP 200 whose rows
184+
// report `quotaUnavailable` settles as a failure, and so does a failed quota read.
185+
// A request superseded mid-flight may only join a newer SUCCESSFUL outcome, so a
186+
// manual refresh racing the visibility poll does not surface "refresh failed" for
187+
// data already on screen, while a newer structured-unavailable or failed quota
188+
// result still surfaces as failure to every caller it superseded.
189+
const quotaOutcomeRef = useRef<Record<string, { generation: number; ok: boolean }>>({});
190+
// Forced quota reads in flight per provider key. The visibility poll skips a provider
191+
// that already has one: its targeted refresh would only supersede the read the operator
192+
// (or the previous tick) is still waiting on, and that read answers the same question.
193+
const forcedQuotaInFlightRef = useRef<Record<string, number>>({});
188194
const supersededByFresher = useCallback((key: string, generation: number): boolean => {
189195
if (!aliveRef.current || !mountedRef.current || serverRef.current !== apiBase) return false;
190-
return (freshLandedRef.current[key] ?? -1) > generation;
196+
const outcome = quotaOutcomeRef.current[key];
197+
return outcome !== undefined && outcome.generation > generation && outcome.ok;
191198
}, [aliveRef, apiBase]);
192199
// Provider lists this instance has already fetched for. The deferred loads below are deliberately
193200
// uncancellable, and StrictMode double-invokes their effects, so dedupe by list identity here.
@@ -231,6 +238,7 @@ export function useProviderAccountPools(deps: {
231238
const currentRequest = () => aliveRef.current && mountedRef.current && serverRef.current === apiBase && accountRequestGenerationRef.current[key] === generation;
232239
const currentRoster = () => currentRequest() && rosterGenerationRef.current[key] === rosterGeneration;
233240
const url = `${apiBase}/api/oauth/accounts?provider=${encodeURIComponent(provider)}`;
241+
if (refresh) forcedQuotaInFlightRef.current[key] = (forcedQuotaInFlightRef.current[key] ?? 0) + 1;
234242
try {
235243
const targetQuery = targetAccountId ? `&accountId=${encodeURIComponent(targetAccountId)}` : "";
236244
// Cheap local read first so account switch / reauth / remove controls appear
@@ -269,10 +277,12 @@ export function useProviderAccountPools(deps: {
269277
accounts: mergeQuotaRows(enriched, current[provider]?.accounts ?? [], true),
270278
},
271279
});
272-
if (currentQuota()) freshLandedRef.current[key] = generation;
273-
return !enriched.some(row => row.quotaUnavailable === true);
280+
const ok = !enriched.some(row => row.quotaUnavailable === true);
281+
if (currentQuota()) quotaOutcomeRef.current[key] = { generation, ok };
282+
return ok;
274283
} catch {
275284
if (!currentQuota()) return supersededByFresher(key, generation);
285+
quotaOutcomeRef.current[key] = { generation, ok: false };
276286
setAccountSets(current => currentQuota() && current[provider] ? {
277287
...current, [provider]: { ...current[provider], accounts: unavailableQuotaRows(current[provider].accounts, rows) },
278288
} : current);
@@ -284,11 +294,15 @@ export function useProviderAccountPools(deps: {
284294
return true;
285295
} catch {
286296
if (!currentRoster()) return supersededByFresher(key, generation);
297+
// The rows below are marked unavailable, so this is the latest quota outcome too.
298+
quotaOutcomeRef.current[key] = { generation, ok: false };
287299
setAccountLoadStates(current => currentRoster() ? { ...current, [provider]: "error" } : current);
288300
setAccountSets(current => currentRoster() && current[provider] ? {
289301
...current, [provider]: { ...current[provider], accounts: unavailableQuotaRows(current[provider].accounts) },
290302
} : current);
291303
return false;
304+
} finally {
305+
if (refresh) forcedQuotaInFlightRef.current[key] = Math.max(0, (forcedQuotaInFlightRef.current[key] ?? 1) - 1);
292306
}
293307
}));
294308
return results.every(Boolean);
@@ -712,6 +726,7 @@ export function useProviderAccountPools(deps: {
712726
if (oauthCardProviders.length === 0) return;
713727
return startVisibilityPoll(() => {
714728
for (const provider of oauthCardProviders) {
729+
if (forcedQuotaInFlightRef.current[`oauth:${provider}`]) continue;
715730
const activeId = accountSetsRef.current[provider]?.activeAccountId;
716731
if (activeId) {
717732
// Force refresh ONLY for the active/selected account; inactive accounts read from cache (10m TTL)

‎gui/tests/provider-account-quota-loading.test.tsx‎

Lines changed: 114 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,9 +107,10 @@ function deferred<T>() {
107107
const promise = new Promise<T>(done => { resolve = done; });
108108
return { promise, resolve };
109109
}
110-
function Harness({ apiBase = "/quota-hook" }: { apiBase?: string }) {
110+
type HarnessConfig = Parameters<typeof useProviderAccountPools>[0]["config"];
111+
function Harness({ apiBase = "/quota-hook", config = null }: { apiBase?: string; config?: HarnessConfig }) {
111112
const aliveRef = useRef(true);
112-
const currentPools = useProviderAccountPools({ apiBase, config: null, aliveRef, t: key => key,
113+
const currentPools = useProviderAccountPools({ apiBase, config, aliveRef, t: key => key,
113114
oauthStatus: {}, notify: () => {}, fetchConfig: noop, fetchOauth: noop,
114115
fetchProviderQuotas: noop, codexActiveNeedsReauth: false });
115116
useLayoutEffect(() => { pools = currentPools; }, [currentPools]);
@@ -358,6 +359,117 @@ test("one unavailable enriched account fails forced refresh and preserves its ow
358359
expect(pools.accountSets.oauth.accounts[0]).toMatchObject({ quota: reading, quotaPending: false, quotaUnavailable: true });
359360
});
360361

362+
// A superseded manual refresh joins the newer request's quota OUTCOME, not merely its
363+
// generation: only a newer successful enrichment reads as success to the caller it overtook.
364+
for (const newer of ["http-failure", "structured-unavailable", "success"] as const) {
365+
test(`superseded OAuth refresh joins the newer quota outcome (${newer})`, async () => {
366+
const lastGood = { ...reading, fiveHourPercent: 55 };
367+
const stale = { ...reading, fiveHourPercent: 99 };
368+
await act(async () => { pools.setAccountSets({ oauth: { activeAccountId: "a",
369+
accounts: ["a", "b"].map(id => ({ id, active: id === "a", quotaMode: "probe" as const, quota: lastGood })) } }); });
370+
const olderQuota = deferred<Response>();
371+
const olderStarted = deferred<void>();
372+
let rosterReads = 0;
373+
let probes = 0;
374+
// The newer request sees a switched selection and an account added after the older one was sent.
375+
const olderRows = ["a", "b"].map(id => ({ id, active: id === "a", quotaMode: "probe" as const }));
376+
const newerRows = ["a", "b", "c"].map(id => ({ id, active: id === "b", quotaMode: "probe" as const }));
377+
respond = async url => {
378+
if (!url.includes("quota=1")) return ++rosterReads === 1
379+
? Response.json({ activeAccountId: "a", accounts: olderRows })
380+
: Response.json({ activeAccountId: "b", accounts: newerRows });
381+
if (++probes === 1) { olderStarted.resolve(); return olderQuota.promise; }
382+
if (newer === "http-failure") return new Response(null, { status: 503 });
383+
return Response.json({ activeAccountId: "b", accounts: newerRows.map(row =>
384+
newer === "structured-unavailable" && row.id === "a" ? { ...row, quotaUnavailable: true } : { ...row, quota: reading }) });
385+
};
386+
let older!: Promise<boolean>;
387+
await act(async () => { older = pools.fetchAccountSets(["oauth"], true); await olderStarted.promise; });
388+
await act(async () => { expect(await pools.fetchAccountSets(["oauth"], true)).toBe(newer === "success"); });
389+
// The older response is a complete success for the roster it was sent for. It must
390+
// neither decide the result nor overwrite what the newer request published.
391+
await act(async () => {
392+
olderQuota.resolve(Response.json({ activeAccountId: "a", accounts: olderRows.map(row => ({ ...row, quota: stale })) }));
393+
expect(await older).toBe(newer === "success");
394+
});
395+
const { activeAccountId, accounts } = pools.accountSets.oauth;
396+
expect(activeAccountId).toBe("b");
397+
expect(accounts.map(row => row.id)).toEqual(["a", "b", "c"]);
398+
expect(accounts.filter(row => row.active).map(row => row.id)).toEqual(["b"]);
399+
expect(accounts.every(row => row.quotaPending === false)).toBe(true);
400+
if (newer === "success") {
401+
expect(accounts.map(row => [row.quota, row.quotaUnavailable])).toEqual([[reading, false], [reading, false], [reading, false]]);
402+
} else if (newer === "structured-unavailable") {
403+
expect(accounts.map(row => [row.quota, row.quotaUnavailable])).toEqual([[lastGood, true], [reading, false], [reading, false]]);
404+
} else {
405+
expect(accounts.map(row => [row.quota, row.quotaUnavailable])).toEqual([[lastGood, true], [lastGood, true], [undefined, true]]);
406+
}
407+
});
408+
}
409+
410+
test("superseded OAuth refresh follows the latest quota outcome, not an earlier success", async () => {
411+
const olderQuota = deferred<Response>();
412+
const olderStarted = deferred<void>();
413+
let probes = 0;
414+
const rows = [{ id: "a", active: true, quotaMode: "probe" as const }];
415+
respond = async url => {
416+
if (!url.includes("quota=1")) return Response.json({ activeAccountId: "a", accounts: rows });
417+
if (++probes === 1) { olderStarted.resolve(); return olderQuota.promise; }
418+
if (probes === 2) return Response.json({ activeAccountId: "a", accounts: rows.map(row => ({ ...row, quota: reading })) });
419+
return new Response(null, { status: 503 });
420+
};
421+
let older!: Promise<boolean>;
422+
await act(async () => { older = pools.fetchAccountSets(["oauth"], true); await olderStarted.promise; });
423+
await act(async () => { expect(await pools.fetchAccountSets(["oauth"], true)).toBe(true); });
424+
await act(async () => { expect(await pools.fetchAccountSets(["oauth"], true)).toBe(false); });
425+
await act(async () => {
426+
olderQuota.resolve(Response.json({ activeAccountId: "a", accounts: rows.map(row => ({ ...row, quota: reading })) }));
427+
expect(await older).toBe(false);
428+
});
429+
expect(pools.accountSets.oauth.accounts[0]).toMatchObject({ quota: reading, quotaPending: false, quotaUnavailable: true });
430+
});
431+
432+
test("visibility poll skips a provider whose forced quota read is still in flight", async () => {
433+
const ticks: Array<() => void> = [];
434+
const setIntervalOriginal = win.setInterval;
435+
win.setInterval = ((fn: () => void, ms?: number, ...rest: unknown[]) => {
436+
if (ms !== 30_000) return (setIntervalOriginal as (...args: unknown[]) => unknown).call(win, fn, ms, ...rest);
437+
ticks.push(fn);
438+
return 0;
439+
}) as typeof win.setInterval;
440+
const held = deferred<Response>();
441+
const heldStarted = deferred<void>();
442+
let hold = false;
443+
const rows = [{ id: "a", active: true, quotaMode: "probe" as const }];
444+
respond = async url => {
445+
if (!url.includes("quota=1")) return Response.json({ activeAccountId: "a", accounts: rows });
446+
if (hold) { hold = false; heldStarted.resolve(); return held.promise; }
447+
return Response.json({ activeAccountId: "a", accounts: rows.map(row => ({ ...row, quota: reading })) });
448+
};
449+
const config = { providers: { oauth: { adapter: "fixture", baseUrl: "http://fixture.invalid", authMode: "oauth" } } } as unknown as HarnessConfig;
450+
await act(async () => { root!.render(<Harness config={config} />); });
451+
await act(async () => { await Promise.resolve(); });
452+
expect(ticks).toHaveLength(1);
453+
expect(pools.accountSets.oauth.activeAccountId).toBe("a");
454+
455+
hold = true;
456+
let manual!: Promise<boolean>;
457+
await act(async () => { manual = pools.fetchAccountSets(["oauth"], true); await heldStarted.promise; });
458+
const sent = requests.length;
459+
await act(async () => { ticks[0](); await Promise.resolve(); });
460+
// The tick neither sends a request nor retires the read the operator is waiting on.
461+
expect(requests).toHaveLength(sent);
462+
await act(async () => {
463+
held.resolve(Response.json({ activeAccountId: "a", accounts: rows.map(row => ({ ...row, quota: reading })) }));
464+
expect(await manual).toBe(true);
465+
});
466+
467+
await act(async () => { ticks[0](); await new Promise<void>(resolve => setIntervalOriginal.call(win, resolve, 0)); });
468+
expect(requests.slice(sent).map(request => request.url.split("?")[1])).toEqual([
469+
"provider=oauth", "provider=oauth&quota=1&refresh=1&accountId=a",
470+
]);
471+
});
472+
361473
test("explicit null in a failed enriched reading invalidates last-good for OAuth and keys", async () => {
362474
await act(async () => {
363475
pools.setAccountSets({ oauth: { activeAccountId: "account", accounts: [

‎gui/tests/provider-quota-refresh-controls.test.tsx‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,3 +264,39 @@ test("changing active account discards the previous refresh feedback", async ()
264264
expect(host.textContent).not.toContain("Quota check completed");
265265
expect(findButton("Refresh quotas")?.disabled).toBe(false);
266266
});
267+
268+
test.each([
269+
["provider", { name: "provider-b", apiBase: "http://proxy-a" }],
270+
["server", { name: "provider-a", apiBase: "http://proxy-b" }],
271+
])("a removal confirmation does not follow the panel to another %s", async (_what, next) => {
272+
const removed: string[] = [];
273+
const handlers = authHandlers({
274+
onRemoveAccount: (provider, row) => { removed.push(`${provider}:${row.id}`); return true; },
275+
});
276+
// Both scopes list the same account id, which is what made a row-only binding unsafe.
277+
const accounts = [
278+
{ id: "shared", email: "[email protected]", active: true },
279+
{ id: "other", email: "[email protected]", active: false },
280+
];
281+
const panel = (name: string, apiBase: string) => (
282+
<ProviderAuthPanel item={{ ...oauthItem, name }} apiBase={apiBase} accounts={accounts} authHandlers={handlers} />
283+
);
284+
const dialog = () => host.querySelector('[role="alertdialog"]');
285+
286+
await render(panel("provider-a", "http://proxy-a"));
287+
const remove = host.querySelector(".pwi-remove-btn") as unknown as HTMLButtonElement | null;
288+
expect(remove).not.toBeNull();
289+
await act(async () => { remove!.click(); });
290+
expect(dialog()).not.toBeNull();
291+
292+
await render(panel(next.name, next.apiBase));
293+
expect(dialog()).toBeNull();
294+
expect(removed).toEqual([]);
295+
296+
// The pending confirmation still belongs to the scope it was opened for, and only there.
297+
await render(panel("provider-a", "http://proxy-a"));
298+
const confirm = host.querySelector('[role="alertdialog"] .btn-danger') as unknown as HTMLButtonElement | null;
299+
expect(confirm).not.toBeNull();
300+
await act(async () => { confirm!.click(); await Promise.resolve(); });
301+
expect(removed).toEqual(["provider-a:shared"]);
302+
});

0 commit comments

Comments
 (0)