Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

routing: the page asks for frames only while its stage moves, and the live dot pulses only while a request is under way (#2827)

yetoneac3a2a3df51c
diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js
index af0e65643..4c636d50b 100644
--- a/internal/gui/assets/plugins/routing/client.js
+++ b/internal/gui/assets/plugins/routing/client.js
@@ -1116,6 +1116,21 @@ function routingPage(part) {
for (const [dot, row] of holds) pose({ dot, legs: wiresTo(row).map((p) => ({ p })) }, 1);
}
let capQ = [], capAt = -1e9, capLo = false, flipUntil = 0;
+ // the frame loop's own state; see frame below
+ let seen = false, lastFrame = 0, ticking = 0;
+ // busy: something on the stage still moves — a flight, a caption waiting
+ // its turn, rows sliding to their new places. Only then does the loop
+ // ask for frames; an idle stage asks for none (#2827: a frame every
+ // vsync, nothing drawn, cost a renderer without a GPU a core and more)
+ const busy = () => trips.length > 0 || capQ.length > 0 || performance.now() < flipUntil;
+ // kick wakes the loop for new motion. Waking from idle is not a gap in
+ // the frames — the page was in sight and still — so the gap resume()
+ // looks for counts from now
+ function kick() {
+ if (ticking || !shown()) return;
+ if (seen) lastFrame = performance.now();
+ ticking = requestAnimationFrame(frame);
+ }
// fly carries a dot along paths one after another, as one flight — and
// the magpie holding it in its beak, if there is one
@@ -1124,6 +1139,7 @@ function routingPage(part) {
const tr = { dot, bird, legs, t0: performance.now(), ms: still() ? 0 : ms, res, g: gen };
pose(tr, 0);
trips.push(tr);
+ kick();
}).finally(() => { for (const l of legs) if (l.j) l.p.remove(); });
// measured is a path's length, and the tips of it flights met, for the d
@@ -1211,6 +1227,7 @@ function routingPage(part) {
if (!lo) capQ = capQ.filter((c) => !c.lo);
capQ.push({ s, lo });
if (capQ.length > 3) capQ.shift();
+ kick();
}
function show(c) { capLo = !!c.lo; cap.textContent = c.s; cap.classList.remove("in"); void cap.offsetWidth; cap.classList.add("in"); capAt = performance.now(); }
@@ -1649,6 +1666,7 @@ function routingPage(part) {
void list.offsetWidth;
for (const [, li] of placed) { li.style.transition = ""; li.style.transform = ""; }
flipUntil = performance.now() + 520;
+ kick();
}
header(cur, ags.length);
layout();
@@ -3343,13 +3361,13 @@ function routingPage(part) {
for (const r of underWay()) play(r.id);
renderAll();
}
- let seen = false, lastFrame = 0, ticking = 0;
// the loop runs only while the page is the one in sight: out of sight it
// is not scheduled at all, so a hidden Routing page — the window hidden,
// another view picked, another tab open — asks for no frames forever
// (#302's other half). Shown again, start() resumes it, and resume()
// draws the page as it is now. The requests that came meanwhile are
- // listed by the poll, which never stops.
+ // listed by the poll, which never stops. In sight, it runs only while
+ // the stage is busy, and kick() wakes it (#2827).
function frame(ts) {
ticking = 0;
const vis = shown();
@@ -3369,7 +3387,7 @@ function routingPage(part) {
if (ts < flipUntil) layout();
if (capQ.length && ts - capAt > (capLo && !capQ[0].lo ? 500 : 1700)) show(capQ.shift());
} else pause();
- if (vis) ticking = requestAnimationFrame(frame);
+ if (vis && busy() && !ticking) ticking = requestAnimationFrame(frame);
}
function pause() {
if (ticking) cancelAnimationFrame(ticking);
@@ -3385,7 +3403,7 @@ function routingPage(part) {
// finish hidden work here too. The first visible frame alone owns resume.
function start() {
if (!shown()) { pause(); return; }
- if (!ticking) ticking = requestAnimationFrame(frame);
+ kick();
}
// in sight again: the view picked, the window shown, another tab left,
// the window covered and drawing frames once more
@@ -3429,6 +3447,15 @@ function routingPage(part) {
layout();
}
+ // the live dots beside "Routing" pulse while a request is under way,
+ // and rest when none is: an endless pulse repainted the head every
+ // frame, which without a GPU is a renderer's whole core (#2827)
+ const anyLive = () => loaded && mine && [...routes.values()].some((r) => !r.done);
+ function liveDots() {
+ const on = anyLive();
+ for (const d of document.querySelectorAll(".rt-livedot")) d.classList.toggle("on", on);
+ }
+
async function poll() {
for (;;) {
try {
@@ -3453,6 +3480,7 @@ function routingPage(part) {
offline(pinned ? "" : t(offMsg));
loaded = false;
renderPanel();
+ liveDots();
await new Promise((r) => setTimeout(r, 5000));
continue;
}
@@ -3468,6 +3496,7 @@ function routingPage(part) {
loaded = true;
offMsg = "";
renderPanel(first || d.routes.some((r) => r.done));
+ liveDots();
// a request done is a day's count grown: heard of now and then
if (first || (d.routes.some((r) => r.done) && performance.now() - daysAt > 15e3)) { daysAt = performance.now(); loadDays(); }
if (first) {
@@ -5877,7 +5906,7 @@ function routingPage(part) {
const open = el("button", "text", t("Open Routing"));
open.type = "button";
open.onclick = (e) => { api("window/main?view=routing", {}); e.currentTarget.blur(); };
- head.append(el("span", "rt-livedot"), sum, el("span", "grow"), open);
+ head.append(el("span", anyLive() ? "rt-livedot on" : "rt-livedot"), sum, el("span", "grow"), open);
const out = [head];
if (picks) out.push(picks);
if (!offMsg && loaded && rs.length) out.push(pStage);
diff --git a/internal/gui/assets/plugins/routing/routing.css b/internal/gui/assets/plugins/routing/routing.css
index bb7c164e3..f370fe313 100644
--- a/internal/gui/assets/plugins/routing/routing.css
+++ b/internal/gui/assets/plugins/routing/routing.css
@@ -387,7 +387,9 @@ button.rt-session { cursor: pointer; }
.rt-act.rt-keys.open .chev { transform: rotate(180deg); }
.rt-act.rt-keys:focus { outline: none; }
.rt-act.rt-keys:focus-visible { box-shadow: inset 0 0 0 2px color-mix(in srgb, var(--accent) 30%, transparent); }
-.rt-livedot { width: 6px; height: 6px; margin-left: 7px; border-radius: 50%; background: var(--green); animation: rtlive 1.8s infinite; --fg: var(--green); }
+.rt-livedot { width: 6px; height: 6px; margin-left: 7px; border-radius: 50%; background: var(--green); --fg: var(--green); }
+/* it pulses while a request is under way only (#2827) */
+.rt-livedot.on { animation: rtlive 1.8s infinite; }
@media (prefers-reduced-motion: reduce) { .rt-livedot { animation: none; } }
/* routing groups, and the providers routing over several of their own */
.rt-gsec { display: grid; gap: 6px; margin-top: 16px; }
diff --git a/internal/gui/tests/routing-idle-frame.test.cjs b/internal/gui/tests/routing-idle-frame.test.cjs
index 73614e747..f7dda0035 100644
--- a/internal/gui/tests/routing-idle-frame.test.cjs
+++ b/internal/gui/tests/routing-idle-frame.test.cjs
@@ -8,6 +8,13 @@
// again the view is picked and the loop resumes. What the poll lists came
// in meanwhile is another test's business (routing-flood); this one counts
// the loop's own callbacks.
+//
+// In sight, it runs only while something on the stage moves (#2827): an
+// idle Routing page asked for a frame every vsync, and the live dot beside
+// its title pulsed forever, which on Linux without a GPU (xrdp, llvmpipe)
+// cost the renderer 459%–830% CPU. Idle, the loop asks for no frames and
+// the dot rests; a request under way wakes both. MAGPIE_ROUTING_ASSETS
+// points the page at an older asset tree, to watch this go red there.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
@@ -15,7 +22,7 @@ const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const engines = process.env.BROWSER ? [process.env.BROWSER] : ["webkit"];
-const assets = path.resolve(__dirname, "../assets");
+const assets = path.resolve(process.env.MAGPIE_ROUTING_ASSETS || path.join(__dirname, "../assets"));
const routing = path.join(assets, "plugins/routing/client.js");
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" });
@@ -27,8 +34,17 @@ function req(id) {
const tries = order.slice(0, 1).map((w) => ({ id: w.id, model: w.model, start: iso(t0), done: true, ms: 300, status: 200 }));
return { id, seq: id, time: iso(t0), agent: agentsOf[id % agentsOf.length], model: order[0].model, provider: order[0].provider, order, tries, done: true, status: 200, ms: 400, tokens: 900 };
}
+// a request still being answered
+function live(id) {
+ const r = req(id);
+ r.done = false;
+ r.status = 0;
+ r.tries.forEach((tr) => { tr.done = false; tr.status = 0; });
+ return r;
+}
-function serve(lang, feed = [req(1)]) {
+// next: what the long poll answers next, one request at a time
+function serve(lang, feed = [req(1)], next = []) {
const state = { agents: agentsOf.map((id) => ({ id, name: id[0].toUpperCase() + id.slice(1), path: `/test/${id}`, fields: [] })), profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const url = new URL(route.request().url());
@@ -37,7 +53,12 @@ function serve(lang, feed = [req(1)]) {
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/plugins") return json({ plugins: [] });
- if (url.pathname === "/api/gateway/trace") return json({ mine: true, now: new Date().toISOString(), seq: url.searchParams.get("after") || 0, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: url.searchParams.get("wait") ? [] : feed });
+ if (url.pathname === "/api/gateway/trace") {
+ const wait = url.searchParams.get("wait");
+ if (wait && !next.length) await new Promise((r) => setTimeout(r, 50));
+ const routes = wait ? next.splice(0, 1) : feed;
+ return json({ mine: true, now: new Date().toISOString(), seq: routes.length ? routes[0].seq : url.searchParams.get("after") || 0, totals: { requests: 0, rerouted: 0, errors: 0 }, routes }).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" } });
@@ -68,6 +89,14 @@ const init = () => {
// asked for when the mark falls is out of the count before it settles
window.__mark = () => { window.__frames = 0; return new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); };
window.__count = (ms) => new Promise((r) => setTimeout(() => r(window.__frames), ms));
+ // settles: the loop's frames stop within ms, or the count of the last try
+ window.__settle = async (ms) => {
+ let n = -1;
+ for (let i = 0; i < 12 && n !== 0; i++) { await window.__mark(); n = await window.__count(ms); }
+ return n;
+ };
+ // the live dot's pulse, running or not
+ window.__pulses = () => [...document.querySelectorAll(".rt-livedot")].filter((d) => d.getAnimations().some((a) => a.playState === "running")).length;
window.requestAnimationFrame = (cb) => {
const self = typeof cb === "function" && /requestAnimationFrame\s*\(\s*([A-Za-z_$][\w$]*)/.test(cb.toString()) && new RegExp(`\\b${RegExp.$1}\\s*\\(`).test(cb.toString());
if (typeof cb === "function" && (cb.name === "frame" || self)) window.__seenFrame = true;
@@ -84,7 +113,7 @@ test("the loop's frame is still there to be counted, and asks for itself", async
});
for (const engine of engines) for (const lang of ["en", "zh"]) {
- test(`${engine} ${lang}: with Agents selected the Routing loop asks for no more frames, and picking Routing again resumes it`, async (t) => {
+ test(`${engine} ${lang}: the Routing loop runs only while its stage moves, asks for no frames with Agents selected, and picking Routing again resumes it`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const context = await browser.newContext({ viewport: { width: 1100, height: 900 } });
await context.addInitScript(init);
@@ -92,7 +121,8 @@ for (const engine of engines) for (const lang of ["en", "zh"]) {
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
- await page.route("**/*", serve(lang));
+ const next = [];
+ await page.route("**/*", serve(lang, [req(1)], next));
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
@@ -102,11 +132,21 @@ for (const engine of engines) for (const lang of ["en", "zh"]) {
});
await page.goto("http://magpie.test/?view=routing");
await page.locator(".rt-req").first().waitFor();
- // Routing in sight: the loop is running, and it is this loop we count
+ // Routing in sight: the loop ran, and it is this loop we count
await page.waitForFunction(() => window.__seenFrame, null, { timeout: 5000 });
+ // nothing under way: once the first caption is shown the loop rests,
+ // and so does the live dot
+ const still = await page.evaluate(() => window.__settle(400));
+ assert.equal(still, 0, `the Routing loop kept asking for frames with nothing on its stage moving (${still} frames in 400ms)`);
+ await page.evaluate(() => window.__mark());
+ assert.equal(await page.evaluate(() => window.__count(1200)), 0, "the idle Routing loop woke on its own");
+ assert.equal(await page.evaluate(() => window.__pulses()), 0, "the live dot pulsed with no request under way");
+ // a request comes in, still being answered: it flies, and the dot pulses
+ next.push(live(2));
await page.evaluate(() => window.__mark());
const flying = await page.evaluate(() => window.__count(600));
- assert(flying > 10, `the loop must run while Routing is in sight (${flying} frames in 600ms)`);
+ assert(flying > 10, `a request coming in must wake the loop (${flying} frames in 600ms)`);
+ await page.waitForFunction(() => window.__pulses() > 0);
assert(errors.length === 0, errors.join("\n"));
// Agents picked: #view-routing.hidden, the tab in sight, frames drawn
@@ -125,7 +165,7 @@ for (const engine of engines) for (const lang of ["en", "zh"]) {
await page.locator('#nav button[data-view="routing"]').click();
await page.evaluate(() => window.__mark());
const again = await page.evaluate(() => window.__count(600));
- assert(again > 10, `picking Routing again must resume the loop (${again} frames in 600ms)`);
+ assert(again > 10, `picking Routing again must resume the loop, and fly the request under way (${again} frames in 600ms)`);
assert.equal(await page.evaluate(() => document.querySelectorAll(".rt-req").length >= 1), true, "the page is drawn again");
assert(errors.length === 0, errors.join("\n"));
// A document visibility event must stop the loop even when the engine
@@ -136,6 +176,12 @@ for (const engine of engines) for (const lang of ["en", "zh"]) {
await page.evaluate(() => window.__visibility(false));
await page.evaluate(() => window.__mark());
assert(await page.evaluate(() => window.__count(600)) > 10);
+ // the request answered: the stage settles, the loop and the dot rest
+ const done = req(2);
+ done.seq = 3;
+ next.push(done);
+ await page.waitForFunction(() => window.__pulses() === 0);
+ assert.equal(await page.evaluate(() => window.__settle(400)), 0, "the loop kept running after the last request was answered");
assert.equal(errors.length, 0, errors.join("\n"));
});
}