Files
magpie/internal/gui/tests/session-terminal.test.cjs
T
yetone ead0bf0059 agents, sessions: open in a terminal on Windows and Linux too, and copy any CLI agent's launch line
lileo0668 on Discord: clicking an agent should start it in a terminal,
and a history session should resume there. Opening a terminal was the
Mac app's only (Open in terminal on an Agents row, and Sessions' Open in
the selected terminal and Continue with another agent), and Copy launch
command was only for agy, Cursor (local) and Claude Science.

- terminal_open.go: openTerminal off a Mac.
  - Windows: Windows PowerShell (the system default), PowerShell 7 and
    Windows Terminal. The line, PowerShell's as Sessions already copies
    it, goes as -EncodedCommand: no script file, so no execution policy,
    no file encoding and no quoting in between. A shell gets its own
    console through cmd's start (magpie's children are CREATE_NO_WINDOW);
    wt is started directly, on pwsh or else powershell.
  - Linux: $TERMINAL, then xdg-terminal-exec, then x-terminal-emulator,
    then the first of GNOME Terminal, Konsole, Xfce Terminal, kitty,
    Alacritty, Ghostty, foot, WezTerm, Terminator and XTerm, each with its
    own words before the command. The line runs from a script of its own
    in sh, then the user's shell, as the Mac's .command file does.
  - A terminal that quits failing within a second says so, with what it
    printed ("cannot open display").
- Settings' Session terminal row lists the terminals found on Windows and
  Linux too; no row when none is found.
- Every agent row with a program now carries `command`, the line the
  server builds (Launch, or the program quoted for this system's shell;
  an agent in a WSL distro is started through wsl.exe on Windows). The
  row menu (right-click or the grip) has Copy launch command after Open in
  terminal, on the web build and in the panel too.

Run:
- mote (macOS 27, go1.26.8): go vet of internal/gui and internal/settings
  for darwin, for linux with -tags nogui, and for windows; GOOS=windows
  and GOOS=linux (nogui) builds of the binary; go test ./internal/gui
  ./internal/settings ./internal/agent. Everything passes except
  TestMainWindowCorners/macOS_26_SDK, which is #3949.
