Files
magpie/internal/gui/tests/routing-served.test.cjs
T
yetone c816c9f828 routing: a request answered by another model than the one asked for is marked, from the model the vendor's reply names (v on Discord #feedback: 模型路由情况其实有的时候还是想知道的,比如之前 openai 会把 sol 降智到 luna 这样的,现在只有走 s2a 和 newapi 这些网关服务才能明确看到) — magpie read the tokens off each reply but not the model it says answered, so a vendor serving sol's requests with luna looked, on the Routing page, like sol answering. The reply's model is now kept as it goes by, never delayed or changed: on a relayed reply by the usage sniffer, which already reads every event and JSON body (Chat Completions' model in its JSON and each chunk, the Responses API's response.model in response.created/completed and model in its JSON, Anthropic's message.model in message_start and model in its JSON); on a translated one from the decoders' start event, which already carried it (Chat, Responses, Anthropic, and Gemini Code Assist's modelVersion), streamed or collected; on a Claude subscription's from the CLI's message_start; and on Codex's own models relayed to the ChatGPT backend. It goes in Usage.Served (and so the request log), each try's Served and the route's (the last try's, when it answered), with Swapped when it is another model than the one the try sent the vendor. Vendors mostly echo a dated or pinned name, which is the same model: the names are compared without a maker or path prefix (openai/, models/, Bedrock's us.anthropic.), case, and a version at the end — a date (-2025-08-07, -20250929, -06-05), a build number (-0613, -001), Bedrock's -v1:0, -latest, -preview — so gpt-5 answered as gpt-5-2025-08-07 or claude-3-5-sonnet-latest as claude-3-5-sonnet-20241022 is not marked, while gpt-5 as gpt-5-mini, gpt-5 as gpt-5.1, claude-opus-4 as claude-opus-4-1-… and deepseek-v3 as deepseek-v2 are. A reply that names no model marks nothing. The Routing page's Requests list puts an amber "served luna" (实际 luna) tag by the answer, its title saying what it means, and the request's story a line "requested sol · served luna" (请求 sol · 实际 luna) with the same sentence; no border stripe, and picking the request leaves the page where it is. Cursor, Devin, Kiro and Qoder name the model they were asked for themselves, so they are never marked.
Tested with new internal/gateway/served_test.go: TestServedModelRecorded (fake vendors in each protocol, streamed and not, relayed — Anthropic, Chat, Responses — and translated — Chat from Anthropic, Anthropic from Chat, Anthropic from Responses — each answering luna (marked), sol-2026-01-01 and models/SOL (not): the route, its try and the request log keep the name, Swapped as said), TestServedModelUnnamed, TestSwappedModel (the names above), TestSniffServedModel and TestCodexOwnModelServedTraced; and new internal/gui/tests/routing-served.test.cjs in Chromium and WebKit, en and zh (the tag on the swapped request alone, whole and in its row, no left border, its title; the story's line; a click that doesn't move the page; the dated and unnamed ones unmarked). With three requests alone the Routing page above the list jiggles by a few to 70px in WebKit on its own (on main too, with no served model in the fixture), so the fixture lists six. go build -tags nogui (and GOOS=linux, GOOS=windows), go test -tags nogui ./... and all GUI tests (80) pass. Not tested against a real vendor serving another model.
2026-09-29 19:41:29 +08:00

111 lines
6.8 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// A request whose vendor's reply names another model than the one asked for
// — sol served as luna — is marked in the Routing page's Requests list and
// in its story; one answered under its dated name is not (v, #feedback:
// 模型路由情况其实有的时候还是想知道的,比如之前 openai 会把 sol 降智到 luna 这样的).
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 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 key = { id: "relay", provider: "relay", name: "Relay", kind: "provider", model: "gpt-6-sol" };
// newest first: swapped, dated (the same model), none named, and a few
// more (with three rows alone the stage above jiggles in WebKit, on main)
const served = [["gpt-6-luna", true], ["gpt-6-sol-2026-09-01", false], ["", false], ["", false], ["", false], ["", false]];
const routes = served.map(([s, swapped], i) => ({
id: 100 - i, seq: 100 - i, time: at(i), agent: "codex", model: "relay/gpt-6-sol", provider: "relay",
order: [key], tries: [{ id: key.id, model: "gpt-6-sol", start: at(i), done: true, status: 200, ms: 900, ...(s ? { served: s } : {}), ...(swapped ? { swapped } : {}) }],
done: true, status: 200, ms: 900, tokens: 1200, ...(s ? { served: s } : {}), ...(swapped ? { swapped } : {}),
}));
function serve(lang) {
const state = { agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } };
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(state);
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/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], 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)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const want = {
en: { row: "served gpt-6-luna", tag: "requested gpt-6-sol · served gpt-6-luna", story: /its reply says gpt-6-luna answered it: another model/ },
zh: { row: "实际 gpt-6-luna", tag: "请求 gpt-6-sol · 实际 gpt-6-luna", story: /回复写明由 gpt-6-luna 作答:这是另一个模型/ },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
test(`${engine} ${lang}: a request served by another model than asked is marked`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const context = await browser.newContext({ viewport: { width: 1100, height: 760 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang));
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}-served.png`), fullPage: true });
}
await browser.close();
});
await page.goto("http://magpie.test/?view=routing");
await page.locator(".rt-day").nth(1).click();
await page.locator(".rt-req").nth(served.length - 1).waitFor();
// the list: the swapped one alone carries the mark, whole, beside the
// model asked for
const tags = await page.locator(".rt-req").evaluateAll((rows) => rows.map((r) => r.querySelector(".to .swap")?.textContent || ""));
assert.deepEqual(tags, [want[lang].row, "", "", "", "", ""]);
const look = await page.locator(".rt-req .to .swap").evaluate((e) => {
const row = e.closest(".rt-req").getBoundingClientRect(), b = e.getBoundingClientRect(), cs = getComputedStyle(e);
return { inRow: b.left >= row.left && b.right <= row.right + 0.5 && b.width > 0, full: e.clientWidth >= e.scrollWidth, border: cs.borderLeftWidth, title: e.title };
});
assert(look.inRow && look.full, JSON.stringify(look));
assert.equal(look.border, "0px");
assert.match(look.title, want[lang].story);
// the story says so, and the click leaves the row where it is
const row = page.locator(".rt-req").nth(0);
const was = await row.evaluate((e) => e.getBoundingClientRect().top);
const scrolled = await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]);
await row.click();
await page.waitForTimeout(600);
assert(Math.abs((await row.evaluate((e) => e.getBoundingClientRect().top)) - was) <= 1, "picking the request moved the page");
assert.deepEqual(await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]), scrolled);
const story = page.locator(".rt-steps li.swap");
assert.equal(await story.count(), 1);
assert.equal(await story.locator(".swap").textContent(), want[lang].tag);
assert.match(await story.textContent(), want[lang].story);
// the same model under its dated name, and a reply naming none: no mark
for (const i of [1, 2]) {
await page.locator(".rt-req").nth(i).click();
await page.waitForTimeout(300);
assert.equal(await page.locator(".rt-steps li.swap").count(), 0);
}
assert.deepEqual(errors, []);
});
}
}