routing: a request still going is patched in its row, not made again, so the page holds still under traffic (#3731)

gpboyer2 (#3731, v0.1.1579): with requests coming, the Routing page kept
redrawing, its stage, caption and request list jumping so nothing could
be read; idle it was still.

Measured on main 4a33cf0a9 with a probe (MutationObserver on
#view-routing, plus animationstart), 12 requests listed, then one still
going answered by the trace every 150ms, as under traffic:
- idle, 5s: 25 nodes put in and 25 taken out, 30 attribute writes. The
  countdown's second ran rebuild(), and header() replaced the head's
  nodes and wrote the mode line and each agent's name, sub and title
  whatever they said.
- one live request, 5s (41 answers): 217 nodes in, 219 out, 824
  attribute writes (nearly all the same value), and the row's rtlive
  pulse started over 62 times. rowOf made the request's row again
  whenever its signature changed, and a request still going changes it
  on each answer (its tokens), so the row and its pulse came in afresh
  4 to 8 times a second: the flashing.

Now rowOf patches the row it has (morphRow, as context.js's morph does
for the Context card), and the head, the agents' nodes, the wires'
viewBox, the list head's titles and aria (setAttr), the hub's title and
the packet's cx/cy are written only when they change. Same probe after:
idle 0 writes of any kind; one live request 0 nodes made again (2 taken
out: the packet's flight ending), 177 attribute writes, 0 pulse
restarts, in Chromium and WebKit.

Not changed: the stage still follows the newest request, so with
several agents at once it shows each in turn (by design; pinning a
request holds it), and the issue's "Pause live" switch and fixed stage
height (#2598) are not added here.

Test: tests/routing-live-calm.test.cjs. Idle three seconds the page
gets no write; with the live request answered again and again the row
is the same element, says the new tokens, its pulse never restarts and
no node is put in afresh. Green in chromium and webkit; with
client.js reverted to 4a33cf0a9 both red (rows made again, pulse
restarted).

Run (rt3731 worktree):
- At 4a33cf0a9 with this change: go test -timeout 45m ./internal/gui/
  ok (176s). Rebased onto e9c1066c4 (no routing file changed between):
  the same run red on TestRestartHandsTheGatewayOver only ("1 of 2
  requests during the restart answered", #3451, the update handover);
  run again with the budgets, -count=3: ok 3 of 3, TestCoreScriptBudget
  ok. routing-live-calm.test.cjs at e9c1066c4: 2 of 2 ok.
- GUI tests/routing-*.test.cjs, whole, at this change and at 4a33cf0a9,
  both cut at 1500s under load 100+: head 509 ok 4 red, base 462 ok 4
  red; every red at head is routing-intent-entry's "Add a rule makes a
  rule by intent" (#3408), red alone at both, different subtests each
  time.
- 30 row, stage and head files alone at this change: 458 ok, 9 red:
  routing-live-patch's folded subtests (an extra 0% context part, red
  the same alone at 4a33cf0a9: 4 ok 6 red, #3637) and routing-keys-fold
  "flies to the fold" in webkit zh/ja/de (#1612, #2658).
This commit is contained in:
yetone
2026-10-26 23:21:30 +08:00
parent e9c1066c4b
commit 834935149a
2 changed files with 161 additions and 23 deletions
+50 -23
View File
@@ -307,6 +307,9 @@ function routingPage(part) {
const path = () => { const p = document.createElementNS(NS, "path"); wires.appendChild(p); return p; };
const setText = (e, s) => { if (e.textContent !== s) e.textContent = s; };
// setAttr: an attribute written only when it changes, as setText: the
// list's head is told again on every trace answer (#3731)
const setAttr = (e, k, v) => { if (e.getAttribute(k) !== v) e.setAttribute(k, v); };
const tick = (e) => { e.classList.remove("tick"); void e.offsetWidth; e.classList.add("tick"); };
// ---------- words ----------
@@ -1727,9 +1730,8 @@ function routingPage(part) {
if (isKey(e) && e.firstElementChild?.checkVisibility?.({ contentVisibilityAuto: true })) usual.set(nobar, x.b - x.t);
}
sight = { at: r.top, scroll: scrolled, lo: Math.max(0, v.top), hi: Math.min(innerHeight, v.bottom) };
wires.setAttribute("viewBox", `0 0 ${r.width} ${r.height}`);
flows.setAttribute("viewBox", `0 0 ${r.width} ${r.height}`);
sky.setAttribute("viewBox", `0 0 ${r.width} ${r.height}`);
const box = `0 0 ${r.width} ${r.height}`;
for (const svg of [wires, flows, sky]) if (svg.getAttribute("viewBox") !== box) svg.setAttribute("viewBox", box);
for (const [p, d] of sets) {
if (d === null) { if (p.hasAttribute("d")) p.removeAttribute("d"); }
else if (p.getAttribute("d") !== d) p.setAttribute("d", d);
@@ -2047,14 +2049,16 @@ function routingPage(part) {
for (const id of ags) {
const a = agents.get(id), r = rs.filter((x) => x.agent === id).pop(), ag = agentOf(id);
if (a.icon !== (ag?.icon || "generic")) { a.icon = ag?.icon || "generic"; a.ic.replaceChildren(icon(a.icon)); }
a.name.textContent = agentName(id);
setText(a.name, agentName(id));
// one agent working in more than one folder at once: which, by
// their last level (#1068). The stage holds an agent's latest
// request alone, so its others still going, or just done, count too.
const n = now(), going = pinned ? [] : [...src().values()].filter((x) => x.agent === id && (!x.done || at(x.time) + (x.ms || 0) > n - LINGER));
const fs = foldersOf([...new Set([...going, ...rs.filter((x) => x.agent === id)])].sort((x, y) => x.id - y.id));
a.sub.textContent = fs.length > 1 ? fs.map(lastLevel).join(", ") : r.model;
a.node.title = [agentName(id), r.model, ...fs.map((f) => t("Folder") + ": " + f)].join("\n");
// told again every second (countdown): only what changed is written
setText(a.sub, fs.length > 1 ? fs.map(lastLevel).join(", ") : r.model);
const tip = [agentName(id), r.model, ...fs.map((f) => t("Folder") + ": " + f)].join("\n");
if (a.node.title !== tip) a.node.title = tip;
}
// the account sets, the latest of each
const latest = new Map();
@@ -2188,11 +2192,11 @@ function routingPage(part) {
chip.hidden = lone;
goTo(chip, g ? "group:" + g.id : pool ? "pool:" + f.provider : "", g ? g.name : f?.name || r.provider);
hubText();
what.replaceChildren(el("b", "", g ? g.name : f?.name || r.provider),
el("span", "", (g ? " · " + t("routing group") : "") + " · " + t(on === 1 ? "one on" : "{n} on", { n: on })
+ (many > 1 ? " · " + t("{n} agents at once", { n: many }) : "")));
const name = g ? g.name : f?.name || r.provider, tail = (g ? " · " + t("routing group") : "") + " · " + t(on === 1 ? "one on" : "{n} on", { n: on })
+ (many > 1 ? " · " + t("{n} agents at once", { n: many }) : "");
if (what.childElementCount !== 2 || what.firstChild.textContent !== name || what.lastChild.textContent !== tail) what.replaceChildren(el("b", "", name), el("span", "", tail));
// keys that read their own windows are weighed as accounts are
mode.textContent = lone ? t(LONE) : g && routing === "order" ? t(GROUP_ORDER) : g && routing === "weight" ? t(GROUP_WEIGHT) : t(!routing && f?.kind === "key" && !r.order.some((x) => x.known) && !g ? KEYS_SMART : m[1]);
setText(mode, lone ? t(LONE) : g && routing === "order" ? t(GROUP_ORDER) : g && routing === "weight" ? t(GROUP_WEIGHT) : t(!routing && f?.kind === "key" && !r.order.some((x) => x.known) && !g ? KEYS_SMART : m[1]));
}
// goTo makes what names a routing a way to where it is set: a provider's
// own under Several accounts or keys, a group's its card
@@ -2884,10 +2888,10 @@ function routingPage(part) {
errors: done.filter(failedRoute).length,
} : traceTotals;
[counts.requests, counts.rerouted, counts.errors].forEach((n, i) => setText(statB[i], String(n)));
stats.title = t(scoped ? "Counts for the requests in this list" : "Counts since the gateway started");
setAttr(stats, "title", t(scoped ? "Counts for the requests in this list" : "Counts since the gateway started"));
const failed = rs.some(failedRoute), btn = statB[2].parentElement;
btn.setAttribute("aria-disabled", String(!failed));
btn.title = t(failed ? "Show the latest request that failed" : "No failed request in this list");
setAttr(btn, "aria-disabled", String(!failed));
setAttr(btn, "title", t(failed ? "Show the latest request that failed" : "No failed request in this list"));
}
// Follow the newest matching request unless the reader picked one still in
// this list. Stop old flights before the scope changes, including replays.
@@ -3123,14 +3127,14 @@ function routingPage(part) {
purposeTools.hidden = opts.length < 2 && !purpose.length;
purposeTools.classList.toggle("set", !!purpose.length);
purposeClear.hidden = !purpose.length;
purposeClear.title = t("Clear filter");
purposeClear.setAttribute("aria-label", t("Clear filter"));
setAttr(purposeClear, "title", t("Clear filter"));
setAttr(purposeClear, "aria-label", t("Clear filter"));
const label = purpose.length ? t("Purpose: {name}", { name: selected.map((o) => o.name).join(", ") }) : t("Purpose filter");
setText(purposeLabel, label);
purposePick.setAttribute("aria-label", label);
purposePick.title = t("Filter routing by purpose") + (purpose.length ? "\n" + label : "");
setAttr(purposePick, "aria-label", label);
setAttr(purposePick, "title", t("Filter routing by purpose") + (purpose.length ? "\n" + label : ""));
setText(metricLabel, t("Metrics"));
metricPick.title = t("Metrics to show");
setAttr(metricPick, "title", t("Metrics to show"));
purposePick.onclick = (e) => {
e.stopPropagation();
if (purposePick.classList.contains("open")) return closeProtoMenu();
@@ -3152,7 +3156,7 @@ function routingPage(part) {
groupButtons.forEach((b, i) => {
setText(b, t(b.dataset.label));
b.classList.toggle("on", bySession === !!i);
b.setAttribute("aria-pressed", String(bySession === !!i));
setAttr(b, "aria-pressed", String(bySession === !!i));
});
groupBar.hidden = !rs.length;
if (!reqs.style.maxHeight) requestAnimationFrame(fitReqs); // first shown
@@ -3223,11 +3227,22 @@ function routingPage(part) {
const sel = String(pinned ? pinned.id === r.id : cur?.id === r.id);
const { said, how, tr, ag, meta, metrics, title, sig } = rowSays(r);
let x = reqRows.get(r.id);
if (!x || x.sig !== sig) {
if (!x) {
const row = x = { sig, b: reqRow(r, said, how, tr, ag, meta, metrics, title) };
row.b.onclick = () => pick(row.r); // the request as it is when clicked
reqRows.set(r.id, x);
rowsMoved = true;
} else if (x.sig !== sig) {
// a request still going says something new on each trace answer,
// 4 to 8 a second under traffic: its row made again each time put
// its pulse in afresh, so the list flashed and jumped as long as
// requests came (#3731, gpboyer2). Patched in place, as Context's
// card is, only what it says changes.
x.sig = sig;
const neu = reqRow(r, said, how, tr, ag, meta, metrics, title);
neu.setAttribute("aria-pressed", sel);
morphRow(x.b, neu);
rowsMoved = true;
}
x.r = r;
if (x.b.getAttribute("aria-pressed") !== sel) x.b.setAttribute("aria-pressed", sel);
@@ -3388,6 +3403,18 @@ function routingPage(part) {
};
reqs.addEventListener("scroll", redrawList, { passive: true });
new ResizeObserver(redrawList).observe(reqs);
// morphRow makes old what neu is, keeping old's nodes wherever they are
// of the same kind (context.js's morph); a row's handler is its own,
// set once on old
function morphRow(old, neu) {
if (old.nodeName !== neu.nodeName || (old.nodeType !== 1 && old.nodeType !== 3)) { old.replaceWith(neu); return; }
if (old.nodeType === 3) { if (old.data !== neu.data) old.data = neu.data; return; }
for (const a of [...old.attributes]) if (!neu.hasAttribute(a.name)) old.removeAttribute(a.name);
for (const a of neu.attributes) if (old.getAttribute(a.name) !== a.value) old.setAttribute(a.name, a.value);
const was = [...old.childNodes], kids = [...neu.childNodes];
kids.forEach((k, i) => { if (i < was.length) morphRow(was[i], k); else old.append(k); });
for (let i = kids.length; i < was.length; i++) was[i].remove();
}
function reqRow(r, said, how, tr, ag, meta, metrics, title) {
const b = el("button", "rt-req " + how);
const when = el("span", "at", rowClock(r.time));
@@ -4063,8 +4090,8 @@ function routingPage(part) {
};
if (!total) return;
const d = e * total, pt = point(d);
tr.dot.setAttribute("cx", pt.x);
tr.dot.setAttribute("cy", pt.y);
setAttr(tr.dot, "cx", String(pt.x));
setAttr(tr.dot, "cy", String(pt.y));
tr.dot.removeAttribute("visibility");
const b = tr.bird;
if (!b) return;
@@ -4326,7 +4353,7 @@ function routingPage(part) {
? t("{serves} (pid {pid}) is routing", { serves: by.serves, pid: by.pid }) + " · "
: "";
setText(hubSub, who + ((g?.url || "").replace(/^https?:\/\//, "") || t("gateway")));
hubSub.title = who ? hubSub.textContent : ""; // whole, where the node cuts it short
setAttr(hubSub, "title", who ? hubSub.textContent : ""); // whole, where the node cuts it short
}
// labels in the page's language, and again when it changes
@@ -0,0 +1,111 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The Routing page holds still while requests come (#3731, gpboyer2: under
// traffic the stage, the caption and the request list kept being made
// again, so nothing could be read). A request still going is answered by
// the trace 4 to 8 times a second, each saying a little more of it; its
// row in the list is the same row throughout, patched in place, so its
// pulse never starts over, while what it says does change. With nothing
// coming, the countdowns' second writes nothing on the page at all.
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 now = Date.now();
const iso = (ms) => new Date(ms).toISOString();
const acct = (n) => ({ id: `acct-${n}`, provider: `prov${n}`, name: `Provider ${n}`, who: `user${n}@example.com`, kind: "account", model: `model-${n}`, known: true, used: 10 * n, plan: "Pro" });
function req(id, agent, done) {
const t0 = now - (done ? 30000 : 3000) - (200 - id) * 10;
const order = [1, 2, 3].map(acct);
const tries = [{ id: order[0].id, model: order[0].model, start: iso(t0), done, ...(done ? { ms: 800, status: 200 } : {}) }];
return { id, seq: id, time: iso(t0), agent, model: order[0].model, provider: order[0].provider, order, tries, done, status: done ? 200 : 0, ms: done ? 900 : 0, tokens: 1500 };
}
const first = Array.from({ length: 12 }, (_, i) => req(100 + i, i % 2 ? "claude" : "codex", true));
const live = req(200, "codex", false);
const state = { agents: ["codex", "claude"].map((id) => ({ id, name: id, path: `/test/${id}`, fields: [] })), profiles: [], settings: { lang: "en", theme: "light" } };
function serve(feed) {
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: 'window.bootPrefs = {lang:"en",theme:"light",web:true};' });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/gateway/trace") {
const trace = (routes, seq) => json({ mine: true, now: new Date().toISOString(), seq, totals: { requests: 0, rerouted: 0, errors: 0 }, routes });
if (!url.searchParams.get("wait")) return trace(first, 111);
// the long poll: held until the test turns the traffic on, then
// answered every 150ms with the same request, its tokens counting up
if (!feed.on) await new Promise((res) => { feed.wake = res; });
if (feed.closed) return route.abort().catch(() => {});
await new Promise((r) => setTimeout(r, 150));
feed.n++;
return trace([{ ...live, seq: 200 + feed.n, tokens: 100 * feed.n }], 200 + feed.n).catch(() => {});
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
if (url.pathname === "/api/providers") return json({ providers: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
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 });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: the Routing page holds still while requests come`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width: 1100, height: 900 } })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const feed = { on: false, n: 0 };
await page.route("**/*", serve(feed));
t.after(async () => { feed.closed = true; feed.wake?.(); await browser.close(); });
await page.goto("http://magpie.test/?view=routing");
await page.locator(".rt-req").nth(first.length - 1).waitFor();
await page.waitForTimeout(2500); // the first request's play
// what the page writes: nodes put in or taken out, attributes, text;
// and each animation that starts
const watch = () => page.evaluate(() => {
const m = window.__m = { nodes: [], attrs: 0, text: 0, anims: [] };
window.__mo = new MutationObserver((ms) => { for (const x of ms) {
if (x.type === "childList") for (const n of [...x.addedNodes, ...x.removedNodes]) m.nodes.push(`${x.target.getAttribute?.("class") || x.target.nodeName} ⊃ ${n.getAttribute?.("class") || n.nodeName}`);
else if (x.type === "attributes") m.attrs++;
else m.text++;
} });
window.__mo.observe(document.querySelector("#view-routing"), { subtree: true, childList: true, attributes: true, characterData: true });
window.__an = (e) => m.anims.push(e.animationName);
document.addEventListener("animationstart", window.__an, true);
});
const read = () => page.evaluate(() => { window.__mo.disconnect(); document.removeEventListener("animationstart", window.__an, true); return window.__m; });
// nothing coming: three of the countdowns' seconds write nothing
await watch();
await page.waitForTimeout(3200);
const idle = await read();
assert.deepEqual(idle, { nodes: [], attrs: 0, text: 0, anims: [] }, "with nothing coming the page was written to");
// a request still going, answered again and again
feed.on = true;
feed.wake?.();
const row = page.locator(".rt-req.wait");
await row.waitFor();
await page.waitForTimeout(600);
await row.evaluate((b) => { window.__row = b; });
const said = await row.textContent();
await watch();
const n0 = feed.n;
await page.waitForTimeout(2500);
const busy = await read();
assert(feed.n - n0 >= 8, `the trace must have answered again and again (${feed.n - n0})`);
assert.equal(await row.evaluate((b) => b === window.__row), true, "the request's row was made again");
assert.notEqual(await row.textContent(), said, "the row must say what the trace says now");
assert.deepEqual(busy.anims.filter((a) => a === "rtlive"), [], "the row's pulse started over");
assert.deepEqual(busy.nodes.filter((n) => !/^rt-sky |\bpkt\b|rt-flier|#text/.test(n)), [], "nodes were put in afresh while the same request came (the packet in flight aside)");
assert.deepEqual(errors, []);
});
}