routing: a rule's agent picker lists agents heard from and takes a typed User-Agent name (raikyou on Discord)

A rule can match a client magpie doesn't know, such as SillyTavern or
someone's own app with its own User-Agent. The gateway already names such a
client by its User-Agent's product name (usage.AgentOf), and a rule compares
agents in lower case (cleanRules, MatchesBesidesIntent, Pauses). Until now
the editor's agent picker listed only the agents magpie knows.

The picker now lists the agents magpie knows, then the agents
/api/usage?period=30d heard from that it doesn't know, leaving out "other"
and magpie. The note on those reads "heard from in the last 30 days". The
usage call is made once per editor and reads the cached SummarizeTop. A name
typed in the filter is read the way the gateway reads a User-Agent: the text
before the first "/", space or comma, in lower case. "MyApp/2.0 (Linux)" is
myapp. A typed name that is already an agent's id is that agent. The
picked name shows in the chip as the others do and is saved in agents:[…].
app.js's openPicker gains field.placeholder and field.typed for this; other
pickers are unchanged.

zh label: 筛选,或输入 Agent 名称… (notes: User-Agent 开头的名称, 近 30 天有请求).
Strings are added in en, zh, zh-TW, ja and de.

No backend change. The TUI takes rules as text (agents=…), so it already
accepts any name. A typed alias of a known agent (claude-cli) isn't mapped
to its id in the picker. Only an exact id is.

Run at 224ea7d5b plus this change, in a worktree with a sandbox HOME:
- routing-rule-agent-typed.test.cjs (new): 20/20, chromium and webkit, 5
  languages, at 1100px and at 390px. With app.js and client.js reverted it
  is red: the placeholder reads 'Filter agent…', and the phone test never
  sees the typed row.
