diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 07fda2c11..9b2a80eaf 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -47,6 +47,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. - An MCP OAuth sign-in canceled or timed out before its callback commits never saves a late token or changes an existing sign-in. The callback's write and the flow's ending share a lock (`flow.keep` in [`mcpauth.go`](../../internal/mcpauth/mcpauth.go)); if the write wins first, it completes and tells the agents before saying done. A cancellation is not a sign-out of credentials already committed. - A server an agent can't reach is not written there, and `mcpFile.supports` says why. For example, Claude Desktop takes no remote server, and Codex, Goose, dsh, Grok, Command Code and Zed take no SSE. - A server's headers (remote) or environment (command) can name a variable as `${NAME}` (#1250). `library.json` keeps the placeholder, and `refsOf` gives each MCP format the agent's own syntax, with the agent's source cited beside it: `${NAME}` for most, `{env:NAME}` for OpenCode and MiMo, `${env:NAME}` for Cursor, and Codex's own keys (`bearer_token_env_var`, `env_http_headers`, `env_vars`). Goose gets `${NAME}` plus `env_keys`. dsh (DeepSeek Harness) gets a `!!js` expression it evaluates as it loads the server (#1435): a whole `${NAME}` is `!!js process.env.NAME`, and a value mixing text and variables is the text as JSON string literals joined with `(process.env.NAME ?? "")`, so the user's text is never run as code and an unset variable inside it is empty. A whole variable that isn't set makes dsh leave the server out as invalid. magpie reads only those forms back as `${NAME}`; any other `!!js` keeps the entry the user's. An agent with no syntax (Claude Desktop, Antigravity, Kimi, Cline, ZCode, Zed, Devin, Alma, Pi with pi-mcp-extension) is never written the value: `refsProblem` makes `supports` refuse the server, a magpie entry already there is taken out, and `AgentView.NoEnvRefs` greys its chip with the reason. Codex and Goose's extra keys are magpie's only while the server names a variable there (`refKeys`), so the user's own `env_vars` or `env_keys` are kept. `CheckServers` expands the variable from magpie's own environment, and one that isn't set is `novar`, naming it. The page paints that as not checked (a ring, `lib-health unknown`), not red: it says nothing of the server, which the agent may start with the variable set, as Codex does its host-only `codex_app` (#2308). It starts a command server in home, with `PWD` set to it (not on Windows), as an agent started from home would, never in magpie's own working folder: a magpie started from the Windows Start menu has `C:\Windows\system32`, where a server that writes into `.` exits before it answers (#1727, `TestCheckStdio`). +- A command server is checked where the agents given it run (loong on Discord: a WSL program, given only to agents in WSL, was checked on Windows and "exited (1)"). `checkSides` reads each agent id's `@wsl:`: with none, or off Windows, or a Windows path for the command (`windowsPath`, magpie's own image server among them), or Settings' Detect agents in WSL off, it is this computer as before. Otherwise each distro is a side, after this computer when an agent here has it too. In a distro the command is found as the agents' shell finds it (`wslrun.In`: a login shell, then an interactive one for nvm's node, the probe `wslrun.Find` uses) and started through `wslrun.Tool.Command` (`wsl.exe -d D --exec /usr/bin/env PATH=… args`), its env passed by `WSLENV`. A distro that isn't running is never started for a check: it is `wsldown`, naming the distro, painted as not checked like `novar`; beside a side that was checked it is left out. `ServerHealth.Checked` lists where it started, `""` for this computer; the first failure ends the check and is the last place's, which the row names (" · WSL Ubuntu") and the tooltip says (`TestCheckWSLOnlyServerInItsDistro`, `TestCheckWindowsServerHere`, `TestCheckMixedServerEachSide`, `library-mcp-health-wsl.test.cjs`). Agents moved between sides is a check anew (`healthKey`, both sides). In a distro the command runs in the folder wsl.exe gives it (the Windows home under `/mnt`), not the Linux home. - A server's tools turned off on the page (nf1qaz2w on Discord) are kept by their names as the server gives them, in `Server.DisabledTools`, and written only to the agents that read a setting for it (`toolsOffOf`), each in its own form, checked against its source: - Codex: `disabled_tools` in the server's table in config.toml (`codex-rs/config/src/mcp_types.rs`, applied by `ToolFilter` in `codex-rs/codex-mcp/src/tools.rs`, openai/codex cc7ba336). - Gemini CLI: `excludeTools` in the server's entry (`docs/tools/mcp-server.md`; `mcp-client.ts` drops a tool by its own name, google-gemini/gemini-cli 9b6e0265). @@ -75,7 +76,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. ## Verification ```sh -go test -tags nogui ./internal/library -run 'TestGit|TestInstallFromGitRepo|TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestServer|TestImportServer|TestCheck|TestInstructions|TestInstructionsSetLinkedToAgentsFile|TestInstructionSets|TestTakesAlma|TestAlma|TestLinkedSet|TestLinkRefused|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks|TestSubagent|TestCheckRenewsMagpiesSignIn|TestCheckSaysSignInRanOut|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut' +go test -tags nogui ./internal/library -run 'TestGit|TestInstallFromGitRepo|TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestServer|TestImportServer|TestCheck|TestInstructions|TestInstructionsSetLinkedToAgentsFile|TestInstructionSets|TestTakesAlma|TestAlma|TestLinkedSet|TestLinkRefused|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks|TestSubagent|TestCheckRenewsMagpiesSignIn|TestCheckWSLOnlyServerInItsDistro|TestCheckWindowsServerHere|TestCheckMixedServerEachSide|TestCheckSaysSignInRanOut|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut' go test -race ./internal/mcpauth go test -tags nogui ./internal/library node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-alma-profile.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-pick-remove.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/skill-git-source.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/found-skill-pick-remove.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs internal/gui/tests/library-hooks.test.cjs internal/gui/tests/library-subagents.test.cjs internal/gui/tests/library-mcp-health.test.cjs internal/gui/tests/mcp-signin-health.test.cjs internal/gui/tests/mcp-signin.test.cjs internal/gui/tests/mcp-editor-cancel.test.cjs internal/gui/tests/mcp-oauth-app.test.cjs internal/gui/tests/library-ime-scroll.test.cjs diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index fa3ad6ac5..d26c77041 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -1580,7 +1580,10 @@ magpie.plugin("library", (ctx) => { // each says it does (nf1qaz2w on Discord), with Check again under them. const health = new Map(); // name → { key: the server as checked, h: what was found, null while checking } const toolsOpen = new Set(); // the servers whose tools are shown - const healthKey = (s) => JSON.stringify([s.transport, s.command, s.args, s.env, s.url, s.headers, s.signIn]); + // a command is started where its agents run, this computer or a WSL + // distro (mcp_check_wsl.go): agents moved between them is a check anew + const healthKey = (s) => JSON.stringify([s.transport, s.command, s.args, s.env, s.url, s.headers, s.signIn, + s.transport === "stdio" ? [...new Set((s.agents || []).map((a) => a.split("@wsl:")[1] || ""))].sort() : null]); const toolList = (name) => { const h = health.get(name)?.h; return h?.state === "ok" ? h.toolList || [] : []; }; // whether an agent the page shows gets the server, here or in a project // magpie keeps whose folder is there. The library keeps every agent it @@ -1754,6 +1757,9 @@ magpie.plugin("library", (ctx) => { // a ${NAME} magpie's own environment hasn't; an agent started from a // shell that has it still gets it case "novar": return [t("{names} not set", { names: h.detail }), t("magpie can't check it: {names} isn't set where magpie runs. An agent started where it is set still gets it", { names: h.detail })]; + // the agents given it run in a WSL distro that isn't running, which + // a check doesn't start: nothing is known of the server + case "wsldown": return [t("WSL {distro} not running", { distro: h.detail }), t("magpie can't check it: the agents given it run in WSL {distro}, which isn't running, and a check doesn't start it", { distro: h.detail })]; default: return [t("couldn't check"), more(t("magpie couldn't check it"))]; } } @@ -1781,12 +1787,20 @@ magpie.plugin("library", (ctx) => { b.title = t("Connecting to it to list its tools"); continue; } - const [text, tip] = healthWords(e.h, lib.servers.find((s) => s.name === b.dataset.server)); + let [text, tip] = healthWords(e.h, lib.servers.find((s) => s.name === b.dataset.server)); + // a command agents in WSL start is checked where they run: the tip + // says where, and a failure which place it was (loong on Discord) + const places = (e.h.checked || []).map((p) => (p ? "WSL " + p : "Windows")); + if (places.length && e.h.state === "ok") tip += "\n" + t("Checked in: {places}", { places: places.join(", ") }); + else if (places.length) { + text += " · " + places[places.length - 1]; + tip += "\n" + t("Failed in: {place}", { place: places[places.length - 1] }); + } // a check magpie couldn't make for want of a variable only the // agent's own launch sets says nothing of the server, so it isn't // painted as broken (#2308, ASD-max: Codex's host-only codex_app, // whose pipe Codex itself hands it) - b.className = "lib-health " + (e.h.state === "ok" ? "ok" : e.h.state === "auth" ? "auth" : e.h.why === "novar" ? "unknown" : "err"); + b.className = "lib-health " + (e.h.state === "ok" ? "ok" : e.h.state === "auth" ? "auth" : e.h.why === "novar" || e.h.why === "wsldown" ? "unknown" : "err"); b.replaceChildren(el("span", "", text)); if (toolList(b.dataset.server).length) { const open = toolsOpen.has(b.dataset.server); diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 2e6c018d0..747fd81d1 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -233,6 +233,10 @@ magpie.strings({ "A value can name a variable, as {ref}: each agent is given it in its own way, so the token stays out of its settings": "值可以引用环境变量,写作 {ref}:每个智能体按自己的语法读取它,令牌不会写进它的设置", "{names} not set": "{names} 未设置", "magpie can't check it: {names} isn't set where magpie runs. An agent started where it is set still gets it": "magpie 无法检查:magpie 运行的环境里没有设置 {names}。在设置了它的环境中启动的智能体仍会拿到它", + "WSL {distro} not running": "WSL {distro} 未运行", + "magpie can't check it: the agents given it run in WSL {distro}, which isn't running, and a check doesn't start it": "magpie 无法检查:用它的智能体运行在 WSL {distro} 里,而它没有在运行,检查不会去启动它", + "Checked in: {places}": "检查位置:{places}", + "Failed in: {place}": "失败位置:{place}", "{agent} runs only a command from its settings — add a remote server in its Connectors instead": "{agent} 的配置文件只支持命令启动的服务器 — 远程服务器请在它的「连接器」里添加", "Add a server once and switch it on for the agents that should have it — magpie writes it into each one's config in the shape that agent reads.": "服务器只需添加一次,再为需要的 Agent 开启,magpie 会按各 Agent 的格式写入其配置。", "+ Add a server": "+ 添加服务器", @@ -843,6 +847,10 @@ magpie.strings({ "A value can name a variable, as {ref}: each agent is given it in its own way, so the token stays out of its settings": "值可以引用環境變數,寫作 {ref}:每個智慧體依自己的語法讀取它,權杖不會寫進它的設定", "{names} not set": "{names} 未設定", "magpie can't check it: {names} isn't set where magpie runs. An agent started where it is set still gets it": "magpie 無法檢查:magpie 執行的環境裡沒有設定 {names}。在設定了它的環境中啟動的智慧體仍會拿到它", + "WSL {distro} not running": "WSL {distro} 未執行", + "magpie can't check it: the agents given it run in WSL {distro}, which isn't running, and a check doesn't start it": "magpie 無法檢查:使用它的智慧體執行在 WSL {distro} 裡,而它沒有在執行,檢查不會去啟動它", + "Checked in: {places}": "檢查位置:{places}", + "Failed in: {place}": "失敗位置:{place}", "{agent} runs only a command from its settings — add a remote server in its Connectors instead": "{agent} 的設定檔只支援命令啟動的伺服器 — 遠端伺服器請在它的「聯結器」裡新增", "Add a server once and switch it on for the agents that should have it — magpie writes it into each one's config in the shape that agent reads.": "伺服器只需新增一次,再為需要的 Agent 開啟,magpie 會按各 Agent 的格式寫入其設定。", "+ Add a server": "+ 新增伺服器", @@ -1448,6 +1456,10 @@ magpie.strings({ "A value can name a variable, as {ref}: each agent is given it in its own way, so the token stays out of its settings": "値には {ref} の形で環境変数を指定できます。各エージェントにはそれぞれの書式で渡されるため、トークンは設定に書き込まれません", "{names} not set": "{names} が未設定", "magpie can't check it: {names} isn't set where magpie runs. An agent started where it is set still gets it": "magpie はチェックできません: magpie の実行環境に {names} が設定されていません。設定済みの環境で起動したエージェントには渡されます", + "WSL {distro} not running": "WSL {distro} は停止中", + "magpie can't check it: the agents given it run in WSL {distro}, which isn't running, and a check doesn't start it": "magpie はチェックできません: これを使うエージェントは WSL {distro} で動きますが、{distro} は起動していません。チェックのために起動はしません", + "Checked in: {places}": "チェックした場所: {places}", + "Failed in: {place}": "失敗した場所: {place}", "{agent} runs only a command from its settings — add a remote server in its Connectors instead": "{agent} は設定ファイルからコマンドのみ実行できます — リモートサーバーは代わりに「コネクタ」で追加してください", "Add a server once and switch it on for the agents that should have it — magpie writes it into each one's config in the shape that agent reads.": "サーバーは一度追加し、必要なエージェントでオンにするだけです — magpie が各エージェントの読める形式で設定に書き込みます。", "+ Add a server": "+ サーバーを追加", @@ -2056,6 +2068,10 @@ magpie.strings({ "A value can name a variable, as {ref}: each agent is given it in its own way, so the token stays out of its settings": "Ein Wert kann eine Umgebungsvariable nennen, als {ref}: Jeder Agent bekommt sie in seiner eigenen Schreibweise, sodass das Token nicht in seinen Einstellungen steht", "{names} not set": "{names} nicht gesetzt", "magpie can't check it: {names} isn't set where magpie runs. An agent started where it is set still gets it": "magpie kann ihn nicht prüfen: {names} ist dort, wo magpie läuft, nicht gesetzt. Ein Agent, der dort startet, wo sie gesetzt ist, bekommt sie trotzdem", + "WSL {distro} not running": "WSL {distro} läuft nicht", + "magpie can't check it: the agents given it run in WSL {distro}, which isn't running, and a check doesn't start it": "magpie kann ihn nicht prüfen: Die Agenten, die ihn bekommen, laufen in WSL {distro}, das nicht läuft, und eine Prüfung startet es nicht", + "Checked in: {places}": "Geprüft in: {places}", + "Failed in: {place}": "Fehlgeschlagen in: {place}", "{agent} runs only a command from its settings — add a remote server in its Connectors instead": "{agent} startet aus seinen Einstellungen nur Befehle – fügen Sie einen Remote-Server stattdessen unter Connectors hinzu", "Add a server once and switch it on for the agents that should have it — magpie writes it into each one's config in the shape that agent reads.": "Fügen Sie einen Server einmal hinzu und schalten Sie ihn für die Agenten ein, die ihn haben sollen – magpie schreibt ihn in jede Konfiguration in der Form, die der jeweilige Agent liest.", "+ Add a server": "+ Server hinzufügen", diff --git a/internal/gui/tests/library-mcp-health-wsl.test.cjs b/internal/gui/tests/library-mcp-health-wsl.test.cjs new file mode 100644 index 000000000..86e1b4fb2 --- /dev/null +++ b/internal/gui/tests/library-mcp-health-wsl.test.cjs @@ -0,0 +1,116 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A command that agents in WSL start is checked where they run, in their +// distro (loong on Discord: a WSL program checked on Windows "exited (1)" +// while his agents started it fine). The row's tooltip says where it was +// checked; a failure names the place that failed on the row itself; a +// distro that isn't running, which a check doesn't start, is said to be +// unknown, not broken. In every language, in both engines. 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 = "C:\\Users\\loong"; +const WSL = "claude@wsl:Ubuntu"; +const agent = (id, name) => ({ id, name, icon: "claudecode-color", skills: `${HOME}\\.claude\\skills`, mcp: `${HOME}\\.claude.json` }); +const fixture = () => ({ + dir: `${HOME}\\.magpie\\library`, backups: `${HOME}\\.magpie\\backups`, home: HOME, + agents: [agent("claude", "Claude Code"), { ...agent(WSL, "Claude Code (Ubuntu)"), wsl: true }, + { ...agent("claude@wsl:Arch", "Claude Code (Arch)"), wsl: true }], + instructions: { agents: [], sets: [] }, foundServers: [], foundSkills: [], skills: [], projects: [], + servers: [ + { name: "inwsl", transport: "stdio", command: "node", args: ["/home/loong/tools/xxx.js"], agents: [WSL] }, + { name: "both", transport: "stdio", command: "npx", args: ["x-mcp"], agents: ["claude", WSL] }, + { name: "down", transport: "stdio", command: "node", args: ["/home/loong/tools/y.js"], agents: ["claude@wsl:Arch"] }, + { name: "here", transport: "stdio", command: "npx", args: ["h-mcp"], agents: ["claude"] }, + ], +}); +const found = { + inwsl: { state: "ok", tools: 2, checked: ["Ubuntu"] }, + both: { state: "error", why: "exited", code: 1, detail: "Node.js v24.9.0", checked: ["", "Ubuntu"] }, + down: { state: "error", why: "wsldown", detail: "Arch" }, + here: { state: "ok", tools: 3 }, +}; + +function server(lang) { + 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 } } }); + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/library") return route.fulfill({ json: fixture() }); + if (url.pathname === "/api/library/mcp/check") { + const names = req.postDataJSON().names || Object.keys(found); + return route.fulfill({ json: { servers: Object.fromEntries(names.map((n) => [n, found[n]])) } }); + } + 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: { checked: "Checked in: ", failed: "Failed in: ", down: "WSL Arch not running", downTip: "magpie can't check it: the agents given it run in WSL Arch, which isn't running, and a check doesn't start it" }, + zh: { checked: "检查位置:", failed: "失败位置:", down: "WSL Arch 未运行", downTip: "magpie 无法检查:用它的智能体运行在 WSL Arch 里,而它没有在运行,检查不会去启动它" }, + "zh-TW": { checked: "檢查位置:", failed: "失敗位置:", down: "WSL Arch 未執行", downTip: "magpie 無法檢查:使用它的智慧體執行在 WSL Arch 裡,而它沒有在執行,檢查不會去啟動它" }, + ja: { checked: "チェックした場所: ", failed: "失敗した場所: ", down: "WSL Arch は停止中", downTip: "magpie はチェックできません: これを使うエージェントは WSL Arch で動きますが、Arch は起動していません。チェックのために起動はしません" }, + de: { checked: "Geprüft in: ", failed: "Fehlgeschlagen in: ", down: "WSL Arch läuft nicht", downTip: "magpie kann ihn nicht prüfen: Die Agenten, die ihn bekommen, laufen in WSL Arch, das nicht läuft, und eine Prüfung startet es nicht" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a server agents in WSL start says where it was checked", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + const errors = []; + t.after(async () => { + if (errors.length) console.log(errors); + await browser.close(); + }); + for (const [lang, w] of Object.entries(words)) { + await t.test(lang, async () => { + const ctx = await browser.newContext({ viewport: { width: 980, height: 500 } }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "mcp"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("http://magpie.test/**", server(lang)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + await page.locator("#view-library .lib-body:not(.lib-skel) .lib-row").first().waitFor(); + const status = (name) => page.locator(`#view-library .lib-health[data-server="${name}"]`); + await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-health:not(.checking):not(.idle)").length >= 3); + const tip = async (n) => (await status(n).getAttribute("title")).split("\n"); + + // checked in its distro: ok, and the tooltip says where + assert.equal(await status("inwsl").evaluate((b) => b.classList.contains("ok")), true); + assert.ok((await tip("inwsl")).includes(w.checked + "WSL Ubuntu"), (await tip("inwsl")).join(" | ")); + // failed in WSL after this computer: the row says which place + assert.match(await status("both").textContent(), / · WSL Ubuntu$/); + assert.equal(await status("both").evaluate((b) => b.classList.contains("err")), true); + assert.ok((await tip("both")).includes(w.failed + "WSL Ubuntu"), (await tip("both")).join(" | ")); + assert.ok((await tip("both")).includes("Node.js v24.9.0")); + // a stopped distro: not checked, and not painted as broken + assert.equal(await status("down").textContent(), w.down); + assert.equal(await status("down").evaluate((b) => b.classList.contains("unknown")), true); + assert.equal((await tip("down"))[0], w.downTip); + // a server only this computer's agents have says nothing of where + const here = await tip("here"); + assert.ok(!here.some((l) => l.startsWith(w.checked) || l.startsWith(w.failed)), here.join(" | ")); + assert.doesNotMatch(await status("here").textContent(), / · /); + // one line high still + const box = await status("both").boundingBox(); + assert.ok(box.height <= 18, "status wraps: " + box.height); + await ctx.close(); + }); + } + assert.deepEqual(errors, []); + }); +} diff --git a/internal/library/mcp_check.go b/internal/library/mcp_check.go index 3f2a3edc4..a99e4c33c 100644 --- a/internal/library/mcp_check.go +++ b/internal/library/mcp_check.go @@ -14,6 +14,7 @@ import ( "os" "os/exec" "runtime" + "slices" "strings" "sync" "time" @@ -22,6 +23,7 @@ import ( "github.com/yetone/magpie/internal/mcpauth" "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/proc" + "github.com/yetone/magpie/internal/wslrun" ) // The Library page says of each server whether it works, found the only @@ -43,7 +45,8 @@ type ServerHealth struct { // Why is the kind of error, for the page to put in its own words: // notfound, start, exited, timeout, http, refused, unreachable, // protocol, novar (a ${NAME} magpie's environment hasn't: Detail names - // them) + // them), wsldown (a command only agents in WSL start, whose distros, + // Detail, aren't running: it wasn't checked) Why string `json:"why,omitempty"` Code int `json:"code,omitempty"` // the exit code, or the HTTP status Detail string `json:"detail,omitempty"` // the last line it wrote to stderr, or the error's text @@ -59,7 +62,12 @@ type ServerHealth struct { // SSE server's stream), and Waited how long it was waited for, in ms Step string `json:"step,omitempty"` Waited int64 `json:"waited,omitempty"` - At int64 `json:"at"` // when it was checked, unix ms + // Checked are where a command was started, in order, for one that agents + // in WSL have (mcp_check_wsl.go): "" for this machine, a distro's name + // for its agents there. A failure is the last one's; none for a + // command only this machine's agents start. + Checked []string `json:"checked,omitempty"` + At int64 `json:"at"` // when it was checked, unix ms } // Each step of a check (initialize, notifications/initialized, tools/list) @@ -105,7 +113,12 @@ func healthKey(s *Server) string { c.Name, c.Agents = "", nil b, _ := json.Marshal(c) st := mcpauth.StatusOf(s.Name, s.URL) - return fmt.Sprintf("%s|%v|%v|%d", b, st.SignedIn, st.Dead, st.At) + // and where a command is started, which its agents decide + var sides []string + if s.Transport == "stdio" { + sides = checkSides(s) + } + return fmt.Sprintf("%s|%v|%v|%d|%q", b, st.SignedIn, st.Dead, st.At, sides) } // CheckServers checks the library's servers called names (every one when @@ -423,14 +436,72 @@ func (t *tail) last() string { return l } +// checkStdio starts the command where the agents given it start it +// (checkSides), each place in turn; the first failure is the answer. func checkStdio(ctx context.Context, s *Server) ServerHealth { + sides := checkSides(s) + if len(sides) == 1 && sides[0] == "" { + return checkStdioAt(ctx, s, "") + } + var done, down []string + var first *ServerHealth + for _, d := range sides { + if len(done) > 0 { + stepTo(ctx, "initialize") + } + h := checkStdioAt(ctx, s, d) + if h.Why == "wsldown" { + down = append(down, d) + continue + } + done = append(done, d) + h.Checked = slices.Clone(done) + if h.State != "ok" { + return h + } + if first == nil { + first = &h + } + } + if first == nil { + return failed("wsldown", strings.Join(down, ", ")) + } + first.Checked = done + return *first +} + +// checkStdioAt starts the command on this machine, or in WSL distro. +func checkStdioAt(ctx context.Context, s *Server, distro string) ServerHealth { // started as the agents start it: in the environment magpie has, with // the server's own variables over it env, unset := expandAll(s.Env) if len(unset) > 0 { return failed("novar", strings.Join(unset, ", ")) } - cmd := proc.Command(s.Command, s.Args...) + var cmd *exec.Cmd + var t wslrun.Tool + stop := func() {} + if distro == "" { + cmd = proc.Command(s.Command, s.Args...) + } else { + var err error + t, err = wslrun.In(distro, s.Command) + switch { + case errors.Is(err, wslrun.ErrDown): + return failed("wsldown", distro) + case errors.Is(err, wslrun.ErrNotFound): + return failed("notfound", s.Command) + case err != nil: + return failed("start", "wsl.exe -d "+distro+": "+err.Error()) + } + // its own context, ended with the check, which ends the run inside + // the distro too (killing wsl.exe alone leaves it there); not the + // check's, whose timeout is told as one rather than as an exit + var rctx context.Context + rctx, stop = context.WithCancel(context.WithoutCancel(ctx)) + cmd = wslCommand(rctx, t, s.Args...) + } + defer stop() // Agents start MCP servers from a project or home directory. A magpie // launched from a shortcut (Windows Start menu) often has C:\Windows\system32 // as its own cwd, which is not writable; inherit that and a server that @@ -441,12 +512,20 @@ func checkStdio(ctx context.Context, s *Server) ServerHealth { // and PWD with it, as exec does itself only when Env is nil: a // shell-script server that reads $PWD would otherwise see magpie's // own folder while it runs in home (Windows doesn't use PWD) - if runtime.GOOS != "windows" { + if runtime.GOOS != "windows" && distro == "" { cmd.Env = append(cmd.Env, "PWD="+d) } } + var names []string for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) + names = append(names, k) + } + if distro != "" { + // a run in the distro is given the server's own variables, by + // WSLENV, and none of Windows' others + slices.Sort(names) + cmd.Env = t.Env(cmd.Env, names...) } stdin, err := cmd.StdinPipe() if err != nil { @@ -471,6 +550,7 @@ func checkStdio(ctx context.Context, s *Server) ServerHealth { // the server ends with the check, and whatever it started with it defer func() { stdin.Close() + stop() tree.Kill() select { case <-exited: diff --git a/internal/library/mcp_check_wsl.go b/internal/library/mcp_check_wsl.go new file mode 100644 index 000000000..593ff67f8 --- /dev/null +++ b/internal/library/mcp_check_wsl.go @@ -0,0 +1,51 @@ +package library + +// A command that an agent in WSL starts runs in its distro: `node +// /home/me/tools/x.js` is a Linux program there, which on Windows is +// another node or none at all (loong on Discord: a server his agents in +// WSL start fine was checked on Windows, where it "exited (1)"). So the +// check starts a command where the agents given it start it: on this +// machine for its own agents, and through wsl.exe (wslrun, as magpie runs +// a distro's Claude Code) in each distro whose agents have it. + +import ( + "context" + "os/exec" + "slices" + "strings" + + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/wslrun" +) + +// wslCommand starts a check's command in t's distro; a var for tests. +var wslCommand = func(ctx context.Context, t wslrun.Tool, args ...string) *exec.Cmd { + return t.Command(ctx, args...) +} + +// checkSides are where s's command is checked: "" for this machine, a +// distro's name for its agents there, this machine first. Everything is +// checked here for a server no agent has, with no WSL to start one in or +// Settings' Detect agents in WSL off, and for a Windows program (magpie's +// own image server, the one an agent in WSL is given, which runs on +// Windows whoever starts it). Nothing here asks WSL anything. +func checkSides(s *Server) []string { + here := false + var distros []string + for _, id := range s.Agents { + _, d, ok := strings.Cut(id, "@wsl:") + if !ok || d == "" { + here = true + } else if !slices.Contains(distros, d) { + distros = append(distros, d) + } + } + if len(distros) == 0 || !wslrun.On || windowsPath.MatchString(s.Command) || settings.Shared().NoWSLAgents { + return []string{""} + } + slices.Sort(distros) + if here { + return append([]string{""}, distros...) + } + return distros +} diff --git a/internal/library/mcp_check_wsl_test.go b/internal/library/mcp_check_wsl_test.go new file mode 100644 index 000000000..bdac935bf --- /dev/null +++ b/internal/library/mcp_check_wsl_test.go @@ -0,0 +1,186 @@ +package library + +import ( + "context" + "errors" + "os" + "os/exec" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/wslrun" +) + +// wslCheck is a Windows machine with WSL whose running distros are up; +// probes are the distros a command was looked for in, and runs the +// wsl.exe command line of each check started there. The check's run is +// this test binary as the fake server, in mode (MAGPIE_FAKE_MCP: "exit" +// for one that fails), or as the server's own variables say for "". +type wslCheck struct { + mu sync.Mutex + probes []string + runs [][]string + mode string +} + +func fakeWSLCheck(t *testing.T, up ...string) *wslCheck { + t.Helper() + sandbox(t) + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + w := &wslCheck{} + on, run, cmd := wslrun.On, wslrun.Run, wslCommand + wslrun.On = true + wslrun.Forget() + wslrun.Run = func(_ time.Duration, args ...string) ([]byte, error) { + switch { + case slices.Equal(args, []string{"-l", "--running", "-q"}): + return []byte(strings.Join(up, "\n")), nil + case len(args) > 4 && args[0] == "-d" && args[2] == "-e" && args[4] == "-lc": + w.mu.Lock() + w.probes = append(w.probes, args[1]) + w.mu.Unlock() + return []byte("bin:/home/loong/.nvm/versions/node/v24.9.0/bin/node\npath:/home/loong/.nvm/versions/node/v24.9.0/bin:/usr/bin\nlpath:/usr/bin\nmount:/mnt/c/\n"), nil + case len(args) > 3 && args[0] == "-d" && args[2] == "--exec": + return nil, nil // the run in the distro ended + } + return nil, errors.New("unexpected wsl.exe " + strings.Join(args, " ")) + } + wslCommand = func(ctx context.Context, tl wslrun.Tool, args ...string) *exec.Cmd { + // wsl.exe as magpie starts it, its program swapped for the fake + c := tl.Command(ctx, args...) + w.mu.Lock() + w.runs = append(w.runs, slices.Clone(c.Args)) + mode := w.mode + w.mu.Unlock() + c.Err = nil + c.Path, c.Args = self, []string{self, "-test.run=^TestFakeMCPServer$"} + if mode != "" { + c.Path, c.Args = "/usr/bin/env", append([]string{"/usr/bin/env", fakeMode + "=" + mode}, c.Args...) + } + return c + } + t.Cleanup(func() { + wslrun.On, wslrun.Run, wslCommand = on, run, cmd + wslrun.Forget() + }) + return w +} + +// loong on Discord: a server whose command is a program in WSL, given +// only to agents there, was checked on Windows, where it "exited (1)", +// while the agents started it fine. It is checked in their distro, through +// wsl.exe, on the PATH an interactive shell there has (nvm's node). +func TestCheckWSLOnlyServerInItsDistro(t *testing.T) { + w := fakeWSLCheck(t, "Ubuntu", "Debian") + s := &Server{Name: "x", Transport: "stdio", Command: "node", Args: []string{"/home/loong/tools/xxx.js"}, + Env: map[string]string{fakeMode: "ok"}, Agents: []string{"claude@wsl:Ubuntu", "codex@wsl:Ubuntu"}} + h := CheckServer(context.Background(), s) + if h.State != "ok" || h.Tools != 3 || !slices.Equal(h.Checked, []string{"Ubuntu"}) { + t.Fatalf("got %+v, want ok with 3 tools, checked in Ubuntu", h) + } + if !slices.Equal(w.probes, []string{"Ubuntu"}) || len(w.runs) != 1 { + t.Fatalf("probes %v, runs %v: want one run, in Ubuntu", w.probes, w.runs) + } + r := w.runs[0] + want := []string{"wsl.exe", "-d", "Ubuntu", "--exec", "/usr/bin/env", "PATH=/home/loong/.nvm/versions/node/v24.9.0/bin:/usr/bin"} + if len(r) != 9 || !slices.Equal(r[:6], want) || !strings.HasPrefix(r[6], "MAGPIE_WSL_RUN=") || + r[7] != "/home/loong/.nvm/versions/node/v24.9.0/bin/node" || r[8] != "/home/loong/tools/xxx.js" { + t.Fatalf("run %q", r) + } + + // a distro that isn't running isn't started to check it: the check + // says it couldn't, not that the server failed + s.Agents = []string{"claude@wsl:Arch"} + h = CheckServer(context.Background(), s) + if h.State != "error" || h.Why != "wsldown" || h.Detail != "Arch" || len(h.Checked) != 0 { + t.Fatalf("got %+v, want wsldown for Arch", h) + } + if slices.Contains(w.probes, "Arch") || len(w.runs) != 1 { + t.Fatalf("a stopped distro was asked: probes %v, runs %v", w.probes, w.runs) + } + + // a program the distro hasn't is not found there + old := wslrun.Run + wslrun.Run = func(d time.Duration, args ...string) ([]byte, error) { + if len(args) > 4 && args[4] == "-lc" { + return []byte("mount:/mnt/c/\n"), nil + } + return old(d, args...) + } + s.Command, s.Agents = "magpie-no-such-node", []string{"claude@wsl:Debian"} + if h = CheckServer(context.Background(), s); h.Why != "notfound" || h.Detail != "magpie-no-such-node" || !slices.Equal(h.Checked, []string{"Debian"}) { + t.Fatalf("got %+v, want notfound in Debian", h) + } +} + +// A server only this machine's agents have is checked here as before, +// WSL never asked; so is a Windows program given to agents in WSL +// (magpie's own image server, which runs on Windows whoever starts it). +func TestCheckWindowsServerHere(t *testing.T) { + w := fakeWSLCheck(t, "Ubuntu") + s := fakeStdio(t, "ok", nil) + s.Agents = []string{"claude", "codex"} + h := CheckServer(context.Background(), s) + if h.State != "ok" || h.Tools != 3 || h.Checked != nil { + t.Fatalf("got %+v, want ok here with nothing named", h) + } + for _, c := range []string{`D:\tools\Magpie\magpie-windows-amd64.exe`, `C:/x/npx.cmd`} { + if got := checkSides(&Server{Transport: "stdio", Command: c, Agents: []string{"claude@wsl:Ubuntu"}}); !slices.Equal(got, []string{""}) { + t.Errorf("%s: sides %q, want this machine", c, got) + } + } + if len(w.probes) != 0 || len(w.runs) != 0 { + t.Fatalf("WSL was asked: probes %v, runs %v", w.probes, w.runs) + } +} + +// A server both this machine's agents and a distro's have is checked in +// each place, and a failure says which one failed. +func TestCheckMixedServerEachSide(t *testing.T) { + w := fakeWSLCheck(t, "Ubuntu") + s := fakeStdio(t, "ok", nil) + s.Agents = []string{"claude", "codex@wsl:Ubuntu"} + h := CheckServer(context.Background(), s) + if h.State != "ok" || h.Tools != 3 || !slices.Equal(h.Checked, []string{"", "Ubuntu"}) { + t.Fatalf("got %+v, want ok here and in Ubuntu", h) + } + if len(w.runs) != 1 || w.runs[0][2] != "Ubuntu" { + t.Fatalf("runs %v", w.runs) + } + + // it fails in WSL only: named as Ubuntu's + w.mode = "exit" + h = CheckServer(context.Background(), s) + if h.State != "error" || h.Why != "exited" || h.Code != 3 || !slices.Equal(h.Checked, []string{"", "Ubuntu"}) { + t.Fatalf("got %+v, want exited 3 in Ubuntu after ok here", h) + } + + // it fails here: named as this machine's, before WSL is asked + w.mode = "" + runs := len(w.runs) + bad := *s + bad.Env = map[string]string{fakeMode: "exit"} + h = CheckServer(context.Background(), &bad) + if h.State != "error" || h.Why != "exited" || !slices.Equal(h.Checked, []string{""}) || len(w.runs) != runs { + t.Fatalf("got %+v (runs %d → %d), want exited here", h, runs, len(w.runs)) + } + + // a distro that isn't running: checked here only, and said so + s.Agents = []string{"claude", "codex@wsl:Arch"} + if h = CheckServer(context.Background(), s); h.State != "ok" || !slices.Equal(h.Checked, []string{""}) { + t.Fatalf("got %+v, want ok here only", h) + } + + // the agents moving from here into WSL is a check of its own + a, b := *s, *s + a.Agents, b.Agents = []string{"claude"}, []string{"claude@wsl:Ubuntu"} + if healthKey(&a) == healthKey(&b) { + t.Fatal("a server moved into WSL keeps its check from Windows") + } +} diff --git a/internal/wslrun/wslrun.go b/internal/wslrun/wslrun.go index 84cb1a89a..349639822 100644 --- a/internal/wslrun/wslrun.go +++ b/internal/wslrun/wslrun.go @@ -10,11 +10,13 @@ package wslrun import ( "bufio" "context" + "errors" "net" "net/url" "os" "os/exec" "path/filepath" + "regexp" "runtime" "slices" "strconv" @@ -112,6 +114,67 @@ func Find(name string) (Tool, bool) { return Tool{}, false } +// ErrDown is In's answer for a distro that isn't running, which it doesn't +// start to look. +var ErrDown = errors.New("the distro isn't running") + +// ErrNotFound is In's answer for a command the distro hasn't. +var ErrNotFound = errors.New("not in the distro") + +// plainName is a command In can look for: the probe names it in a shell +// script unquoted, so a name with anything else in it isn't looked for. +var plainName = regexp.MustCompile(`^[A-Za-z0-9_./+@:-]+$`) + +var foundIn struct { + sync.Mutex + at map[string]time.Time + tools map[string]Tool +} + +// In is command name, a program's name or its path, as distro has it, for +// a run there: found as Find finds one (a login shell's PATH, then an +// interactive one's, where nvm puts node), in that distro only. A distro +// that isn't running is ErrDown and isn't started. A path the probe can't +// name for the shell is taken as it is, on a login shell's usual PATH. +// What was found is kept for findAge. +func In(distro, name string) (Tool, error) { + if !On { + return Tool{}, errors.New("no WSL") + } + if !Up(distro) { + return Tool{}, ErrDown + } + if !plainName.MatchString(name) { + if strings.HasPrefix(name, "/") { + return Tool{Distro: distro, Path: name, PATH: defaultPATH, Mount: "/mnt/"}, nil + } + return Tool{}, ErrNotFound + } + key := distro + "\x00" + name + foundIn.Lock() + t, ok := foundIn.tools[key] + fresh := ok && time.Since(foundIn.at[key]) < findAge + foundIn.Unlock() + if fresh { + return t, nil + } + out, err := Run(30*time.Second, "-d", distro, "-e", "sh", "-lc", probeScript(name)) + if err != nil { + return Tool{}, err + } + t, ok = parseProbe(distro, string(out)) + if !ok { + return Tool{}, ErrNotFound + } + foundIn.Lock() + if foundIn.at == nil { + foundIn.at, foundIn.tools = map[string]time.Time{}, map[string]Tool{} + } + foundIn.at[key], foundIn.tools[key] = time.Now(), t + foundIn.Unlock() + return t, nil +} + var up struct { sync.Mutex at time.Time @@ -171,11 +234,14 @@ func Known(name string) (Tool, bool) { return Tool{}, false } -// Forget drops what Find knows, so the next Find looks again. +// Forget drops what Find and In know, so the next one looks again. func Forget() { found.Lock() found.at, found.tools = nil, nil found.Unlock() + foundIn.Lock() + foundIn.at, foundIn.tools = nil, nil + foundIn.Unlock() up.Lock() up.at = time.Time{} up.Unlock() @@ -198,6 +264,9 @@ func probeScript(name string) string { `command -v wslinfo >/dev/null 2>&1 && echo "net:$(wslinfo --networking-mode 2>/dev/null)"; true` } +// defaultPATH is a login shell's PATH, for a distro that printed none. +const defaultPATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + func parseProbe(distro, out string) (Tool, bool) { t := Tool{Distro: distro, Mount: "/mnt/"} var ipath, lpath, net_ string @@ -237,7 +306,7 @@ func parseProbe(distro, out string) (Tool, bool) { t.PATH = ipath } if t.PATH == "" { - t.PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + t.PATH = defaultPATH } if dir := t.Path[:strings.LastIndex(t.Path, "/")]; dir != "" && !onPath(t.PATH, dir) { t.PATH = dir + ":" + t.PATH