- Windows (win-run, xiaomi-gpu): go test ./internal/gui ./internal/settings.
  The new tests pass, among them TestAgentLineWindows, where real
  PowerShell runs the encoded line on a claude.cmd in a folder named
  `it's a $(New-Item made1) & New-Item made2 #` and runs nothing else.
  The six reds are filed: TestLodyImportHandoff,
  TestImportStatusUnreadableIsUnknown and TestAionUiImportRow (#4115),
  TestUpdateThatWontStart (#1827), and TestPluginAgentMissingSaysSo and
  TestGatewayHeldByAContainer (#5324).
- Linux (wsl-run, magpie-desktop): go test -tags nogui -timeout 45m
  ./internal/gui ./internal/settings: both ok (internal/gui 630s; at
  the default 10m it timed out with nothing hung)
- Real use. A throwaway test called openTerminal, not committed.
  - On xiaomi-gpu's console desktop (schtasks /IT): system default and
    wt each opened a window and ran a line with ' and 中文. pwsh isn't
    installed there and was refused by name.
  - On magpie-desktop under Xvfb: the system default
    (x-terminal-emulator, the xfce4-terminal wrapper) and xfce4-terminal
    each ran it (TERM=xterm-256color, set by the terminal). xterm isn't
    installed there and was refused. Without a display, xfce4-terminal's
    "cannot open display" came back as the error.
- GUI (mote, Playwright Chromium and WebKit): agent-open-terminal (five
  languages, 980px and 420px; Copy sends the server's line to /api/copy
  unchanged), session-terminal (Win32 and Linux platforms at 420px, and
  no row when nothing is found), settings-general, and the agent-*,
  sessions-*, session-*, gui-de, gui-ja and gui-zh-tw files with
  fold-show-grip, grip-inset, tap-click, menu-input-scroll and
  click-scroll (102 files): 1689 pass, 5 fail. The fails:
  menu-input-scroll, 4 of 4 red alone on origin/main 152c3852f too
  (#3402), and i18n-keys' "a plugin's words are its own" is
  red on origin/main too (#5332, #5327, #5426, #5482).
- gofmt -l is clean. TestCoreScriptBudget passes; no budget was raised.

Broken by hand:
- PowerShell quoting turned into POSIX quoting: TestAgentLineWindows red.
- cmd's start dropped: TestWinTerminalArgv red.
- A terminal's failure ignored: TestOpenLinuxTerminalRuns red.
- app.js and settings.js put back as they were: 32 GUI tests red
  (agent-open-terminal, session-terminal).

Not tried:
- A real GNOME, KDE, kitty, Alacritty, Ghostty, foot or WezTerm. Their
  words come from their docs.
- Omarchy's xdg-terminal-exec.
- PowerShell 7 on a real desktop (not installed on the box).
- The packaged GUI app on Windows or Linux; the real runs called
  openTerminal from a test binary.

Refs #4474.

Reported-by: lileo0668 (Discord)
2026-11-06 16:02:04 +08:00

212 lines
12 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.
// The Mac settings page lists registered terminal apps and keeps the choice
// when another preference is saved. On Windows and Linux (lileo0668 on
// Discord) it lists the terminals the server found, and no row when it
// found none. The API is faked; no terminal is opened.
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 terminalApps = [
{ id: "com.apple.Terminal", name: "Terminal" },
{ id: "com.mitchellh.ghostty", name: "Ghostty" },
];
function serve(lang, posts, terminalDefault = "com.apple.Terminal", apps = terminalApps) {
let settings = {
theme: "light", lang, tray: "panel", sessionTerminal: "", terminalApps: apps,
terminalDefault, version: "test", dir: "/tmp/magpie",
gateway: "http://127.0.0.1:3425", visionModels: [], imageGenModels: [],
fx: { rate: 7.2, stale: false },
};
return async (route) => {
const request = route.request();
const pathname = new URL(request.url()).pathname;
const json = (data) => route.fulfill({ json: data });
if (pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
if (pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (pathname === "/api/state") return json({ agents: [], profiles: [], settings });
if (pathname === "/api/settings") {
if (request.method() === "POST") {
const body = request.postDataJSON();
posts.push(body);
settings = { ...settings, ...body };
}
return json(settings);
}
if (pathname === "/api/usage/quotas") return json([]);
if (pathname === "/api/groups") return json({ groups: [], models: [] });
if (pathname.startsWith("/api/")) return json({});
const file = path.join(assets, pathname === "/" ? "index.html" : pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
return route.fulfill({ body: await fs.readFile(file), contentType });
};
}
// The Session terminal row wheeled into view as a reader would: rows keep
// being added above it, so it sits under the window's foot, and a click
// Playwright scrolls in for is put back (a scroll that isn't the reader's,
// #1554) and lands on the foot
async function reach(page) {
const view = await page.locator("#view-settings").boundingBox();
await page.mouse.move(view.x + view.width / 2, view.y + view.height / 2);
const rest = () => page.evaluate(() => new Promise((done) => {
const v = document.querySelector("#view-settings");
let last = -1;
const look = () => { if (v.scrollTop === last) done(); else { last = v.scrollTop; setTimeout(look, 100); } };
look();
}));
for (let i = 0; i < 60; i++) {
const b = await page.locator("#sessionTerminalSelect").boundingBox();
if (b && b.y > view.y && b.y + b.height < view.y + view.height) return;
await page.mouse.wheel(0, b && b.y < view.y ? -40 : 40);
await rest();
}
assert.fail("the Session terminal row never came into view");
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
test(`${engine} ${lang}: session terminal preference`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const context = await browser.newContext({ viewport: { width: 900, height: 700 }, reducedMotion: "reduce" });
await context.addInitScript(() => Object.defineProperty(navigator, "platform", { get: () => "MacIntel" }));
const page = await context.newPage();
const errors = [], posts = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.route("**/*", serve(lang, posts));
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-session-terminal.png`) });
}
await browser.close();
});
await page.goto("http://magpie.test/");
await page.locator("#prefs").click();
const row = page.locator("#sessionTerminalRow");
await row.waitFor({ state: "visible" });
await reach(page);
// the app's own menu, not a native select
const select = page.locator("#sessionTerminalSelect");
assert.equal(await page.locator("#sessionTerminalRow select").count(), 0, "no native select");
const names = async () => {
await select.click();
await page.locator(".proto-menu").waitFor();
const got = (await page.locator(".proto-menu .pm-item .pm-name").allTextContents()).map((s) => s.trim());
await select.click();
assert.equal(await page.locator(".proto-menu").count(), 0, "a second click closes it");
return got;
};
const choose = async (name) => {
await select.click();
await page.locator(".proto-menu .pm-item", { hasText: name }).click();
assert.equal(await page.locator(".proto-menu").count(), 0, "a pick closes it");
};
assert.deepEqual(await names(), lang === "zh" ? ["系统默认(Terminal)", "Ghostty"] : ["System default (Terminal)", "Ghostty"]);
assert.equal(await select.getAttribute("data-value"), "system");
assert.equal((await select.textContent()).trim(), lang === "zh" ? "系统默认(Terminal)" : "System default (Terminal)");
const top = await page.evaluate(() => document.scrollingElement.scrollTop);
// the page is drawn again once the save is in; a Theme button from
// before then still sends the page as it was drawn, the old terminal
// with it, so the Theme click below waits for the new buttons, as a
// reader can only click what is on the page
await page.evaluate(() => document.querySelectorAll("#themeSegs .opt").forEach((b) => { b.dataset.before = "1"; }));
await choose("Ghostty");
assert.equal(await page.evaluate(() => document.scrollingElement.scrollTop), top, "the page doesn't move");
await page.waitForFunction(() => document.querySelector("#sessionTerminalSelect").dataset.value === "com.mitchellh.ghostty");
assert.equal((await select.textContent()).trim(), "Ghostty");
await page.waitForFunction(() => !document.querySelector("#themeSegs .opt[data-before]"));
// another setting saved (Theme, scrolled away above) keeps the terminal
await page.locator("#themeSegs .opt").last().evaluate((b) => b.click());
await page.waitForFunction(() => document.documentElement.dataset.theme === "dark");
assert.equal(posts.at(-1).sessionTerminal, "com.mitchellh.ghostty");
await page.reload();
await page.locator("#prefs").click();
await row.waitFor({ state: "visible" });
await reach(page);
assert.equal(await select.getAttribute("data-value"), "com.mitchellh.ghostty");
const savedSystem = page.waitForResponse((response) => response.url().endsWith("/api/settings") && response.request().method() === "POST");
await choose(lang === "zh" ? "系统默认" : "System default");
await savedSystem;
assert.equal(posts.at(-1).sessionTerminal, "");
await page.reload();
await page.locator("#prefs").click();
await row.waitFor({ state: "visible" });
await reach(page);
assert.equal(await select.getAttribute("data-value"), "system");
await page.setViewportSize({ width: 520, height: 700 });
assert.equal(await row.evaluate((element) => element.scrollWidth > element.clientWidth), false);
assert.deepEqual(errors, []);
});
// an editor as the .command default: the server opens Terminal, and says so
test(`${engine} ${lang}: an editor as the default reads as Terminal`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const context = await browser.newContext({ viewport: { width: 900, height: 700 }, reducedMotion: "reduce" });
await context.addInitScript(() => Object.defineProperty(navigator, "platform", { get: () => "MacIntel" }));
const page = await context.newPage();
await page.route("**/*", serve(lang, [], "com.apple.TextEdit"));
await page.goto("http://magpie.test/");
await page.locator("#prefs").click();
await page.locator("#sessionTerminalRow").waitFor({ state: "visible" });
await reach(page);
await page.locator("#sessionTerminalSelect").click();
assert.deepEqual((await page.locator(".proto-menu .pm-item .pm-name").allTextContents()).map((s) => s.trim()),
lang === "zh" ? ["系统默认(Terminal)", "Ghostty"] : ["System default (Terminal)", "Ghostty"]);
});
}
// Windows and Linux: the terminals found, the system's named; no Terminal.app
const own = {
Win32: { apps: [{ id: "wt", name: "Windows Terminal" }, { id: "pwsh", name: "PowerShell" }, { id: "powershell", name: "Windows PowerShell" }], def: "powershell", pick: "wt", zh: ["系统默认(Windows PowerShell)", "Windows Terminal", "PowerShell"], en: ["System default (Windows PowerShell)", "Windows Terminal", "PowerShell"] },
"Linux x86_64": { apps: [{ id: "xfce4-terminal", name: "Xfce Terminal" }, { id: "kitty", name: "kitty" }], def: "xfce4-terminal", pick: "kitty", zh: ["系统默认(Xfce Terminal)", "kitty"], en: ["System default (Xfce Terminal)", "kitty"] },
};
for (const [platform, o] of Object.entries(own)) {
for (const lang of ["en", "zh"]) {
test(`${engine} ${lang} ${platform}: the terminals found here`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const context = await browser.newContext({ viewport: { width: 420, height: 700 }, reducedMotion: "reduce" });
await context.addInitScript((p) => Object.defineProperty(navigator, "platform", { get: () => p }), platform);
const page = await context.newPage();
const errors = [], posts = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.route("**/*", serve(lang, posts, o.def, o.apps));
await page.goto("http://magpie.test/");
await page.locator("#prefs").click();
const row = page.locator("#sessionTerminalRow");
await row.waitFor({ state: "visible" });
await reach(page);
const select = page.locator("#sessionTerminalSelect");
await select.click();
await page.locator(".proto-menu").waitFor();
assert.deepEqual((await page.locator(".proto-menu .pm-item .pm-name").allTextContents()).map((s) => s.trim()), o[lang]);
const saved = page.waitForResponse((r) => r.url().endsWith("/api/settings") && r.request().method() === "POST");
await page.locator(".proto-menu .pm-item").nth(1).click();
await saved;
assert.equal(posts.at(-1).sessionTerminal, o.pick);
assert.equal(await row.evaluate((element) => element.scrollWidth > element.clientWidth), false, "fits 420px");
assert.deepEqual(errors, []);
});
}
test(`${engine} ${platform}: no terminal found, no row`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const context = await browser.newContext({ viewport: { width: 900, height: 700 }, reducedMotion: "reduce" });
await context.addInitScript((p) => Object.defineProperty(navigator, "platform", { get: () => p }), platform);
const page = await context.newPage();
await page.route("**/*", serve("en", [], "", []));
await page.goto("http://magpie.test/");
await page.locator("#prefs").click();
await page.locator("#themeSegs").waitFor();
assert.equal(await page.locator("#sessionTerminalRow").isHidden(), true);
});
}
}