Files
magpie/internal/gui/tests/stand-in.test.cjs
T
yetone 72e804d2b5 gateway: a provider set Never a fallback takes no other model's request (sonnnnnnnnnnnna on X)
sonnnnnnnnnnnna asked that a request a local uncensored model was given
never falls back to an online provider (Anthropic, OpenAI) when the local
model is full (kv slots) or down, where it could get the account banned.

A provider now has Never a fallback (NoStandIn), off by default: the
Providers page's right-click, under Use first, ticks it; the CLI's
`magpie provider set <id> fallback-for-others=no` sets it. Its keys and
accounts are dropped from a request's plan once a candidate of an
unmarked provider was planned before them (standInsOut, run in planPaused
and in planGroup before restLast and sinkPlanned, so a local model that
failed and is resting still counts as first; a primary with nothing
planned counts too). A request that goes to a marked provider first still
moves on as before, and a weighed group (Smart, Cheapest) that picks a
marked member first sends it there. The dropped rows go to the trace's
left-out list as StandIn; the Routing page says why ("it is set never to
be a fallback for another model"), and the cap, held and barred refusal
checks ignore them so a refusal keeps its old status.

No classifier was built: the model that would judge the request is the
local one that is down, and any other would send the text somewhere the
user didn't choose.

Run on mote (macOS 27) at this tree on 065ca02c2: gofmt -l clean; go
vet darwin, GOOS=linux -tags nogui, GOOS=windows over gateway, provider,
gui, cli; go test ./internal/cli ./internal/gui ./internal/provider ok
(TestCoreScriptBudget after four comments cut in app.js, core 1,533,187
of 1,533,802, no raise), ./internal/gateway -run
'StandIn|UseFirst|Fallback|Barred|Capped|Group' ok (the whole package
ok at e6f151507); GUI in chromium and webkit, 126 of 126: stand-in (new,
5 languages, 1100 and 420 wide), provider-find (with the next commit),
use-first, menu-first-second, routing-held-member, unlisted-models,
i18n-keys, i18n-en-no-cjk; plugin-actions, routing-wb-refused and
group-found-skip ok at ca7a39291. provider-models-rest is red the same
at ca7a39291 (10 !== 83), #4396.

Broken by hand: standInsOut's drop turned off (`other && false`), and
TestNoStandInTakesNoOtherModelsRequest went red ("local down: 200 ...
from cloud2, want the spare").

Not tried: a real local model (llama.cpp/Ollama) going full or down, the
Windows box, a click in the real app.
2026-11-10 22:53:58 +08:00

138 lines
8.3 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// sonnnnnnnnnnnna on X: a local uncensored model that is down or out of
// room must not hand its request to Claude or Codex, whose vendor may ban
// the account for it. A provider row's right-click has Never a fallback:
// it posts provider/standin, and once on the item shows a tick and posts
// it off again. On the Routing page, a request whose fallback was left out
// for it says why. The page doesn't move. Every language, Chromium and
// WebKit, at 1100 and 420 wide; no backend, the API is faked here.
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 CHECK = "m3.5 8.5 3 3 6-7";
const now = new Date();
const ago = (minutes) => new Date(now.getTime() - minutes * 60e3).toISOString();
const prov = (id, name, extra = {}) => ({
id, name, icon: "generic", host: id + ".example.com", chat: "https://" + id + ".example.com/v1", responses: "", anthropic: "", catalog: "",
models: [{ id: "gpt-5.5", name: "GPT-5.5", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…" + id }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", ...extra,
});
const order = [{ id: "ollama#k", provider: "ollama", name: "Ollama", who: "Ollama", kind: "key", model: "qwen3", routing: "" }];
const left = [{ id: "openai#k", provider: "openai", name: "OpenAI", who: "OpenAI", kind: "key", model: "gpt-5.5", routing: "", fallback: true, unlisted: true, standIn: true }];
function serve(lang, posts) {
let list = [prov("ollama", "Ollama", { fallback: ["openai/gpt-5.5"] }), prov("openai", "OpenAI")];
const providers = () => ({ providers: list, presets: [], excluded: [], gateway: { running: true, window: true } });
const route = {
id: 1, seq: 1, time: ago(1), agent: "codex", model: "ollama/qwen3", provider: "ollama", done: true, status: 503, ms: 900, order, left,
tries: [{ id: "ollama#k", model: "qwen3", start: ago(1), done: true, status: 503, ms: 900 }],
};
return async (request) => {
const url = new URL(request.request().url());
const json = (data) => request.fulfill({ json: data });
if (url.pathname === "/boot.js") return request.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return request.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json(providers());
if (url.pathname === "/api/provider/standin") {
const body = request.request().postDataJSON();
posts.push(body);
list = list.map((p) => p.id === body.id ? { ...p, noStandIn: body.noStandIn } : p);
return json(providers());
}
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 1 }, routes: [route] });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json({ groups: [] });
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 request.fulfill({ body: await fs.readFile(file), contentType });
};
}
const strings = [
"Never a fallback",
"{name} is never a fallback for another model",
"{name} can be a fallback again",
"{who} is left out: it is set never to be a fallback for another model.",
"set never to be another model's fallback",
];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const width of [1100, 420]) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
const open = async (t, view) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts));
await page.goto("http://magpie.test/?view=" + view);
const say = (key, vars = {}) => page.evaluate(([lang, key, vars]) => {
const s = (lang !== "en" && I18N[lang]?.[key]) || key;
return s.replace(/\{(\w+)\}/g, (_, k) => vars[k] ?? `{${k}}`);
}, [lang, key, vars]);
return { page, errors, posts, say };
};
test(`${engine} ${width} ${lang}: a provider's right-click turns Never a fallback on and off`, async (t) => {
const { page, errors, posts, say } = await open(t, "providers");
await page.locator(".row.provider").first().waitFor();
if (lang === "en") {
const missing = await page.evaluate((ks) => ["zh", "zh-TW", "ja", "de"].flatMap((l) => ks.filter((k) => !I18N[l][k]).map((k) => `${l}: ${k}`)), strings);
assert.deepEqual(missing, [], "every string has its translations");
}
const scrollers = () => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => e.scrollTop).concat(document.scrollingElement.scrollTop));
const before = await scrollers();
const row = page.locator('#providers > .row.provider[data-id="openai"]');
const menu = page.locator(".pop.row-menu");
const item = menu.locator(".rm-item", { hasText: await say("Never a fallback") });
await row.locator(".name").click({ button: "right" });
await menu.waitFor();
assert.equal(await item.count(), 1);
assert.notEqual(await item.locator("path").getAttribute("d"), CHECK, "off, no tick");
const box = await menu.boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= width, `the menu fits across ${width}`);
await item.click();
await page.waitForFunction(() => !document.querySelector(".pop.row-menu"));
assert.deepEqual(posts, [{ id: "openai", noStandIn: true }]);
assert.equal(await page.locator("#providers > .row.provider.selected").count(), 0, "the right-click opened the row");
await row.locator(".name").click({ button: "right" });
await menu.waitFor();
assert.equal(await item.locator("path").getAttribute("d"), CHECK, "on, a tick");
await item.click();
await page.waitForFunction(() => !document.querySelector(".pop.row-menu"));
assert.deepEqual(posts, [{ id: "openai", noStandIn: true }, { id: "openai", noStandIn: false }]);
await page.locator('#providers > .row.provider[data-id="ollama"] .name').click({ button: "right" });
await menu.waitFor();
assert.notEqual(await item.locator("path").getAttribute("d"), CHECK, "another provider is off");
await page.keyboard.press("Escape");
assert.deepEqual(await scrollers(), before, "the page doesn't move");
assert.deepEqual(errors, []);
});
test(`${engine} ${width} ${lang}: the Routing page says why the fallback was left out`, async (t) => {
const { page, errors, say } = await open(t, "routing");
const req = page.locator(".rt-req").first();
await req.waitFor();
if (await req.getAttribute("aria-pressed") !== "true") await req.click();
await page.getByText(await say("{who} is left out: it is set never to be a fallback for another model.", { who: "OpenAI" })).first().waitFor();
assert.deepEqual(errors, []);
});
}
}
}