diff --git a/internal/agent/cliupdate.go b/internal/agent/cliupdate.go index 737ef837e..98bb070fe 100644 --- a/internal/agent/cliupdate.go +++ b/internal/agent/cliupdate.go @@ -817,6 +817,23 @@ func (a *Agent) cliBin() (string, cliSpec) { return bin, spec } +// BinPath is where the agent's own program is, as Detected finds its Bin, +// else where cliBin looks for one with no Bin (Grok Build's); "" for an +// agent in a WSL distro and one with no program here (a desktop app). +func (a *Agent) BinPath() string { + if a.WSL != "" { + return "" + } + if a.Bin == "" { + bin, _ := a.cliBin() + return bin + } + if bin := binAt(a.Bin); bin != "" { + return bin + } + return proc.FindTool(a.Bin) +} + // CLI is the agent's CLI: its version, the newest, and whether magpie can // update it, with its desktop app's version. ok is false for an agent with // neither a CLI magpie knows nor its app. diff --git a/internal/gui/agent_open_test.go b/internal/gui/agent_open_test.go new file mode 100644 index 000000000..b0538837a --- /dev/null +++ b/internal/gui/agent_open_test.go @@ -0,0 +1,121 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/proc" +) + +// Open in terminal on an Agents row (coolmantou on Discord): the page +// sends only the agent's id, and the line Terminal runs is made here from +// the agent's own program. A path that spells shell commands runs that +// program and nothing else, and an id that isn't an agent's opens nothing. +func TestAgentOpenRunsOnlyTheAgent(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the .command file is a POSIX shell's") + } + sandboxHome(t) + // the folder Claude Code's program is in, named to run commands if + // its path went into the line unquoted + dir := filepath.Join(t.TempDir(), `it's a' $(touch made1) `+"`touch made2`"+`; touch made3 #`) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + prog := filepath.Join(dir, "claude") + if err := os.WriteFile(prog, []byte("#!/bin/sh\necho ran >> ran\n"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+"/usr/bin:/bin") + proc.Forget() + t.Cleanup(proc.Forget) + + var opened []string + was := agentTerminal + agentTerminal = func(run, choice string) error { opened = append(opened, run); return nil } + t.Cleanup(func() { agentTerminal = was }) + + h := Handler(nil, nil) + post := func(id string) int { + t.Helper() + b, _ := json.Marshal(map[string]string{"agent": id}) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("POST", "/api/agents/open", strings.NewReader(string(b)))) + return rec.Code + } + // an id that isn't an agent's, whatever it spells, opens nothing + for _, id := range []string{"claude; touch made4", "claude'$(touch made5)'", "cl"} { + if code := post(id); code == http.StatusNoContent || len(opened) != 0 { + t.Fatalf("%q: %d, opened %q", id, code, opened) + } + } + + var row *agentJSON + s := state() + for i := range s.Agents { + if s.Agents[i].ID == "claude" { + row = &s.Agents[i] + } + } + if row == nil { + t.Fatalf("claude not detected on PATH %q", os.Getenv("PATH")) + } + if row.Terminal != (runtime.GOOS == "darwin") { + t.Fatalf("the row's terminal is %v on %s", row.Terminal, runtime.GOOS) + } + + a, err := agent.Find("claude") + if err != nil { + t.Fatal(err) + } + run := agentCommand(a) + if runtime.GOOS == "darwin" { + if code := post("claude"); code != http.StatusNoContent || len(opened) != 1 { + t.Fatalf("claude: %d, opened %q", code, opened) + } + run = opened[0] + } else if code := post("claude"); code == http.StatusNoContent || len(opened) != 0 { + t.Fatalf("off a Mac: %d, opened %q", code, opened) + } + + // the line run as the .command file runs it, in a folder of its own + work := t.TempDir() + cmd := proc.Command("/bin/sh", "-c", run) + cmd.Dir = work + out, err := cmd.CombinedOutput() + for _, d := range []string{work, dir} { + if made, _ := filepath.Glob(filepath.Join(d, "made*")); len(made) != 0 { + t.Fatalf("%q ran more than the agent: %q", run, made) + } + } + if b, _ := os.ReadFile(filepath.Join(work, "ran")); err != nil || string(b) != "ran\n" { + t.Fatalf("%q didn't run the agent's program: %q (%v %s)", run, b, err, out) + } +} + +// A desktop app's row has no command to open, and neither has an agent in +// a WSL distro: no Open in terminal. +func TestAgentCommandNeedsAProgram(t *testing.T) { + sandboxHome(t) + proc.Forget() + t.Cleanup(proc.Forget) + for _, a := range []*agent.Agent{ + {ID: "app", Name: "An app"}, + {ID: "claude@wsl:Ubuntu", Bin: "sh", WSL: "Ubuntu", Launch: func() string { return "claude" }}, + } { + if run := agentCommand(a); run != "" { + t.Errorf("%s: %q", a.ID, run) + } + } + // one that starts on magpie by its environment (agy) opens on that + if run := agentCommand(&agent.Agent{ID: "agy", Bin: "agy", Launch: func() string { return "X=1 agy" }}); run != "X=1 agy" { + t.Errorf("agy: %q", run) + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index 40b51f7a1..e19907af2 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -243,6 +243,9 @@ type agentJSON struct { // another agent offers it again where magpie knows how CLIMissing bool `json:"cliMissing,omitempty"` Native *agent.NativeState `json:"native,omitempty"` + // Terminal: a Mac's row menu offers Open in terminal, a command + // starting it being here (agentCommand) + Terminal bool `json:"terminal,omitempty"` } // clientJSON is an agent, or another client the gateway knows, as a @@ -2702,6 +2705,8 @@ func state() stateJSON { aj.Typed = a.Typed() } aj.CLIMissing = a.CLIMissing() + // as agentCommand makes it, Launch asked once + aj.Terminal = runtime.GOOS == "darwin" && a.WSL == "" && (aj.Launch != "" || a.BinPath() != "") if a.Native != nil { native := a.Native.Read() aj.Native = &native diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 431e4bcf1..984d0047f 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -3869,13 +3869,16 @@ function openAgentMenu(anchor, a, inFold) { const { shown } = arrangeAgents(); const i = shown.findIndex((x) => x.id === a.id); const reapply = !a.cliMissing && (a.drift || a.fields.some((f) => optionFor(f, f.value)?.ref)); + // a Mac window's (coolmantou) + const term = a.terminal && mode != "panel" && !web ? [{ name: "Open in terminal", icon: LAUNCH_GLYPH, sep: !0, run: () => api("agents/open", { agent: a.id }).catch(statusErr) }] : []; const acts = inFold && isHidden(a) ? [{ name: "Show", icon: EYE, run: () => setAgentHidden(a, false) }] : inFold - ? [{ name: "Hide", icon: EYE_OFF, run: () => setAgentHidden(a, true) }] + ? [{ name: "Hide", icon: EYE_OFF, run: () => setAgentHidden(a, true) }, ...term] : [ { name: "Move up", icon: MOVE_UP, key: ALT + "↑", off: i <= 0, run: () => moveAgent(a.id, i - 1) }, { name: "Move down", icon: MOVE_DOWN, key: ALT + "↓", off: i < 0 || i >= shown.length - 1, run: () => moveAgent(a.id, i + 1) }, + ...term, // its own settings, as the square on its row opens them ...(agentPrefsOf(a) ? [{ name: t("{agent} settings", { agent: a.name }), literal: true, icon: PREFS_GLYPH, sep: true, run: () => openAgentPrefs(a) }] : []), // for a config rewritten in a way magpie can't see: set it again anyway @@ -3946,11 +3949,8 @@ const TIER_EFFORTS = TIERS.map((tier) => tier + " effort"); // other agents' small model is a picker of its own) const FOLLOWS_MODEL = [...TIERS, "subagents", "smol", "slow"]; // omp's roles share one square as Claude Code's tiers do (#1397), each -// with its thinking level under its model: the level omp reads off the end -// of the role's model ("…:high"). The roles after slow don't follow the -// model; each says what omp does when it is unset: plan and vision are -// omp's own pick, the advisor the slow role's model first, commit and tiny -// the smol role's, memory the tiny role's (omp's chat roles, #1397) +// with its level ("…:high") under its model; the roles after slow say +// what omp does when unset const OMP_UNSET = { plan: "omp's own pick", vision: "omp's own pick", advisor: "the slow role's model, else omp's own pick", commit: "the smol role's model", tiny: "the smol role's model", memory: "the tiny role's model, else the smol role's", diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index ebf418024..da42c5bac 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2936,6 +2936,7 @@ const I18N = { "Type {command} in a new terminal to start {name} on magpie · click to copy the command for a terminal open now:": "在新终端输入 {command} 即可让 {name} 走 magpie · 点击复制在已打开终端中用的命令:", "Launch command": "启动命令", "Copy launch command": "复制启动命令", + "Open in terminal": "在终端中打开", "Copied — run it to start {name} on magpie": "已复制,运行它即可让 {name} 走 magpie", // the Sessions page (sessions.js) "Filter sessions": "筛选会话", @@ -7138,6 +7139,7 @@ const I18N = { "Type {command} in a new terminal to start {name} on magpie · click to copy the command for a terminal open now:": "在新終端機輸入 {command} 即可讓 {name} 走 magpie · 點選複製在已開啟終端機中用的命令:", "Launch command": "啟動命令", "Copy launch command": "複製啟動命令", + "Open in terminal": "在終端機中開啟", "Copied — run it to start {name} on magpie": "已複製,執行它即可讓 {name} 走 magpie", "Filter sessions": "篩選會話", "No sessions yet": "還沒有會話", @@ -11344,6 +11346,7 @@ const I18N = { "Type {command} in a new terminal to start {name} on magpie · click to copy the command for a terminal open now:": "新しいターミナルで {command} と入力すると {name} が magpie 経由で起動します · クリックで開いているターミナル用のコマンドをコピー:", "Launch command": "起動コマンド", "Copy launch command": "起動コマンドをコピー", + "Open in terminal": "ターミナルで開く", "Copied — run it to start {name} on magpie": "コピーしました。実行すると {name} が magpie 経由で起動します", "Filter sessions": "セッションを絞り込む", "No sessions yet": "セッションはまだありません", @@ -15560,6 +15563,7 @@ const I18N = { "Type {command} in a new terminal to start {name} on magpie · click to copy the command for a terminal open now:": "In einem neuen Terminal startet {command} {name} über magpie · klicken, um den Befehl für ein schon offenes Terminal zu kopieren:", "Launch command": "Startbefehl", "Copy launch command": "Startbefehl kopieren", + "Open in terminal": "Im Terminal öffnen", "Copied — run it to start {name} on magpie": "Kopiert — ausführen, um {name} über magpie zu starten", "Filter sessions": "Sitzungen filtern", "No sessions yet": "Noch keine Sitzungen", diff --git a/internal/gui/sessions.go b/internal/gui/sessions.go index b62cffb8c..4cacae71e 100644 --- a/internal/gui/sessions.go +++ b/internal/gui/sessions.go @@ -371,6 +371,35 @@ func sessionRoutes(mux *http.ServeMux, w Windows) { } rw.WriteHeader(http.StatusNoContent) }) + // agents/open opens Terminal on an agent of the Agents list: the command + // is made here from the agent as detected (agentCommand), and the page + // sends only its id. + mux.HandleFunc("POST /api/agents/open", func(rw http.ResponseWriter, r *http.Request) { + var in struct{ Agent string } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if runtime.GOOS != "darwin" || isWeb(w) { + fail(rw, errors.New("opening Terminal is only for the Mac app")) + return + } + run := "" + for _, a := range agent.Detected() { + if a.ID == in.Agent { + run = agentCommand(a) + } + } + if run == "" { + fail(rw, errors.New("no command starts this agent")) + return + } + if err := agentTerminal(run, settings.Load().SessionTerminal); err != nil { + fail(rw, err) + return + } + rw.WriteHeader(http.StatusNoContent) + }) // carry converts a session for another agent (one its Carry offers with // Convert): a new session of that agent's, in its own folder, the // source only read. It runs only when the user picks the agent, never @@ -736,6 +765,30 @@ func tightenGC() (undo func()) { const tightGCPercent = 25 +// agentCommand is the shell line that starts a: its Launch where it has +// one (agy, Claude Science, Cursor Private Inference), else its own +// program, quoted; "" for one in a WSL distro or with no program here (a +// desktop app). Nothing of the page's goes into it. +func agentCommand(a *agent.Agent) string { + if a.WSL != "" { + return "" + } + if a.Launch != nil { + if run := a.Launch(); run != "" { + return run + } + } + if bin := a.BinPath(); bin != "" { + return shellQuote(bin) + } + return "" +} + +// agentTerminal is openTerminal, a var so a test opens no terminal. +var agentTerminal = openTerminal + +func shellQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" } + // openTerminal runs a command in the chosen Mac terminal through a .command // file, as it would open from Finder: no Automation consent. // The shell is left open when the agent quits. diff --git a/internal/gui/tests/agent-open-terminal.test.cjs b/internal/gui/tests/agent-open-terminal.test.cjs new file mode 100644 index 000000000..5147a65a9 --- /dev/null +++ b/internal/gui/tests/agent-open-terminal.test.cjs @@ -0,0 +1,120 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// coolmantou on Discord: start an agent from magpie's Agents list. On the +// Mac app's window, a row whose agent has a program to run (terminal) has +// "Open in terminal" in its menu, connected or under Not set up; it posts +// agents/open with the agent's id and nothing else (the command is made on +// the server). A desktop app with no program has no such item, and neither +// has the web build nor the tray panel. In every language; 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 options = ["gpt-5.4", "magpie/relay/m1"].map((m) => ({ value: m, label: "Label " + m, ...(m.startsWith("magpie/") ? { ref: "relay/m1" } : {}) })); +const state = { + agents: [ + { id: "codex", name: "Codex", icon: "generic", path: "/fixture/codex", wired: true, terminal: true, fields: [{ key: "model", label: "model", value: "magpie/relay/m1", options }] }, + { id: "desk", name: "Desk App", icon: "generic", path: "/Applications/Desk.app", wired: true, fields: [{ key: "model", label: "model", value: "magpie/relay/m1", options }] }, + { id: "claude", name: "Claude Code", icon: "generic", path: "/fixture/claude", terminal: true, fields: [{ key: "model", label: "model", value: "gpt-5.4", options }] }, + ], + profiles: [], +}; + +function server(lang, web, posts) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web}};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ ...state, settings: { lang, theme: "light" } }); + if (url.pathname === "/api/agents/open") { posts.push([url.pathname, req.postData()]); return route.fulfill({ status: 204, body: "" }); } + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/agents/cli") return json({ agents: {}, pending: false }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + 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 route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const words = { + en: { item: "Open in terminal" }, + zh: { item: "在终端中打开" }, + "zh-TW": { item: "在終端機中開啟" }, + ja: { item: "ターミナルで開く" }, + de: { item: "Im Terminal öffnen" }, +}; +const row = (id) => `.row.agent[data-id="${id}"]`; + +async function open(engine, t, lang, web, query) { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 980, height: 560 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(30000); // the page loads every core script + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, web, posts)); + await page.goto("http://magpie.test/" + query); + return { page, errors, posts }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + const w = words[lang]; + test(`${engine} ${lang}: Open in terminal on an agent's row`, async (t) => { + const { page, errors, posts } = await open(engine, t, lang, false, "?view=agents"); + await page.locator(row("codex")).waitFor(); + const item = () => page.locator(".pop.row-menu .rm-item", { hasText: w.item }); + const menu = async (id) => { + await page.locator(`${row(id)} .ag-handle`).click(); + await page.locator(".pop.row-menu").waitFor(); + }; + const close = async () => { await page.keyboard.press("Escape"); await page.locator(".pop.row-menu").waitFor({ state: "detached" }); }; + + await menu("desk"); + assert.equal(await item().count(), 0, "a desktop app with no program has nothing to open"); + await close(); + // Claude Code, not connected, is under Not set up: it has a program too + await page.locator(".agent-more").click(); + await page.waitForFunction(() => !document.querySelector(".agent-fold-inner")?.inert); + await menu("claude"); + assert.equal(await item().count(), 1, "a row under Not set up opens too"); + await close(); + + await menu("codex"); + assert.equal(await item().count(), 1); + const sent = page.waitForResponse((r) => new URL(r.url()).pathname === "/api/agents/open"); + await item().click(); + await sent; + await page.locator(".pop.row-menu").waitFor({ state: "detached" }); + assert.deepEqual(posts.map(([p, b]) => [p, JSON.parse(b)]), [["/api/agents/open", { agent: "codex" }]], "the id and nothing else"); + assert.deepEqual(errors, []); + }); + } + + test(`${engine}: the web build has no Open in terminal`, async (t) => { + const { page, errors } = await open(engine, t, "en", true, "?view=agents"); + await page.locator(row("codex")).waitFor(); + await page.locator(`${row("codex")} .ag-handle`).click(); + await page.locator(".pop.row-menu").waitFor(); + assert.equal(await page.locator(".pop.row-menu .rm-item", { hasText: "Open in terminal" }).count(), 0); + assert.deepEqual(errors, []); + }); + + test(`${engine}: the tray panel has no Open in terminal`, async (t) => { + const { page, errors, posts } = await open(engine, t, "en", false, "?mode=panel"); + // the panel's Agent tab has the same rows and menu, without the item + await page.locator(`${row("codex")} .ag-handle`).first().click(); + await page.locator(".pop.row-menu").waitFor(); + assert.equal(await page.locator(".rm-item", { hasText: "Open in terminal" }).count(), 0); + assert.deepEqual(posts, []); + assert.deepEqual(errors, []); + }); +}