Files
magpie/internal/gui/tests/gateway-card.test.cjs
T
yetone d55881730d gateway: a key can be held to some MCP servers and tools
wakaka on Discord (#help, 11-06) asked for gateway keys limited to some
MCP servers and tools, as keys already are to models (#882).

A key's MCP list (caller-keys.json "mcp") holds entries "server" (every
tool of it) or "server/tool"; "-" alone is no MCP server; an empty list
is every server, as before. A key issued under another is held to its
issuer's list too.

Every MCP route checks it:
- magpie's own servers (web search, vision, image, Magpie Browser, plugin
  tools) through serveMCP: initialize/tools/list/tools/call are refused
  or filtered per server and tool, and /v1/magpie/key-limits names "mcp";
- the Library hub ("magpie"): only the backing servers and tools the key
  may use are listed, and a call by name or by fallback is refused;
- /mcp/<name> and /mcp/run/<name>: the server is refused, tools/list is
  filtered in JSON and SSE replies, tools/call refused; a reply the
  filter can't read (an encoded body) is a 502, never passed through.

GUI: "MCP servers" in the key row's menu opens the app's own picker (no
native select) with All, No MCP server, each server and its tools (GET
/api/caller-keys/mcp lists magpie's own servers and the Library's). A
key held to some shows a badge saying which, that opens the same list;
a free key shows nothing more in its row, on hover either. A hover badge
was tried first: it pushed the row past 560px (gateway-caller-keys) and
squeezed the masked key under a drag at 420px (gateway-key-arrange).
CLI: magpie gateway-key mcp <id> github fs/read_file | none | all.
zh, zh-TW, ja, de strings; docs/reference.md and the gateway-routing and
library subsystem pages.

Not covered: a model's own built-in web search (a vendor tool, not MCP).

GET /api/caller-keys/mcp is named in the CLI parity test's notYet (its
list is what `magpie gateway-key mcp` takes; TestEveryRouteHasACommandOrIsNamed
caught it at the rebased head).

