Files
magpie/internal/gui/tests/desktop-subagent-model.test.cjs
T
Haogao Gu 20350dafaf gateway, agent, gui: Claude Desktop's subagents can be held to one model, set in its row on the Agents page
Claude Code in a terminal holds every subagent to one model through
CLAUDE_CODE_SUBAGENT_MODEL (its "subagents" field), and Codex through
magpie's own setting (settings.CodexSubagentModel). Claude Desktop runs
its Code tab's Claude Code with CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST=1,
and Claude Code 2.1.295 then ignores CLAUDE_CODE_SUBAGENT_MODEL,
CLAUDE_CODE_SUBAGENT_MODEL_FORCE and the tier variables in its settings
files ("Ignoring … this session's provider routing is managed by the
host"). The env Desktop 2.31226 builds for the Code tab has no key for it
either. So Desktop's subagents ran on the lead's model or on a tier's, and
only the tiers could be picked.

Claude Desktop's row now has a "subagent model" square, the same square
and strings as Codex's. It is magpie's setting
(settings.DesktopSubagentModel), which the gateway applies
(desktopSubagentPick):

- Only a claude-desktop request with x-claude-code-agent-id and tools is
  moved: a subagent's turn. The lead's turns, the tool-less helper calls
  Claude Code makes inside a subagent (on the haiku tier's model),
  terminal Claude Code and every other agent stay as asked.
- It is applied after desktopTurn, the tiers and the groups. A turn
  already on the model set isn't marked as moved. Route.Subagent,
  Route.Model and the ledger's Requested keep the model asked for; Kind
  stays empty.
- The model set must be served by its exact id (Resolve takes any model
  name under a provider that is on), enabled, and allowed to a gateway key
  held to some models (groupAllowed for a group). Otherwise the subagent
  stays on the model asked for and the trace says why, in the reasons
  Codex's subagent model already has.
- count_tokens counts on the same model.
- It is read on each request, so Desktop needn't restart. The field is
  Live (a new Field flag): /api/set and `magpie <agent> <field> <value>`
  leave Desktop's restart notice out after it, unless the pick connected
  Desktop. Codex's subagent model is unchanged.
- The getter follows a provider renamed since it was set (RenamedRef).
  The setter takes any provider/model or group/<id>, also one not served
  now (a restored profile), refuses a bare name, and keeps a Desktop
  alias by its catalog id. Options are shown while Desktop is on magpie.
- POST /api/settings keeps it; a stopped WSL distro's field copy keeps
  Live.
- The Routing page says why a Desktop subagent was moved or kept
  (subagentWhy, for a route with a subagent pick and no kind). "it is
  disabled in magpie" gets its zh, zh-TW, ja and de, which Codex's kept
  reason lacked as well.
- Unset, the pick costs one held settings read (no body decode, no
  catalog build).

Not changed: a Desktop on another computer that reaches magpie with a
named gateway key is read as Claude Code (agentOf), so none of Desktop's
routing applies to it, this included. There is no fallback when the model
set has a smaller window than the lead's.

Verified at this head, on 20769439, under a temporary HOME with Go's
caches pinned:
- Each new test fails with the guarantee it names broken by hand (a real
  FAIL, not a compile error), then passes restored. 48 Go breaks were
  first run on 8f34bbcd: settings trim and bare-name refusal; setter
  validation and clear; RenamedRef in the getter and in Unserved; the
  exact served check and served groups; the serve pick, each guard
  (agent id, tools, claude-desktop only, unset, same and resolved model);
  the named id kept in Route.Model, Kind and the ledger's Requested; each
  kept reason (unserved, disabled, held model, held group); groupAllowed;
  the next request reading a change; the session pick kept; count_tokens;
  the unset pick allocating; Live on the field, not on the tiers or on
  Codex's, copied by WSL; options while unwired and wired; alias
  conversion; the settings keep line; the GUI and CLI notice rules.
  Re-run at this head:
  - no tools guard: TestDesktopSubagentLeavesOtherRequests/helper,
    `sent "m2", want m1`
  - no agent-id guard: TestDesktopSubagentLeavesOtherRequests/lead,
    `sent "m2", want m1`
  - no count_tokens pick: TestDesktopSubagentCountTokens,
    `count sent "m1" to "/v1/messages/count_tokens", want m2`
  - Resolve instead of the exact served check: TestDesktopSubagentUnserved,
    `fake/missing: "", want "magpie doesn't serve it now"`
  - no Live rule in /api/set: TestDesktopSubagentModelNotice (gui),
    `wired Live pick notice "Claude Desktop reads this at start-up …"`
  - no keep line in POST /api/settings: TestSettingsSaveKeepsWhatItDoesNotSend,
    `DesktopSubagentModel:  after a save of the Settings page, was fake/m2`
  GUI breaks (0 pass / 2 fail in each engine): renderSteps' new aside
  removed (Desktop's moved story missing); the four "it is disabled in
  magpie" translations removed (the kept story keeps the English reason);
  the Default note's translation removed.
- go test -tags nogui ./...: 52 packages ok, no failure.
- go test -race -count=20 -run '^TestDesktopSubagent' ./internal/gateway: ok.
- gofmt -l on the changed files: nothing. go vet ./...,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...,
  go build, GOOS=linux go build -tags nogui, GOOS=windows go build: exit 0.
- Playwright 1.62.1: desktop-subagent-model.test.cjs (en, zh, zh-TW, ja,
  de; 1100 and 560 wide) with codex-subagent-model, codex-subagents-lead,
  codex-start-model-field, desktop-tiers, desktop-model-menu,
  subagent-effort and every routing-*.test.cjs: 472/472 in Chromium and
  in WebKit. The whole suite: Chromium 4580/4580; WebKit 4570/4572. The
  two are red on 20769439 untouched as well: group-fold.test.cjs 3 of 3
  alone (195a1009b, fixed upstream since by a125d5c9), usage-fold.test.cjs
  4 of 9 alone there and 4 of 9 here ("as many accounts on the first
  screen as before the curves: 12 of 29").
- The built binary in a temporary HOME, `magpie serve` on a free port, a
  fake Anthropic upstream, requests shaped like Desktop's Claude Code:
  `magpie claude-desktop subagent_model fake/m2` printed no restart
  advice; a subagent's turn and its count went to m2; the lead's turn,
  a subagent's tool-less call, terminal Claude Code's and a subagent turn
  after `… subagent_model default` went to m1; claude-desktop.model stayed
  fake/m1; the ledger kept requested fake/m1.
- Not tried: a real Claude Desktop or Cowork (that needs the live
  gateway), Linux and Windows machines (GOOS vet and build only),
  WebKitGTK.

Maintainer's review on origin/main c4c3cafa2 (#2081), under a scratchpad
HOME with Go's caches pinned, machine load 120-330:
- Claude Code 2.1.299's bundled source has the "Ignoring … this
  session's provider routing is managed by the host" path, with
  CLAUDE_CODE_SUBAGENT_MODEL_FORCE in the set it ignores.
- Breaks re-run: no tools guard -> TestDesktopSubagentLeavesOtherRequests/
  helper `sent "m2", want m1` and TestDesktopSubagentCountTokens helper
  count; no count_tokens pick -> TestDesktopSubagentCountTokens `count
  sent "m1" … want m2`; the Routing page's subagentWhy aside removed ->
  desktop-subagent-model 0 pass / 2 fail (webkit, zh).
- go test -tags nogui ./internal/{gateway,agent,settings,gui,cli,provider}:
  ok on 2fbbd1694 (agent with -timeout 40m: 1857s under the load; the
  default 10m timed out mid TestClaudeNewSessionEffortLastsModelSwitch, a
  test this change doesn't touch). After rebasing onto c4c3cafa2, the
  Desktop/Subagent/SettingsSave/Live/Notice tests of those six packages: ok.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: ok.
- desktop-subagent-model.test.cjs now runs at 1100 and 420 (was 560):
  20/20, chromium and webkit, en zh zh-TW ja de. codex-subagent-model,
  desktop-tiers, routing-purpose-state, routing-request-model,
  routing-sealed-task: all pass in both engines.
- usage-fold's "29 accounts" case passed 4 of 4 alone in WebKit here.
- Not repeated: the author's built-binary run; a real Claude Desktop or
  Cowork; Linux and Windows machines.

Decisions on the author's questions: Live is kept as named, and Codex's
subagent model is left as it is; a subagent's tool-less helper calls stay
on the model they asked for, being Claude Code's own housekeeping rather
than the subagent's work.

Reported-by: Koohoko (#2081)
2026-10-14 15:48:19 +08:00

195 lines
14 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// Desktop's gateway-applied subagent model shares Codex's square and picker.
// Desktop's routing trace has a subagent pick without a kind. All APIs and
// assets are intercepted; no backend or external network is used.
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 = [
{ value: "fake/m1", label: "M1", ref: "fake/m1", group: "Fake" },
{ value: "fake/m2", label: "M2", ref: "fake/m2", group: "Fake" },
];
const fresh = (wired = true) => ({
agents: [{
id: "claude-desktop", name: "Claude Desktop", path: "/test/claude_desktop_config.json", icon: "claude-color", wired,
fields: [
{ key: "provider", label: "provider", value: wired ? "magpie" : "", options: [{ value: "magpie", label: "magpie" }] },
...["opus", "sonnet", "haiku", "fable"].map((tier) => ({ key: tier, label: tier, value: "", options: wired ? models : [] })),
{ key: "subagent_model", label: "subagent model", value: "", options: wired ? models : [] },
],
}],
profiles: [],
});
const now = new Date();
const day = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map((n) => String(n).padStart(2, "0")).join("-");
const at = (i) => new Date(now.getTime() - (i + 1) * 60e3).toISOString();
const seat = { id: "fake", provider: "fake", name: "Fake", who: "Test key", kind: "key", agent: "claude-desktop", model: "m2" };
// Deliberately no kind: Desktop must explain the pick without a Codex tag.
const routes = [
{ id: 2, seq: 2, time: at(0), agent: "claude-desktop", model: "fake/m1", provider: "fake", subagent: { asked: "fake/m1", to: "fake/m2" },
order: [seat], tries: [{ id: "fake", model: "m2", start: at(0), done: true, status: 200, ms: 900 }], done: true, status: 200, ms: 900, tokens: 1200 },
{ id: 1, seq: 1, time: at(1), agent: "claude-desktop", model: "fake/m1", provider: "fake", subagent: { asked: "fake/m1", to: "fake/m2", kept: "it is disabled in magpie" },
order: [{ ...seat, model: "m1" }], tries: [{ id: "fake", model: "m1", start: at(1), done: true, status: 200, ms: 900 }], done: true, status: 200, ms: 900, tokens: 1200 },
];
function server(lang, fixture) {
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ ...fixture.state, settings: { lang, theme: "light" } });
if (url.pathname === "/api/set") {
const body = req.postDataJSON();
fixture.sets.push(body);
fixture.state = JSON.parse(JSON.stringify(fixture.state));
fixture.state.agents.find((a) => a.id === body.agent).fields.find((f) => f.key === body.field).value = body.value;
return json({ ...fixture.state, settings: { lang, theme: "light" } });
}
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3));
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
}
if (url.pathname === "/api/gateway/history") {
const d = url.searchParams.get("day");
return json({ cut: false, days: [{ day, requests: routes.length }], routes: d ? routes : [] });
}
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/agents/cli") return json({ agents: {}, pending: false });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
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 route.fulfill({ body: await fs.readFile(file), contentType });
};
}
// Expected reader-facing words, independent of the translation lookup.
const W = {
en: { unset: "subagent model: the model the lead asks for", def: "Default", set: "subagent model: M2",
note: "each subagent on the model Claude Desktop's lead asks for",
moved: "Claude Desktop requested a subagent on fake/m1; magpie put it on fake/m2, the model set for its subagents.",
kept: "Claude Desktop requested a subagent on fake/m1 and it stayed there: its subagents are set to fake/m2, but it is disabled in magpie." },
zh: { unset: "子代理模型:主代理请求的模型", def: "默认", set: "子代理模型:M2",
note: "每个子代理都用 Claude Desktop 主代理请求的模型",
moved: "Claude Desktop 请求了使用 fake/m1 的子代理;magpie 将其改用 fake/m2,即为它的子代理设定的模型。",
kept: "Claude Desktop 请求了使用 fake/m1 的子代理,并保留在该模型上:它的子代理设为 fake/m2,但该模型在 magpie 中已停用。" },
"zh-TW": { unset: "子代理模型:主代理請求的模型", def: "預設", set: "子代理模型:M2",
note: "每個子代理都用 Claude Desktop 主代理請求的模型",
moved: "Claude Desktop 請求了使用 fake/m1 的子代理;magpie 將其改用 fake/m2,即為它的子代理設定的模型。",
kept: "Claude Desktop 請求了使用 fake/m1 的子代理,並保留在該模型上:它的子代理設為 fake/m2,但該模型在 magpie 中已停用。" },
ja: { unset: "サブエージェントのモデル:リードがリクエストしたモデル", def: "デフォルト", set: "サブエージェントのモデル:M2",
note: "各サブエージェントは Claude Desktop のリードがリクエストしたモデルを使います",
moved: "Claude Desktop が fake/m1 のサブエージェントをリクエストしました。magpie はサブエージェント用に設定された fake/m2 に切り替えました。",
kept: "Claude Desktop が fake/m1 のサブエージェントをリクエストし、そのモデルのままになりました。サブエージェントは fake/m2 に設定されていますが、このモデルは magpie で無効になっています。" },
de: { unset: "Modell der Subagenten: das Modell, das der Haupt-Agent anfordert", def: "Standard", set: "Modell der Subagenten: M2",
note: "jeder Subagent auf dem Modell, das der Haupt-Agent von Claude Desktop anfordert",
moved: "Claude Desktop hat einen Subagent mit fake/m1 angefordert; magpie hat ihn auf fake/m2 gesetzt, das für seine Subagenten festgelegte Modell.",
kept: "Claude Desktop hat einen Subagent mit fake/m1 angefordert, und er blieb dort: Seine Subagenten sind auf fake/m2 gesetzt, aber es ist in magpie deaktiviert." },
};
const cd = '.row.agent[data-id="claude-desktop"]';
const engines = process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"];
const langs = process.env.LANGS ? process.env.LANGS.split(",") : Object.keys(W);
for (const engine of engines) {
for (const lang of langs) {
for (const width of [1100, 420]) {
test(`${engine} ${lang} ${width}px: Desktop's subagent square, translated picker and routing story`, async (t) => {
const w = W[lang];
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await browser.newPage({ viewport: { width, height: 760 } });
page.setDefaultTimeout(5000);
const errors = [], fixture = { state: fresh(), sets: [] };
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, fixture));
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-desktop-subagent-model.png`) });
}
await browser.close();
});
await page.goto("http://magpie.test/");
await page.locator(cd).waitFor();
await page.locator(`${cd} .ag-link`).click();
await page.locator(`${cd} .ag-exp`).waitFor();
const square = page.locator(`${cd} .ag-exp .field.extra[data-key="subagent_model"]`);
assert.equal(await square.count(), 1, "Desktop's opened row has one subagent square");
assert.equal(await page.locator(`${cd} .field:not(.extra)[data-key="subagent_model"]`).count(), 0, "no plain subagent picker");
assert.equal(await square.getAttribute("title"), w.unset, "translated unset title");
assert.equal(await square.getAttribute("aria-label"), w.unset);
assert.equal(await square.evaluate((e) => e.classList.contains("set")), false);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "no sideways scroll");
const box = await square.boundingBox();
assert(box && box.x >= 0 && box.x + box.width <= width, JSON.stringify(box));
const y = await page.evaluate(() => scrollY);
await square.click();
await page.locator("#pop:not([hidden]) #list li").first().waitFor();
assert.equal(await page.evaluate(() => scrollY), y, "opening the square does not scroll");
assert.equal(await page.locator("#pop").evaluate((e) => e.classList.contains("model-picker")), true, "app's own model picker");
assert.equal(await page.locator("select").count(), 0, "no native select");
const first = await page.locator("#pop #list li").first().evaluate((e) => [e.querySelector(".v")?.textContent, e.querySelector(".n")?.textContent]);
assert.deepEqual(first, [w.def, w.note], "translated Default first with Desktop's lead note");
const items = await page.locator("#pop #list li").allInnerTexts();
for (const model of models) assert(items.some((s) => s.includes(model.label)), `${model.label} offered by magpie`);
const pop = await page.locator("#pop").boundingBox();
assert(pop && pop.x >= 0 && pop.x + pop.width <= width, JSON.stringify(pop));
const left = await page.locator(`${cd} .field.extra[data-key="subagent_model"], #pop #list li`).evaluateAll((es) => es.flatMap((e) => [e, ...e.querySelectorAll("*")]).filter((e) => {
const s = getComputedStyle(e);
return parseFloat(s.borderLeftWidth) > 1 && s.borderLeftWidth !== s.borderRightWidth;
}).length);
assert.equal(left, 0, "no coloured left border on square or picker rows");
await page.locator("#pop #list li", { hasText: "M2" }).first().click();
await page.waitForFunction(() => document.querySelector('.row.agent[data-id="claude-desktop"] .field.extra.set[data-key="subagent_model"]'));
assert.deepEqual(fixture.sets, [{ agent: "claude-desktop", field: "subagent_model", value: "fake/m2" }], "Desktop pick posts the catalog id");
assert.equal(await square.getAttribute("title"), w.set);
assert.equal(await square.getAttribute("aria-label"), w.set);
assert.equal(await page.evaluate(() => scrollY), y, "picking does not scroll");
await square.click();
await page.locator("#pop:not([hidden]) #list li").first().waitFor();
assert.equal(await page.evaluate(() => scrollY), y, "reopening does not scroll");
await page.locator("#pop #list li").first().click();
await page.waitForFunction(() => !document.querySelector('.row.agent[data-id="claude-desktop"] .field.extra.set[data-key="subagent_model"]'));
assert.deepEqual(fixture.sets, [
{ agent: "claude-desktop", field: "subagent_model", value: "fake/m2" },
{ agent: "claude-desktop", field: "subagent_model", value: "" },
], "Default posts an empty value");
assert.equal(await square.getAttribute("title"), w.unset);
assert.equal(await page.evaluate(() => scrollY), y, "Default does not scroll");
fixture.state = fresh(false);
await page.goto("http://magpie.test/");
await page.locator(cd).waitFor();
assert.equal(await page.locator(`${cd} .field[data-key="subagent_model"]`).count(), 0, "unwired Desktop with no options or value has no square");
// A narrow window covers the list with the story, so reopen it afresh.
for (const [i, said] of [[0, w.moved], [1, w.kept]]) {
await page.goto("http://magpie.test/?view=routing");
await page.locator(".rt-days .rt-day").nth(1).click();
await page.locator(".rt-req").nth(1).waitFor();
await page.locator(".rt-req").nth(i).evaluate((e) => e.click());
await page.waitForFunction((i) => document.querySelectorAll(".rt-req")[i]?.getAttribute("aria-pressed") === "true", i);
const story = await page.locator(".rt-steps").textContent();
assert(story.includes(said), `Desktop ${i === 0 ? "moved" : "kept"} story: ${said}\nnot in\n${story}`);
assert.equal(await page.locator(".rt-steps .aside", { hasText: said }).count(), 1, "one subagent aside without a kind");
assert.equal(await page.locator(".rt-steps .kind").count(), 0, "Desktop has no Codex purpose tag");
if (i === 1 && lang !== "en") assert(!story.includes("it is disabled in magpie"), "kept reason must be translated");
}
assert.deepEqual(errors, []);
});
}
}
}