diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 5ca755286..7872e7e9b 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -328,7 +328,7 @@ function routingPage(part) { for (const [cls, fits] of Object.entries(marks)) node.classList.toggle(cls, fits(w)); }); }).observe(node); - byWidth(box, { max560: (w) => w <= 560 }); + byWidth(box, { max560: (w) => w <= 560, max720: (w) => w <= 720 }); byWidth(list, { max460: (w) => w <= 460, max560: (w) => w <= 560 }); byWidth(more, { max520: (w) => w <= 520 }); for (const col of [colA, colB]) byWidth(col, { max440: (w) => w <= 440, max760: (w) => w <= 760 }); @@ -1452,6 +1452,41 @@ function routingPage(part) { } // a try in words, and how its reasoning came to differ from the agent's + // answered: what the caption shows of a try that answered, its + // figures each in a place of its own (Puremilk_chun on X: a sentence + // whose length and line breaks moved with every value had the reader + // look for each one again): who, on which model and at what effort over + // the time it took, its tokens, its first token, its speed and how much + // of its prompt the cache held. A figure not told is a dash in its place, + // so the others stay where they are. The sentence is on hover, and in + // the list of steps below. + function answered(r, i) { + const tr = r.tries[i], w = tried(r, tr), text = tryWhy(r, i); + const card = () => { + const box = el("div", "rt-done"); + const model = w ? (tr.auto?.length ? `${w.model} → ${tr.auto[tr.auto.length - 1].model}` : w.model) : tr.model || ""; + box.append(el("b", "who", w ? who(w) : tr.id), el("span", "mdl", model || ""), el("span", "effort-of", tr.effort || "")); + const v = speedOf(r, tr.ms, tr.ttft, tr.firstText, tr.flow, tr.firstReasoning || 0, tr.reasoningHidden || false); + const { prompt, read } = promptOf(r); + for (const [value, label] of [ + [tr.ms ? took(tr.ms) : "", "Duration"], + [r.tokens ? tokens(r.tokens) : "", "Tokens"], + [tr.ttft ? took(tr.ttft) : "", "First token"], + [v ? t("{n} tok/s", { n: Math.round(v) }) : "", "Speed"], + [prompt ? hitPct(read / prompt) : "", "Cache"], + ]) { + const f = el("span", "fig" + (value ? "" : " none")); + // the number large, its unit beside it small: "40 tok/s" + const b = el("b"), m = value && /^([\d.,]+) (\S.*)$/.exec(value); + if (m) b.append(m[1], el("small", "", " " + m[2])); + else b.textContent = value || "—"; + f.append(b, el("span", "", t(label))); + box.append(f); + } + return box; + }; + return { text, card }; + } function tryWhy(r, i) { const tr = r.tries[i], said = trySaid(r, i); // a prompt turned away is turned away at every level: the level is no part of it @@ -2032,7 +2067,14 @@ function routingPage(part) { if (capQ.length > 3) capQ.shift(); kick(); } - function show(c) { capLo = !!c.lo; cap.textContent = c.s; rerun(cap, "in", "rtin"); capAt = performance.now(); } + // a caption is words, or a try's answer laid out (answered), its words + // on hover + function show(c) { + capLo = !!c.lo; + if (c.s.card) { cap.replaceChildren(c.s.card()); cap.title = c.s.text; } + else { cap.textContent = c.s; cap.removeAttribute("title"); } + rerun(cap, "in", "rtin"); capAt = performance.now(); + } // curve is a wire's S from (x0, y0) to (x3, y3), its bends at mx: one // cubic, cut into exact pieces of it about 1000 px tall (the middle ones @@ -5380,7 +5422,7 @@ function routingPage(part) { await until(() => g !== gen || rt().done); if (g !== gen) break; r = rt(); - say(tryWhy(r, i), true); + say(answered(r, i), true); renderAll(); dot.classList.add("back"); dot.setAttribute("r", 4); @@ -5772,7 +5814,7 @@ function routingPage(part) { // the mode line above already says what plays here; a caption saying // it again was one more line to read (yujezhang on X, 11-10) capQ = []; - cap.textContent = ""; + cap.textContent = ""; cap.removeAttribute("title"); log.hidden = true; renderHist(); // none live, but the days the history keeps are still there to look at layout(); diff --git a/internal/gui/assets/plugins/routing/routing.css b/internal/gui/assets/plugins/routing/routing.css index 9251a10f8..77ede31d7 100644 --- a/internal/gui/assets/plugins/routing/routing.css +++ b/internal/gui/assets/plugins/routing/routing.css @@ -188,8 +188,26 @@ .rt-accts li.rt-fold:focus { outline: none; } .rt-accts li.rt-fold:focus-visible { box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 30%, transparent); } .rt-foot { display: flex; align-items: center; justify-content: space-between; gap: 10px 20px; flex-wrap: wrap; padding-top: 10px; border-top: 1px solid var(--line); } -.rt-cap { flex: 1 1 20em; margin: 0; min-height: 3em; display: flex; align-items: center; font-size: 13px; line-height: 1.45; color: var(--fg); } +.rt-cap { flex: 1 1 20em; margin: 0; min-height: 54px; display: flex; align-items: center; font-size: 13px; line-height: 1.45; color: var(--fg); } .rt-cap.in { animation: rtin .4s ease-out; } +/* a try's answer in the caption (answered): who, model and effort over + its figures, each in a column of its own whatever the others say, as + the counts beside it are (Puremilk_chun on X) */ +.rt-done { flex: 1; min-width: 0; display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 3px 14px; } +.rt-done > * { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.rt-done > .who { grid-column: span 2; font-size: 12px; line-height: 17px; font-weight: 560; } +.rt-done > .mdl { grid-column: span 2; font-size: 12px; line-height: 17px; color: var(--fg-2); } +.rt-done > .effort-of { font-size: 12px; line-height: 17px; color: var(--muted); } +.rt-done > .fig { display: flex; flex-direction: column; font-size: 11px; line-height: 14px; color: var(--muted); } +.rt-done > .fig > * { overflow: hidden; text-overflow: ellipsis; } +.rt-done > .fig b { font-size: 15px; line-height: 19px; font-weight: 650; letter-spacing: -.01em; color: var(--fg); font-variant-numeric: tabular-nums; } +.rt-done > .fig b small { line-height: 0; font-size: 11px; font-weight: 500; letter-spacing: 0; color: var(--fg-2); } +/* a narrow stage (max720, set by client.js): three to a line, in the + same places on every answer */ +:where(.rt.max720) .rt-done { grid-template-columns: repeat(3, minmax(0, 1fr)); } +:where(.rt.max720) .rt-done > .who { grid-column: span 2; } +:where(.rt.max720) .rt-done > .mdl { grid-column: 1 / -1; grid-row: 2; } +.rt-done > .fig.none b { color: var(--faint); font-weight: 400; } @keyframes rtin { from { opacity: 0; transform: translateY(4px); } } .rt-stats { display: flex; gap: 18px; font-size: 11px; color: var(--muted); } .rt-stats > span { display: flex; flex-direction: column; } diff --git a/internal/gui/tests/routing-answer-figures.test.cjs b/internal/gui/tests/routing-answer-figures.test.cjs new file mode 100644 index 000000000..41994e966 --- /dev/null +++ b/internal/gui/tests/routing-answer-figures.test.cjs @@ -0,0 +1,168 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The caption over the Routing stage tells a try that answered as figures, +// each in a place of its own (Puremilk_chun on X: "Codex's own sign-in +// (gpt-6.1-sol) 以 high 推理强度 用 41 秒 完成回答 · 197.5k token · 35 秒 +// 后出首字 · 40 token/秒 · 请求缓存命中率 98%" was one sentence whose +// length and line breaks moved with every value, so the reader looked for +// each one again). Who answered, its model and its effort head it; under +// them the time it took, its tokens, its first token, its speed and its +// cache hit rate, each a value over its name. The next request's figures +// take the same places, whatever their length, and a figure it doesn't +// tell is a dash in its place, not a gap the others close up. The sentence +// is still on hover. English, Chinese (simplified and traditional), +// Japanese and German, at 1100px and 420px, in both engines; no backend, +// the API is faked here. +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 ago = (s) => new Date(Date.now() - s * 1e3).toISOString(); +const M = "gpt-6.1-sol"; +const order = [ + { id: "codex", provider: "codex", name: "Codex", who: "me@example.com", kind: "account", agent: "codex", model: M, known: true, used: 20 }, + { id: "codex@team", provider: "codex", name: "Codex", who: "a-much-longer-name@team.example.com", kind: "account", agent: "codex", model: M, known: true, used: 20 }, +]; +// the reporter's request: 41 s, 197.5k tokens, its first token at 35 s, +// 240 written in the 6 s after it (40 tok/s), 98% of its prompt cached +const first = (done) => ({ + id: 1, seq: 1, time: ago(42), agent: "codex", model: M, provider: "codex", done, status: done ? 200 : 0, ms: done ? 41000 : 0, + tokens: done ? 197500 : 0, out: done ? 240 : 0, effort: "high", + usage: done ? [{ in: 3950, cache_read: 193310, out: 240 }] : [], + order, + tries: [{ id: "codex", model: M, effort: "high", start: ago(41), done, ...(done ? { status: 200, ms: 41000, ttft: 35000 } : {}) }], +}); +// the next: another account, no first token told (so no speed), nothing +// cached that the vendor counted +const second = (done) => ({ + id: 2, seq: 2, time: ago(3), agent: "codex", model: M, provider: "codex", done, status: done ? 200 : 0, ms: done ? 2100 : 0, + tokens: done ? 900 : 0, out: done ? 60 : 0, effort: "low", + usage: done ? [{ in: 840, out: 60, cache_unknown: true }] : [], + order: [order[1], order[0]], + tries: [{ id: "codex@team", model: M, effort: "low", start: ago(2), done, ...(done ? { status: 200, ms: 2100 } : {}) }], +}); + +function serve(lang, live) { + return async (request) => { + const url = new URL(request.request().url()); + const json = (data) => request.fulfill({ json: data }); + if (url.pathname === "/boot.js") return request.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return request.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) { + if (live.queued.length) return json(live.queued.shift()); + live.pending.push(request); + return; + } + return json({ mine: true, now: new Date().toISOString(), seq: 0, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], excluded: [], gateway: { running: true, window: true } }); + 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 request.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}px: an answer's figures each keep a place of their own`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await browser.newPage({ viewport: { width, height: 900 } }); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.locator(".rt-cap").evaluate((e) => e.scrollIntoView({ block: "center" })).catch(() => {}); + await page.waitForTimeout(800); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `answer-${engine}-${lang}-${width}.png`) }).catch(() => {}); + } + await browser.close(); + }); + page.setDefaultTimeout(15000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (error) => errors.push(error.message)); + const live = { pending: [], queued: [], seq: 0 }; + await page.route("**/*", serve(lang, live)); + const send = (...routes) => { + const d = { mine: true, now: new Date().toISOString(), seq: ++live.seq, totals: { requests: live.seq, rerouted: 0, errors: 0 }, routes }; + const r = live.pending.shift(); + if (r) r.fulfill({ json: d }); else live.queued.push(d); + }; + const say = (key, vars = {}) => page.evaluate(([lang, key, vars]) => { + const s = (lang !== "en" && I18N[lang]?.[key]) || key; + return s.replace(/\{(\w+)\}/g, (_, k) => vars[k] ?? `{${k}}`); + }, [lang, key, vars]); + const card = () => page.evaluate(() => { + const box = document.querySelector(".rt-cap .rt-done"); + if (!box) return null; + const left = box.getBoundingClientRect().left; + const at = (e) => Math.round(e.getBoundingClientRect().left - left); + return { + who: box.querySelector(".who").textContent, mdl: box.querySelector(".mdl").textContent, eff: box.querySelector(".effort-of").textContent, + figs: [...box.querySelectorAll(".fig")].map((f) => [f.querySelector("b").textContent, f.querySelector("span").textContent, f.classList.contains("none")]), + at: [...box.children].map(at), + top: [...box.querySelectorAll(".fig")].map((f) => Math.round(f.getBoundingClientRect().top - box.getBoundingClientRect().top)), + head: [".who", ".effort-of"].map((q) => { const r = box.querySelector(q).getBoundingClientRect(); return [Math.round(r.top), Math.round(r.height)]; }), + cut: [...box.querySelectorAll(".fig b")].filter((b) => b.scrollWidth > b.clientWidth + 1).map((b) => b.textContent), + tip: box.parentElement.title, + capH: Math.round(box.parentElement.getBoundingClientRect().height), + w: Math.round(box.getBoundingClientRect().width), + }; + }); + await page.goto("http://magpie.test/?view=routing"); + await page.waitForFunction(() => document.querySelector(".rt-cap")); + await page.waitForTimeout(300); // the first trace in, the long poll waiting + + send(first(false)); + await page.waitForTimeout(1500); + send(first(true)); + await page.waitForFunction(() => document.querySelector(".rt-cap .rt-done .who")?.textContent.includes("me@example.com")); + const a = await card(); + assert.equal(a.mdl, M); + assert.equal(a.eff, "high"); + // the effort on the account's line, as tall as it + assert.deepEqual(a.head[1], a.head[0], `effort at ${a.head[1]}, account at ${a.head[0]}`); + assert.deepEqual(a.figs, [ + [await say("{n} s", { n: "41" }), await say("Duration"), false], + ["197.5k", await say("Tokens"), false], + [await say("{n} s", { n: "35" }), await say("First token"), false], + [await say("{n} tok/s", { n: 40 }), await say("Speed"), false], + ["98%", await say("Cache"), false], + ]); + assert.deepEqual(a.cut, [], `${lang} at ${width}: cut ${a.cut.join(", ")} in ${a.w}px`); + // the five figures on one line where the stage is wide; three to a + // line on a narrow one + if (width === 1100) assert.equal(new Set(a.top).size, 1, `figures on more than one line: ${a.top}`); + else assert.deepEqual([a.top[0] === a.top[2], a.top[2] < a.top[3], a.top[3] === a.top[4]], [true, true, true], `${a.top}`); + // the sentence on hover + assert.ok(a.tip && a.tip.includes("me@example.com"), a.tip); + // the whole sentence in the list of steps still + assert.ok(a.tip.length > 20); + + send(second(false)); + await page.waitForTimeout(1500); + send(second(true)); + await page.waitForFunction(() => document.querySelector(".rt-cap .rt-done .who")?.textContent.includes("a-much-longer-name")); + const b = await card(); + assert.equal(b.eff, "low"); + assert.deepEqual(b.figs.map((f) => f[2]), [false, false, true, true, true], JSON.stringify(b.figs)); + assert.deepEqual(b.figs.slice(2).map((f) => f[0]), ["—", "—", "—"]); + // every part where it was, whatever the values' lengths + assert.deepEqual(b.at, a.at); + assert.deepEqual(b.top, a.top); + assert.equal(b.capH, a.capH, "the caption kept its height"); + // nothing scrolls sideways + const over = await page.evaluate(() => document.documentElement.scrollWidth - innerWidth); + assert.ok(over <= 1, `${lang} at ${width}: ${over}px past`); + assert.deepEqual(errors, []); + }); + } + } +}