Run on mote (mote-run), at the pushed head:
- go test ./internal/access ./internal/cli ./internal/gui
  ./internal/library ./internal/gateway at a9c40186d (this change on
  2ce44dc28): ok except internal/gui's TestMainWindowCorners/macOS_26_SDK
  (#3949, the same message on macOS 27). After the rebase onto a9667daad
  (no file in common): TestCoreScriptBudget, TestCallerKey*,
  TestEveryRoute*, TestGatewayKey*, TestKeyMCP*, internal/access and
  go vet ./internal/... at d36f89224's tree: ok.
- gateway-caller-keys chromium en reads wider than 560px 4 of 6 runs
  alone on this branch and 4 of 6 on origin/main a9667daad: #3797,
  recorded there.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: clean; darwin, linux (nogui) and windows builds ok; gofmt -l
  clean.
- GUI: gateway-key-mcp.test.cjs in chromium and webkit, widths 1100 and
  420, en/zh/zh-TW/ja/de: 20/20. Every gateway-key*, gateway-keys* and
  i18n* file in both engines: ok except gateway-key-models en (red on
  origin/main ecc26a339 too, #4081/#5233) and i18n-keys "a plugin's words
  are its own" (red on main, #5332).
- The whole GUI suite (both engines, every language) with the hover
  badge: 91 reds in 25 files. Rerun alone on this branch and on
  origin/main 54dc257f1: only gateway-caller-keys (560px sideways),
  gateway-key-readonly, models-fold and models-select-all-api were red
  on the branch alone; the badge moved into the row menu for the first
  two. After it, every gateway-key*, gateway-caller-keys, gateway-card,
  gateway-connect-keys, api-key-theme and i18n* file passes in both
  engines, except i18n-keys "a plugin's words are its own" (red on main,
  #5332, none of the three strings are this change's) and 1 of 20
  models-select-all-api "the click scrolled" (#4389; models-fold is
  #4071). The rest are red on origin/main too and each has an issue:
  account-weight #4644, codex-auto-reset #2360, header-centre #3479,
  images-codex-one #4618, key-replace #4126, menu-input-scroll #3402,
  mobile-web #3952, model-chip-steady #4388, model-copy-id #4621,
  models-works-only #4391, nav-timeout #4787, omarchy #4624,
  page-width-steady #5013, phone-connect-menu #4706/#4707,
  plugin-move-unserved #4392.

Broken by hand, each went red: the serveMCP server gate, call check and
list filter, the own-server list filter and key-limits "mcp"
(TestKeyMCPOwnServer); hubTools, hubServersOf, the hubToolNamed
fallback and hubMCPRun (TestKeyMCPHub); /mcp/run (TestKeyMCPRun); the
/mcp/<name> guard and filter (TestKeyMCPProxy); the GUI's "No MCP
server" being exclusive (gateway-key-mcp).
gateway-key-readonly chromium 420 ja was red with the hover badge (the
sibling run, the whole suite and its rerun; green on origin/main) and
passes with the badge in the row menu.

Not tried: a real Library server through a live gateway, the hub with a
real agent, and running on Windows or Linux (vet and build only).

Reported-by: wakaka
2026-11-07 03:21:57 +08:00

141 lines
9.8 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");
const { fixture } = require("./fixtures/caller-keys.cjs");
// The Gateway page's card (the owner: "一点都不精致、优雅", and the key
// row's copy "很奇怪的位置"): the gateway's mark and state, Share on local
// network switched on the card itself with the addresses it answers on,
// each to copy; a key's copy right beside its masked key, Disable key (or
// Enable key), Rotate key and Remove under its … (wei_VC on X: the tick
// alone wasn't seen as a switch, so a key was removed and added again);
// and Connect folded until it is opened.
const WORDS = {
en: { share: "Share on local network", local: "This computer", lan: "Local network", more: "Key actions", off: "Disable key", on: "Enable key", readOnly: "Make read-only", rotate: "Rotate key", remove: "Remove" },
zh: { share: "局域网共享", local: "本机", lan: "局域网", more: "密钥操作", off: "停用密钥", on: "启用密钥", readOnly: "设为只读", rotate: "轮换密钥", remove: "移除" },
"zh-TW": { share: "區域網共享", local: "本機", lan: "區域網", more: "金鑰操作" },
ja: { share: "ローカルネットワークで共有", local: "このコンピュータ", lan: "ローカルネットワーク", more: "キーの操作" },
de: { share: "Im lokalen Netzwerk freigeben", local: "Dieser Computer", lan: "Lokales Netzwerk", more: "Schlüsselaktionen" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const locale of Object.keys(WORDS)) {
for (const width of [1100, 420]) {
test(`${engine} ${locale} ${width}: the gateway card shares on the network, and a key's copy sits by the key`, async (t) => {
const w = WORDS[locale];
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
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}-${locale}-${width}-gateway-card.png`), fullPage: true });
}
await browser.close();
});
page.setDefaultTimeout(6000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const events = [];
await page.route("**/*", fixture(locale, "dark", events));
await page.goto("http://magpie.test/?view=gateway");
const lanBox = page.locator("#gatewayLan");
await lanBox.locator(".gw-share").waitFor();
// the mark in its tile, the state beside it
assert.equal(await page.locator("#gateway > .gw-mark.on svg .led").count(), 2, "the mark's two lights");
assert.equal(await page.locator("#gateway .url").count(), 0, "no address pill in the status row");
// the state centred on the title's line, not sat low on its baseline
// (the owner: "没有水平对齐")
const off = await page.locator("#gateway .name").evaluate((n) => {
const r = document.createRange();
r.selectNodeContents(n.firstChild);
const a = r.getBoundingClientRect(), b = n.querySelector(".state").getBoundingClientRect();
return Math.abs((a.top + a.bottom) / 2 - (b.top + b.bottom) / 2);
});
assert(off <= 0.25, `the state's middle is ${off}px off the title's`);
// Connect folded by default, its base URL in its head
assert.equal(await page.locator("#foldConnect").getAttribute("aria-expanded"), "false", "Connect starts folded");
assert(await page.locator("#connect").evaluate((c) => c.hidden));
// not shared: the choice says This computer, one address, the keys away
assert.equal((await lanBox.locator(".gw-share .name").textContent()).trim(), w.share);
const opts = lanBox.locator(".segs button");
assert.deepEqual((await opts.allTextContents()).map((s) => s.trim()), [w.local, w.lan]);
assert.equal(await lanBox.locator(".gw-url").count(), 1);
assert.equal((await lanBox.locator(".gw-url code").textContent()).trim(), "http://127.0.0.1:3999");
assert.equal((await lanBox.locator(".gw-url-label").textContent()).trim(), w.local);
assert.equal(await page.locator("#gatewayKeysBlock").isVisible(), false);
// shared from the card, without a scroll: every LAN address, each with a copy
const y = await page.locator("#view-gateway").evaluate((v) => v.scrollTop);
await opts.last().click();
await page.locator("#gatewayKeysBlock").waitFor({ state: "visible" });
await page.waitForFunction(() => document.querySelectorAll("#gatewayLan .gw-url").length === 3);
assert.deepEqual(events.filter((e) => e.action === "lan").map((e) => e.body), [{ on: true }]);
assert.deepEqual((await lanBox.locator(".gw-url code").allTextContents()).map((s) => s.trim()),
["http://127.0.0.1:3999", "http://192.168.1.10:3999", "http://10.0.0.10:3999"]);
assert.deepEqual((await lanBox.locator(".gw-url-label").allTextContents()).map((s) => s.trim()), [w.local, w.lan, ""]);
assert.equal(await lanBox.locator(".gw-url .copy").count(), 3);
assert.equal(y, await page.locator("#view-gateway").evaluate((v) => v.scrollTop), "sharing moved the page");
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}-${locale}-${width}-gateway-card-shared.png`), fullPage: true });
}
await lanBox.locator(".gw-url").nth(1).locator(".copy").click();
await page.waitForFunction(() => document.querySelector("#gatewayLan .copy.done"));
assert(events.some((e) => e.action === "clipboard" && e.body.text === "http://192.168.1.10:3999"));
// a key's row: the copy right after the masked key, the … at the end
await page.waitForFunction(() => document.querySelectorAll("#gatewayKeys .acc[data-key]").length >= 3);
const row = page.locator('#gatewayKeys .acc[data-key="work"]');
const near = await row.evaluate((r) => {
const plan = r.querySelector(".plan"), copy = plan.nextElementSibling, more = r.querySelector(".gw-key-more");
const p = plan.getBoundingClientRect(), c = copy.getBoundingClientRect(), m = more.getBoundingClientRect(), b = r.getBoundingClientRect();
return { isCopy: copy.classList.contains("copy"), gap: c.left - p.right, moreRight: b.right - m.right, last: r.lastElementChild === more, label: more.getAttribute("aria-label") };
});
assert(near.isCopy, "the copy follows the masked key");
assert(near.gap >= 0 && near.gap <= 6, `the copy sits ${near.gap}px from the key`);
assert(near.last && near.moreRight <= 14, "the … ends the row");
assert.equal(near.label, w.more);
assert.equal(await row.locator(".text.quiet").count(), 0, "no Rotate or Remove words in the row");
await row.locator(".gw-key-more").click();
const menu = page.locator(".row-menu");
await menu.waitFor();
const items = (await menu.getByRole("menuitem").allTextContents()).map((s) => s.trim());
assert.equal(items.length, 5);
if (w.rotate) assert.deepEqual(items.filter((s) => !/MCP/.test(s)), [w.off, w.readOnly, w.rotate, w.remove]);
assert.deepEqual(items, await page.evaluate(() => [t("Disable key"), t("Make read-only"), t("MCP servers"), t("Rotate key"), t("Remove")]));
// off from the menu, then on again: the key stays, only its switch moves
await menu.getByRole("menuitem").first().click();
await menu.waitFor({ state: "detached" });
await page.locator('#gatewayKeys .acc.off[data-key="work"]').waitFor();
await row.locator(".gw-key-more").click();
await menu.waitFor();
const again = (await menu.getByRole("menuitem").allTextContents()).map((s) => s.trim());
if (w.on) assert.equal(again[0], w.on);
assert.equal(again[0], await page.evaluate(() => t("Enable key")));
await menu.getByRole("menuitem").first().click();
await page.locator('#gatewayKeys .acc.in-use[data-key="work"]').waitFor();
assert.deepEqual(events.filter((e) => /^(on|off|remove)-key$/.test(e.action)).map((e) => [e.action, e.body.key]), [["off-key", "work"], ["on-key", "work"]]);
// nothing runs out of the page or a card, no coloured left border
const over = await page.evaluate(() => [...document.querySelectorAll("#gateway, #gatewayLan *, #gatewayKeys .acc")]
.filter((e) => e.scrollWidth > e.clientWidth + 1 && !e.matches("code, .gw-url-label, .plan, .rename, .n")).map((e) => e.className || e.tagName));
assert.deepEqual(over, [], "a row overflows");
assert(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth + 1), "the page scrolls sideways");
const borders = await page.evaluate(() => [...document.querySelectorAll(".gwcard *")].filter((e) => { const s = getComputedStyle(e); return parseFloat(s.borderLeftWidth) > 1 && s.borderLeftStyle !== "none"; }).map((e) => e.className));
assert.deepEqual(borders, []);
// back to This computer: one address again, the keys away
await opts.first().click();
await page.locator("#gatewayKeysBlock").waitFor({ state: "hidden" });
await page.waitForFunction(() => document.querySelectorAll("#gatewayLan .gw-url").length === 1);
assert.deepEqual(errors, []);
});
}
}
}