From eadc6cdb96d40fca9dc82b1804fd661c8d398952 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 8 Nov 2026 15:05:41 +0800 Subject: [PATCH] routing: a request with a named gateway key is drawn as that key MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit acezan (Discord) sent the Routing flow for an Antigravity group: a script's requests showed only "Python-urllib", the caller's User-Agent, on the left node. The request should be named by the gateway key it came with. The trace and history routes already carry callerKey (the key's id) and callerKeyName, never the secret. The stage now groups callers by agent plus key, so two keys behind one User-Agent are two nodes, each in its own colour. A keyed node reads the key's name as Gateway keys lists it now, else the name the route kept. A request with no key keeps the agent's name, as before. The agent's icon stays, and the tooltip names the key and then the agent. No new labels. Siblings: - The request rows' swatch, wire hue, the play dots and the replay marks follow the same caller, and "Sent by" names the key. - The tray panel's stage and its .pr-who rows name the key the same way. The panel doesn't read /api/caller-keys, so it shows the name the route kept; a key renamed later shows its old name there until the next request. - Usage already shows "agent · key name" on ledger rows and has its own key split. Unchanged. - The By-key and By-session group heads and the story prose ("X asked for...") are unchanged. Run on mote at 1aabc66fd + this commit: - New internal/gui/tests/routing-caller-key-node.test.cjs: 11/11 in chromium and 11/11 in webkit. It covers en, zh, zh-TW, ja and de at 1100 and 420, plus the tray panel. - With routing-by-key, agents-apart, agent-hue-not-red, fifth-agent and panel-routing: 46/46 in each engine. - go test: TestKeptRoutesNameTheirCallerKey (new), TestCoreScriptBudget and TestTraceNamesCallerKey ok. gofmt -l is clean. go vet passes on internal/gui and internal/gateway for darwin, linux (-tags nogui) and windows. - Every routing-*, panel-routing* and click-scroll file at the previous base 15918265e + this change, under load (60 to 100): - chromium: 1546/1554. - webkit: 1542/1554. The reds are in routing-intent-entry (#5392), routing-row-swap (#3799), routing-context-fold (#5586) and routing-story-shrinks (#3954). They are red the same way when run alone at origin/main 15918265e, without this change. ctx-sessions and many-keys went red only in the parallel run and passed alone. Broken by hand: - With client.js from origin/main, the new GUI test is 0/11 red. - TestKeptRoutesNameTheirCallerKey passes on the old code too, because the Go side already carried both fields. It guards history keeping them: with callerKeyName's JSON tag set to "-", it goes red. Not tried: a real request with a named key through a live gateway. The fixtures are faked trace routes. Full suite: not run at push. Reported-by: acezan (Discord) --- internal/gui/assets/plugins/routing/client.js | 71 ++++++---- internal/gui/history_caller_key_test.go | 69 ++++++++++ .../tests/routing-caller-key-node.test.cjs | 129 ++++++++++++++++++ 3 files changed, 240 insertions(+), 29 deletions(-) create mode 100644 internal/gui/history_caller_key_test.go create mode 100644 internal/gui/tests/routing-caller-key-node.test.cjs diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index d81c85a76..d7f20bceb 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -661,6 +661,17 @@ function routingPage(part) { // sillytavern; a comma would part it in two (ParseRule) const uaName = (s) => String(s || "").trim().split(/[\/\s,]/)[0].toLowerCase(); const agentName = (id) => agentOf(id)?.name || (id && id !== "other" ? id : t("your agent")); + // callerName is who sent a request, as the stage and the lists name it: + // the gateway key it came with, by the key's name now, else the name it + // had then; a request with no named key, its agent (acezan on Discord: + // a script's key read "Python-urllib"). srcOf is the stage's node for + // it: each key's its own, two keys' scripts saying one User-Agent too. + // Never the key's secret: a route carries its id and name alone. + function callerName(r) { + const k = r.callerKey && (callerKeys.find((x) => x.id === r.callerKey)?.name || r.callerKeyName); + return k || agentName(r.agent); + } + const srcOf = (r) => r.callerKey ? r.agent + "\u0001" + r.callerKey : r.agent; // userShown is an account of provider as the user named it in magpie // (provider.AccountNames, #1515), else as its plugin's usage names it // (accountUsers, #4416), else as its vendor names it. The name @@ -2294,7 +2305,7 @@ function routingPage(part) { const out = new Map(); for (const r of rs) { const key = wayOf(r), g = r.group, f = r.order.find((x) => !x.fallback) || r.order[0]; - const agents = [...new Set([...(out.get(key)?.agents || []), agentName(r.agent)])]; + const agents = [...new Set([...(out.get(key)?.agents || []), callerName(r)])]; out.set(key, g ? { id: key, route: true, pk: "route/group/" + g.id, name: g.name, ref: g.ref || "group/" + g.id, routing: g.routing || "", agents } : { id: key, route: true, pk: "route/" + r.provider, name: f?.name || r.provider, ref: r.model, routing: f?.routing || "", icon: f ? f.icon || f.preset || "generic" : "", lone: r.order.filter((x) => !x.fallback).length <= 1, agents }); @@ -2309,12 +2320,12 @@ function routingPage(part) { if (day && !rp) return []; const n = now(), last = new Map(), map = src(); const rs = [...map.values()].filter(matchesPurpose).sort((a, b) => a.id - b.id); - for (const r of rs) last.set(r.agent, r); - const out = rs.filter((r) => playing.has(r.id) || (last.get(r.agent) === r && (!r.done || at(r.time) + (r.ms || 0) > n - LINGER))); + for (const r of rs) last.set(srcOf(r), r); + const out = rs.filter((r) => playing.has(r.id) || (last.get(srcOf(r)) === r && (!r.done || at(r.time) + (r.ms || 0) > n - LINGER))); const c = cur && map.get(cur.id); if (c && !out.includes(c)) out.push(c); - const ags = [...new Set(out.map((r) => r.agent))].slice(-4); - return out.filter((r) => ags.includes(r.agent)).sort((a, b) => a.id - b.id); + const ags = [...new Set(out.map(srcOf))].slice(-4); + return out.filter((r) => ags.includes(srcOf(r))).sort((a, b) => a.id - b.id); } // hueOf is the colour an agent's requests and answers fly in, and it is @@ -2555,7 +2566,7 @@ function routingPage(part) { srcs.replaceChildren(); } // agents - const ags = [...new Set(rs.map((r) => r.agent))]; + const ags = [...new Set(rs.map(srcOf))]; for (const [id, a] of agents) if (!ags.includes(id)) { a.node.remove(); a.wire.remove(); agents.delete(id); } const keep = [...agents.keys()]; const nodes = [...keep, ...ags.filter((a) => !keep.includes(a))].map((id) => agentNode(id).node); @@ -2563,18 +2574,18 @@ function routingPage(part) { srcs.classList.toggle("many", ags.length > 1); hues(ags); for (const id of ags) { - const a = agents.get(id), r = rs.filter((x) => x.agent === id).pop(), ag = agentOf(id); + const a = agents.get(id), r = rs.filter((x) => srcOf(x) === id).pop(), ag = agentOf(r.agent); for (const n of [a.node, a.wire]) n.style.setProperty("--agent", hueOf(id)); if (a.icon !== (ag?.icon || "generic")) { a.icon = ag?.icon || "generic"; a.ic.replaceChildren(icon(a.icon)); } - setText(a.name, agentName(id)); + setText(a.name, callerName(r)); // 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)); + const n = now(), going = pinned ? [] : [...src().values()].filter((x) => srcOf(x) === id && (!x.done || at(x.time) + (x.ms || 0) > n - LINGER)); + const fs = foldersOf([...new Set([...going, ...rs.filter((x) => srcOf(x) === id)])].sort((x, y) => x.id - y.id)); // 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"); + const tip = [...new Set([callerName(r), agentName(r.agent)]), 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 @@ -2841,7 +2852,7 @@ function routingPage(part) { hubText(); const n = now(), rs = staged(); const trying = new Map(), busy = new Set(); // a seat → the request it answers now - for (const r of rs) for (const tr of r.tries) if (!tr.done) { trying.set(tryseat(r, tr), r); busy.add(r.agent); } + for (const r of rs) for (const tr of r.tries) if (!tr.done) { trying.set(tryseat(r, tr), r); busy.add(srcOf(r)); } askUnnamed(rs); const onWire = new Map(); // a seat → the agent whose magpie is at it for (const f of flying.values()) { onWire.set(f.id, f.agent); busy.add(f.agent); } @@ -2977,7 +2988,7 @@ function routingPage(part) { // answers now, the one whose magpie is at it, else the request it // answered, and none once it is off, so a row kept from before // never shows the last agent's colour (Pkh on Discord) - const by = trying.get(id)?.agent ?? onWire.get(id) ?? r.agent; + const by = trying.has(id) ? srcOf(trying.get(id)) : onWire.get(id) ?? srcOf(r); if (on) row.wire.style.setProperty("--agent", hueOf(by)); else row.wire.style.removeProperty("--agent"); row.wire.classList.toggle("rest", !!resting || !!w.unlisted || !!w.window); } @@ -4489,7 +4500,7 @@ function routingPage(part) { const when = el("span", "at", rowClock(r.time)); const asked = el("span", "asked"); const sw = el("i", "ag"); - sw.style.setProperty("--agent", hueOf(r.agent)); + sw.style.setProperty("--agent", hueOf(srcOf(r))); asked.append(sw, icon(ag?.icon || "generic"), el("span", "m", r.model)); const tags = rowTags(r); if (tags.length) { asked.classList.add("kinded"); asked.append(...tags); } @@ -5094,7 +5105,7 @@ function routingPage(part) { if (aside) say(aside, true); } renderAll(); - const A = agents.get(r.agent); + const A = agents.get(srcOf(r)); // an agent past the stage's four (staged) isn't drawn: its request is // listed, not flown if (!A) { @@ -5102,7 +5113,7 @@ function routingPage(part) { return; } const dot = packet(); - dot.style.setProperty("--agent", hueOf(r.agent)); + dot.style.setProperty("--agent", hueOf(srcOf(r))); // from: where in magpie the dot is, once it is — the way it came in let carrier = bird("req"), from = null, back = null; // rt: the route as the gateway has it now — or, dropped from what it @@ -5125,7 +5136,7 @@ function routingPage(part) { } const row = shownRow(tryseat(r, r.tries[i])); // a folded key's fold if (!row) { i++; continue; } - flying.set(dot, { id: tryseat(r, r.tries[i]), agent: r.agent }); + flying.set(dot, { id: tryseat(r, r.tries[i]), agent: srcOf(r) }); if (!carrier) carrier = bird("req"); if (from) tick(hub); const ws = wiresTo(row); @@ -5247,8 +5258,8 @@ function routingPage(part) { rTrack.replaceChildren(rHead, ...plan.map((g) => { const m = el("i", "rp-mark"); m.style.left = (g.s / (v || 1)) * 100 + "%"; - m.style.setProperty("--agent", hueOf(g.r.agent)); - m.title = `${clock(g.r.time)} · ${agentName(g.r.agent)} · ${g.r.model}`; + m.style.setProperty("--agent", hueOf(srcOf(g.r))); + m.title = `${clock(g.r.time)} · ${callerName(g.r)} · ${g.r.model}`; g.mark = m; return m; })); @@ -5327,10 +5338,10 @@ function routingPage(part) { rWhat.replaceChildren(...(shown_.length ? shown_.map((g) => { const r = p.routes.get(g.r.id) || g.r, row = el("div", "rp-req" + (on.includes(g) ? " on" : "")); const sw = el("i", "ag"); - sw.style.setProperty("--agent", hueOf(r.agent)); + sw.style.setProperty("--agent", hueOf(srcOf(r))); const [said] = outcome(r); row.append(el("span", "rp-n", t("request {i} of {n}", { i: g.n, n: p.plan.length })), sw, - el("b", "", agentName(r.agent)), el("code", "mdl", r.model), ...rowTags(r), el("span", "rp-to", "→ " + said), + el("b", "", callerName(r)), el("code", "mdl", r.model), ...rowTags(r), el("span", "rp-to", "→ " + said), el("span", "rp-at", t("sent {time}", { time: new Date(r.time).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false }) }))); row.onclick = () => { cur = r; renderLog(); }; return row; @@ -8493,12 +8504,14 @@ function routingPage(part) { 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 } + const byOf = new Map(); // a caller (srcOf) → its latest request + for (const r of recent) if (!byOf.has(srcOf(r))) byOf.set(srcOf(r), r); for (const r of flying) { - if (!ags.includes(r.agent)) ags.push(r.agent); + if (!ags.includes(srcOf(r))) ags.push(srcOf(r)); for (const tr of r.tries) { const s = pSeat(r, tr); if (!dst.has(s.key)) dst.set(s.key, s); } } for (const r of recent) { - if (ags.length < P_SIDE && !ags.includes(r.agent)) ags.push(r.agent); + if (ags.length < P_SIDE && !ags.includes(srcOf(r))) ags.push(srcOf(r)); const tr = r.tries[r.tries.length - 1]; if (tr) { const s = pSeat(r, tr); if (!dst.has(s.key) && dst.size < P_SIDE) dst.set(s.key, s); } } @@ -8517,12 +8530,12 @@ function routingPage(part) { pFrom.replaceChildren(...pAg.map((id) => { const n = pNode("a:" + id); keep.add("a:" + id); - const ag = agentOf(id); + const r = byOf.get(id), ag = agentOf(r.agent); n.node.className = "ps-node ps-ag"; n.node.style.setProperty("--agent", hueOf(id)); n.wire.style.setProperty("--agent", hueOf(id)); - n.node.replaceChildren(icon(ag?.icon || "generic"), el("span", "ps-name", agentName(id))); - n.node.title = [agentName(id), ...foldersOf(recent.filter((r) => r.agent === id).slice(0, 20).reverse()).map((f) => t("Folder") + ": " + f)].join("\n"); + n.node.replaceChildren(icon(ag?.icon || "generic"), el("span", "ps-name", callerName(r))); + n.node.title = [...new Set([callerName(r), agentName(r.agent)]), ...foldersOf(recent.filter((x) => srcOf(x) === id).slice(0, 20).reverse()).map((f) => t("Folder") + ": " + f)].join("\n"); return n.node; })); pTo.replaceChildren(...pDst.map((k) => { @@ -8613,9 +8626,9 @@ function routingPage(part) { dot.setAttribute("r", 3.5); dot.setAttribute("class", "ps-dot"); dot.setAttribute("visibility", "hidden"); - dot.style.setProperty("--agent", hueOf(r.agent)); + dot.style.setProperty("--agent", hueOf(srcOf(r))); pSky.appendChild(dot); - const home = () => pNodes.get("a:" + r.agent); + const home = () => pNodes.get("a:" + srcOf(r)); // rt: the route as the gateway has it now — or, dropped from the 60 // kept while it flew, over: its dot goes, as nothing more will be heard // of it. Waiting on it held the dot and its place for three minutes @@ -8784,7 +8797,7 @@ function routingPage(part) { b.type = "button"; const ag = agentOf(r.agent); const asked = el("span", "pr-a"); - asked.append(icon(ag?.icon || "generic"), el("span", "pr-who", agentName(r.agent)), el("code", "m", r.model)); + asked.append(icon(ag?.icon || "generic"), el("span", "pr-who", callerName(r)), el("code", "m", r.model)); asked.append(...rowTags(r)); const when = el("span", "at", new Date(r.time).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" })); // where it went: the provider, the account or key, and the model that diff --git a/internal/gui/history_caller_key_test.go b/internal/gui/history_caller_key_test.go new file mode 100644 index 000000000..224fe1675 --- /dev/null +++ b/internal/gui/history_caller_key_test.go @@ -0,0 +1,69 @@ +package gui + +import ( + "bytes" + "encoding/json" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "github.com/yetone/magpie/internal/gateway" +) + +// The Routing stage names a request by the gateway key it came with +// (acezan on Discord: a script's requests read "Python-urllib", its +// User-Agent). A day gone by is drawn from /api/gateway/history, so a kept +// route keeps the key's id and name through the GUI's priced routes, as +// the live trace does (TestTraceNamesCallerKey); a route with no key names +// none, and its agent stays the User-Agent's product name. +func TestKeptRoutesNameTheirCallerKey(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + mux := keptMux(t) + traceRoutes(mux) + + dir := gateway.HistoryDir() + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + now := time.Now() + day := now.Format("2006-01-02") + var b bytes.Buffer + for i, key := range [][2]string{{"k-nightly", "Nightly job"}, {"", ""}} { + r := ctxRoute(int64(i+1), "Python-urllib", "", 3000, 100, 200000, 0) + r.Time = now.Add(-time.Duration(2-i) * time.Minute) + r.CallerKey, r.CallerKeyName = key[0], key[1] + j, _ := json.Marshal(r) + b.Write(append(j, '\n')) + } + if err := os.WriteFile(filepath.Join(dir, day+".jsonl"), b.Bytes(), 0o600); err != nil { + t.Fatal(err) + } + + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest("GET", "/api/gateway/history?day="+day, nil)) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + var hist struct { + Routes []map[string]any `json:"routes"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &hist); err != nil { + t.Fatal(err) + } + if len(hist.Routes) != 2 { + t.Fatalf("routes: %s", rec.Body) + } + by := map[float64]map[string]any{} + for _, r := range hist.Routes { + by[r["id"].(float64)] = r + } + if r := by[1]; r["callerKey"] != "k-nightly" || r["callerKeyName"] != "Nightly job" || r["agent"] != "Python-urllib" { + t.Fatalf("the keyed route doesn't name its key: %v", r) + } + if r := by[2]; r["callerKey"] != nil || r["callerKeyName"] != nil || r["agent"] != "Python-urllib" { + t.Fatalf("the route with no key names one: %v", r) + } +} diff --git a/internal/gui/tests/routing-caller-key-node.test.cjs b/internal/gui/tests/routing-caller-key-node.test.cjs new file mode 100644 index 000000000..220ce2289 --- /dev/null +++ b/internal/gui/tests/routing-caller-key-node.test.cjs @@ -0,0 +1,129 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Routing stage names who sent a request by the gateway key it came +// with (acezan on Discord: a script's requests through an Antigravity group +// read "Python-urllib", its User-Agent, where the key's name says whose +// they are). A request with a named key is drawn as that key, by the name +// Gateway keys has for it now, else the name the route kept; two keys whose +// scripts say one User-Agent are two callers, each its own colour; a +// request with no key keeps its agent's name. The agent stays under the +// pointer. The tray panel's stage and rows name it the same way. In every +// language, at 1100 and 420; the API is faked. +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"); + +function fixture() { + const now = Date.now(), at = (s) => new Date(now - s * 1000).toISOString(); + const seat = { id: "agy", provider: "agy", name: "Antigravity", who: "me@example.com", kind: "account", model: "gemini-3-pro" }; + // under way, so each stays on the stage + const req = (id, agent, key) => ({ id, seq: id, time: at(5 - id), agent, + ...(key ? { callerKey: key.id, callerKeyName: key.name } : {}), + model: "group/agy", provider: "agy", order: [seat], tries: [{ id: seat.id, model: "gemini-3-pro", start: at(4), done: false }], + done: false, status: 0 }); + return [ + req(1, "Python-urllib", { id: "k-nightly", name: "爬虫 nightly" }), + req(2, "Python-urllib", { id: "k-server", name: "Old box" }), // renamed since: Server + req(3, "Python-urllib", null), // no key: its User-Agent + req(4, "claude", null), + ]; +} +// the keys as Gateway keys lists them now +const keys = [{ id: "k-nightly", name: "爬虫 nightly" }, { id: "k-server", name: "Server" }]; + +function serve(lang) { + 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:"${lang}",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({ agents: [{ id: "claude", name: "Claude Code", fields: [] }], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.has("wait") || Number(url.searchParams.get("after"))) return new Promise(() => {}); + return json({ mine: true, now: new Date().toISOString(), seq: 4, totals: { requests: 4, rerouted: 0, errors: 0 }, routes: fixture() }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/caller-keys") return json({ keys, accountNames: {} }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname.startsWith("/api/window/")) return route.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)]; + return route.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", "zh-TW", "ja", "de"]) { + for (const width of [1100, 420]) { + test(`${engine} ${lang} ${width}: the stage names a request's caller by its gateway key`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const errors = []; + const page = await browser.newPage({ viewport: { width, height: 900 }, reducedMotion: "reduce" }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/?view=routing"); + // Server is the name /api/caller-keys gives once it is read + await page.waitForFunction(() => [...document.querySelectorAll(".rt-src b")].some((b) => b.textContent === "Server")); + const nodes = await page.locator(".rt-src").evaluateAll((es) => es.map((e) => ({ + name: e.querySelector("b").textContent, title: e.title, hue: e.style.getPropertyValue("--agent").trim(), + }))); + assert.deepEqual(nodes.map((n) => n.name).sort(), ["Claude Code", "Python-urllib", "Server", "爬虫 nightly"].sort(), JSON.stringify(nodes)); + const of = (name) => nodes.find((n) => n.name === name); + // the agent behind a key stays under the pointer + assert.match(of("爬虫 nightly").title, /^爬虫 nightly\nPython-urllib\n/); + assert.match(of("Server").title, /^Server\nPython-urllib\n/); + assert.match(of("Python-urllib").title, /^Python-urllib\n/); + assert.doesNotMatch(of("Python-urllib").title, /^Python-urllib\nPython-urllib/, "no key: the agent once"); + assert.equal(new Set(nodes.map((n) => n.hue)).size, 4, "each caller its own colour: " + nodes.map((n) => n.hue)); + // a key's request row is in its node's colour + const rowHue = await page.locator(".rt-req").evaluateAll((es) => es.map((e) => e.querySelector(".asked .ag").style.getPropertyValue("--agent").trim())); + assert.equal(new Set(rowHue).size, 4, "rows: " + rowHue); + const fit = await page.evaluate(() => ({ client: document.documentElement.clientWidth, scroll: document.documentElement.scrollWidth })); + assert(fit.scroll <= fit.client + 1, `the page overflows at ${width}: ${JSON.stringify(fit)}`); + const inside = await page.locator(".rt-src").evaluateAll((es) => es.every((e) => { + const b = e.querySelector("b").getBoundingClientRect(), n = e.getBoundingClientRect(); + return b.right <= n.right + 1 && b.left >= n.left - 1; + })); + assert(inside, "each name inside its node"); + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-caller-key.png`) }); + } + assert.deepEqual(errors, []); + }); + } + } + + test(`${engine}: the tray panel names a request's caller by its gateway key`, 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 {} }); + const page = await ctx.newPage(); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + await page.route("**/*", serve("en")); + await page.goto("http://magpie.test/?mode=panel"); + await page.locator("#panelRouting .pr-req").nth(3).waitFor(); + const who = await page.locator("#panelRouting .pr-who").allTextContents(); + // the panel reads no key list: a key by the name its route kept + assert.deepEqual(who.slice().sort(), ["Claude Code", "Old box", "Python-urllib", "爬虫 nightly"].sort(), JSON.stringify(who)); + await page.waitForFunction(() => document.querySelectorAll("#panelRouting .ps-ag").length === 3); + const names = await page.locator("#panelRouting .ps-ag .ps-name").allTextContents(); + // three a side: the newest three callers, each its own + assert.equal(new Set(names).size, 3, JSON.stringify(names)); + for (const n of names) assert(["Claude Code", "Old box", "Python-urllib", "爬虫 nightly"].includes(n), n); + assert.deepEqual(errors, []); + }); +}