Files
magpie/internal/gui/tests/this-device.test.cjs
T
yetone 05cadcafd4 sync: a provider can stay only on this device (treydtw on X)
Providers sync between computers (WebDAV, S3, GitHub), so a model served
from one machine's localhost reached the others, where it can't be
reached. A provider now has "Only on this device": sync neither sends it
out nor lets a copy from another computer replace or delete it.

Provider.ThisDevice is set from the provider row's right-click menu
(Only on this device, a check when on) or `magpie provider this-device
<id> yes|no`, over POST /api/provider/thisdevice. davsync's collect drops
those providers and their order entries (provider.SyncedOnly); Mirror
skips an incoming copy of one and keeps the local ones; Restore keeps a
local mark. A normal editor save keeps the mark. File backups still carry
the provider with its mark.

Default is off for every provider, localhost included. A 127.0.0.1
provider is also what another computer runs for its own copy of the same
local server, and default-on would remove those copies on their next
sync; a LAN address is reachable from the other computers. Turning it on
at one computer removes the synced copy at the others on their next sync.
docs/subsystems/sync-backup.md says so.

The menu item gives no toast: its check mark is the answer, which also
keeps the core script budget at +151 bytes (1,263,700 to
1,263,851).

Run, on mica: new davsync TestProviderOnThisDeviceStaysOnIt (two
computers over a fake DAV) and this-device.test.cjs (chromium and
webkit, en zh zh-TW ja de, widths 1100 and 420); provider-find updated
for the new menu entry; davsync, provider, backup, cli, gui Go packages
ok except TestCoreScriptBudget, then fixed; vet on darwin, windows and
linux nogui clean. Broken by hand: SyncedOnly made a no-op turns the
davsync test red ("a sends its own model out"), and the Mirror skip
removed turns it red ("b after a's model synced"). GUI files that fail
in a loaded run (claude-quota-onboarding, provider-find, skill-fold-all,
usage-agents-hide, usage-cards-hide, usage-hidden-way-back) were run
alone on origin/main 5e933e153: usage-hidden-way-back (#6295) and
usage-agents-hide (#3414) are red there too, the rest pass; this branch
gives the same result. gui-de and gui-ja "has every zh string" are red on
5e933e153 as well.

Not tried: a real WebDAV/S3/GitHub server between two real computers;
the CLI command has no test of its own.
2026-11-12 19:31:11 +08:00

111 lines
6.7 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// treydtw on X: a local model that exists only on this computer must not be
// synced to the others. A provider row's right-click has Only on this
// device: it posts provider/thisdevice, and once on the item shows a tick
// and posts it off again. 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/thisdevice") {
const body = request.request().postDataJSON();
posts.push(body);
list = list.map((p) => p.id === body.id ? { ...p, thisDevice: body.thisDevice } : 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 = [
"Only on this device",
];
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"]) {
test(`${engine} ${width} ${lang}: a provider's right-click turns Only on this device on and off`, async (t) => {
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=providers");
const say = (key) => page.evaluate(([lang, key]) => (lang !== "en" && I18N[lang]?.[key]) || key, [lang, key]);
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 row = page.locator('#providers > .row.provider[data-id="ollama"]');
const menu = page.locator(".pop.row-menu");
const item = menu.locator(".rm-item", { hasText: await say("Only on this device") });
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: "ollama", thisDevice: true }]);
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: "ollama", thisDevice: true }, { id: "ollama", thisDevice: false }]);
await page.locator('#providers > .row.provider[data-id="openai"] .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(errors, []);
});
}
}
}