Files
magpie/internal/gui/tests/cli-path.test.cjs
T
yetone 2afacd7d18 windows: a terminal waits for magpie, through a magpie.com beside the app (#3737)
The Windows app is linked with -H windowsgui so a double click opens no
console, and PowerShell and cmd don't wait for a GUI program. The prompt
came back before magpie printed, and `magpie plugin login`'s password
keys went to the shell as well as to magpie (tom047784 / TomXPRIME on
Discord, 10-27; the handle error in the same report was 9298d2a).

A shell looks for `magpie` by PATHEXT, which lists .COM before .EXE. So
magpie now writes magpie.com beside the app. It is a 1.9MB console program
(internal/update/launcher), built and embedded by `make release-windows`
(the comlauncher tag). The shell waits for it. It runs the app with its own
std handles, passes MAGPIE_COM=1, waits, and exits with the app's code. The
app keeps those handles and borrows the console for the streams Windows
dropped (a GUI child gets no console handles), so redirection, pipes and
hidden prompts work. A command that opens the window (none, app, gui, tray,
panel, -Embedding, magpie: links) is started DETACHED, and the shell isn't
held. A double click and the Start menu still open magpie.exe.

Why this, and not a console-subsystem copy or a magpie-cli.exe: the
running process is still magpie.exe, so autostart, shortcuts, relaunch and
every os.Executable() use are unchanged. There is no new release asset (still
16), and magpie-releases needs no change. The trailer names the app, so a
download kept as magpie-windows-amd64.exe is run by its own name.

Where it is written:
- Settings › Command line's Add (cliPlace) writes it instead of magpie.cmd
  in a build that carries it.
- A terminal command run as magpie.exe writes it when the folder is on PATH
  or has a magpie.com or magpie.cmd, so existing users get it on their next
  `magpie <cmd>`.
- The app's start (placeExe) writes it again when the bytes differ, so an
  update brings it along.
- A running magpie.com is moved aside and cleared on the next run.
- A copy beside a magpie.exe leaves `magpie` to it (comOwner).
- The Command line row reads magpie.com as this app, with "(which runs
  magpie.exe)".

Run, at 2e165fe9d (main since then touches none of these files):
- gofmt -l: clean
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...
- go build for darwin, linux -tags nogui and windows
- make release-windows: amd64 and arm64 are PE subsystem 2 (GUI), as before
- go test -tags nogui -count=1 -timeout 45m ./internal/update/...
  ./internal/cli/ ./internal/gui/ ./internal/proc/: all ok
- cli-path.test.cjs in chromium and webkit (11 + 11 pass); i18n-keys,
  gui-zh-tw, gui-ja, gui-de pass
- The Windows box, with GOOS=windows test binaries: launcher's TestArgsOf,
  TestOpensWindow and TestTargetName pass; update's TestWriteCom,
  TestComOwner, TestEnsureCompanion, TestFindCLIPrefersCom and
  TestCLIShim pass. TestComMagicIsTheLaunchers reads the source, so it
  can't run from a copied binary there; it passes on macOS.
- The Windows box, sandbox HOME, release build, interactive ConPTY over
  ssh -tt with typed keys:
  - Old v0.1.1675 in PowerShell 7.5.4: the prompt comes back before
    "magpie 0.1.1675", $LASTEXITCODE is empty, `> out.txt` is empty, and
    backup's passphrase is split between the shell and magpie.
  - New build in PowerShell 7.5.4: the first `magpie` as magpie.exe wrote
    magpie.com, and Get-Command then resolves it. `magpie version` prints
    before the next line, with exit 0. A bad command gives 1. `> out.txt`
    holds the version. backup reads "Passphrase for the backup:" and
    "Again:" typed. restore reads "Passphrase:" typed. A piped passphrase
    is read (wrong passphrase, exit 1).
  - New build in cmd: `where` lists magpie.com first. The same version,
    ERRORLEVEL 0 and 1, and typed backup and restore passphrases work.
    Ctrl+C at a prompt ends it with 0xC000013A and leaves no magpie.exe.
  - The update: an older magpie.com in place was moved aside and rewritten
    by the first command of the new build, and the .old was gone after the
    next one.

