Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
usage: Sessions' agent filter is a menu, as the model and folder ones beside it
yetone11cbf4de1d7b
diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.cssindex f09edeed3..58965acb6 100644--- a/internal/gui/assets/app.css+++ b/internal/gui/assets/app.css@@ -3083,19 +3083,19 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }which #929 left widening the whole page until its last agent'sfilter was only reachable by dragging the page sideways, and Plugins'kinds on GitHub, wider than a 420px window in Japanese */-.segs.regions, .connect .segs, #sessAgent, .pm-ghbar .segs { max-width: 100%; overflow-x: auto; }+.segs.regions, .connect .segs, .pm-ghbar .segs { max-width: 100%; overflow-x: auto; }/* no scrollbar-width here: Chromium (WebView2) then drops every::-webkit-scrollbar rule and draws Windows' classic bar, arrows and all,under the strip; the app's thin thumb instead, slimmer still */-:where(body:not(.mac)) :is(.segs.regions, .connect .segs, #sessAgent, .pm-ghbar .segs)::-webkit-scrollbar { height: 6px; }-:where(body:not(.mac)) :is(.segs.regions, .connect .segs, #sessAgent, .pm-ghbar .segs)::-webkit-scrollbar-thumb { border-width: 1px; }+:where(body:not(.mac)) :is(.segs.regions, .connect .segs, .pm-ghbar .segs)::-webkit-scrollbar { height: 6px; }+:where(body:not(.mac)) :is(.segs.regions, .connect .segs, .pm-ghbar .segs)::-webkit-scrollbar-thumb { border-width: 1px; }/* on a Mac they scroll with no bar, as a Mac's own tab strips do: thesystem's overlay bar showed over the options' lower half for a momentafter each scroll, and a click there went to the bar, which paged thestrip sideways and picked nothing (#1620) */-:where(body.mac) :is(.segs.regions, .connect .segs, #sessAgent, .pm-ghbar .segs) { scrollbar-width: none; }-:where(body.mac) :is(.segs.regions, .connect .segs, #sessAgent, .pm-ghbar .segs)::-webkit-scrollbar { display: none; }-.segs.regions .opt, .connect .segs .opt, #sessAgent .opt, .pm-ghbar .segs .opt { flex: none; }+:where(body.mac) :is(.segs.regions, .connect .segs, .pm-ghbar .segs) { scrollbar-width: none; }+:where(body.mac) :is(.segs.regions, .connect .segs, .pm-ghbar .segs)::-webkit-scrollbar { display: none; }+.segs.regions .opt, .connect .segs .opt, .pm-ghbar .segs .opt { flex: none; }/* a custom provider's five Base URL APIs wrap to a second row where theeditor is too narrow for them (#1346); the thumb follows the row */.segs.base-apis { max-width: 100%; flex-wrap: wrap; }diff --git a/internal/gui/assets/plugins/usage/client.js b/internal/gui/assets/plugins/usage/client.jsindex 31519a69c..b74feaa5a 100644--- a/internal/gui/assets/plugins/usage/client.js+++ b/internal/gui/assets/plugins/usage/client.js@@ -105,7 +105,7 @@ magpie.plugin("usage", (ctx) => {<div class="usage-pane ctx-pane" id="contextPane" hidden></div><div class="usage-pane sess-pane" id="sessionsPane" hidden><div class="sess-tools">- <div class="segs" id="sessAgent"></div>+ <button class="sess-pick" id="sessAgent" type="button" hidden></button><button class="sess-pick" id="sessModel" type="button" hidden></button><button class="sess-pick" id="sessFolder" type="button" hidden></button></div>diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.jsindex bf52a3fc8..bef94de5f 100644--- a/internal/gui/assets/plugins/usage/page.js+++ b/internal/gui/assets/plugins/usage/page.js@@ -2519,8 +2519,7 @@ function renderSessionsLoading() {view.setAttribute("aria-busy", "true");$("#usageCost").replaceChildren(el("span", "skeleton sk-cost"));renderSessRange(true);- $("#sessAgent").replaceChildren();- $("#sessModel").hidden = $("#sessFolder").hidden = true;+ $("#sessAgent").hidden = $("#sessModel").hidden = $("#sessFolder").hidden = true;$("#sessChart").hidden = true;$("#sessGrid").hidden = true;$("#sessListHead").hidden = true;@@ -2799,35 +2798,11 @@ function renderSessions() {const rows = st.days.flatMap((d) => d.usage.map((u) => ({ ...u, date: d.date })));const acts = st.days.flatMap((d) => d.active.map((a) => ({ ...a, date: d.date })));- // one segment per agent that has sessions, or usage in the range+ // the agent filter is a menu, as the model and folder ones beside it: a+ // strip of a segment per agent ran past the window with a dozen of them+ // in range, and scrolled sideways to reach the lastconst agents = [...new Map([...all.map((s) => [s.agent, s.name]), ...Object.entries(st.agents || {})]).entries()];if (sessAgent !== "all" && !agents.some(([id]) => id === sessAgent)) sessAgent = "all";- const seg = $("#sessAgent");- seg.hidden = agents.length < 2;- const opts = [["all", t("All")], ...agents];- // the same agents keep their buttons: drawn anew, a strip with more than- // fit (#929) would lose where it was scrolled to (WebKit)- const was = [...seg.querySelectorAll(":scope > .opt")];- if (was.length !== opts.length || was.some((b, i) => b.dataset.agent !== opts[i][0] || b.textContent !== opts[i][1])) {- seg.replaceChildren();- for (const [id, name] of opts) {- const b = el("button", "opt", name);- b.dataset.agent = id;- b.onclick = () => { sessAgent = id; renderSessions(); };- seg.append(b);- }- }- for (const b of seg.querySelectorAll(":scope > .opt")) {- b.classList.toggle("on", b.dataset.agent === sessAgent);- b.setAttribute("aria-pressed", String(b.dataset.agent === sessAgent));- }- // and the agent picked is brought into the strip, the page left where it is- const picked = seg.querySelector(":scope > .on");- if (picked && seg.scrollWidth > seg.clientWidth) {- if (picked.offsetLeft < seg.scrollLeft) seg.scrollLeft = picked.offsetLeft;- else if (picked.offsetLeft + picked.offsetWidth > seg.scrollLeft + seg.clientWidth) seg.scrollLeft = picked.offsetLeft + picked.offsetWidth - seg.clientWidth;- }- slide(seg, "sessAgent");// the model and folder filters offer what the range has, under the other filtersconst byAgent = (x) => sessAgent === "all" || x.agent === sessAgent;@@ -2840,6 +2815,10 @@ function renderSessions() {};const models = spent(rows.filter((r) => byAgent(r) && byFolder(r)), "model").map(([v, n]) => ({ v, name: v, note: t("{n} tokens", { n: fmtN(n) }) }));const folders = spent(rows.filter((r) => byAgent(r) && byModel(r)), "cwd").map(([v, n]) => ({ v, name: baseName(v), note: v + " · " + t("{n} tokens", { n: fmtN(n) }) }));+ const agentSpent = new Map(spent(rows.filter((r) => byModel(r) && byFolder(r)), "agent"));+ const agentOpts = agents.map(([v, name]) => ({ v, name: name || v, note: agentSpent.has(v) ? t("{n} tokens", { n: fmtN(agentSpent.get(v)) }) : "" }))+ .sort((a, b) => (agentSpent.get(b.v) || 0) - (agentSpent.get(a.v) || 0));+ sessPick($("#sessAgent"), "All agents", sessAgent === "all" ? "" : sessAgent, agentOpts, "Agent", (v) => { sessAgent = v || "all"; renderSessions(); });sessPick($("#sessModel"), "All models", sessModel, models, "Model", (v) => { sessModel = v; renderSessions(); });sessPick($("#sessFolder"), "All folders", sessFolder, folders, "Folder", (v) => { sessFolder = v; renderSessions(); });diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.mdindex 61cdf39ca..5e2b9d2aa 100644--- a/internal/gui/tests/README.md+++ b/internal/gui/tests/README.md@@ -1090,10 +1090,13 @@ at least 5em, at 420 wide the long names are shortened while no bar is underChromium and WebKit, English and Chinese.`usage-sessions-agents-fit.test.cjs` checks Usage › Sessions with 15 agents-(#929): at 860 and 560 wide the page, its main and the Usage view never-scroll sideways; the agent strip fits the window and scrolls in itself, and-the last agent, clicked at the strip's end, stays in view as the strip is-drawn again; in Chromium and WebKit, English and Chinese.+(#929): the agent filter is a menu button like the model and folder ones, no+segment per agent; at 860 and 560 wide nothing scrolls sideways and the three+filters sit on one line inside the window; the menu lists "All agents" and+every agent, the most used first, a few letters narrow it, a pick shows on the+button and stays checked when the page is drawn again, and "All agents" clears+it. One agent in range leaves the filter hidden. Chromium and WebKit, English+and Chinese.`usage-unpriced-names.test.cjs` checks Usage › Sessions where an agentrecorded tokens under no model name (tony on Discord: the cost's note read@@ -1481,17 +1484,6 @@ scroll refused), another agent's switches the page to it, and All sessionsopens the page. At 420px a row still fits with its title readable. Englishand Chinese, WebKit (Chromium too where it launches), API faked.-`sess-agent-strip.test.cjs` keeps Usage → Sessions' agent filter inside the-window (#929): with eleven agents in range the strip is wider than an 866px-window, and it scrolls in itself instead of the page scrolling sideways, the-way the regions strip and Connect's five APIs do; its first and last option-are both reachable and both choose their agent, the model and folder picks-beside it stay visible and open, and in a window wider than the strip nothing-scrolls and the options keep their own widths. One agent in range still-leaves the filter hidden, and the other strips on the page and elsewhere keep-their behaviour. No left-border accent. English and Chinese, Chromium and-WebKit, API faked.-`sessions-purge.test.cjs` erases sessions in magpie's trash for good (#487):a trashed row's Delete forever and the Trash's Empty trash each ask inmagpie's own dialog (a browser `confirm()` fails the test), Cancel sendsdiff --git a/internal/gui/tests/sess-agent-strip.test.cjs b/internal/gui/tests/sess-agent-strip.test.cjsdeleted file mode 100644index 6f9579191..000000000--- a/internal/gui/tests/sess-agent-strip.test.cjs+++ /dev/null@@ -1,208 +0,0 @@-// Run with Node's test runner and Playwright on the module path; see README.md.-// #929 (yetone/magpie): with a dozen agents in range, Usage → Sessions' agent-// filter grew wider than the window, so the whole page scrolled sideways and-// the last agent's filter was only reachable by dragging the page itself. A-// strip too wide for the window scrolls in itself — the regions strip and-// Connect's five APIs already do — so this one does too, and its options keep-// their own width. English and Chinese, Chromium and WebKit.-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 at = (min) => new Date(Date.now() - min * 60e3).toISOString();-// names long enough that eleven agents make a strip wider than an 866px window,-// and short enough to fit a wide one, whose pages keep to 1200px (面条 on Discord),-// with room to spare: a strip that fits by a fraction of a pixel fails on a-// glyph's rounding-const NAMES = ["Trae CN Agent", "Kilo Code Agent", "Pi", "WorkBuddy",- "DeepSeek Harness Agent", "Claude Code", "Codex", "omp", "OpenCode Agent", "Qoder Code", "ZCode Agent"];-const NARROW = { width: 866, height: 800 };-const WIDE = { width: 1600, height: 800 };--const sess = (agent, name, k) => ({- agent, id: `${agent}-${k}`, cwd: `/work/${agent}/part${k}`, title: `task ${k} on ${name}`, start: at(20), last: at(10),- models: [{ model: k ? "m-two" : "m-one", input: 1000, output: 100, cache_read: 500, cache_write: 0, cost: 0.5, priced: true }],- input: 1000, output: 100, cache_read: 500, cache_write: 0, cost: 0.5, unpriced: 0,- resume: "x", path: `~/.${agent}/x/${k}.jsonl`, name, icon: "generic",-});--function serve(lang, names) {- const sessions = names.flatMap((name, i) => [0, 1].map((k) => sess(`ag${i}`, name, k)));- const agents = Object.fromEntries(names.map((name, i) => [`ag${i}`, name]));- const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };- return async (r) => {- const url = new URL(r.request().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:false};` });- 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/sessions") return json({ sessions, terminal: true, dirs: [] });- if (url.pathname === "/api/sessions/stats") {- const today = new Date().toISOString().slice(0, 10);- const usage = sessions.map((s) => ({ agent: s.agent, cwd: s.cwd, model: s.models[0].model, input: s.input, output: s.output, cache_read: s.cache_read, cache_write: 0, cost: s.cost, priced: true }));- return json({ from: today, to: today, days: [{ date: today, usage, active: [] }], agents });- }- if (url.pathname === "/api/sessions/overview") return json({ count: sessions.length, median: 5000, p90: 15000, days: [1], top: { tokens: [], cost: [], active: [] } });- if (url.pathname === "/api/sessions/manage") {- const ids = Object.keys(agents);- const want = url.searchParams.get("agent");- const agent = ids.includes(want) ? want : ids[0];- return json({- agents: ids.map((id) => ({ agent: id, count: 2, deletable: true, name: agents[id], icon: "generic" })),- agent, sessions: sessions.filter((s) => s.agent === agent), terminal: true, trash: [], trashDir: "~/magpie/trash/sessions",- });- }- if (url.pathname === "/api/groups") return json({ groups: [] });- if (url.pathname === "/api/usage/quotas") return json([]);- 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)];- const body = await fs.readFile(file).catch(() => null);- await (body ? r.fulfill({ body, contentType }) : r.fulfill({ status: 404, body: "" }));- };-}--// a box's own sideways overflow, and whether it scrolls sideways at all-const box = (page, sel) => page.locator(sel).evaluate((el) => ({- scroll: el.scrollWidth, client: el.clientWidth, overflow: getComputedStyle(el).overflowX,-}));-const inside = (page, sel, outer = "#view-usage") => page.locator(sel).evaluate((el, o) => {- const o1 = document.querySelector(o).getBoundingClientRect();- const r = el.getBoundingClientRect();- return r.left >= o1.left - 1 && r.right <= o1.right + 1;-}, outer);--for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {- for (const lang of ["en", "zh"]) {- test(`${engine}: ${lang}: Usage → Sessions' agent strip scrolls in itself, not the page`, async (t) => {- const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));- const page = await (await browser.newContext({ viewport: NARROW, reducedMotion: "reduce" })).newPage();- t.after(() => browser.close());- page.setDefaultTimeout(8000);- const errors = [];- page.on("pageerror", (e) => errors.push(e.message));- await page.route("**/*", serve(lang, NAMES));- await page.addInitScript(() => {- localStorage.setItem("magpie.usageTab", "sessions");- localStorage.setItem("magpie.sessRange", "all");- // the Usage page's own 5 s refresh would rebuild the strip between a- // measurement and the click it measures; one read is enough here- localStorage.setItem("magpie.usageEvery", "0");- });- await page.goto("http://magpie.test/?view=usage");- await page.waitForFunction(() => document.querySelectorAll("#sessAgent .opt").length === 12);-- // #929: eleven agents in range made the strip wider than the window, and- // the page scrolled sideways instead of the strip- const view = await box(page, "#view-usage");- assert.ok(view.scroll <= view.client + 1, `the Usage page scrolls sideways by ${view.scroll - view.client}px with ${NAMES.length} agents in range`);- const seg = await box(page, "#sessAgent");- assert.equal(seg.overflow, "auto", "the agent strip doesn't scroll sideways in itself");- assert.ok(seg.scroll > seg.client + 1, `the strip fits the window at ${seg.client}px, so nothing is being fixed`);-- // every option is reachable: the last one, then the first, by scrolling- // the strip — none of them is cut off past the strip's own edge- const opts = page.locator("#sessAgent .opt");- // a real click where a reader's would land: scroll the option into the- // strip, then press the middle of it rather than trust a stale handle- const press = async (which) => {- for (let tries = 3; tries; tries--) {- const p = await page.locator("#sessAgent").evaluate((strip, which) => {- const all = strip.querySelectorAll(".opt");- const el = which === "first" ? all[0] : all[all.length - 1];- el.scrollIntoView({ block: "nearest", inline: "nearest" });- const r = el.getBoundingClientRect();- const s = strip.getBoundingClientRect();- return { x: r.left + r.width / 2, y: r.top + r.height / 2, text: el.textContent, cut: r.left < s.left - 1 || r.right > s.right + 1 };- }, which);- assert.equal(p.cut, false, `the ${which} agent's filter sits outside the strip and is cut off`);- await page.mouse.click(p.x, p.y);- try {- await page.waitForFunction((text) => document.querySelector("#sessAgent .opt.on")?.textContent === text, p.text, { polling: 100, timeout: 2000 });- return p.text;- } catch (e) {- if (!tries) throw e; // WebKit drops the odd press; a reader would press again- }- }- };- const first = (await opts.first().innerText()).trim();- assert.equal(await press("last"), NAMES[NAMES.length - 1], "clicking the last agent's filter didn't choose it");- assert.equal(await press("first"), first, "clicking the first agent's filter didn't choose it again");-- // the picks beside the strip stay visible and inside the window- for (const id of ["#sessModel", "#sessFolder"]) {- assert(await page.locator(id).isVisible(), `${id} is not visible beside the strip`);- assert(await inside(page, id), `${id} sits outside the window`);- }- await page.locator("#sessModel").click();- await page.locator(".pop.proto-menu.sess-menu").waitFor();- await page.keyboard.press("Escape");- await page.locator("#sessFolder").click();- await page.locator(".pop.proto-menu.sess-menu").waitFor();- await page.keyboard.press("Escape");- // no click on the strip left an accent behind; the picks beside it keep- // their own box border on all four sides- const borders = await page.evaluate(() => [...document.querySelectorAll("#sessAgent .opt")]- .map((e) => getComputedStyle(e).borderLeftWidth).filter((w) => w && parseFloat(w) > 0));- assert.deepEqual(borders, [], "no left-border accent");-- // a window wider than the strip: nothing scrolls sideways, and the- // options keep their own widths instead of being stretched to fill it- await page.setViewportSize(WIDE);- await page.waitForTimeout(120);- const wideView = await box(page, "#view-usage");- assert.ok(wideView.scroll <= wideView.client + 1, `a window wider than the strip still scrolls the page sideways by ${wideView.scroll - wideView.client}px`);- const fit = await box(page, "#sessAgent");- assert.ok(fit.scroll <= fit.client + 1, `the strip scrolls sideways in a window that fits it (${fit.scroll} in ${fit.client})`);- const widths = await opts.evaluateAll((els) => els.map((el) => ({ w: el.getBoundingClientRect().width, need: el.scrollWidth })));- assert.ok(widths.every((o) => o.need <= o.w + 1), "an option was squeezed narrower than its own text");- assert.ok(new Set(widths.map((o) => Math.round(o.w))).size > 1, "every option is the same width: they were stretched, not laid out by their text");- assert.deepEqual(errors, []);-- // one agent: the strip stays hidden, as it was before (#929 changed- // nothing about when the filter shows)- await page.unroute("**/*");- await page.route("**/*", serve(lang, NAMES.slice(0, 1)));- await page.reload();- await page.waitForFunction(() => document.querySelectorAll("#sessAgent .opt").length > 0);- assert.equal(await page.locator("#sessAgent").isVisible(), false, "one agent in range should leave the agent filter hidden");- const one = await box(page, "#view-usage");- assert.ok(one.scroll <= one.client + 1, "one agent in range still scrolls the page sideways");-- // the other strips are untouched: the Usage page's own tab strip and- // range strip still don't scroll in themselves, and the regions strip- // and Connect's still do- await page.unroute("**/*");- await page.route("**/*", serve(lang, NAMES));- await page.goto("http://magpie.test/?view=usage");- await page.waitForFunction(() => document.querySelectorAll("#sessAgent .opt").length === 12);- assert.equal((await box(page, "#period")).overflow, "visible", "the Usage page's range strip started scrolling in itself");- assert.equal((await box(page, "#usageTab")).overflow, "visible", "the Usage page's tab strip started scrolling in itself");- const others = await page.evaluate(() => {- const out = {};- const probe = (classes, host) => {- const wrap = document.createElement("div");- if (host) wrap.className = host;- const el = document.createElement("div");- el.className = classes;- el.append(Object.assign(document.createElement("button"), { className: "opt", textContent: "x" }));- wrap.append(el);- document.body.append(wrap);- out[host ? `${classes} in ${host}` : classes] = { overflow: getComputedStyle(el).overflowX, flex: getComputedStyle(el.firstChild).flex };- wrap.remove();- };- probe("segs regions");- probe("segs", "connect");- return out;- });- assert.equal(others["segs regions"].overflow, "auto", "the regions strip stopped scrolling in itself");- assert.equal(others["segs regions"].flex, "0 0 auto", "the regions strip's options lost their own width");- assert.equal(others["segs in connect"].overflow, "auto", "Connect's API strip stopped scrolling in itself");- assert.equal(others["segs in connect"].flex, "0 0 auto", "Connect's API options lost their own width");- assert.deepEqual(errors, []);- });- }-}\ No newline at end of filediff --git a/internal/gui/tests/sessions-empty-range.test.cjs b/internal/gui/tests/sessions-empty-range.test.cjsindex 1dc5a5ae9..be2ea229e 100644--- a/internal/gui/tests/sessions-empty-range.test.cjs+++ b/internal/gui/tests/sessions-empty-range.test.cjs@@ -34,10 +34,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",});await page.addInitScript(() => { localStorage.setItem("magpie.usageTab", "sessions"); localStorage.setItem("magpie.sessRange", "today"); });await page.goto("http://magpie.test/?view=usage");- await page.locator('#sessAgent [data-agent="opencode"]').click();+ // the agent filter is a menu (as the model and folder ones)+ await page.locator("#sessAgent").click();+ await page.locator('.sess-menu .pm-item[title="opencode"]').click();await page.locator("#sessStats .sess-show-history").click();await page.getByText("Historical conversation", { exact: true }).waitFor();- assert.equal(await page.locator('#sessAgent [data-agent="opencode"]').getAttribute("aria-pressed"), "true");+ assert.equal(await page.locator("#sessAgent").innerText(), "OpenCode");+ assert.match(await page.locator("#sessAgent").getAttribute("class"), /\bset\b/);assert.equal(await page.locator("#sessRange .opt.on").innerText(), all);});}diff --git a/internal/gui/tests/sessions-overview-once.test.cjs b/internal/gui/tests/sessions-overview-once.test.cjsindex e7a66d3ef..f90283508 100644--- a/internal/gui/tests/sessions-overview-once.test.cjs+++ b/internal/gui/tests/sessions-overview-once.test.cjs@@ -61,7 +61,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",await page.clock.install();await page.addInitScript(() => { localStorage.setItem("magpie.usageTab", "sessions"); localStorage.setItem("magpie.sessRange", "today"); });await page.goto("http://magpie.test/?view=usage");- await page.locator('#sessAgent [data-agent="codex"]').click();+ await page.locator("#sessAgent").click();+ await page.locator('.sess-menu .pm-item[title="codex"]').click();for (let i = 0; i < 100 && !held.length; i++) await new Promise((r) => setTimeout(r, 20));assert.equal(held.length, 1, "the filter asked for its overview");const stats = seen.stats;diff --git a/internal/gui/tests/usage-sessions-agents-fit.test.cjs b/internal/gui/tests/usage-sessions-agents-fit.test.cjsindex c86e8e5a6..b460d8385 100644--- a/internal/gui/tests/usage-sessions-agents-fit.test.cjs+++ b/internal/gui/tests/usage-sessions-agents-fit.test.cjs@@ -1,8 +1,11 @@// Run with Node's test runner and Playwright on the module path; see README.md.// Usage › Sessions with more agents than fit on one line (#929, liuweifeng):-// the agent strip scrolls in itself, so the page never gets a sideways-// scrollbar, and the agent picked stays in view. English and Chinese,-// Chromium and WebKit.+// the agent filter is a menu beside the model and folder ones, not a strip+// of a segment per agent, which ran past the window and was scrolled+// sideways to reach the last (the owner, 10-28: "这应该是个 Combo Box").+// The page never scrolls sideways, every agent is in the menu, most used+// first, a few letters find one, and one agent in range leaves it hidden.+// English and Chinese, Chromium and WebKit.const assert = require("node:assert/strict");const fs = require("node:fs/promises");const path = require("node:path");@@ -16,11 +19,11 @@ const iso = (d) => [d.getFullYear(), d.getMonth() + 1, d.getDate()].map((n) => Sconst today = iso(new Date());const days = [{date: today,- usage: names.map((_, i) => ({ agent: "a" + i, cwd: "/work/app", model: "m" + (i % 3), input: 1000 * (i + 1), output: 100, cache_read: 0, cache_write: 0, cost: 0.1, priced: true })),+ usage: names.map((_, i) => ({ agent: "a" + i, cwd: "/work/app" + (i % 2), model: "m" + (i % 3), input: 1000 * (i + 1), output: 100, cache_read: 0, cache_write: 0, cost: 0.1, priced: true })),active: [],}];-function serve(lang) {+function serve(lang, n = names.length) {return async (route) => {const url = new URL(route.request().url());const json = (data) => route.fulfill({ json: data });@@ -29,7 +32,7 @@ function serve(lang) {if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });if (url.pathname === "/api/sessions/progress") return json({ indexing: false });if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] });- if (url.pathname === "/api/sessions/stats") return json({ from: today, to: today, days, agents });+ if (url.pathname === "/api/sessions/stats") return json({ from: today, to: today, days: days.map((d) => ({ ...d, usage: d.usage.slice(0, n) })), agents: Object.fromEntries(Object.entries(agents).slice(0, n)) });if (url.pathname === "/api/groups") return json({ groups: [] });if (url.pathname === "/api/usage/quotas") return json([]);if (url.pathname.startsWith("/api/")) return json({});@@ -41,8 +44,8 @@ function serve(lang) {}for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {- for (const lang of ["en", "zh"]) {- test(`${engine} ${lang}: many agents don't widen Usage › Sessions`, async (t) => {+ for (const [lang, everyAgent] of [["en", "All agents"], ["zh", "全部 Agent"]]) {+ test(`${engine} ${lang}: many agents are a menu that doesn't widen Usage › Sessions`, async (t) => {const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));t.after(() => browser.close());const page = await (await browser.newContext({ viewport: { width: 860, height: 700 }, reducedMotion: "reduce" })).newPage();@@ -50,47 +53,56 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",const errors = [];page.on("pageerror", (e) => errors.push(e.message));await page.route("**/*", serve(lang));- await page.addInitScript(() => { localStorage.setItem("magpie.usageTab", "sessions"); localStorage.setItem("magpie.sessRange", "all"); });+ await page.addInitScript(() => { localStorage.setItem("magpie.usageTab", "sessions"); localStorage.setItem("magpie.sessRange", "all"); localStorage.setItem("magpie.usageEvery", "0"); });await page.goto("http://magpie.test/?view=usage");- const strip = page.locator("#sessAgent");- await page.waitForFunction((n) => document.querySelectorAll("#sessAgent .opt").length === n, names.length + 1);+ const pick = page.locator("#sessAgent");+ await pick.waitFor({ state: "visible" });+ assert.equal(await pick.evaluate((e) => e.tagName + "." + e.className), "BUTTON.sess-pick", "the agent filter is the same menu button as the model and folder ones");+ assert.equal((await pick.innerText()).trim(), everyAgent);+ assert.equal(await pick.locator(".opt").count(), 0, "no segment per agent is left");const settle = () => page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));- const all = strip.locator('.opt[data-agent="all"]');- assert.equal(await all.getAttribute("aria-pressed"), "true", "All starts selected for assistive technology");- assert.equal(await strip.getByRole("button", { pressed: false }).count(), names.length);for (const width of [860, 560]) {await page.setViewportSize({ width, height: 700 });await settle();- const sideways = await page.evaluate(() => [document.documentElement, document.body, document.querySelector("main"), document.querySelector("#view-usage")]+ const sideways = await page.evaluate(() => [document.documentElement, document.body, document.querySelector("main"), document.querySelector("#view-usage"), document.querySelector(".sess-tools")].filter(Boolean).filter((e) => e.scrollWidth > e.clientWidth + 1).map((e) => `${e.tagName}#${e.id} ${e.scrollWidth}>${e.clientWidth}`));- assert.deepEqual(sideways, [], `${width}px: nothing scrolls sideways but the strip`);- const box = await strip.boundingBox();- assert(box.x >= 0 && box.x + box.width <= width, `${width}px: the agent strip fits the window: ${JSON.stringify(box)}`);- assert(await strip.evaluate((e) => e.scrollWidth > e.clientWidth), "the strip itself scrolls");+ assert.deepEqual(sideways, [], `${width}px: something scrolls sideways`);+ // the three filters sit on one line, inside the window+ const boxes = await Promise.all(["#sessAgent", "#sessModel", "#sessFolder"].map((id) => page.locator(id).boundingBox()));+ for (const b of boxes) assert(b && b.x >= 0 && b.x + b.width <= width, `${width}px: a filter sits outside the window: ${JSON.stringify(boxes)}`);+ assert(boxes.every((b) => Math.abs(b.y - boxes[0].y) < 1), `${width}px: the filters aren't on one line: ${JSON.stringify(boxes)}`);}- // the last agent, clicked where the strip was scrolled to, stays there:- // the strip drawn again kept its buttons and where it was scrolled- await strip.evaluate((e) => { e.scrollLeft = e.scrollWidth; });- const last = strip.locator(".opt").last();- // Playwright's WebKit stops hit-testing a scroller's children once it- // has been scrolled (a click lands on the strip, ~70% of runs; the- // system's WKWebView takes it, tried from a WKWebView in AppKit), so- // there the button is clicked as an element- if (engine === "webkit") await last.evaluate((b) => b.click());- else {- const lb = await last.boundingBox();- await page.mouse.click(lb.x + lb.width / 2, lb.y + lb.height / 2);- }- await page.waitForFunction(() => document.querySelector("#sessAgent .opt.on")?.textContent === "Zed");++ // every agent is in the menu, after "All agents", the most used first+ await pick.click();+ const menu = page.locator(".pop.proto-menu.sess-menu");+ await menu.waitFor();+ const items = menu.locator(".pm-item .pm-name");+ assert.deepEqual(await items.allInnerTexts(), [everyAgent, ...[...names].reverse()]);+ // a few letters find one, and picking it says so on the button+ await menu.locator(".sc-q").fill("zed");+ assert.deepEqual(await items.allInnerTexts(), ["Zed"]);+ await menu.locator(".pm-item").first().click();+ await menu.waitFor({ state: "detached" });+ await page.waitForFunction(() => document.querySelector("#sessAgent span")?.textContent === "Zed");+ assert.match(await pick.getAttribute("class"), /\bset\b/);+ // drawn again, the pick holds, and the menu shows it checkedawait settle();- assert.equal(await strip.getByRole("button", { pressed: true }).textContent(), "Zed", "the reused button exposes its new selection");- assert.equal(await all.getAttribute("aria-pressed"), "false", "the previous selection is cleared");- const on = await strip.locator(".opt.on").boundingBox();- const sb = await strip.boundingBox();- const seen = Math.min(on.x + on.width, sb.x + sb.width) - Math.max(on.x, sb.x);- assert(seen >= on.width * 0.75, `the picked agent stays in view after the strip is drawn again: ${JSON.stringify({ on, sb })}`);- assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth), true);+ assert.equal((await pick.innerText()).trim(), "Zed");+ await pick.click();+ await menu.waitFor();+ assert.equal(await menu.locator('.pm-item[aria-checked="true"] .pm-name').innerText(), "Zed");+ await menu.locator(".pm-item").first().click();+ await page.waitForFunction((all) => document.querySelector("#sessAgent span")?.textContent === all, everyAgent);+ assert.doesNotMatch(await pick.getAttribute("class"), /\bset\b/);assert.deepEqual(errors, []);++ // one agent: the filter stays hidden, as the strip was+ await page.unroute("**/*");+ await page.route("**/*", serve(lang, 1));+ await page.reload();+ await page.waitForFunction(() => !document.querySelector("#view-usage").classList.contains("loading") && document.querySelector("#sessStats").childElementCount > 0);+ assert.equal(await pick.isVisible(), false, "one agent in range should leave the agent filter hidden");});}}