library: a program whose path has spaces, typed as it is, is that program (zachzhao1984)

Library → MCP's command field splits a line at each unquoted space, as a
shell does, so "/Applications/Agent HUD.app/Contents/MacOS/Agent HUD --mcp"
reached the library as the program /Applications/Agent with the arguments
HUD.app/Contents/MacOS/Agent, HUD and --mcp. The save itself went through;
what was saved and written into every agent's config was a program that
isn't there, so the server never started. `magpie mcp add` with an
unquoted path and the TUI's line (strings.Fields) split it the same way.

Server.check, which every way in passes (the GUI's save, `magpie mcp add`,
the TUI, a market install, a backup or sync read in), now joins the words
back: when the command is a full path to no file, and it with the words
after it, joined by a space, is a program on this computer (a regular
file, executable outside Windows), that is the program and the rest are
its arguments; the fewest words that make one, as Windows reads an
unquoted path. A command that is there, a bare name (npx -y foo), or a
path no join makes stay as typed. Each agent is then given the program as
one argument with its spaces (JSON's and TOML's own quoting), and the GUI
shows it quoted ('/Applications/…/Agent HUD' --mcp), which reads back as
one word. A path typed in quotes, or with \ before its spaces, was already
one word. A server saved split before stays so until it is saved again:
opened and saved, its line is joined.

Tests:
- internal/library TestSpacedProgram: split, no arguments, given whole,
  a bare name, a path no join makes, a program that is there keeps its
  next word, a folder is no program.
- TestSpacedProgramSaved: ServerOf from the split words, SaveServer, the
  library and Claude Code's .claude.json and Codex's config.toml each
  hold the program whole and --mcp.
- internal/gui/tests/library-mcp-spaced-path.test.cjs: the reporter's
  line typed in a new server's dialog is sent as typed; the row and the
  editor show the path quoted; saving unchanged sends it whole; a quoted
  path is sent whole; a save the library refuses (a name with a space)
  shows its reason and the dialog stays. en and zh, 1100 and 390 wide,
  Chromium and WebKit, nothing scrolls sideways. The fake save stands in
  for the Go join.

Run (mote, via mote-run, at this tree on 30ae0e3f9):
- go test -count=1 ./internal/library ./internal/cli ./internal/tui: ok.
- go vet (library, cli, tui), GOOS=linux go vet -tags nogui and
  GOOS=windows go vet ./internal/library, go build ./..., GOOS=linux
  go build -tags nogui ./..., GOOS=windows go build ./...: ok. gofmt -l:
  nothing.
- win-run go test -run TestSpacedProgram ./internal/library (Windows 11):
  ok.
