Files
magpie/internal/gui/tests/library-all.test.cjs
T
yetone 22358d5d6e library: a project gets its own MCP servers, agent by agent (#500) — the library's servers could only be given to agents user-wide, while its skills could already go into a project. The MCP tab now lists the same projects as Skills under "In projects" (add one by its folder, or the folder picker in the app), and a project's card opens to each server with chips for the agents that read a project's own servers: Claude Code .mcp.json, Codex .codex/config.toml, Gemini CLI .gemini/settings.json, Cursor .cursor/mcp.json, OpenCode opencode.json (opencode.jsonc when that is the project's file), each as its docs give it. Other agents have no chip and are named under the card; the project files of Copilot, Crush, Droid, Kimi and the rest weren't confirmed, so none is written. The server is written with the same encoders and edit helpers as the user-wide files, so the rest of a file (its comments, other keys, the team's own servers) is kept; magpie records what it wrote in the project (Project.Servers, Wrote, MadeFiles) and only ever takes that away again, a same-named server that isn't magpie's is left as it is and named as a problem, as is an SSE server for Codex. A file magpie made is listed in the project's .gitignore between magpie's lines (a server's env and headers can hold keys) and removed with its folders once nothing of magpie's is left in it, unless the user wrote something else into it; a file that was there already is never ignored or removed. Renaming a library server renames it in its projects, removing it takes it out of them, and removing a project takes out its servers as well as its skills. A project whose MCP file is an agent's user-wide file (the home folder) is refused, as for skills. The chips of a project row (servers and skills) now light at once and send one write at a time, the last click winning: two quick clicks posted the first's stale list before. Claude Code still asks before it starts a project's servers and Codex reads .codex/config.toml only in a trusted project; the card says so. library-all.test.cjs gets a 800px-high window: the MCP tab's new "In projects" made it overflow 700 by a pixel, and Chromium's scroll anchoring then moved it when the problems card came in above. TestProjectServers (merge into a user's .mcp.json keeping its comment, key and server; Codex TOML; .gitignore; rename; removal down to the made folders; RemoveProject keeping the user's own), TestProjectServerNotOurs, TestProjectServerFileKept, TestProjectServerChecks and TestProjectServerOpenCodeJSONC run in a temp HOME; project-servers.test.cjs (en, zh; chromium and webkit) checks the chips, the greyed Codex chip for SSE, two clicks before magpie answers, and that nothing scrolls. No real agent was started on a written project. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass; the library's Playwright tests pass in webkit, and in chromium except list-sort, shared-skills and import-all-skills, which fail the same way at HEAD.
2026-10-02 12:37:07 +08:00

169 lines
9.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Run with Node's test runner and Playwright on the module path; see README.md.
// A server's or a skill's All chip (Discord: MCP 服务器 SKILL 都得一个个选):
// one click gives the item to every agent shown that can take it — not one
// whose chip is greyed out (an SSE server for an agent without SSE), not one
// hidden on the Agents page, which keeps what it has — in a single write;
// an agent that couldn't be given it is named in the toast with how many
// have it; a second click takes it from all. The click moves nothing. In English and Chinese. 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 HOME = "/Users/loosheng";
const agent = (id, name, icon, more = {}) => ({ id, name, icon, skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json`, ...more });
const base = () => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
// Pi has no MCP file, Droid no skills folder; Codex and Droid no SSE
agents: [
agent("claude", "Claude Code", "claudecode-color"),
agent("codex", "Codex", "codex-color", { noSSE: true }),
agent("zcode", "ZCode", "zcode"),
agent("pi", "Pi", "pi", { mcp: "" }), // skills only
agent("gemini", "Gemini CLI", "gemini-color"), // hidden on the Agents page
agent("droid", "Droid", "factory", { noSSE: true, skills: "" }),
],
instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [],
servers: [
{ name: "files", transport: "stdio", command: "npx", args: ["files-mcp"], agents: ["claude", "gemini"] },
{ name: "events", transport: "sse", url: "https://example.com/sse", agents: [] },
],
skills: [{ name: "pdf", kind: "folder", description: "d", source: `${HOME}/skills/pdf`, agents: ["codex"] }],
});
function server(lang, posts, fail) {
let lib = base();
return async (route) => {
const req = route.request(), url = new URL(req.url());
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 route.fulfill({ json: { agents: [], profiles: [], settings: { lang, agentsHidden: ["gemini"] } } });
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
if (url.pathname === "/api/library") return route.fulfill({ json: lib });
const m = /^\/api\/library\/(servers|skills)\/agents$/.exec(url.pathname);
if (m) {
const body = req.postDataJSON();
posts.push({ path: m[1], ...body });
lib = structuredClone(lib);
const item = lib[m[1]].find((x) => x.name === body.name);
item.agents = body.agents;
const what = (m[1] === "servers" ? "mcp:" : "skill:") + body.name;
const problems = fail && body.agents.includes(fail.agent) ? [{ agent: fail.agent, what, error: fail.error }] : [];
item.problems = Object.fromEntries(problems.map((p) => [p.agent, p.error]));
return route.fulfill({ json: { ...lib, problems, result: { changed: body.agents.filter((a) => !problems.some((p) => p.agent === a)), problems } } });
}
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
if (url.pathname.startsWith("/api/")) return route.fulfill({ 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 words = {
en: {
all: "All", on: "files is on for all 4 agents", off: "files is off for every agent",
partial: "events is on for 1 of 2 agents — ZCode: config.json: permission denied",
skill: "pdf is on for all 4 agents",
},
zh: {
all: "全部", on: "已为全部 4 个 Agent 启用 files", off: "已从所有 Agent 中移除 files",
partial: "events 已在 2 个 Agent 中的 1 个启用 — ZCode:config.json: permission denied",
skill: "已为全部 4 个 Agent 启用 pdf",
},
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a server's or skill's All chip", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const errors = [];
t.after(async () => {
if (errors.length) console.log(errors);
await browser.close();
});
const open = async (lang, tab, posts, fail) => {
const ctx = await browser.newContext({ viewport: { width: 980, height: 800 } }); // the MCP tab fits, its "In projects" too
await ctx.addInitScript((tab) => { try { localStorage.setItem("magpie.libTab", tab); } catch {} }, tab);
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("http://magpie.test/**", server(lang, posts, fail));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
await page.locator("#view-library .lib-row").first().waitFor();
return page;
};
const row = (page, name) => page.locator("#view-library .lib-row").filter({ has: page.locator(".name", { hasText: new RegExp("^" + name + "$") }) });
const toast = (page, text) => page.waitForFunction((text) => document.querySelector("#status").textContent === text, text).catch(async () => {
assert.equal(await page.locator("#status").textContent(), text);
});
// clicked where it is, and the page not moved by it
const click = async (page, loc) => {
const top = await page.evaluate(() => document.querySelector("#view-library").scrollTop);
await loc.click();
assert.equal(await page.evaluate(() => document.querySelector("#view-library").scrollTop), top);
};
const lit = (r) => r.locator(".lib-ag[data-agent]").evaluateAll((cs) => cs.filter((c) => c.getAttribute("aria-pressed") === "true").map((c) => c.dataset.agent));
for (const lang of ["en", "zh"]) {
await t.test(lang + ": All gives a server to every agent that can take it, and takes it from all", async () => {
const posts = [];
const page = await open(lang, "mcp", posts);
const r = row(page, "files");
const all = r.locator(".lib-ag.all");
assert.equal(await all.textContent(), words[lang].all);
assert.equal(await all.getAttribute("aria-pressed"), "false");
// it comes first, and no chip covers it
assert.equal(await r.locator(".lib-agents > :first-child").evaluate((c) => c.classList.contains("all")), true);
const [a, next] = await r.locator(".lib-agents > .lib-ag").evaluateAll((cs) => cs.slice(0, 2).map((c) => c.getBoundingClientRect().toJSON()));
assert.ok(next.left >= a.right, `the first chip overlaps All: ${a.right} > ${next.left}`);
await click(page, all);
// Gemini CLI, hidden, keeps it; Pi has no MCP
await toast(page, words[lang].on);
assert.deepEqual(posts.map((p) => [p.path, p.name, [...p.agents].sort()]), [["servers", "files", ["claude", "codex", "droid", "gemini", "zcode"]]]);
assert.deepEqual(await lit(r), ["claude", "codex", "zcode", "droid"]);
assert.equal(await all.getAttribute("aria-pressed"), "true");
await click(page, all);
assert.equal(await all.getAttribute("aria-pressed"), "false");
await toast(page, words[lang].off);
assert.deepEqual(posts[1].agents, ["gemini"]);
assert.deepEqual(await lit(r), []);
await page.close();
});
await t.test(lang + ": an SSE server's All leaves out an agent without SSE, and names one that couldn't take it", async () => {
const posts = [];
const page = await open(lang, "mcp", posts, { agent: "zcode", error: "config.json: permission denied" });
const r = row(page, "events");
await click(page, r.locator(".lib-ag.all"));
await toast(page, words[lang].partial);
assert.deepEqual([...posts[0].agents].sort(), ["claude", "zcode"]);
assert.equal(await r.locator('.lib-ag[data-agent="zcode"]').evaluate((c) => c.classList.contains("warn")), true);
assert.equal(await r.locator('.lib-ag[data-agent="codex"]').evaluate((c) => c.disabled && c.getAttribute("aria-pressed") === "false"), true);
await page.close();
});
await t.test(lang + ": a skill's All gives it to every agent with a skills folder", async () => {
const posts = [];
const page = await open(lang, "skills", posts);
const r = row(page, "pdf");
await click(page, r.locator(".lib-ag.all"));
await toast(page, words[lang].skill);
assert.deepEqual(posts.map((p) => [p.path, p.name, [...p.agents].sort()]), [["skills", "pdf", ["claude", "codex", "pi", "zcode"]]]);
// the row's own click (open the SKILL.md) wasn't set off
assert.equal(await page.locator("#modal").isHidden(), true);
await page.close();
});
}
assert.deepEqual(errors, []);
});
}