- whole GUI suite (concurrency 4, load 160-380 from other sessions): 11170
  tests, 11062 pass, 108 fail across 27 files. Rerun alone at concurrency 2
  on this tree and on base 224ea7d5b, the same files are red on both (87
  here, 93 on base). The only extra red here is gateway-key-groups, once, a
  load flake (#1974, commented; it passes alone 3/3). Also red on base:
  codex-predictions (#2624), routing-bodies (#2559), lightweight (#2638,
  commented), segs-glide (#2683), and routing-keys-fold/-model-rest/
  -request-metrics/-wb-restricted, usage-*, quota-*, s3-sync (#1544, #2658).
- set -o pipefail; go test -timeout 45m ./...: exit=0, every package ok.
- gofmt -l: nothing (no Go files changed). go vet ./... on darwin,
  GOOS=linux go vet -tags nogui ./..., and GOOS=windows go vet ./...: clean.

- Rebased onto ef655acb4. b0b076421 had added warn() to the agents
  onPick, and the new onPick keeps it. After the rebase:
  routing-rule-agent-typed, routing-rule-remove, routing-pause and
  routing-pause-folder: 74/74 in both engines.
This commit is contained in:
yetone
2026-10-20 00:40:08 +08:00
parent d155ab1619
commit e5b57794e2
5 changed files with 245 additions and 9 deletions
File diff suppressed because one or more lines are too long
+9 -1
View File
@@ -4605,7 +4605,7 @@ function openPicker(agent, field, anchor, ev, only) {
}
const q = $("#q");
q.value = "";
q.placeholder = modelPicker && extra(field) ? t("{field} — filter, or type any model id…", { field: t(field.label) }) : modelPicker ? t("Filter, or type any model id…") : t("Filter {field}…", { field: t(field.label) });
q.placeholder = field.placeholder || (modelPicker && extra(field) ? t("{field} — filter, or type any model id…", { field: t(field.label) }) : modelPicker ? t("Filter, or type any model id…") : t("Filter {field}…", { field: t(field.label) }));
filter();
// On touch screens leave the keyboard closed until the filter is tapped,
// so opening a model list leaves room to browse its choices.
@@ -4843,6 +4843,14 @@ function filter(keep) {
if (typed && pick.free && ["model", "small", "large", "executor", "planner", ...ROLE_MODELS].includes(pick.field.label) && !pick.items.some((o) => o.value === typed)) {
pick.items.push({ value: typed, note: t("use as typed"), custom: true });
}
// a picker that takes a name it doesn't list (a rule's agents: one known
// only by its User-Agent) offers what is typed as the field reads it, or
// the option that name already is
const own = typed && pick.field.typed?.(typed);
if (own) {
const listed = pick.options.find((o) => o.value === own.value);
if (!pick.items.includes(listed)) pick.items.push(listed || { ...own, custom: true });
}
pick.items = foldSame(pick.items);
// a model the filter finds among those kept for routing groups, which
// aren't offered: said why, rather than missing without a word
+33 -8
View File
@@ -465,6 +465,11 @@ function routingPage(part) {
const LONE = "Only one account or key is on for this, so routing has nothing to choose between. Turn on a second in the provider's editor, and how it routes is set under Several accounts or keys below.";
const agentOf = (id) => (state.clients || state.agents).find((a) => a.id === id);
// uaName is a client as the gateway names one it doesn't know
// (usage.AgentOf): its User-Agent's product name, before the first / or
// space, in lower case as a rule keeps it. "SillyTavern/1.12" is
// sillytavern; a comma would part it in two (ParseRule)
const uaName = (s) => String(s || "").trim().split(/[\/\s,]/)[0].toLowerCase();
const agentName = (id) => agentOf(id)?.name || (id && id !== "other" ? id : t("your agent"));
// who names an account or key in a sentence
const who = (w) => w.kind === "provider" ? w.name : w.who;
@@ -4440,6 +4445,13 @@ function routingPage(part) {
// More are picked with the model picker the agents use.
const infoOf = (id) => g?.memberInfo?.find((x) => x.id === id);
const pickFrom = (label, anchor, ev, options, onPick, value = "") => openPicker({ id: "", name: "", fields: [] }, { key: "rule", label, value, menu: true, options, onPick }, anchor, ev);
// the agents magpie heard from in the last 30 days that it doesn't
// know, by the names the gateway gave them (usage.AgentOf), asked for
// once while the editor is open; none when usage can't be read
let heardFrom = null;
const heard = () => heardFrom || (heardFrom = api("usage?period=30d")
.then((u) => (u?.agents || []).map((a) => uaName(a.id)).filter((id) => id && id !== "other" && id !== "magpie"))
.catch(() => []));
const box = el("div", "fallback");
const list = el("div", "fbl");
const addBtn = el("button", "rt-gadd");
@@ -5032,18 +5044,31 @@ function routingPage(part) {
wrap("compact", cp);
if (mine === "compact") focus = () => cp.focus({ preventScroll: true });
}
// agents
// agents: the ones magpie knows, the others it has heard from, and
// any typed by the name the gateway gives a client it doesn't know
// (raikyou on Discord: SillyTavern, one's own app)
if (kinds.includes("agents")) {
const clients = state.clients || state.agents || [];
const agentsName = () => r.agents.length ? r.agents.map((id) => clients.find((a) => a.id === id)?.name || id).join(", ") : t("any agent");
const ag = el("button", "rt-cond" + (r.agents.length ? " on" : ""), agentsName());
ag.onclick = (ev) => pickFrom("agent", ag, ev, [
{ value: "", label: t("any agent"), note: t("not a condition") },
...clients.map((a) => ({ value: a.id, label: a.name, icon: a.icon, note: r.agents.includes(a.id) ? "✓" : "" })),
], (v) => {
r.agents = !v ? [] : r.agents.includes(v) ? r.agents.filter((x) => x !== v) : [...r.agents, v];
ag.textContent = agentsName(); ag.classList.toggle("on", r.agents.length > 0); warn();
});
heard();
ag.onclick = async (ev) => {
ev.stopPropagation();
const known = new Set(clients.map((a) => a.id));
const others = [...(await heard()), ...r.agents].filter((id, i, all) => !known.has(id) && all.indexOf(id) === i);
const tick = (id) => r.agents.includes(id) ? "✓" : "";
openPicker({ id: "", name: "", fields: [] }, { key: "rule", label: "agent", value: "", menu: true,
placeholder: t("Filter, or type an agent's name…"),
typed: (s) => { const id = uaName(s); return id && { value: id, label: id, note: t("the name its User-Agent begins with") }; },
options: [
{ value: "", label: t("any agent"), note: t("not a condition") },
...clients.map((a) => ({ value: a.id, label: a.name, icon: a.icon, note: tick(a.id) })),
...others.map((id) => ({ value: id, label: id, icon: "generic", note: tick(id) || t("heard from in the last 30 days") })),
], onPick: (v) => {
r.agents = !v ? [] : r.agents.includes(v) ? r.agents.filter((x) => x !== v) : [...r.agents, v];
ag.textContent = agentsName(); ag.classList.toggle("on", r.agents.length > 0); warn();
} }, ag, ev);
};
wrap("agents", ag);
if (mine === "agents") focus = () => { ag.focus({ preventScroll: true }); ag.onclick({ stopPropagation() {} }); };
}
@@ -2,6 +2,9 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
"Filter, or type an agent's name…": "筛选,或输入 Agent 名称…",
"the name its User-Agent begins with": "User-Agent 开头的名称",
"heard from in the last 30 days": "近 30 天有请求",
"The subagent effort set in magpie is {effort}; the model's supported levels and a routing group's fixed member effort still apply.": "magpie 为子代理设定的推理强度是 {effort};仍按模型支持的等级适配,并保留路由组成员的固定强度。",
"{agent}'s call to magpie's web_search MCP tool": "{agent} 对 magpie 的 web_search MCP 工具的调用",
"{agent}'s {model}": "{agent} 的 {model}",
@@ -532,6 +535,9 @@ magpie.strings({
"{h} h {m} min": "{h} 小时 {m} 分钟",
},
"zh-TW": {
"Filter, or type an agent's name…": "篩選,或輸入 Agent 名稱…",
"the name its User-Agent begins with": "User-Agent 開頭的名稱",
"heard from in the last 30 days": "近 30 天有請求",
"The subagent effort set in magpie is {effort}; the model's supported levels and a routing group's fixed member effort still apply.": "magpie 為子代理設定的推理強度是 {effort};仍按模型支援的等級適配,並保留路由群組成員的固定強度。",
"{agent} guessed your next message for its composer by itself, reading the whole conversation again. Not a turn of the conversation; Settings › General › Codex composer predictions picks its model, and Codex's Settings › General › Show predictions turns it off.": "{agent} 自行為輸入框猜測你的下一則訊息,每次都把整段對話重讀一遍。不屬於對話輪次;在 設定 › 常規 › Codex 輸入框預測 裡選它用的模型,在 Codex 的 設定 › 一般 › 顯示預測內容 裡可以關掉。",
"{agent}'s call to magpie's web_search MCP tool": "{agent} 對 magpie 的 web_search MCP 工具的呼叫",
@@ -1062,6 +1068,9 @@ magpie.strings({
"{h} h {m} min": "{h} 小時 {m} 分鐘",
},
ja: {
"Filter, or type an agent's name…": "絞り込み、またはエージェント名を入力…",
"the name its User-Agent begins with": "User-Agent の先頭の名前",
"heard from in the last 30 days": "過去 30 日にリクエストあり",
"The subagent effort set in magpie is {effort}; the model's supported levels and a routing group's fixed member effort still apply.": "magpie で設定したサブエージェントの推論レベルは {effort} です。モデルが対応するレベルへの調整と、ルーティンググループのメンバーに固定されたレベルは引き続き適用されます。",
"{agent}'s call to magpie's web_search MCP tool": "{agent} による magpie の web_search MCP ツールの呼び出し",
"{agent}'s {model}": "{agent} の {model}",
@@ -1592,6 +1601,9 @@ magpie.strings({
"These routing groups will no longer be available to agents.": "これらのルーティンググループはエージェントから利用できなくなります。",
},
de: {
"Filter, or type an agent's name…": "Filtern oder Namen eines Agenten eingeben…",
"the name its User-Agent begins with": "der Name, mit dem sein User-Agent beginnt",
"heard from in the last 30 days": "in den letzten 30 Tagen gesehen",
"The subagent effort set in magpie is {effort}; the model's supported levels and a routing group's fixed member effort still apply.": "Der in magpie gesetzte Reasoning-Effort der Subagenten ist {effort}; die unterstützten Stufen des Modells und die feste Stufe eines Mitglieds der Routing-Gruppe gelten weiterhin.",
"{agent}'s call to magpie's web_search MCP tool": "den Aufruf von {agent} an magpies MCP-Werkzeug web_search",
"{agent}'s {model}": "{model} von {agent}",
@@ -0,0 +1,190 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A rule's agents may be one magpie doesn't know (raikyou on Discord:
// SillyTavern, one's own app with its own User-Agent). The gateway names
// such a client by its User-Agent's product name (usage.AgentOf), and a
// rule matches it in lower case. In the editor the agent picker offers the
// agents magpie knows, then those usage heard from in the last 30 days that
// it doesn't (not "other", nor magpie's own), and a name typed in the
// filter, read as the gateway reads a User-Agent: "MyApp/2.0 (Linux)" is
// myapp, and a name that is a known agent's is that agent. Saved as
// agents:[…]. In every language, and at a phone's width the menu stays on
// the screen with nothing run past the side.
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 models = [
{ id: "a/opus", name: "opus", providerName: "A", icon: "generic", context: 1000000, ready: true },
{ id: "b/kimi", name: "kimi", providerName: "B", icon: "generic", context: 256000, ready: true },
];
const groups = () => ({
models,
groups: [{ id: "main", name: "Main", members: ["a/opus", "b/kimi"], routing: "order", ready: true,
memberInfo: [{ id: "a/opus", ready: true, context: 1000000 }, { id: "b/kimi", ready: true, context: 256000 }], rules: [{ use: "b/kimi", agents: ["codex"] }] }],
pools: [],
});
// /api/usage?period=30d's agents, as usageapi.Page names them: a known
// one, one by its User-Agent as the gateway kept it, and the two the
// picker leaves out
const usage = { agents: [
{ id: "claude", name: "Claude Code", icon: "claudecode-color", calls: 9 },
{ id: "SillyTavern", name: "SillyTavern", icon: "generic", calls: 4 },
{ id: "other", name: "other", icon: "generic", calls: 2 },
{ id: "magpie", name: "magpie", icon: "generic", calls: 1 },
] };
const words = {
en: { edit: "Edit", save: "Save", filter: "Filter, or type an agent's name…", heard: "heard from in the last 30 days", typed: "the name its User-Agent begins with" },
zh: { edit: "编辑", save: "保存", filter: "筛选,或输入 Agent 名称…", heard: "近 30 天有请求", typed: "User-Agent 开头的名称" },
"zh-TW": { edit: "編輯", save: "儲存", filter: "篩選,或輸入 Agent 名稱…", heard: "近 30 天有請求", typed: "User-Agent 開頭的名稱" },
ja: { edit: "編集", save: "保存", filter: "絞り込み、またはエージェント名を入力…", heard: "過去 30 日にリクエストあり", typed: "User-Agent の先頭の名前" },
de: { edit: "Bearbeiten", save: "Speichern", filter: "Filtern oder Namen eines Agenten eingeben…", heard: "in den letzten 30 Tagen gesehen", typed: "der Name, mit dem sein User-Agent beginnt" },
};
function serve(lang, posts, asked) {
const state = {
agents: [{ id: "claude", name: "Claude Code", path: "/test/claude", fields: [] }],
clients: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }, { id: "codex", name: "Codex", icon: "codex-color" }],
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:true};` });
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/gateway/trace") {
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
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/usage") {
asked.push(url.search);
return json(url.searchParams.get("period") === "30d" ? usage : { agents: [] });
}
if (url.pathname === "/api/groups") return json(groups());
if (url.pathname.startsWith("/api/groups/")) {
posts.push({ path: url.pathname, body: JSON.parse(r.request().postData() || "{}") });
return json(groups());
}
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({});
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 r.fulfill({ body: await fs.readFile(file), contentType });
};
}
async function open(t, engine, lang, width) {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 1400 } })).newPage();
page.setDefaultTimeout(5000);
const errors = [], posts = [], asked = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts, asked));
await page.goto("http://magpie.test/?view=routing");
const group = page.locator(".rt-group").first();
await group.waitFor();
return { page, group, errors, posts, asked };
}
// the view wheeled down to a button, as the reader would (the page keeps
// still for any other scroll), and the button clicked where it is
async function press(page, b) {
await page.mouse.move(Math.min(550, page.viewportSize().width / 2), 600);
await b.waitFor();
for (let i = 0; i < 10 && (await b.boundingBox()).y > 1400 - 160; i++) {
await page.mouse.wheel(0, 300);
await page.waitForTimeout(150);
}
const bb = await b.boundingBox();
await page.mouse.click(bb.x + bb.width / 2, bb.y + bb.height / 2);
}
// the menu's rows, by name
const names = (page) => page.locator("#list li .v").evaluateAll((vs) => vs.map((v) => v.textContent));
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
const w = words[lang];
test(`${engine} ${lang}: a rule for an agent magpie knows only by its User-Agent`, async (t) => {
const { page, group, errors, posts, asked } = await open(t, engine, lang, 1100);
await press(page, group.locator("button", { hasText: w.edit }));
const ed = page.locator(".rt-gedit");
const ag = ed.locator(".rt-rule").first().locator('.rt-c[data-k="agents"] > button.rt-cond');
await ag.waitFor();
assert.equal(await ag.textContent(), "Codex");
// the known agents, then the one usage heard from, by the gateway's name
await press(page, ag);
const q = page.locator("#q");
await q.waitFor();
assert.equal(await q.getAttribute("placeholder"), w.filter);
await page.waitForFunction(() => [...document.querySelectorAll("#list li .v")].some((v) => v.textContent === "sillytavern"));
const listed = await names(page);
assert.deepEqual(listed.slice(1), ["Claude Code", "Codex", "sillytavern"], `known, then heard from: ${JSON.stringify(listed)}`);
const heard = page.locator("#list li", { hasText: "sillytavern" });
assert((await heard.textContent()).includes(w.heard), `said where it came from: ${await heard.textContent()}`);
assert.equal(asked.filter((x) => x === "?period=30d").length, 1, `usage asked once, for 30 days: ${asked}`);
await press(page, heard);
assert.equal(await ag.textContent(), "Codex, sillytavern");
// a name typed in, as the gateway reads a User-Agent
await press(page, ag);
await q.waitFor();
await q.fill("MyApp/2.0 (Linux)");
const typed = page.locator("#list li", { hasText: "myapp" });
await typed.waitFor();
assert((await typed.textContent()).includes(w.typed), `said how it is read: ${await typed.textContent()}`);
await q.press("Enter");
assert.equal(await ag.textContent(), "Codex, sillytavern, myapp");
assert.equal(await ag.getAttribute("class"), "rt-cond on");
// a known agent's name typed is that agent, once
await press(page, ag);
await q.waitFor();
await q.fill("Codex/0.50");
await page.waitForFunction(() => document.querySelectorAll("#list li .v").length > 0);
assert.deepEqual(await names(page), ["Codex"]);
// the ones picked come back ticked, the typed one among them
await q.fill("");
await page.waitForFunction(() => [...document.querySelectorAll("#list li .v")].some((v) => v.textContent === "myapp"));
assert.deepEqual((await names(page)).slice(1), ["Claude Code", "Codex", "sillytavern", "myapp"]);
await page.keyboard.press("Escape");
// saved as the gateway names them
const saveBtn = ed.locator("button.primary", { hasText: w.save });
await press(page, saveBtn);
await page.waitForFunction(() => !document.querySelector(".rt-gedit"));
const save = posts.find((p) => p.path === "/api/groups/save");
assert(save, `saved: ${JSON.stringify(posts)}`);
assert.deepEqual(save.body.rules.map((r) => [r.use, r.agents]), [["b/kimi", ["codex", "sillytavern", "myapp"]]]);
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: the agent picker at a phone's width`, async (t) => {
const { page, group, errors } = await open(t, engine, lang, 390);
await press(page, group.locator("button", { hasText: w.edit })); // the group is below the fold here
const ag = page.locator('.rt-gedit .rt-rule .rt-c[data-k="agents"] > button.rt-cond').first();
await ag.waitFor();
await press(page, ag);
const q = page.locator("#q");
await q.waitFor();
await q.fill("SillyTavern-Desktop/1.0");
await page.locator("#list li", { hasText: "sillytavern-desktop" }).waitFor();
const pop = await page.locator("#pop").boundingBox();
assert(pop.x >= 0 && pop.x + pop.width <= 390 + 1, `the menu stays on the screen: ${JSON.stringify(pop)}`);
await q.press("Enter");
assert.equal(await ag.textContent(), "Codex, sillytavern-desktop");
const [b, row] = await Promise.all([ag.boundingBox(), page.locator(".rt-gedit .rt-rule").first().boundingBox()]);
assert(b.x >= row.x - 1 && b.x + b.width <= row.x + row.width + 1, `the agents' condition stays in its rule: ${JSON.stringify([b, row])}`);
const wide = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
assert(wide <= 0, `no sideways scroll: ${wide}px`);
assert.deepEqual(errors, []);
});
}
}