- node --test library-mcp-spaced-path: 10 of 10, four runs in a row.
  library-mcp-win-line, library-mcp-json, mcp-local-server: ok.
  i18n-keys "a plugin's words are its own" is red, the same three lines
  on a clean origin/main 30ae0e3f9 copy (filed: #5332, #5426, #5482);
  this change adds no strings.

Broken by hand:
- the spacedProgram call in check() commented out: TestSpacedProgramSaved
  FAIL, the library has Command .../Agent and Args [HUD.app/Contents/
  MacOS/Agent HUD --mcp].
- quote() taking a space as safe: library-mcp-spaced-path 0 of 10, the
  editor shows the line unquoted.
- The GUI test first flaked 2 of 10: a new dialog focuses its name a
  frame after it opens, and a command typed sooner landed in the name.
  The test waits for that focus now.

Not tried: the real Agent HUD app (not installed here), nor a real agent
starting the saved server; a program path with spaces given to an agent
in WSL (the join stats this computer's files, so a Linux path typed for a
distro is left as typed); the full go suite before this push (runs after,
under the lock).

Reported-by: zachzhao1984 (Discord)
This commit is contained in:
yetone
2026-11-07 12:59:36 +08:00
parent 30ae0e3f92
commit e932cd2589
3 changed files with 290 additions and 0 deletions
@@ -0,0 +1,146 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// zachzhao1984 on Discord: an app's binary by full path, with spaces in
// it, typed as it is in Library → MCP's command field
// ("/Applications/Agent HUD.app/Contents/MacOS/Agent HUD --mcp"), was the
// program /Applications/Agent with three arguments. The page sends the
// words as typed and the library makes them the program that is there
// (library.spacedProgram, stood in for here by the fake save); the row
// and the editor then show the path quoted, and saving it unchanged keeps
// it one argument. A path typed in quotes is one argument at once. A save
// the library refuses says why in the dialog, which stays open. English
// and Chinese, Chromium and WebKit, 1100 and 390 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 { I18N } = require("./strings.cjs").strings(); // i18n.js's and the plugins'
const tr = (lang, s) => (lang === "en" ? s : I18N[lang][s]) || s;
const HOME = "/Users/zz";
const EXE = "/Applications/Agent HUD.app/Contents/MacOS/Agent HUD";
const TYPED = EXE + " --mcp";
const SHOWN = "'" + EXE + "' --mcp";
const REFUSED = 'server name "Agent HUD": use letters, digits, - and _ only';
function server(lang, saves) {
const lib = {
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [{ id: "claude", name: "Claude Code", icon: "", skills: `${HOME}/.claude/skills`, mcp: `${HOME}/.claude.json` }],
instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [],
servers: [{ name: "mine", transport: "stdio", command: "/opt/mine/mcp", agents: ["claude"] }],
};
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, theme: "light" } } });
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
if (url.pathname === "/api/library") return route.fulfill({ json: lib });
if (url.pathname === "/api/library/mcp/check") return route.fulfill({ json: { servers: {} } });
if (url.pathname === "/api/library/servers/save") {
const { old, server: s } = req.postDataJSON();
saves.push(structuredClone(s));
if (!/^[A-Za-z0-9_-]+$/.test(s.name)) return route.fulfill({ status: 400, json: { error: REFUSED } });
// the library's check, on a Mac where Agent HUD is installed
const words = [s.command, ...s.args];
for (let i = 1; i <= words.length; i++) {
if (words.slice(0, i).join(" ") === EXE) { s.command = EXE; s.args = words.slice(i); break; }
}
const i = lib.servers.findIndex((x) => x.name === (old || s.name));
if (i < 0) lib.servers.push(s); else lib.servers[i] = { ...lib.servers[i], ...s };
return route.fulfill({ json: { ...lib, result: { changed: ["claude"] } } });
}
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 });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a program whose path has spaces, typed as it is", 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 of ["en", "zh"]) {
for (const width of [1100, 390]) {
await t.test(`${lang} ${width}`, async () => {
const w = (s) => tr(lang, s);
if (lang !== "en") for (const s of ["+ Add server", "e.g. github", "Add", "Save"]) assert.ok(I18N[lang][s], `${lang}: ${s}`);
const ctx = await browser.newContext({ viewport: { width, height: 800 } });
await ctx.addInitScript(() => {
Object.defineProperty(Navigator.prototype, "platform", { get: () => "MacIntel" });
try { localStorage.setItem("magpie.libTab", "mcp"); } catch {}
});
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
const saves = [];
await page.route("http://magpie.test/**", server(lang, saves));
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 ed = page.locator("#modal .lib-editor");
const name = ed.locator(`input[placeholder="${w("e.g. github")}"]`);
const cmd = ed.locator("textarea.lib-cmd");
const ok = ed.locator(":scope > .bar button.primary");
const row = (n) => page.locator("#view-library .lib-server", { has: page.locator(`.lib-health[data-server="${n}"]`) });
const add = async (n, line) => {
const b = page.locator("#view-library .after-list button");
assert.equal(await b.textContent(), w("+ Add server"));
await b.click();
await ed.waitFor();
// a new server's dialog puts the caret in its name a frame after
// it opens: typed sooner, the command would land there
await page.waitForFunction(() => document.activeElement?.matches("#modal .lib-editor input"));
await name.fill(n);
await cmd.fill(line);
await ok.click();
};
// a name the library refuses: its reason, and the dialog stays
await add("Agent HUD", TYPED);
await ed.locator(".editor-error", { hasText: REFUSED }).waitFor();
assert.equal(await ed.count(), 1);
await name.fill("agent-hud");
await ok.click();
await ed.waitFor({ state: "detached" });
assert.deepEqual([saves.at(-1).command, ...saves.at(-1).args], TYPED.split(" "), "sent as typed");
const line = row("agent-hud").locator(".sub.mono");
assert.equal(await line.textContent(), SHOWN);
// the editor shows it quoted, and saving it unchanged keeps it
await row("agent-hud").locator(".name").click();
await ed.waitFor();
assert.equal(await cmd.inputValue(), SHOWN);
await ok.click();
await ed.waitFor({ state: "detached" });
assert.deepEqual([saves.at(-1).command, ...saves.at(-1).args], [EXE, "--mcp"]);
// typed in quotes, it is one argument as it is sent
await add("hud-quoted", `"${EXE}" --mcp`);
await ed.waitFor({ state: "detached" });
assert.deepEqual([saves.at(-1).command, ...saves.at(-1).args], [EXE, "--mcp"]);
assert.equal(await row("hud-quoted").locator(".sub.mono").textContent(), SHOWN);
const wide = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
assert.ok(wide <= 0, `scrolls sideways by ${wide}px`);
await ctx.close();
});
}
}
assert.deepEqual(errors, []);
});
}
+36
View File
@@ -8,8 +8,10 @@ import (
"io/fs"
"maps"
"math"
"os"
"path/filepath"
"regexp"
"runtime"
"slices"
"sort"
"strconv"
@@ -128,6 +130,7 @@ func (s *Server) check() error {
if s.Command == "" {
return fmt.Errorf("%s: a command is needed", s.Name)
}
s.Command, s.Args = spacedProgram(s.Command, s.Args)
s.URL, s.Headers = "", nil
case "http", "sse":
if !strings.HasPrefix(s.URL, "http://") && !strings.HasPrefix(s.URL, "https://") {
@@ -180,6 +183,39 @@ func (s *Server) check() error {
return nil
}
// spacedProgram is a program by full path that has spaces in it, typed
// as it is: "/Applications/Agent HUD.app/Contents/MacOS/Agent HUD --mcp"
// (zachzhao1984 on Discord), or C:\Program Files\… on Windows, which a
// command line split at each space makes /Applications/Agent and three
// arguments, a program that isn't there. When cmd is a full path to no
// file and cmd with the words after it, joined back by a space, is a
// program on this computer, that is the program and the rest are its
// arguments: the fewest words that make one, as Windows reads an unquoted
// path. A command that is there, a bare name, or a path no join makes a
// program are left as typed.
func spacedProgram(cmd string, args []string) (string, []string) {
if len(args) == 0 || !filepath.IsAbs(cmd) || program(cmd) {
return cmd, args
}
p := cmd
for i, a := range args {
p += " " + a
if program(p) {
return p, slices.Clone(args[i+1:])
}
}
return cmd, args
}
// program is whether path is a file this computer can run.
func program(path string) bool {
fi, err := os.Stat(path)
if err != nil || !fi.Mode().IsRegular() {
return false
}
return runtime.GOOS == "windows" || fi.Mode().Perm()&0o111 != 0
}
// same reports whether two definitions start the same server; which agents
// have it doesn't matter.
func (s *Server) same(o *Server) bool {
+108
View File
@@ -0,0 +1,108 @@
package library
import (
"encoding/json"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
toml "github.com/pelletier/go-toml/v2"
"github.com/yetone/magpie/internal/testenv"
)
// An app's binary by full path, with spaces in it, typed as it is
// (zachzhao1984 on Discord: "/Applications/Agent HUD.app/Contents/MacOS/
// Agent HUD --mcp"). A command line split at each space made it the
// program /Applications/Agent and three arguments; it is the program
// with its spaces, and --mcp.
func spacedApp(t *testing.T) string {
t.Helper()
exe := filepath.Join(t.TempDir(), "Agent HUD.app", "Contents", "MacOS", "Agent HUD")
testenv.Program(t, exe, "#!/bin/sh\n")
return exe
}
func TestSpacedProgram(t *testing.T) {
exe := spacedApp(t)
split := strings.Fields(exe + " --mcp")
for _, c := range []struct {
name string
cmd string
args, want []string
}{
{"split at its spaces", split[0], split[1:], []string{exe, "--mcp"}},
{"with no arguments", split[0], split[1 : len(split)-1], []string{exe}},
{"given whole", exe, []string{"--mcp"}, []string{exe, "--mcp"}},
{"a bare name", "npx", []string{"-y", "foo"}, []string{"npx", "-y", "foo"}},
{"a path no join makes", "/nowhere/x", []string{"y", "--z"}, []string{"/nowhere/x", "y", "--z"}},
} {
t.Run(c.name, func(t *testing.T) {
cmd, args := spacedProgram(c.cmd, c.args)
if got := append([]string{cmd}, args...); !slices.Equal(got, c.want) {
t.Fatalf("got %q, want %q", got, c.want)
}
})
}
// a program that is there, given the words after it, keeps them
dir := t.TempDir()
short := filepath.Join(dir, "srv")
testenv.Program(t, short, "#!/bin/sh\n")
testenv.Program(t, short+" more", "#!/bin/sh\n")
if cmd, args := spacedProgram(short, []string{"more"}); cmd != short || !slices.Equal(args, []string{"more"}) {
t.Fatalf("a program that is there: %q %q", cmd, args)
}
// a folder by that name is no program
if runtime.GOOS != "windows" {
if err := os.MkdirAll(filepath.Join(dir, "a b"), 0o755); err != nil {
t.Fatal(err)
}
if cmd, _ := spacedProgram(filepath.Join(dir, "a"), []string{"b"}); cmd != filepath.Join(dir, "a") {
t.Fatalf("a folder taken for the program: %q", cmd)
}
}
}
// Saved from the GUI's words, the CLI's or the TUI's, the program is one
// argument with its spaces in the library and in each agent's file,
// Claude Code's JSON and Codex's TOML.
func TestSpacedProgramSaved(t *testing.T) {
h := sandbox(t)
exe := spacedApp(t)
s, err := ServerOf("hud", strings.Fields(exe+" --mcp"))
if err != nil {
t.Fatal(err)
}
s.Agents = []string{"claude", "codex"}
ok(t)(SaveServer("", s))
if got := serverIn(t, "hud"); got == nil || got.Command != exe || !slices.Equal(got.Args, []string{"--mcp"}) {
t.Fatalf("library has %+v", got)
}
var claude struct {
MCPServers map[string]struct {
Command string `json:"command"`
Args []string `json:"args"`
} `json:"mcpServers"`
}
if err := json.Unmarshal([]byte(read(t, filepath.Join(h, ".claude.json"))), &claude); err != nil {
t.Fatal(err)
}
if e := claude.MCPServers["hud"]; e.Command != exe || !slices.Equal(e.Args, []string{"--mcp"}) {
t.Fatalf("Claude Code is given %+v", e)
}
var codex struct {
MCPServers map[string]struct {
Command string `toml:"command"`
Args []string `toml:"args"`
} `toml:"mcp_servers"`
}
if err := toml.Unmarshal([]byte(read(t, filepath.Join(h, ".codex", "config.toml"))), &codex); err != nil {
t.Fatal(err)
}
if e := codex.MCPServers["hud"]; e.Command != exe || !slices.Equal(e.Args, []string{"--mcp"}) {
t.Fatalf("Codex is given %+v", e)
}
}