Broken by hand, red:
- writeCom always rewriting: TestWriteCom
- EnsureCompanion ignoring PATH: TestEnsureCompanion
- comOwner always true: TestComOwner
- app.js's old shim-only condition: the "magpie.com is said to run the app"
  case in en and zh

Not tried:
- A real double click or the Start menu on the box. magpie.exe is still
  GUI-subsystem and is what they open, but no window was opened there. The
  sandbox app would share the gateway's port with the box's own magpie.
- Windows Terminal itself; the ConPTY ssh -tt gives is what it uses.
- The arm64 build on a real ARM machine.
- The full go test ./... at this head. Another session's agent and
  gateway suite was running on the machine (load ~115), so only the
  touched packages and internal/proc ran.
2026-10-27 12:08:16 +08:00

216 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.
// Run with Node's test runner and Playwright on the module path; see README.md.
// Settings › About › Command line (PAMI on Discord): whether `magpie` in a
// terminal opened now runs this app, said for each shell (a dot, no left
// border), and Add to PATH, which posts /api/cli and shows the answer. On
// Windows a program not named magpie.exe (the site's portable download,
// #942) is said to get a magpie.cmd that runs it, and a magpie.com that
// runs the app is said to run it (#3737). A
// shell whose PATH lacks the folder has its own button naming its profile,
// and only that button posts that shell. On Windows PowerShell and cmd are
// listed, with no profile to write; a translocated app gets no button. No
// click moves the page, nothing is a native select. English and Chinese; no
// backend, the API is faked.
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 { watchSettingsReads, settingsDrawn, openPart } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const words = {
en: { row: "Command line", add: "Add to PATH", none: "can't find the magpie command", ours: "runs this app", fish: "Add to ~/.config/fish/config.fish",
added: "open a new terminal window", ps: "PowerShell and cmd take up a change in new windows", moved: "moved to Applications",
shimTitle: "writes magpie.cmd there, which runs magpie-windows-amd64.exe", shimAdded: "magpie.cmd beside magpie-windows-amd64.exe runs it as magpie", shimRuns: "which runs magpie-windows-amd64.exe", comRuns: "which runs magpie.exe" },
zh: { row: "命令行", add: "添加到 PATH", none: "新终端里找不到 magpie 命令", ours: "运行这个 app", fish: "添加到 ~/.config/fish/config.fish",
added: "新开一个终端窗口", ps: "PowerShell 和 cmd 在新窗口里生效", moved: "移到「应用程序」",
shimTitle: "写一个 magpie.cmd 来运行 magpie-windows-amd64.exe", shimAdded: "magpie-windows-amd64.exe 旁边的 magpie.cmd", shimRuns: "它运行 magpie-windows-amd64.exe", comRuns: "它运行 magpie.exe" },
};
const EXE = "/Applications/magpie.app/Contents/MacOS/magpie";
function view(ctl) {
if (ctl.windows) {
// the site's portable download (#942) runs as magpie through the
// magpie.cmd Add writes beside it
const dir = ctl.portable ? "D:\\portable_app" : "C:\\Users\\u\\AppData\\Local\\magpie";
const exe = dir + (ctl.portable ? "\\magpie-windows-amd64.exe" : "\\magpie.exe"), shim = ctl.portable ? dir + "\\magpie.cmd" : "";
// a release build runs as magpie through the magpie.com it writes
// beside the app, which a shell waits for (#3737)
const cmd = ctl.added ? shim || (ctl.com ? dir + "\\magpie.com" : exe) : "";
return { exe, ours: ctl.added, command: cmd, dir, windows: true, shim,
shells: ["PowerShell", "cmd"].map((name, i) => ({ name, default: i === 0, known: true, ours: ctl.added, command: cmd })) };
}
const link = "/Users/u/.local/bin/magpie";
return {
exe: EXE, ours: ctl.added, command: ctl.added ? link : "", dir: ctl.added ? "" : "/Users/u/.local/bin", stuck: ctl.stuck || "",
shells: [
{ name: "zsh", default: true, known: true, ours: ctl.added, command: ctl.added ? link : "", profile: "~/.zshrc", hasDir: !ctl.added },
{ name: "fish", known: true, ours: ctl.fish, command: ctl.fish ? link : "/opt/old/magpie", profile: "~/.config/fish/config.fish" },
],
};
}
function server(lang, ctl) {
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:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { theme: "light", lang, version: "0.1.900", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425", lanURLs: [], fx: { rate: 7.2 } } });
if (url.pathname === "/api/cli") {
if (req.method() === "POST") {
const body = req.postDataJSON();
ctl.posts.push(body);
if (body.shell === "fish") ctl.fish = true;
else if (!body.shell) ctl.added = true;
} else ctl.gets++;
return json(view(ctl));
}
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
async function showRow(page, row) {
await page.locator("#view-settings").hover();
for (let i = 0; i < 40; i++) {
const box = await row.boundingBox();
const v = await page.locator("#view-settings").boundingBox();
if (box && v && box.y >= v.y + 4 && box.y + box.height <= v.y + v.height - 4) break;
await page.mouse.wheel(0, 180);
await page.waitForTimeout(16);
}
await page.waitForTimeout(250);
}
const scrolls = (page) => page.evaluate(() => [window.scrollY, document.scrollingElement.scrollTop, ...[...document.querySelectorAll(".view")].map((v) => v.scrollTop)].join(","));
async function open(browser, lang, ctl, errors) {
const page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, ctl));
await watchSettingsReads(page);
await page.goto("http://magpie.test/?view=settings");
await settingsDrawn(page); // rows found are the ones that stay (#1659)
await openPart(page, "about");
await page.locator("#setPage-about").waitFor({ state: "visible" });
const row = page.locator("#about .row.pref.cli-row");
await row.locator(".cli-shell").first().waitFor();
return { page, row };
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": Command line says what `magpie` runs, and adds it", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh"]) {
const w = words[lang];
await t.test(lang + ": Mac, Add to PATH then fish's own profile", async () => {
const ctl = { posts: [], gets: 0 };
const errors = [];
const { page, row } = await open(browser, lang, ctl, errors);
assert.equal((await row.locator(".name").innerText()).trim(), w.row);
await row.locator(".sub", { hasText: w.none }).waitFor();
const zsh = row.locator('.cli-shell[data-shell="zsh"]'), fish = row.locator('.cli-shell[data-shell="fish"]');
assert.equal(await zsh.evaluate((e) => e.classList.contains("on")), false);
assert.match(await fish.innerText(), /\/opt\/old\/magpie/, "fish names the other magpie it runs");
assert.equal(await row.locator("select").count(), 0, "no native select");
assert.equal(await zsh.locator("button").count(), 0, "zsh, whose PATH has the folder, is reached by Add to PATH");
assert.equal(await fish.locator("button", { hasText: w.fish }).count(), 1, "fish, whose PATH hasn't, has its profile's button");
for (const sel of [".cli-shell", ".cli-dot", ".row.pref.cli-row"]) {
const widths = await page.locator(sel).evaluateAll((es) => es.map((e) => parseFloat(getComputedStyle(e).borderLeftWidth) || 0));
assert.ok(widths.every((x) => x === 0), sel + " has no left border");
}
const add = row.locator("button.cli-add");
assert.equal((await add.innerText()).trim(), w.add);
await showRow(page, row);
let before = await scrolls(page);
await add.click();
await row.locator(".sub", { hasText: "/Users/u/.local/bin/magpie" }).waitFor();
await zsh.locator(".cli-state", { hasText: w.ours }).waitFor();
assert.deepEqual(ctl.posts, [{}], "Add to PATH posts no shell");
assert.equal(await zsh.evaluate((e) => e.classList.contains("on")), true);
assert.ok(await add.isHidden(), "Add is gone once it runs this app");
assert.match(await page.locator("#status").innerText(), new RegExp(w.added));
assert.equal(await scrolls(page), before, "the click must not scroll the page");
assert.equal(await zsh.locator("button").count(), 0, "zsh, which runs it, has no profile button");
// fish's own button names its profile and posts fish alone
const fb = fish.locator("button", { hasText: w.fish });
before = await scrolls(page);
await fb.click();
await fish.locator(".cli-state", { hasText: w.ours }).waitFor();
assert.deepEqual(ctl.posts, [{}, { shell: "fish" }]);
assert.equal(await scrolls(page), before, "the click must not scroll the page");
assert.deepEqual(errors, []);
await page.context().close();
});
await t.test(lang + ": Windows lists PowerShell and cmd, no profile", async () => {
const ctl = { posts: [], gets: 0, windows: true };
const errors = [];
const { page, row } = await open(browser, lang, ctl, errors);
assert.deepEqual(await row.locator(".cli-shell").evaluateAll((es) => es.map((e) => e.dataset.shell)), ["PowerShell", "cmd"]);
assert.equal(await row.locator(".cli-shell button").count(), 0);
assert.match(await row.locator(".cli-note").innerText(), new RegExp(w.ps));
await row.locator("button.cli-add").click();
await row.locator('.cli-shell.on[data-shell="cmd"]').waitFor();
assert.deepEqual(ctl.posts, [{}]);
assert.deepEqual(errors, []);
await page.context().close();
});
await t.test(lang + ": Windows' portable download gets a magpie.cmd, and says so (#942)", async () => {
const ctl = { posts: [], gets: 0, windows: true, portable: true };
const errors = [];
const { page, row } = await open(browser, lang, ctl, errors);
const add = row.locator("button.cli-add");
assert.match(await add.getAttribute("title"), new RegExp(w.shimTitle));
await add.click();
await row.locator(".sub", { hasText: "D:\\portable_app\\magpie.cmd" }).waitFor();
assert.match(await row.locator(".sub").innerText(), new RegExp(w.shimRuns));
assert.match(await page.locator("#status").innerText(), new RegExp(w.shimAdded));
assert.deepEqual(ctl.posts, [{}]);
assert.deepEqual(errors, []);
await page.context().close();
});
await t.test(lang + ": Windows' magpie.com is said to run the app (#3737)", async () => {
const ctl = { posts: [], gets: 0, windows: true, com: true };
const errors = [];
const { page, row } = await open(browser, lang, ctl, errors);
await row.locator("button.cli-add").click();
await row.locator(".sub", { hasText: "AppData\\Local\\magpie\\magpie.com" }).waitFor();
assert.match(await row.locator(".sub").innerText(), new RegExp(w.comRuns));
assert.deepEqual(errors, []);
await page.context().close();
});
await t.test(lang + ": a translocated app gets no button", async () => {
const ctl = { posts: [], gets: 0, stuck: "translocated" };
const errors = [];
const { page, row } = await open(browser, lang, ctl, errors);
await row.locator(".sub", { hasText: w.moved }).waitFor();
assert.ok(await row.locator("button.cli-add").isHidden());
assert.equal(await row.locator(".cli-shell button").count(), 0);
const missing = await page.evaluate(() => {
const src = String(renderCLI);
const keys = [...src.matchAll(/t\("((?:[^"\\]|\\.)*)"/g)].map((m) => JSON.parse('"' + m[1] + '"'));
return keys.filter((k) => !I18N.zh[k] || !I18N.ja[k] || !I18N.de[k]);
});
assert.deepEqual(missing, [], "every string has zh, ja and de");
assert.deepEqual(errors, []);
await page.context().close();
});
}
});
}