routing: the hidden tray panel no longer draws its Routing tab for every request (#2515)

The tray panel is hidden nearly all the time, yet renderPanel put up a
new head, stage and row list for every trace update (about 200 a minute
under 1 request a second), whichever tab was picked. A hidden page draws
no frames, so the infinite CSS animations on what each draw replaced
(.rt-livedot in the head, .pr-req.wait .pr-to > i on a waiting row,
.ps-dst.wait > i on the stage) were never dropped from the document's
timeline, and each held its detached tab, rows and all.

On the Windows box (WebView2, where a hidden panel reports
visibilityState "hidden"), magpie-gm sandbox, base build 9fd80b212,
main window on Routing, panel hidden on its Agents tab, a fake vendor
at 1 request a second:
- panel page after GC: 265,012 DOM nodes and 13,731 listeners after 11
  minutes of traffic (1,071 elements at start); Runtime.queryObjects:
  68,015 of 69,591 elements detached, 760 div.pr-list roots (58,733
  elements) and 1,110 div.pr-head (8,874); the heap snapshot's retainer
  path Window > HTMLDocument > DocumentTimeline > CSSAnimation > <i> >
  span.pr-to > span.pr-line > button.pr-req.wait > div.pr-list
  (detached), 6,505 ElementAnimations
- WebView2 renderers' private bytes 131 MB at minute 6, 443 MB at 17,
  555 MB at 25 (about 20 MB a minute); the reporter's 5.2 GB after 28 h
  is this rate.

Now renderPanel, while document.hidden, draws again only when the tab's
shape changes (rows shown, the off message, loaded, the group picks,
today's totals there or not), as the panel's height is fitted to every
tab measured; otherwise it marks the tab stale and draws it in full on
visibilitychange. pDraw waits the same way, and no request's dot flies
in a hidden panel. A panel shown draws exactly as before.

After, the same soak with this build (magpie-fix.exe), main window
also on Routing:
- panel page after GC at minutes 17, 47 and 60: 4,698, 4,654 and 4,654
  DOM nodes, 317 listeners, JS heap 5.0-5.2 MB, 5 animations
- WebView2 renderers 274 MB at minute 5, 318 at 25, 423 at 60 (2.7 MB a
  minute, against about 20); 3,690 requests answered by minute 60.
  The panel's own renderer (told apart by a 200 MB allocation made in
  it) still grows about 0.75 MB a minute natively with its JS heap and
  DOM flat; that is not explained by this commit.

panel-routing-hidden.test.cjs fakes a hidden page (headless pages are
never hidden: a minimised window still says "visible" and runs rAF),
sends a request every 80 ms and checks the hidden tab is drawn 0 times
over 20 of them, flies no dot, and is drawn once, newest request first,
on visibilitychange. On 9fd80b212's client.js it is red in all four
(chromium, webkit x en, zh): "the hidden tab was drawn 20 times over 20
requests" (expected 0, actual 20). With the visibilitychange redraw
taken out by hand it is red: "drawn once as the panel shows" expected
1, actual 0. With the fix, 4/4 ok.

Every GUI file that opens the tray panel (70 files, chromium and
webkit, their languages and narrow widths; node --test
--test-concurrency=4, machine load ~275): 960 of 962 pass. The two:
usage-chart-axis chromium was browserType.launch timing out at 180 s
(passes alone), and usage-fold "the view didn't scroll" 184 !== 180,
which fails the same way twice with 9fd80b212's client.js put back
(#2163, #2399). No Go code changed.
This commit is contained in:
yetone
2026-10-20 20:23:51 +08:00
parent 60a42875cd
commit 67f8dbb16c
2 changed files with 139 additions and 4 deletions
+21 -4
View File
@@ -5618,6 +5618,8 @@ function routingPage(part) {
const P_ROWS = 6;
let today = null, todayAt = 0;
const pShown = () => pBox && document.body.dataset.ptab === "routing";
let pStale = false; // a draw skipped while the panel was hidden
if (pBox) document.addEventListener("visibilitychange", () => { if (pStale && !document.hidden) renderPanel(); });
async function loadToday() {
todayAt = performance.now();
try { today = await api("usage?period=today"); } catch { return; }
@@ -5672,6 +5674,7 @@ function routingPage(part) {
}
function pDraw() {
if (!pBox || !pStage.isConnected) return;
if (document.hidden) { pStale = true; return; }
const recent = [...routes.values()].sort((a, b) => b.id - a.id);
const flying = recent.filter((r) => pPlays.has(r.id));
const ags = [], dst = new Map(); // seat key → { name, sub, how }
@@ -5785,7 +5788,7 @@ function routingPage(part) {
}
const pRest = (ms) => new Promise((res) => setTimeout(res, pShown() && !still() ? ms : 0));
async function pPlay(id) {
if (!pBox || !pShown() || still() || pPlays.has(id) || pPlays.size >= 4) return;
if (!pBox || !pShown() || document.hidden || still() || pPlays.has(id) || pPlays.size >= 4) return;
let r = routes.get(id);
if (!r) return;
pPlays.add(id);
@@ -5843,10 +5846,26 @@ function routingPage(part) {
}
}
// renderPanel draws the tab; counted is a request just done, for today's
// totals to be read again (now and then)
// totals to be read again (now and then).
// While the panel is hidden, which is most of the time, it is drawn
// again only when its shape changes (what the panel's height is fitted
// to, every tab measured), and in full once it shows (#2515). A hidden
// page draws no frames, so the infinite CSS animations on what a draw
// replaces (the live dot, a waiting row's arrow, a waiting provider's
// mark) stay on the document's timeline, each holding its old tab, rows
// and all. On Windows, where a hidden WebView2 says so, the panel grew
// ~20 MB a minute under 1 request a second, 265k nodes in 11 minutes,
// and GBs over a day.
let pShape = "";
function renderPanel(counted) {
if (!pBox) return;
if (counted && (!todayAt || performance.now() - todayAt > 5e3)) loadToday();
const picks = panelPicks();
const rs = [...routes.values()].sort((a, b) => b.id - a.id).slice(0, P_ROWS);
const shape = [offMsg, loaded, rs.length, picks?.childElementCount || 0, !!today].join("|");
if (document.hidden && shape === pShape) { pStale = true; return; }
pStale = false;
pShape = shape;
const v = $("#view-agents"), keep = v.scrollTop;
const head = el("div", "pr-head");
const sum = el("span", "pr-today");
@@ -5860,9 +5879,7 @@ function routingPage(part) {
open.onclick = (e) => { api("window/main?view=routing", {}); e.currentTarget.blur(); };
head.append(el("span", "rt-livedot"), sum, el("span", "grow"), open);
const out = [head];
const picks = panelPicks();
if (picks) out.push(picks);
const rs = [...routes.values()].sort((a, b) => b.id - a.id).slice(0, P_ROWS);
if (!offMsg && loaded && rs.length) out.push(pStage);
if (offMsg) out.push(el("p", "pr-none", t(offMsg)));
else if (!loaded) for (let i = 0; i < 3; i++) out.push(el("span", "skeleton pr-sk-row"));
@@ -0,0 +1,118 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The tray panel is hidden most of the time, and its Routing tab is not
// drawn again for every request while it is (#2515): a hidden page draws no
// frames, so the infinite animations on each replaced tab (the live dot, a
// waiting row's arrow) stayed on the document's timeline and held every old
// tab. On Windows the hidden panel grew to 265k nodes in 11 minutes and GBs
// over a day. Hidden, the tab is drawn again only when its shape (what the
// panel's height is fitted to) changes, no request's dot flies, and once
// the panel shows it is drawn in full, newest request first. The page's
// hidden state is faked here, as headless pages are never hidden.
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");
const relay = { id: "relay:team", provider: "relay", name: "Relay", kind: "key", who: "team", model: "gpt-6-sol" };
const route = (id, done) => ({
id, seq: id, time: new Date().toISOString(), agent: "codex", model: `relay/m-${id}`, provider: "relay", order: [relay],
tries: [{ id: relay.id, model: "gpt-6-sol", start: new Date().toISOString(), done, status: done ? 200 : 0, ms: done ? 900 : 0 }],
done, status: done ? 200 : 0, ms: done ? 900 : 0,
});
function serve(lang) {
const state = { agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } };
return async (r) => {
const req = r.request(), url = new URL(req.url());
const json = (data) => r.fulfill({ json: data });
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/gateway/trace") {
// a request every 80 ms, under way: each is a tab drawn again
const after = Number(url.searchParams.get("after"));
const now = new Date().toISOString();
if (!after) return json({ mine: true, now, seq: 2, totals: { requests: 2 }, routes: [route(1, true), route(2, true)] });
await new Promise((res) => setTimeout(res, 80));
return json({ mine: true, now, seq: after + 1, totals: { requests: after + 1 }, routes: [route(after + 1, false)] });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/usage" && url.searchParams.get("period") === "today") return json({ calls: 2, input: 1000, output: 200, series: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, window: true } });
if (url.pathname.startsWith("/api/window/")) return r.fulfill({ status: 204 });
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 r.fulfill({ body: await fs.readFile(file), contentType });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
test(`${engine} ${lang}: the hidden tray panel doesn't draw its Routing tab again for every request`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const ctx = await browser.newContext({ viewport: { width: 360, height: 560 }, reducedMotion: "no-preference" });
await ctx.addInitScript(() => {
try { localStorage.setItem("magpie.panelTab", "routing"); } catch {}
// the panel's window put away, as WebView2 tells a hidden page
window.__hid = false;
Object.defineProperty(Document.prototype, "hidden", { configurable: true, get: () => window.__hid });
Object.defineProperty(Document.prototype, "visibilityState", { configurable: true, get: () => (window.__hid ? "hidden" : "visible") });
window.__hide = (h) => { window.__hid = h; document.dispatchEvent(new Event("visibilitychange")); };
});
const page = await ctx.newPage();
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
page.setDefaultTimeout(5000);
await page.route("**/*", serve(lang));
await page.goto("http://magpie.test/?mode=panel");
await page.locator("#panelRouting .pr-req").first().waitFor();
assert(await page.locator("#panelRouting").isVisible());
// shown, the tab keeps up: its newest request is the one heard last
await page.waitForFunction(() => document.querySelectorAll("#panelRouting .pr-req").length === 6);
// hidden: requests keep coming, the tab is (nearly) never drawn again
const seqAt = await page.evaluate(() => {
window.__hide(true);
window.__draws = 0;
window.__dots = 0;
// each draw puts up a new head
new MutationObserver((ms) => {
for (const m of ms) for (const n of m.addedNodes) {
if (n.classList?.contains("pr-head")) window.__draws++;
if (n.classList?.contains("ps-dot")) window.__dots++;
}
}).observe(document.querySelector("#panelRouting"), { childList: true, subtree: true });
return Number(document.querySelector("#panelRouting .pr-req .pr-a .m").textContent.replace(/\D+/g, ""));
});
let heard = 0;
page.on("request", (q) => { if (q.url().includes("/api/gateway/trace")) heard++; });
for (let i = 0; i < 40 && heard < 20; i++) await page.waitForTimeout(100);
assert(heard >= 20, `the trace was read ${heard} times while hidden`);
const hidden = await page.evaluate(() => ({ draws: window.__draws, dots: window.__dots, shown: Number(document.querySelector("#panelRouting .pr-req .pr-a .m").textContent.replace(/\D+/g, "")) }));
assert.equal(hidden.draws, 0, `the hidden tab was drawn ${hidden.draws} times over ${heard} requests`);
assert.equal(hidden.dots, 0, "no request's dot flies in a hidden panel");
assert.equal(hidden.shown, seqAt, "what the tab shows is left as it was");
// shown again: drawn at once, the newest request first
const after = await page.evaluate(async () => {
window.__hide(false);
await Promise.resolve(); // the observer's records
return {
draws: window.__draws,
first: Number(document.querySelector("#panelRouting .pr-req .pr-a .m").textContent.replace(/\D+/g, "")),
rows: document.querySelectorAll("#panelRouting .pr-req").length,
};
});
assert.equal(after.draws, 1, "drawn once as the panel shows");
assert(after.first >= seqAt + 20, `the newest request is shown (${after.first}, was ${seqAt})`);
assert.equal(after.rows, 6);
assert.deepEqual(errors, []);
});
}
}