Files
magpie/internal/gui/tests/routing-affinity-lead.test.cjs
T
yetone 00198b26e0 gateway: a session's side call goes on the account its main conversation is on (#5655)
With two Claude accounts, Claude Desktop's own Sonnet calls beside an
Opus chat (desktop-beside), and Claude Code's auto mode classifier, ran
on account B while the chat was on A. Each model's conversation is kept
under its own scope (p.ID/model), so the side call was routed as a
session of its own: leastHeld, or Smart's order once its cache was cold,
put it on the account the fewest others held, and B's 5 hours drained on
calls the user never made there.

Decided (product call delegated): one session goes on one account. The
user picked one, the vendor sees one client, and the cost is one cache
write of the side call where the session goes on reading it.

withSession (affinity.go) puts first, for a request whose session a
header names, the key or account of that session's largest conversation
under another model's scope (answered within heldFor, at least
cacheWorth kept, larger than this one's own). It acts for Why first,
gone, cold, no-cache, cache and session; never mid-turn, under Strict,
for a subagent (withLead), past a rest, reserve, credits or a fallback
routing put first, nor to an account that isn't readyForNew. The trace
says Why "lead" with LeadModel, and the Routing page says "Put on
{first}, where this session's {model} is: one session goes on one
account." in en, zh, zh-TW, ja and de. docs/subsystems/gateway-routing.md
says the same.

Not fixed here: the classifier's ~110-130K cache write per call. That one
is ours too: in Claude Code's interactive mode the bridge pastes the
classifier's transcript as one block without the client's marks
(claudetui userPieces, clientCache.pasted), so only the fixed prefix
(Claude Code's system plus the appended rules, the 68,925) is read and
the rest is written again on every call. The cause and a candidate fix
are on #5585. It changes what a real Claude Code sends and can't be
checked without a real account.

Run (mote, through mote-run), at this head (aeeeed54a's tree, origin/main
0fc3455e2 unchanged after a fresh fetch):
- go test ./internal/gateway ./internal/gui -count=1 -timeout 45m: ok (964s, 157s).
- TestSessionSide*, TestGroupAccountsHoldEveryRoute,
  TestPluginFactoryStandardOnlyCaps, TestWholeSession*, TestBusyModel*,
  TestInOrderKeeps* -count=2: ok.
- gofmt -l: clean. go vet ./internal/gateway for darwin, linux, windows: ok.
- node --test routing-affinity-lead (new), routing-affinity-order,
  routing-affinity-cache-write, i18n-keys, i18n-en-no-cjk: 67/68
  (Chromium + WebKit, 1100 and 420, en/zh/zh-TW/ja/de). The one red is
  i18n-keys "a plugin's words are its own", red on main for strings this
  change doesn't touch (#5327/#5332, #5426, #5482).
- The first package run of this change failed TestGroupAccountsHoldEveryRoute
  and TestPluginFactoryStandardOnlyCaps/auto (both green at 0fc3455e2):
  without a session header the id is the opening's hash, so two
  conversations that opened with "hi" were one session, and a main with
  nothing cached led. Both are excluded now, each with a subtest.
- The full go test ./... under the suite lock was queued behind four
  other sessions' suites and had not started when this was pushed.

Broken by hand, each red: the withSession call removed (both new tests;
"the session's m2 call went to k2 while its chat is on k1"); the named
session check removed (no session named); the cacheWorth bar removed
(main holds no cache, and TestPluginFactoryStandardOnlyCaps).

Not tried: real Claude accounts, real Claude Desktop. A session already
split before this release moves its side call at the side call's next
turn, writing its cache once on the main's account.

Reported-by: jerrychoi
Reported-by: iamnil (Discord)
2026-11-08 10:40:22 +08:00

75 lines
4.6 KiB
JavaScript

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");
// #5655 (jerrychoi; iamnil on Discord): a session's call to another model
// than its chat's (Claude Desktop's own Sonnet beside an Opus chat) goes
// to the account the chat is on (withSession, why "lead"), and the
// Routing page says so, naming the chat's model.
const words = {
en: ["where this session's", "claude-opus-5-5", "one account"],
zh: ["这个会话的", "claude-opus-5-5", "一个账号"],
"zh-TW": ["這個會話的", "claude-opus-5-5", "一個帳號"],
ja: ["このセッションの", "claude-opus-5-5", "1 つのアカウント"],
de: ["dieser Sitzung", "claude-opus-5-5", "einem Konto"],
};
function routes(now) {
const time = new Date(now.getTime() - 5000).toISOString();
const at = new Date(now.getTime() - 65000).toISOString();
const a = { id: "claude#a", provider: "claude", name: "Claude", kind: "account", who: "a@example.com", model: "claude-sonnet-5" };
const b = { id: "claude#b", provider: "claude", name: "Claude", kind: "account", who: "b@example.com", model: "claude-sonnet-5" };
return [{ id: 1, seq: 1, time, agent: "claude-desktop", model: "claude/claude-sonnet-5", provider: "claude", order: [a, b], done: true, status: 200, ms: 20,
affinity: { mode: "", turn: 3, last: "claude#b", lastTurn: 2, at, cacheRead: 68925, cacheWrite: 110000, why: "lead", leadModel: "claude-opus-5-5" },
tries: [{ id: a.id, model: "claude-sonnet-5", start: time, done: true, status: 200, ms: 20 }] }];
}
function serve(lang, getRoutes, now) {
const assets = path.resolve(__dirname, "../assets");
return async (route) => {
const url = new URL(route.request().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({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.has("wait")) return;
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 1, rerouted: 0, errors: 0 }, routes: getRoutes() });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json({ groups: [] });
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" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType });
};
}
for (const engine of process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"]) {
for (const width of [1100, 420]) {
for (const lang of Object.keys(words)) {
test(`${engine} ${width} ${lang}: affinity says a side call went with its session's account`, 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 } });
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const now = new Date();
await page.route("**/*", serve(lang, () => routes(now), now));
await page.goto("http://magpie.test/?view=routing");
await page.waitForFunction(() => /\d/.test(document.body.innerText) && document.querySelector(".rt-cap")?.textContent);
const text = await page.evaluate(() => document.body.innerText + "\n" + document.querySelector(".rt-cap").textContent);
for (const w of words[lang]) assert.ok(text.includes(w), `${w} not in\n${text}`);
assert.doesNotMatch(text, /\{(first|model)\}/);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "no sideways scroll");
assert.deepEqual(errors, []);
});
}
}
}