From 923cc8747fd09dddd0e6f9e227cf62bdb522d1b5 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 15 Nov 2026 16:31:13 +0800 Subject: [PATCH] routing: filtering groups reuses indexed lookups and cards (liu-kan, #6744) Ported from liu-kan's routing_mod_filter branch at 5aca86598 (#6744). Typing in the Routing groups filter re-ran every member's lookups as a linear .find over all models, deciders, drawers and accounts, and redrew the whole page each keystroke. Now a lazy index (Maps built first-match like .find, splitMember and memberInfo cached, search text cached per group and locale) is rebuilt whenever `groups` is reassigned (it never is mutated in place) and dropped 5 minutes after both Routing pages are hidden. The filter's input redraws only the group list from cached cards, falling back to a full draw when groups or the locale changed. No look, matching or saved config change; no new strings; app.js untouched (client.js is outside the core budget). Measured (mote, Playwright, 4000 models, 20 groups x 20 members, 16 keystrokes, ms per keystroke incl. layout): chromium: before mean 4767.6 / median 5086.3, after 0.37 / 0.2 webkit: before mean 4813 / median 5075, after 0.88 / 1 Run: - go test -count=1 ./internal/gui/ on 2bc25a2d6 (mote): ok 137.9s. Main since (1f04ed219) touches no routing file. - New and touched GUI files (group-filter-render, group-index, group-search-cache, routing-group-plans) on 2bc25a2d6 on mote: 54 pass, 0 fail. - make test-ui (both engines) on mica before the rebase onto 2bc25a2d6 (main's two routing commits since touch the stage only): the run stopped after 453 of 1542 files, 5788 results. Its 34 red files were each run on origin/main and on this branch: the same tests fail on both (main 2bc25a2d6: 378 pass / 204 fail; branch identical but one context-cap Settings flake, #6514). Each has an issue: #6010, #5814, #5982, #6369, #6371, #6365, #5925, #4959, #6444, #6212, #6543, #6029, #6179, #6658, #3293, #6372, #5972, #6514, #5801, #4870, #6475, #6424, #6156, #6201, #6660, #5013, #6268, #6293, #5049 (group-editor-selected), #5594 (group-new-head), #3479, #6414, #4086. - The other 1089 files: a run on mica went bad under another session's suite (load 117) and was stopped; a whole suite at 2bc25a2d6 is queued on mote behind the suite lock, followed up after push. Not tried: the real app, a Linux WebKitGTK app, Windows. Co-authored-by: liu-kan --- docs/subsystems/gui-shell.md | 42 ++++ internal/gui/assets/plugins/routing/client.js | 223 ++++++++++++------ .../gui/tests/group-filter-render.test.cjs | 148 ++++++++++++ internal/gui/tests/group-index.test.cjs | 59 +++++ .../gui/tests/group-search-cache.test.cjs | 49 ++++ .../gui/tests/routing-group-plans.test.cjs | 33 ++- internal/gui/tests/routing-group-source.cjs | 31 +++ 7 files changed, 508 insertions(+), 77 deletions(-) create mode 100644 internal/gui/tests/group-filter-render.test.cjs create mode 100644 internal/gui/tests/group-index.test.cjs create mode 100644 internal/gui/tests/group-search-cache.test.cjs create mode 100644 internal/gui/tests/routing-group-source.cjs diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index a36544acd..c4c5974cf 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -185,6 +185,48 @@ filter only when that request is excluded. Usage's purpose picker remains a single choice sent to the ledger API. See `purpose-filter.test.cjs` and `routing-purpose-state.test.cjs`. +### Routing group lookup caches + +The routing script's `groupIndexOf` in +[`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js) +lazily indexes the current `/api/groups` response by model, group and account +ID and caches parsed member IDs. Exact model IDs take precedence over +reasoning suffixes; duplicate IDs retain the first match, as array lookup did. +A new response replaces the indexes on the next lookup. The maps reference +response objects, not copies. They serve both Routing and Routing groups, +and are released after both pages have been out of sight for five minutes +(including a hidden browser tab); returning cancels expiry. A later lookup +rebuilds them from current data. This changes no saved configuration or +routing behavior. `group-index.test.cjs` checks lookup work, member semantics, +data replacement and expiry with a controlled clock. + +`hayMatches` caches each group's lower-case search text in that same cache. +Queries retain AND and substring matching over group names, IDs, refs, +patterns and member labels (including accounts, reasoning and fast/free). +Changing the language discards the text cache; a new groups response also +invalidates it, including model/provider/account renames and membership +changes. Default routing settings and quota readings do not affect search +text. `group-search-cache.test.cjs` verifies reuse and invalidation. + +The group's input event and Escape use `drawGroups`' filter-only path: +matching cards are retained, unmatched cards detached and reused if the +query changes back. The toolbar, settings and provider pools are left in +place, and an open editor and import text keep their live DOM and draft. +Bulk selection still drops groups outside the query and rebuilds its +selection controls for the shown list. A data, language, settings or quota +redraw discards the row cache; filtering also falls back to a full redraw +when the data or language changed since the last one. A filter-only draw +does not mark new quota readings as painted: after the input loses focus, +the usual quota tick refreshes the cards. Detached cards are +released with the lookup cache after five minutes away. This is display +only; saving, ordering and routing semantics are unchanged. +The Hide plans button follows the filtered cards: it appears only when a +shown card has a quota line, and its folded choice survives filtering. +`group-filter-render.test.cjs` exercises node reuse, drafts and expiry with +4,000 models in both browser engines and all five languages; existing +`filter-ime`, `group-pick-filter`, `group-bulk-remove`, `group-arrange`, +`group-import-replace` and `group-morph` tests cover their neighboring flows. + ### Routing mode chip The stage's chip and the Accounts and keys heading in diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index fca9747e0..22e444697 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -6345,6 +6345,48 @@ function routingPage(part) { } const slug = (s) => String(s || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""); let groups = null, gEdit = null; // gEdit: { id: "" for a new one, draft } + // Built on first lookup, shared by the stage and the groups page. Maps + // point at the current response's objects; they never copy model data. + let groupIndex = null, groupIndexTimer = 0; + let groupRows = new Map(), groupRowsFor = null, groupRowsLocale = "", groupImportRow = null; + const GROUP_CACHE_KEEP = 5 * 60 * 1000; + const firstBy = (xs, key = (x) => x.id) => { + const map = new Map(); + for (const x of xs || []) { const k = key(x); if (!map.has(k)) map.set(k, x); } + return map; + }; + function dropGroupCaches() { + groupIndex = null; + tellsFor = tellsOf = null; + groupRows.clear(); + groupRowsFor = groupImportRow = null; + groupIndexTimer = 0; + } + function keepGroupCaches() { + if (shown() || gShown()) { + clearTimeout(groupIndexTimer); + groupIndexTimer = 0; + } else if ((groupIndex || groupRows.size) && !groupIndexTimer) groupIndexTimer = setTimeout(dropGroupCaches, GROUP_CACHE_KEEP); + } + function groupIndexOf() { + if (!groupIndex || groupIndex.source !== groups) { + const off = new Map(); + for (const g of groups?.groups || []) for (const i of g.memberInfo || []) { + if (i.providerOff && !off.has(i.id)) off.set(i.id, i); + } + groupIndex = { source: groups, models: firstBy(groups?.models), deciders: firstBy(groups?.deciders), + drawers: firstBy(groups?.drawers), groups: firstBy((groups?.groups || []).filter((g) => !g.hidden), (g) => "group/" + g.id), + accounts: new Map(Object.entries(groups?.accounts || {}).map(([pid, xs]) => [pid, firstBy(xs)])), + off, members: new Map(), info: new WeakMap(), search: new WeakMap(), searchLocale: locale }; + keepGroupCaches(); + } + return groupIndex; + } + function memberInfoOf(g, id) { + const ix = groupIndexOf(); + if (!ix.info.has(g)) ix.info.set(g, firstBy(g.memberInfo)); + return ix.info.get(g).get(id); + } // poolOf is the provider's own routing over several accounts or keys, // none while it has one on (or before the groups are in) function poolOf(id) { @@ -6437,14 +6479,19 @@ function routingPage(part) { // splitMember's third is that account's id, "" for every account function splitMember(id) { id = id || ""; - let acct = ""; + const ix = groupIndexOf(); + if (ix.members.has(id)) return ix.members.get(id); + const original = id; + let acct = "", level = ""; const a = id.startsWith("group/") ? null : /^(.+)#([^#/]+)$/.exec(id); if (a && a[2].trim()) { id = a[1]; acct = a[2].trim(); } - if (id.startsWith("group/") || groups?.models.some((m) => m.id === id) || groups?.drawers?.some((m) => m.id === id)) return [id, "", acct]; - const m = /^(.+):((?:none|minimal|low|medium|high|xhigh|max)(?:\+(?:none|minimal|low|medium|high|xhigh|max))*)$/i.exec(id); - if (!m) return [id, "", acct]; - const parts = m[2].toLowerCase().split("+"); - return [m[1], LEVELS.filter((v) => parts.includes(v)).join("+"), acct]; + if (!id.startsWith("group/") && !ix.models.has(id) && !ix.drawers.has(id)) { + const m = /^(.+):((?:none|minimal|low|medium|high|xhigh|max)(?:\+(?:none|minimal|low|medium|high|xhigh|max))*)$/i.exec(id); + if (m) { id = m[1]; const parts = m[2].toLowerCase().split("+"); level = LEVELS.filter((v) => parts.includes(v)).join("+"); } + } + const parts = [id, level, acct]; + ix.members.set(original, parts); + return parts; } // a member's id from its model, reasoning and account const memberId = (model, level, acct) => (level ? `${model}:${level}` : model) + (acct ? "#" + acct : ""); @@ -6455,17 +6502,22 @@ function routingPage(part) { if (!acct || subOf(id)) return null; const pid = modelOf(id)?.provider || model.split("/")[0]; const full = pid + "/" + acct; - const a = (groups?.accounts?.[pid] || []).find((x) => x.id === full); + const a = groupIndexOf().accounts.get(pid)?.get(full); return { id: full, name: a?.name || acct, plan: a?.plan || "" }; }; // a decision model (Jev) is a member of a group of decision models only, // asked at /v1/systemone (provider/decide_group.go): it is in // groups.deciders, not groups.models - const deciderOf = (id) => groups?.deciders?.find((m) => m.id === splitMember(id)[0]); + const deciderOf = (id) => groupIndexOf().deciders.get(splitMember(id)[0]); // an image model (jzw690 on X) is in groups.drawers: a group holding it // draws on it at the images API, and it takes no reasoning - const drawerOf = (id) => groups?.drawers?.find((m) => m.id === id); - const modelOf = (id) => groups?.models.find((m) => m.id === id) || groups?.models.find((m) => m.id === splitMember(id)[0]) || deciderOf(id) || drawerOf(id); + const drawerOf = (id) => groupIndexOf().drawers.get(id); + const modelOf = (id) => { + const ix = groupIndexOf(), exact = ix.models.get(id); + if (exact) return exact; + const base = splitMember(id)[0]; + return ix.models.get(base) || ix.deciders.get(base) || ix.drawers.get(id); + }; // a group's patterns (#766, provider.IsPattern): a glob, * any run of // characters over the provider/model id, or re: over the whole // id, both in any case (provider.compilePattern). The group keeps them, @@ -6509,7 +6561,7 @@ function routingPage(part) { const fixedOf = (id) => subOf(id) ? "" : splitMember(id)[1]; const fixedWords = (level) => t("{level} reasoning", { level: level.split("+").join(" / ") }); // a routing group among a group's members: group/ - const subOf = (id) => id?.startsWith("group/") ? groups?.groups.find((x) => "group/" + x.id === id && !x.hidden) : null; + const subOf = (id) => id?.startsWith("group/") ? groupIndexOf().groups.get(id) : null; // a group's editor, its draft being the group as it is now. The group's own // card opens it, and so does a group that is a member of another: such a // member takes no reasoning of its own (provider.SaveGroup refuses @@ -6533,7 +6585,7 @@ function routingPage(part) { // offOf: a member whose provider is switched off (groupsState's // providerOff), said by its provider's name and model rather than a bare // id: the group skips it until the provider is on again - const offOf = (id) => { for (const g of groups?.groups || []) { const i = g.memberInfo?.find((x) => x.id === id && x.providerOff); if (i) return i; } }; + const offOf = (id) => groupIndexOf().off.get(id); const offWords = (i) => t("{name} is switched off: the group skips it until it is on again", { name: i.name }); const memberIcon = (id) => { const s = subOf(id); return s ? stackIcon(groupIcons(s)) : icon(modelOf(id)?.icon || offOf(id)?.icon || "generic"); }; // models of one provider that would read alike (several "DeepSeek-V4.1-Flash" @@ -6554,9 +6606,9 @@ function routingPage(part) { // provider is Free for me, or its vendor serves it free (memberJSON.Free), // said whatever the group's routing, so it shows before Free first is // picked (jiabubu on Discord) - const freeIn = (g, id) => !!g?.memberInfo?.find((x) => x.id === id)?.free; + const freeIn = (g, id) => !!(g && memberInfoOf(g, id)?.free); function memberLabel(g, id) { - const i = g.memberInfo?.find((x) => x.id === id), m = modelOf(id), s = subOf(id), f = fixedOf(id); + const i = memberInfoOf(g, id), m = modelOf(id), s = subOf(id), f = fixedOf(id); if (s) return `${t("routing group")} · ${s.name}`; const acct = memberAccount(id); const at = (acct ? ` · ${acct.name}` : "") + (f ? ` · ${fixedWords(f)}` : "") + (fastIn(g, id) ? ` · ${t("fast")}` : "") + (freeIn(g, id) ? ` · ${t("free")}` : ""); @@ -6564,11 +6616,11 @@ function routingPage(part) { if (i?.providerOff) return `${i.name} · ${i.model}${at} (${t("switched off")})`; return i?.name ? `${i.name} · ${i.model}${at}` : id; } - function renderGroups() { + function renderGroups(filterOnly = false) { if (!groups) return; // not under a row being dragged: it is drawn when let go if (groupArranging) { groupRenderPending = true; return; } - steady(drawGroups, gView()); + steady(() => drawGroups(filterOnly), gView()); } // gSel: the groups picked to be removed together, while picking (lc on // Discord: they could only be removed one at a time); null otherwise @@ -6580,8 +6632,8 @@ function routingPage(part) { gQ.type = "search"; gQ.spellcheck = false; gQ.autocomplete = "off"; - gQ.oninput = () => renderGroups(); - gQ.onkeydown = (e) => { if (e.key === "Escape" && gQ.value) { e.stopPropagation(); gQ.value = ""; renderGroups(); } }; + gQ.oninput = () => renderGroups(true); + gQ.onkeydown = (e) => { if (e.key === "Escape" && gQ.value) { e.stopPropagation(); gQ.value = ""; renderGroups(true); } }; // gImport: Import a group's box (laincatx on X): the text pasted, kept // in the page across redraws as gQ is, and what the import added and // left out once it has; null while closed @@ -6596,7 +6648,13 @@ function routingPage(part) { try { return hayMatches(g, words); } catch { return true; } // a group that can't be read is shown, flagged } function hayMatches(g, words) { - const hay = [g.name, g.id, "group/" + g.id, g.ref || "", ...g.members.flatMap((id) => [id, memberLabel(g, id)]), ...(g.patterns || []).map((p) => p.pattern)].join("\n").toLowerCase(); + const ix = groupIndexOf(); + if (ix.searchLocale !== locale) { ix.searchLocale = locale; ix.search = new WeakMap(); } + let hay = ix.search.get(g); + if (hay === undefined) { + hay = [g.name, g.id, "group/" + g.id, g.ref || "", ...g.members.flatMap((id) => [id, memberLabel(g, id)]), ...(g.patterns || []).map((p) => p.pattern)].join("\n").toLowerCase(); + ix.search.set(g, hay); + } return words.every((w) => hay.includes(w)); } // rowOrFlag: a group's row, or when drawing it fails, a row that says so @@ -6664,8 +6722,17 @@ function routingPage(part) { }; return b; } - function drawGroups() { - groupsQuotas = typeof quotas === "undefined" ? undefined : quotas; + function drawGroups(filterOnly = false) { + // Only input uses this path. Data, language, settings and quota redraws + // replace the row cache, so its event handlers always use current data. + filterOnly = filterOnly && groupRowsFor === groups && groupRowsLocale === locale; + if (!filterOnly) { + groupRows = new Map(); + groupRowsFor = groups; + groupRowsLocale = locale; + groupImportRow = null; + } + if (!filterOnly) groupsQuotas = typeof quotas === "undefined" ? undefined : quotas; // the ones switched off are listed after the ones on, each part in the // order the user set (justacati on X); moving one still moves it in // that order, which is the one agents' pickers show @@ -6676,63 +6743,67 @@ function routingPage(part) { const shown = words.length ? all.filter((g) => gEdit?.id === g.id || groupMatches(g, words)) : all; if (gSel) gSel = new Set([...gSel].filter((id) => shown.some((g) => g.id === id))); if (gSel && !all.length) gSel = null; - // the page's toolbar (11-06): the filter and how many there are on the - // left, what makes or picks groups on the right, New group the one - // filled button - const newBtn = el("button", "text primary rt-gnew"); - newBtn.type = "button"; - newBtn.dataset.feature = "groups"; // off with them, as the note says - newBtn.append(svg(PLUS, 11, 1.8), el("span", "", t("New group"))); - newBtn.title = t("Make a routing group of any models you like — agents pick it as one model"); - newBtn.onclick = () => newGroup(); - gBack.lastChild.textContent = t("Routing"); // in the language now - const head = [gBack]; - if (all.length > 1 || gQ.value) { - gQ.placeholder = t("Filter groups and models"); - gQ.setAttribute("aria-label", gQ.placeholder); - head.push(gQ); - } - if (all.length) head.push(el("span", "note rt-gcount", t("{n} groups · {m} on", { n: all.length, m: all.filter((g) => !g.disabled).length }))); - head.push(el("span", "grow")); - // templates: a group for a common need made of the user's own models - // in a click (provider.Templates). Cards while the user has no group of - // their own, a menu by New group after const own = all.some((g) => !g.auto), tpls = groups.templates || []; - // shown when a group has a line to fold, after the rows are drawn - const plans = gSel ? null : plansButton(); - if (plans) head.push(plans); - if (!gSel) { - if (own && tpls.length) head.push(templateButton(tpls)); - const imp = el("button", "text rt-gimportbtn", t("Import")); - imp.type = "button"; - imp.title = t("Add a routing group someone shared from their magpie"); - imp.setAttribute("aria-expanded", gImport ? "true" : "false"); - imp.onclick = () => gImport ? closeImport() : openImport(); - head.push(imp); - // several removed at once: pick them, then Remove - if (all.length > 1) { - const pick = el("button", "text rt-gselect", t("Select")); - pick.title = t("Pick several groups to remove together"); - pick.onclick = async () => { - if (groupDirty() && !(await confirmDiscard())) return; - gEdit = null; gSel = new Set(); renderGroups(); - }; - head.push(pick); + if (!filterOnly) { + // the page's toolbar (11-06): the filter and how many there are on the + // left, what makes or picks groups on the right, New group the one + // filled button + const newBtn = el("button", "text primary rt-gnew"); + newBtn.type = "button"; + newBtn.dataset.feature = "groups"; // off with them, as the note says + newBtn.append(svg(PLUS, 11, 1.8), el("span", "", t("New group"))); + newBtn.title = t("Make a routing group of any models you like — agents pick it as one model"); + newBtn.onclick = () => newGroup(); + gBack.lastChild.textContent = t("Routing"); // in the language now + const head = [gBack]; + if (all.length > 1 || gQ.value) { + gQ.placeholder = t("Filter groups and models"); + gQ.setAttribute("aria-label", gQ.placeholder); + head.push(gQ); } - head.push(newBtn); + if (all.length) head.push(el("span", "note rt-gcount", t("{n} groups · {m} on", { n: all.length, m: all.filter((g) => !g.disabled).length }))); + head.push(el("span", "grow")); + if (!gSel) head.push(plansButton()); + // templates: a group for a common need made of the user's own models + // in a click (provider.Templates). Cards while the user has no group of + // their own, a menu by New group after + if (!gSel) { + if (own && tpls.length) head.push(templateButton(tpls)); + const imp = el("button", "text rt-gimportbtn", t("Import")); + imp.type = "button"; + imp.title = t("Add a routing group someone shared from their magpie"); + imp.setAttribute("aria-expanded", gImport ? "true" : "false"); + imp.onclick = () => gImport ? closeImport() : openImport(); + head.push(imp); + // several removed at once: pick them, then Remove + if (all.length > 1) { + const pick = el("button", "text rt-gselect", t("Select")); + pick.title = t("Pick several groups to remove together"); + pick.onclick = async () => { + if (groupDirty() && !(await confirmDiscard())) return; + gEdit = null; gSel = new Set(); renderGroups(); + }; + head.push(pick); + } + head.push(newBtn); + } + // the filter stays in the page as the rest of the row is drawn again, + // so the key being typed into it lands once (#1055) + replaceKeeping(gHead, head); + drawFound(); + drawNames(); + drawDefaults(); } - // the filter stays in the page as the rest of the row is drawn again, - // so the key being typed into it lands once (#1055) - replaceKeeping(gHead, head); - drawFound(); - drawNames(); - drawDefaults(); const rows = []; if (!gSel && !own && !words.length && tpls.length) rows.push(templateCards(tpls)); if (gSel) rows.push(selectBar(shown)); - if (gImport && !gSel) rows.push(importBox()); - if (gEdit && !gEdit.id) rows.push(groupEditor(null)); - for (const g of shown) rows.push(rowOrFlag(g, () => gSel ? pickedRow(g) : gEdit?.id === g.id ? groupEditor(g) : groupRow(g))); + if (gImport && !gSel) { groupImportRow ||= importBox(); rows.push(groupImportRow); } + const rowFor = (id, draw) => { + if (!groupRows.has(id)) groupRows.set(id, draw()); + return groupRows.get(id); + }; + if (gEdit && !gEdit.id) rows.push(rowFor("", () => groupEditor(null))); + for (const g of shown) rows.push(rowFor(g.id, () => rowOrFlag(g, () => gSel ? pickedRow(g) : gEdit?.id === g.id ? groupEditor(g) : groupRow(g)))); if (!rows.length && all.length) rows.push(el("div", "none rt-gnone", t("No group or model matches “{q}”", { q: gQ.value.trim() }))); if (!rows.length) rows.push(el("div", "none rt-gnone", groups.found === false ? t("No group yet. New group makes one of any models you like.") @@ -6759,12 +6830,12 @@ function routingPage(part) { rows.push(h); } // the import box's text stays in the page as the list is drawn again + const plans = gHead.querySelector(".rt-gplans"); if (plans) plans.hidden = !rows.some((r) => r.querySelector?.(".rt-gquota")); gList.classList.toggle("rt-noplans", gPlansHid); - const was = slotsOf(); + const was = filterOnly ? null : slotsOf(); replaceKeeping(gList, rows); - morphSlots(was); - renderPools(); + if (!filterOnly) { morphSlots(was); renderPools(); } } // A group's row opens into its editor and folds back into it, as a cell // does on iOS (the owner, 10-23): its slot goes from the height it had to @@ -9204,6 +9275,8 @@ function routingPage(part) { // on either page: Routing names the groups too (its stage, the story) for (const v of [$("#view-routing"), gView()]) new MutationObserver(() => { if (!v.hidden) loadGroups(true); }).observe(v, { attributes: true, attributeFilter: ["hidden"] }); window.addEventListener("focus", () => { if (shown() || gShown()) loadGroups(true); }); + for (const v of [$("#view-routing"), gView()]) new MutationObserver(keepGroupCaches).observe(v, { attributes: true, attributeFilter: ["hidden"] }); + document.addEventListener("visibilitychange", keepGroupCaches); // the groups' rows say what is left of their accounts, drawn again when // the Usage page's readings come while the page is open (Routing's own // second does it there); the page may be open already, from ?view=groups diff --git a/internal/gui/tests/group-filter-render.test.cjs b/internal/gui/tests/group-filter-render.test.cjs new file mode 100644 index 000000000..d9cebc073 --- /dev/null +++ b/internal/gui/tests/group-filter-render.test.cjs @@ -0,0 +1,148 @@ +// Filtering reuses cards and leaves controls/editors in place. Real assets, +// fixture APIs only; no running magpie or agent configuration is touched. +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 = process.env.MAGPIE_GROUP_ASSETS || path.resolve(__dirname, "../assets"); +function fixture() { + const models = Array.from({ length: 4000 }, (_, i) => ({ id: `p${i % 10}/model-${i}`, name: "Model " + i, + provider: "p" + i % 10, providerName: "Provider " + i % 10, icon: "generic" })); + return { models, pools: [{ provider: "p9", name: "Pool", kind: "account", who: ["A", "B"] }], + groups: Array.from({ length: 10 }, (_, i) => { + const id = models[3990 + i].id + ":high#acct"; + return { id: "g" + i, name: "Group " + i, members: [id], ready: true, routing: "order", + memberInfo: [{ id, provider: models[3990 + i].provider, name: "Provider", model: models[3990 + i].name, ready: true }] }; + }), accounts: Object.fromEntries(Array.from({ length: 10 }, (_, i) => ["p" + i, [{ id: `p${i}/acct`, name: "Account A" }]])) }; +} +async function serve(route, lang, feed) { + const url = new URL(route.request().url()), json = (x) => route.fulfill({ json: x }); + 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: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/groups") return json(feed.data); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.has("wait")) return new Promise(() => {}); + return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: {}, routes: [] }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], 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)]; + try { + let body = await fs.readFile(file); + if (feed.inspect && url.pathname === "/plugins/routing/client.js") { + body = body.toString().replace(" // ---------- where the reader is, as requests come ----------", + ' window.__routingGroupCache = () => ({ cached: !!groupIndex, rows: groupRows.size, timer: !!groupIndexTimer });\n // ---------- where the reader is, as requests come ----------'); + } + await route.fulfill({ body, contentType }); + } catch { await route.fulfill({ status: 404, body: "" }); } +} +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, 440]) { + test(`${engine} ${lang} ${width}px: group filtering reuses cards, controls and an editor`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await browser.newPage({ viewport: { width, height: 900 }, reducedMotion: "reduce" }); + page.setDefaultTimeout(10000); + page.setDefaultNavigationTimeout(60000); + const feed = { data: fixture() }, errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + page.on("console", (m) => { if (m.type() === "error") console.error(m.text()); }); + await page.route("**/*", (r) => serve(r, lang, feed)); + await page.goto("http://magpie.test/?view=groups"); + await page.locator('.rt-group[data-id="g9"]').waitFor().catch(async (e) => { console.error(errors, await page.locator("body").innerText()); throw e; }); + const q = page.locator("input.rt-gfilter"), rows = page.locator(".rt-groups .rt-group"); + await page.evaluate(() => { + window.keptCard = document.querySelector('.rt-group[data-id="g9"]'); + window.keptPool = document.querySelector(".rt-pool"); + window.keptFound = document.querySelector('.rt-gfound button[role="switch"]'); + window.keptInput = document.querySelector("input.rt-gfilter"); + }); + await q.fill("3999"); + assert.deepEqual(await rows.evaluateAll((rs) => rs.map((r) => r.dataset.id)), ["g9"]); + assert.equal(await page.evaluate(() => window.keptCard === document.querySelector('.rt-group[data-id="g9"]')), true, "filtering rebuilt a matching card"); + assert.equal(await page.evaluate(() => window.keptPool === document.querySelector(".rt-pool")), true, "filtering rebuilt an unrelated pool"); + assert.equal(await page.evaluate(() => window.keptFound === document.querySelector('.rt-gfound button[role="switch"]')), true, "filtering rebuilt settings"); + await q.fill("absent-query"); + assert.equal(await rows.count(), 0); + await q.fill(""); + assert.equal(await rows.count(), 10); + assert.equal(await page.evaluate(() => window.keptCard === document.querySelector('.rt-group[data-id="g9"]')), true, "clearing the query rebuilt a card"); + assert.equal(await page.evaluate(() => document.activeElement === window.keptInput && window.keptInput.isConnected), true); + // An open editor stays in place, including its draft and live fields. + await q.fill("3999"); + await page.locator('.rt-group[data-id="g9"] > button.text').click(); + const editor = page.locator(".rt-gedit"); + await editor.waitFor(); + const name = editor.locator("input").first(); + await name.fill("Unsaved name"); + await editor.evaluate((e) => { window.keptEditor = e; }); + await q.fill("no-match"); + assert.equal(await page.evaluate(() => window.keptEditor === document.querySelector(".rt-gedit")), true, "filtering recreated the editor"); + assert.equal(await name.inputValue(), "Unsaved name"); + assert.equal(await rows.count(), 0); + assert.deepEqual(errors, []); + }); + } + } +} + +for (const engine of process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"]) { + test(`${engine}: group caches expire five minutes after leaving and refresh on return`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await browser.newPage({ reducedMotion: "reduce" }); + page.setDefaultTimeout(10000); + page.setDefaultNavigationTimeout(60000); + await page.clock.install(); + await page.clock.pauseAt(new Date(Date.now() + 1000)); + const feed = { data: fixture(), inspect: true }; + await page.route("**/*", (r) => serve(r, "en", feed)); + await page.goto("http://magpie.test/?view=groups"); + await page.locator('.rt-group[data-id="g9"]').waitFor(); + assert.equal(await page.evaluate(() => window.__routingGroupCache().cached), true); + await page.evaluate(() => window.show("agents")); + await page.waitForFunction(() => window.__routingGroupCache().timer); + await page.clock.fastForward(299999); + assert.equal(await page.evaluate(() => window.__routingGroupCache().cached), true); + await page.clock.fastForward(1); + assert.deepEqual(await page.evaluate(() => window.__routingGroupCache()), { cached: false, rows: 0, timer: false }); + feed.data.models[3999].name = "Renamed model"; + feed.data.accounts.p9[0].name = "Account B"; + await page.evaluate(() => window.show("groups")); + await page.waitForFunction(() => document.querySelector('.rt-group[data-id="g9"]')?.textContent.includes("Renamed model")); + const q = page.locator("input.rt-gfilter"); + await q.fill("renamed account b"); + assert.deepEqual(await page.locator(".rt-groups .rt-group").evaluateAll((rs) => rs.map((r) => r.dataset.id)), ["g9"]); + }); +} + +for (const engine of process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"]) { + test(`${engine}: quota readings arriving during filtering are drawn after blur`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await browser.newPage({ reducedMotion: "reduce" }); + page.setDefaultTimeout(10000); + page.setDefaultNavigationTimeout(60000); + const feed = { data: fixture() }; + await page.route("**/*", (r) => serve(r, "en", feed)); + await page.goto("http://magpie.test/?view=groups"); + await page.locator('.rt-group[data-id="g9"]').waitFor(); + const q = page.locator("input.rt-gfilter"); + await q.focus(); + await page.evaluate(() => { + quotas = ["A", "B"].map((user) => ({ provider: "p9", name: "Provider 9", kind: "subscription", user, + windows: [{ name: "Credits", amount: 100, limit: 500, unit: "credits", used: 20 }] })); + }); + await q.fill("3999"); + assert.equal(await page.locator('.rt-group[data-id="g9"] .rt-gquota').count(), 0, "filtering should reuse the card while typing"); + await q.evaluate((input) => input.blur()); + const line = page.locator('.rt-group[data-id="g9"] .rt-gquota'); + await line.waitFor(); + assert.match(await line.innerText(), /200/); + }); +} diff --git a/internal/gui/tests/group-index.test.cjs b/internal/gui/tests/group-index.test.cjs new file mode 100644 index 000000000..9f2436bf6 --- /dev/null +++ b/internal/gui/tests/group-index.test.cjs @@ -0,0 +1,59 @@ +const assert = require("node:assert/strict"); +const { test } = require("node:test"); +const { load } = require("./routing-group-source.cjs"); +const model = (id, name = id) => ({ id, name, provider: "p", providerName: "Provider" }); +const data = () => ({ models: [model("p/base"), model("p/literal:high"), model("p/base", "duplicate")], + drawers: [model("p/image:high")], deciders: [model("p/judge")], groups: [ + { id: "nested", name: "Nested", members: [] }, { id: "hidden", hidden: true, members: [] }, + { id: "off", members: [], memberInfo: [{ id: "gone/model", providerOff: true, name: "Gone", model: "Model" }] }, + ], accounts: { p: [{ id: "p/acct", name: "Account A" }] } }); + +test("routing members use bounded model reads, including effort, account and missing IDs", () => { + const models = Array.from({ length: 1000 }, (_, i) => model("p/model-" + i)); + let reads = 0; + for (const m of models) { const id = m.id; Object.defineProperty(m, "id", { get: () => { reads++; return id; } }); } + const api = load({ models, groups: [], drawers: [], deciders: [] }); + for (let i = 0; i < 10; i++) { + assert.equal(api.modelOf("p/model-999:high#acct"), models[999]); + assert.equal(api.modelOf("p/missing:high"), undefined); + } + assert.ok(reads < 10000, `member lookups rescanned the model catalog: ${reads} ID reads`); +}); + +test("indexed members preserve literal IDs, effort order, account names and first match", () => { + const state = data(), api = load(state); + assert.deepEqual(Array.from(api.splitMember("p/base:HIGH+low# acct ")), ["p/base", "low+high", "acct"]); + assert.deepEqual(Array.from(api.splitMember("p/literal:high#acct")), ["p/literal:high", "", "acct"]); + assert.deepEqual(Array.from(api.splitMember("p/image:high")), ["p/image:high", "", ""]); + assert.equal(api.modelOf("p/base"), state.models[0], "a duplicate must keep find's first match"); + assert.equal(api.modelOf("p/judge:high"), state.deciders[0]); + assert.equal(api.modelOf("p/image:high"), state.drawers[0]); + assert.equal(api.memberAccount("p/base:high#acct").name, "Account A"); + assert.equal(api.subOf("group/nested").name, "Nested"); + assert.equal(api.subOf("group/hidden"), undefined); + assert.equal(api.offOf("gone/model").name, "Gone"); + const next = data(); next.models[0].name = "Renamed"; next.accounts.p[0].name = "Account B"; + api.refresh(next); + assert.equal(api.modelOf("p/base").name, "Renamed"); + assert.equal(api.memberAccount("p/base#acct").name, "Account B"); +}); + +test("routing indexes are lazy, expire after five minutes away and rebuild from current data", () => { + const state = data(), api = load(state); + assert.equal(api.cache(), null); + api.modelOf("p/base:high"); + assert.ok(api.cache(), "a lookup must build the index"); + const first = api.cache(); + api.visible(false); + assert.equal(api.delay(), 300000); + assert.equal(api.pending(), true); + api.visible(true); + assert.equal(api.pending(), false, "returning cancels expiry"); + assert.equal(api.cache(), first); + api.visible(false); api.expire(); + assert.equal(api.cache(), null, "expiry must release the index"); + state.models[0].name = "After expiry"; + api.visible(true); + assert.equal(api.modelOf("p/base").name, "After expiry"); + assert.notEqual(api.cache(), first); +}); diff --git a/internal/gui/tests/group-search-cache.test.cjs b/internal/gui/tests/group-search-cache.test.cjs new file mode 100644 index 000000000..e7574d408 --- /dev/null +++ b/internal/gui/tests/group-search-cache.test.cjs @@ -0,0 +1,49 @@ +const assert = require("node:assert/strict"); +const { test } = require("node:test"); +const { load } = require("./routing-group-source.cjs"); +function data() { + const id = "p/base:high#acct"; + return { models: [{ id: "p/base", name: "Astra", provider: "p", providerName: "Provider" }], + groups: [{ id: "g", name: "Main", ref: "auto/main", members: [id, "group/nested", "off/base"], + patterns: [{ pattern: "p/glob-*" }], fast: [id], memberInfo: [ + { id, free: true }, { id: "off/base", providerOff: true, name: "Disabled", model: "Lost" }, + ] }, { id: "nested", name: "Nested", members: [] }], + accounts: { p: [{ id: "p/acct", name: "Account A" }] }, drawers: [], deciders: [] }; +} + +test("successive queries reuse group search text instead of rebuilding member labels", () => { + const state = data(), g = state.groups[0], api = load(state); + let reads = 0; + const name = state.models[0].name; + Object.defineProperty(state.models[0], "name", { get: () => { reads++; return name; } }); + assert.equal(api.groupMatches(g, ["astra"]), true); + const firstReads = reads; + for (const query of ["a", "as", "ast", "astra", "missing", "provider"]) api.groupMatches(g, [query]); + assert.equal(reads, firstReads, "typing another query rebuilt the group's model labels"); +}); + +test("cached search preserves AND, substrings, refs, patterns, accounts and member labels", () => { + const state = data(), api = load(state), g = state.groups[0]; + for (const words of [["main", "astra"], ["roup/g"], ["auto/main"], ["p/glob-*"], ["account a"], + ["high reasoning", "fast", "free"], ["routing group", "nested"], ["disabled", "lost", "switched off"]]) { + assert.equal(api.groupMatches(g, words), true, words.join(" + ")); + } + assert.equal(api.groupMatches(g, ["astra", "missing"]), false); +}); + +test("search text follows data replacement, language changes and five-minute eviction", () => { + const state = data(), api = load(state), g = state.groups[0]; + assert.equal(api.groupMatches(g, ["routing group"]), true); + api.lang("zh"); + assert.equal(api.groupMatches(g, ["路由组"]), true); + assert.equal(api.groupMatches(g, ["routing group"]), false); + const next = data(); + next.models[0].name = "Sol"; next.accounts.p[0].name = "Account B"; + next.groups[1].name = "Renamed"; next.groups[0].memberInfo[0].free = false; next.groups[0].fast = []; + api.refresh(next); + const ng = next.groups[0]; + assert.equal(api.groupMatches(ng, ["sol", "account b", "renamed"]), true); + for (const word of ["astra", "account a", "fast", "free"]) assert.equal(api.groupMatches(ng, [word]), false, word); + api.visible(false); api.expire(); api.visible(true); + assert.equal(api.groupMatches(ng, ["sol", "account b"]), true); +}); diff --git a/internal/gui/tests/routing-group-plans.test.cjs b/internal/gui/tests/routing-group-plans.test.cjs index db6fe3439..d1a0352b3 100644 --- a/internal/gui/tests/routing-group-plans.test.cjs +++ b/internal/gui/tests/routing-group-plans.test.cjs @@ -40,7 +40,7 @@ const words = { de: { hide: "Tarife ausblenden", show: "Tarife zeigen" }, }; -function serve(lang, web, withQuotas) { +function serve(lang, web, withQuotas, extraGroups = []) { const state = { agents: [{ id: "claude", name: "Claude Code", path: "/test/claude", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; return async (r) => { const url = new URL(r.request().url()); @@ -54,7 +54,7 @@ function serve(lang, web, withQuotas) { 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({ models, pools: [], deciders: [], found: true, groups, templates }); + if (url.pathname === "/api/groups") return json({ models, pools: [], deciders: [], found: true, groups: [...groups, ...extraGroups], templates }); if (url.pathname === "/api/usage/quotas") return json(withQuotas ? quotas : []); if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); if (url.pathname.startsWith("/api/")) return json({}); @@ -64,6 +64,35 @@ function serve(lang, web, withQuotas) { }; } +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: filtering updates the plans button while preserving cached cards and the folded choice`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await browser.newPage({ viewport: { width: 1280, height: 700 }, reducedMotion: "reduce" }); + page.setDefaultTimeout(10000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const extra = [{ id: "plain", name: "Plain group", members: ["c/x"], ready: true, memberInfo: info(["c/x"]) }]; + await page.route("**/*", serve("en", false, true, extra)); + await page.goto("http://magpie.test/?view=groups"); + const card = page.locator('.rt-group[data-id="mine"]'), btn = page.locator(".rt-gplans"), q = page.locator("input.rt-gfilter"); + await card.locator(".rt-gquota").first().waitFor({ timeout: boot }); + await card.evaluate((e) => { window.keptPlanCard = e; }); + await btn.click(); + assert.equal(await card.locator(".rt-gquota").first().isVisible(), false); + await q.fill("Plain group"); + assert.equal(await btn.isVisible(), false); + await q.fill("Mine"); + assert.equal(await btn.isVisible(), true); + assert.equal((await btn.textContent()).trim(), "Show plans"); + assert.equal(await card.evaluate((e) => e === window.keptPlanCard), true); + assert.equal(await card.locator(".rt-gquota").first().isVisible(), false); + await btn.click(); + assert.equal(await card.locator(".rt-gquota").first().isVisible(), true); + assert.deepEqual(errors, []); + }); +} + // the page's boot under the whole suite's load (#3478) const boot = 15000; diff --git a/internal/gui/tests/routing-group-source.cjs b/internal/gui/tests/routing-group-source.cjs new file mode 100644 index 000000000..a485cba8f --- /dev/null +++ b/internal/gui/tests/routing-group-source.cjs @@ -0,0 +1,31 @@ +// The real routing lookup/search functions, without a DOM or a live API. +// Counting model reads tests algorithmic work without a wall-clock limit. +const fs = require("node:fs"); +const path = require("node:path"); +const vm = require("node:vm"); +const assets = process.env.MAGPIE_GROUP_ASSETS || path.resolve(__dirname, "../assets"); +const source = fs.readFileSync(path.join(assets, "plugins/routing/client.js"), "utf8"); +const app = fs.readFileSync(path.join(assets, "app.js"), "utf8"); +const section = (s, a, b) => { const start = s.indexOf(a); return start < 0 ? "" : s.slice(start, s.indexOf(b, start)); }; +function load(data) { + let visible = true, timer = null, timerDelay = 0; + const context = vm.createContext({ + groups: data, locale: "en", shown: () => visible, gShown: () => false, + setTimeout: (fn, ms) => { timer = fn; timerDelay = ms; return 1; }, clearTimeout: () => { timer = null; }, + t: (s, vars) => Object.entries(vars || {}).reduce((s, [k, v]) => s.replaceAll("{" + k + "}", v), context.locale === "zh" && s === "routing group" ? "路由组" : s), + }); + vm.runInContext([ + section(app, "function modelTells(", "// tellTag:"), + section(source, " // Built on first lookup,", " // poolOf is"), + section(source, " const LEVELS =", " // a group's editor,"), + section(source, " const offOf =", " function renderGroups("), + section(source, " function groupMatches(", " // rowOrFlag:"), + `globalThis.api = { splitMember, modelOf, memberAccount, memberLabel, subOf, offOf, freeIn, groupMatches, + refresh: (x) => { groups = x; }, lang: (x) => { locale = x; }, + cache: () => typeof groupIndex === "undefined" ? null : groupIndex, + keep: () => { if (typeof keepGroupCaches === "function") keepGroupCaches(); } };`, + ].join("\n"), context); + return { ...context.api, visible: (on) => { visible = on; context.api.keep(); }, + expire: () => { const fn = timer; timer = null; fn?.(); }, delay: () => timerDelay, pending: () => !!timer }; +} +module.exports = { load };