gui: on the Requests tab a read the reader moved on from is cancelled, and Refresh waits for the one on its way (Vantiboo1ean)
Vantiboo1ean (Discord, ~750k requests): on Usage > Requests each filter, model pick or refresh sent another read of the page and of the heatmap. The page dropped the answers it no longer wanted, but the requests kept running. A browser opens about 6 connections to one host, so the newest read queued behind them and the page spun on, and every press added another read. Now loadLedger and loadLedHeat go through ledRead: - A read with a different query aborts the one before it (AbortController; api() takes a signal). - A read of the same query (the refresh button, the timer) joins the one already on its way instead of sending a second. - An aborted read returns quietly and is never shown as an error. The server side (the reads themselves taking seconds) is the commit before this one. Tests: - usage-ledger-abort.test.cjs (new) runs in Chromium and WebKit at 1180 and 560 px with every answer held. It types three narrowings and checks that the page and heatmap reads for the first two are cancelled and the wanted one is not. It checks that Refresh pressed during that read sends no second read, that the newest answer is drawn, that "abort" is never shown, and that a later refresh reads afresh. Against the old assets (MAGPIE_ASSETS) it fails: the stale reads are left running. - usage-ledger-chart.test.cjs accepts that its held first read is now cancelled by the second click. - No new strings. Run: the Usage GUI suite (32 files: usage-*, ledger-*, request-archive*, panel-usage, routing-upstream, web-page …): - WebKit: 150/150. - Chromium: 149/150. The one failure is panel-usage "chromium zh" (the tray panel shows 4 tabs, where the test expects 3). It fails the same way, run alone, on the base8d95ebc8and on origin/main0a11b183. These assets don't touch the panel; it is reported to be fixed on its own.
This commit is contained in:
@@ -74,8 +74,9 @@ 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);
|
||||
|
||||
// heads, when given, is shown the answer's headers (loadQuotas' X-Magpie-Reading)
|
||||
async function api(path, body, heads) {
|
||||
// heads, when given, is shown the answer's headers (loadQuotas' X-Magpie-Reading);
|
||||
// signal, when given, cancels the request (a read the reader moved on from)
|
||||
async function api(path, body, heads, signal) {
|
||||
if (web && path === "open") { window.open(body.url, "_blank", "noopener"); return null; }
|
||||
// a segment may be an agent id, and omp's named profiles are omp#<name>:
|
||||
// left raw, the browser reads #work as the fragment and the request
|
||||
@@ -86,6 +87,7 @@ async function api(path, body, heads) {
|
||||
method: body === undefined ? "GET" : "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
heads?.(res.headers);
|
||||
if (res.status === 204) return null;
|
||||
@@ -16003,12 +16005,36 @@ function ledParams(extra) {
|
||||
return q.toString();
|
||||
}
|
||||
|
||||
// One read of the ledger at a time (Vantiboo1ean, ~750k requests): the page
|
||||
// asked again while it is read (the refresh button, the timer) waits for
|
||||
// that read, and another page or filter cancels it. Each pick and press
|
||||
// used to send one more, and a long history's reads, all still running,
|
||||
// took the browser's few connections to magpie, so the page never came.
|
||||
// flight: { want, ctl, p }
|
||||
const ledFlights = { page: null, heat: null };
|
||||
function ledRead(kind, path, want) {
|
||||
const was = ledFlights[kind];
|
||||
if (was?.want === want) return was.p;
|
||||
was?.ctl.abort();
|
||||
const ctl = new AbortController();
|
||||
const f = { want, ctl, p: api(path + want, undefined, undefined, ctl.signal) };
|
||||
ledFlights[kind] = f;
|
||||
const done = () => { if (ledFlights[kind] === f) ledFlights[kind] = null; };
|
||||
f.p.then(done, done);
|
||||
return f.p;
|
||||
}
|
||||
const ledAborted = (e) => e?.name === "AbortError";
|
||||
|
||||
// quiet: a refresh while it's looked at, redrawn only on a change
|
||||
async function loadLedger(quiet) {
|
||||
if (!ledger && !quiet) renderLedgerLoading();
|
||||
loadLedHeat().catch(() => {});
|
||||
const want = ledParams({ offset: ledOffset, limit: LED_PAGE });
|
||||
const l = await api("usage/requests?" + want);
|
||||
let l;
|
||||
try { l = await ledRead("page", "usage/requests?", want); } catch (e) {
|
||||
if (ledAborted(e)) return; // another page or filter was picked, and is read instead
|
||||
throw e;
|
||||
}
|
||||
if (want !== ledParams({ offset: ledOffset, limit: LED_PAGE })) return; // another page or filter was picked meanwhile
|
||||
if (quiet && JSON.stringify(l) === JSON.stringify(ledger)) return;
|
||||
ledger = l;
|
||||
@@ -16721,7 +16747,8 @@ function ledHeatParams() {
|
||||
async function loadLedHeat() {
|
||||
const want = ledHeatParams();
|
||||
ledHeatWant = want;
|
||||
const h = await api("usage/heatmap?" + want);
|
||||
const h = await ledRead("heat", "usage/heatmap?", want).catch((e) => { if (ledAborted(e)) return ledAborted; throw e; });
|
||||
if (h === ledAborted) return;
|
||||
if (want !== ledHeatWant) return; // another filter was picked meanwhile
|
||||
if (ledHeat && ledHeat.want === want && JSON.stringify(ledHeat.data) === JSON.stringify(h)) return;
|
||||
ledHeat = { want, data: h };
|
||||
|
||||
@@ -1068,6 +1068,15 @@ at its own time; a request the files can't tell says why (no session, an agent w
|
||||
files aren't read, no such call); a row opened again, or the list read anew, asks no
|
||||
more; the details fit the table's box at 560; in English and Chinese.
|
||||
|
||||
`usage-ledger-abort.test.cjs` narrows the Requests tab three times while
|
||||
each read is still on its way (Vantiboo1ean, ~750k requests): the reads of the
|
||||
page and of the heatmap no longer wanted are cancelled, not left holding the
|
||||
browser's connections; Refresh pressed while the page is read sends no second
|
||||
read and turns until that one answers; the newest answer is drawn and a
|
||||
cancelled read is never said as an error; a refresh afterwards reads afresh.
|
||||
Chromium and WebKit, at 1180 and 560. `MAGPIE_ASSETS` points it at an older
|
||||
assets directory to see it fail there.
|
||||
|
||||
`shared-skills.test.cjs` opens the Library's Skills tab with skills found in
|
||||
the user-wide `~/.agents/skills` (#227): one row for a skill there that
|
||||
agents link or junction to, "shared in ~/.agents/skills/…" with those
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Usage › Requests over a long history (Vantiboo1ean, ~750k requests): a read
|
||||
// of the ledger can take seconds, and every filter picked, page turned or
|
||||
// refresh pressed sent one more beside it. The answers no longer wanted were
|
||||
// dropped when they came, but their requests kept running, and a browser
|
||||
// sends only a few at a time to one host: the newest waited behind them and
|
||||
// the page spun on. Now a read the reader moved on from is cancelled (the
|
||||
// page's and the heatmap's), and the page asked again while it is read (the
|
||||
// refresh button, the timer) waits for that read instead of sending another.
|
||||
// Checked in Chromium and WebKit, wide and narrow; no backend, every answer
|
||||
// held until the test lets it go. MAGPIE_ASSETS selects another assets
|
||||
// directory to check the same cases against the code before the fix.
|
||||
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 { inView } = require("./reader.cjs");
|
||||
|
||||
const assets = process.env.MAGPIE_ASSETS || path.resolve(__dirname, "../assets");
|
||||
const now = Date.now();
|
||||
const ROW = (req) => ({ t: new Date(now - 60e3).toISOString(), agent: "codex", agentName: "Codex", icon: "codex-color", provider: "relay", providerName: "Relay", host: "team", req, model: "gpt-6-sol", in: 100, out: 10, ms: 900, status: 200, cost: 0.01, priced: true });
|
||||
|
||||
function server(lang, seen, held) {
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.url());
|
||||
const json = (data) => route.fulfill({ json: data }).catch(() => {}); // a cancelled request has no one to answer
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
|
||||
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" }, fx: { rate: 7.2, at: new Date().toISOString() } });
|
||||
if (url.pathname === "/api/usage/requests" || url.pathname === "/api/usage/heatmap") {
|
||||
const kind = url.pathname.endsWith("heatmap") ? "heat" : "page", q = url.searchParams.get("q") || "";
|
||||
seen.push({ kind, q, url: req.url() });
|
||||
await new Promise((go) => held.push(go));
|
||||
if (kind === "heat") return json({ from: "", to: "", days: [] });
|
||||
return json({ period: url.searchParams.get("period"), rows: [ROW("asked-" + (q || "none"))], offset: 0, total: 1, calls: 1, errors: 0, input: 100, output: 10, cache_read: 0, cache_write: 0, reasoning: 0, cost: 0.01, unpriced: 0, bucket: "day", series: [], agents: [], providers: [] });
|
||||
}
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/usage") return json({ calls: 1, errors: 0, input: 100, output: 10, cache_read: 0, cache_write: 0, reasoning: 0, unpriced: 0, cost: 0.01, bucket: "day", series: [], agents: [], models: [], path: "~/.config/magpie/usage.jsonl" });
|
||||
if (url.pathname === "/api/gateway/trace") return json({ mine: false, seq: 0, routes: [], totals: { requests: 0, rerouted: 0, errors: 0 }, now: new Date().toISOString() });
|
||||
if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] });
|
||||
if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
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)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const settle = async (page, seen, n) => {
|
||||
for (let i = 0; i < 100 && seen.length < n; i++) await page.waitForTimeout(20);
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const width of [1180, 560]) {
|
||||
test(`${engine} ${width}px: a read the reader moved on from is cancelled, and a refresh waits for the one on its way`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const errors = [], seen = [], held = [], failed = [];
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(8000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
page.on("requestfailed", (r) => { if (/\/api\/usage\/(requests|heatmap)\?/.test(r.url())) failed.push(r.url()); });
|
||||
await page.route("**/*", server("en", seen, held));
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.locator('[data-view="usage"]').first().click();
|
||||
await page.locator("#usageTab .opt").nth(1).click();
|
||||
// the tab's opening reads, let go so the page is drawn
|
||||
await settle(page, seen, 2);
|
||||
held.splice(0).forEach((go) => go());
|
||||
await page.locator("#ledWrap .led tbody tr").first().waitFor();
|
||||
|
||||
// the reader narrows the list three times, each read still on its way
|
||||
const box = page.locator("#ledQ");
|
||||
await inView(page, box);
|
||||
for (const q of ["a", "ab", "abc"]) {
|
||||
const n = seen.length;
|
||||
await box.fill(q);
|
||||
await settle(page, seen, n + 2);
|
||||
}
|
||||
const asked = (kind, q) => seen.filter((s) => s.kind === kind && s.q === q);
|
||||
for (const q of ["a", "ab", "abc"]) assert.equal(asked("page", q).length, 1, `one read of the page for "${q}"`);
|
||||
await page.waitForTimeout(150);
|
||||
for (const q of ["a", "ab"]) {
|
||||
for (const kind of ["page", "heat"]) {
|
||||
for (const s of asked(kind, q)) assert(failed.includes(s.url), `the ${kind} read for "${q}" was left running after "abc" was asked: ${JSON.stringify(failed)}`);
|
||||
}
|
||||
}
|
||||
for (const s of asked("page", "abc")) assert(!failed.includes(s.url), "the read wanted was cancelled");
|
||||
|
||||
// Refresh pressed while that read is on its way: no second read (the
|
||||
// button turns until the read it waits for is done)
|
||||
const before = asked("page", "abc").length;
|
||||
await page.locator("#usageReload").click();
|
||||
await page.waitForTimeout(250);
|
||||
assert.equal(asked("page", "abc").length, before, "a refresh sent another read of the page beside the one on its way");
|
||||
|
||||
// the answers come; the page shows the newest, and no error is said
|
||||
held.splice(0).forEach((go) => go());
|
||||
await page.waitForFunction(() => /asked-abc/.test(document.querySelector("#ledWrap")?.textContent || ""), null, { timeout: 4000 }).catch(async () => {
|
||||
throw new Error("the newest answer was not drawn: " + (await page.locator("#ledWrap").innerText()).slice(0, 400));
|
||||
});
|
||||
await page.waitForFunction(() => !document.querySelector("#usageReload").classList.contains("busy"), null, { timeout: 4000 });
|
||||
const text = await page.locator("body").innerText();
|
||||
assert(!/abort/i.test(text), "a cancelled read was said as an error");
|
||||
assert.equal(await page.locator("#ledWrap .led tbody tr", { hasText: "asked-ab" }).filter({ hasNotText: "asked-abc" }).count(), 0);
|
||||
// a refresh after the read is done reads afresh
|
||||
const n = seen.length;
|
||||
await page.locator("#usageReload").click();
|
||||
await settle(page, seen, n + 1);
|
||||
assert(asked("page", "abc").length > before, "a refresh with nothing on its way did not read");
|
||||
held.splice(0).forEach((go) => go());
|
||||
await page.waitForTimeout(150);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -323,7 +323,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
blocked = true;
|
||||
asked.push(q);
|
||||
await held;
|
||||
await route.fulfill({ json: page(q, "daily") });
|
||||
// the read the second click moved on from is cancelled (Vantiboo1ean):
|
||||
// there is no one left to answer
|
||||
await route.fulfill({ json: page(q, "daily") }).catch(() => {});
|
||||
return;
|
||||
}
|
||||
await route.fallback();
|
||||
@@ -336,7 +338,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
delay();
|
||||
const beforeClicks = asked.length, clickedDay = await days.nth(4).getAttribute("data-day");
|
||||
const requested = p.waitForRequest((r) => new URL(r.url()).searchParams.get("day") === clickedDay);
|
||||
const selectedReply = reply(clickedDay), clearedReply = reply("");
|
||||
// the first read either answers late or, as now, is cancelled by the second
|
||||
const cancelled = p.waitForEvent("requestfailed", (r) => new URL(r.url()).pathname === "/api/usage/requests" && new URL(r.url()).searchParams.get("day") === clickedDay);
|
||||
const selectedReply = Promise.race([reply(clickedDay), cancelled]), clearedReply = reply("");
|
||||
await days.nth(4).dispatchEvent("click");
|
||||
await requested;
|
||||
await days.nth(4).dispatchEvent("click");
|
||||
|
||||
Reference in New Issue
Block a user