Files
magpie/internal/gui/tests/quit-ask.test.cjs
T
yetone 8826a15ea4 gui: a Quit while agents go through magpie asks first, naming them (Aisiverto on X)
Aisiverto on X (Windows, v0.1.2519) wired Codex to magpie and quit magpie.
Codex then retried "unexpected status 502 Bad Gateway ... url:
http://127.0.0.1:3425/backend-api/codex/responses" five times and gave up,
and it took a long search to find magpie's openai_base_url in config.toml.

A Quit the user chooses (the tray's Quit, the panel's and window's Quit,
Command-Q on the Mac) now asks first when this process serves the gateway
and agents are wired to it. The window comes up on a sheet
(quitask.js, lazy-loaded) that names each agent cut off, says closing the
window keeps magpie running (menu bar on a Mac, system tray elsewhere),
and offers Quit (focused), Disconnect and quit, and Cancel. Disconnect and
quit puts each agent back as its row's Disconnect does, then quits; a
disconnect that fails keeps magpie open, named in the status line. A
second Quit within a minute of the question quits, so a window that
can't show it traps nobody. With nothing wired, or another magpie serving
the gateway, Quit quits at once.

Not asked: a restart to update, Uninstall, a browser's page (magpie web),
logging out or shutting down, and the Dock's Quit (AppKit terminate:).

Found while checking the report:
- Closing the window on Windows hides it; magpie stays in the tray and
  the gateway keeps serving (tried for real, below). Not a bug.
- Autostart is off by default on Windows.
- The proxy / NO_PROXY in the report isn't magpie's to fix: the 502 is
  magpie's port with nothing behind it.

Strings in en, zh, zh-TW, ja and de (existing terms: Agent, 退出). No
native dialog, no <select>. TestCoreScriptBudget met without a raise:
app.js gains two lines, the sheet is outside the core, and driftFix's
comment block is cut to six lines (453 bytes back; main's core had grown
to 258 bytes over with these lines in).

Run, at this head (on origin/main 94f6f6092), on mote unless said:
- gofmt -l internal/gui: clean.
- go vet ./..., GOOS=windows go vet ./..., GOOS=linux go vet -tags
  nogui ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows
  go build: ok.
- go test ./internal/gui -run 'Budget|Quit|CommandQ', and with -tags
  nogui -run 'Budget|Quit': ok (TestCommandQAsksFirst runs AppKit in a
  child process).
- quit-ask.test.cjs, old-webkit.test.cjs, i18n-keys.test.cjs in chromium
  and webkit, en/zh/zh-TW/ja/de: 60/60 ok.
- At the previous base (9d08993c8): go test ./internal/gui (whole
  package, GUI build): two reds. TestCoreScriptBudget (258 over, fixed
  above) and TestMainWindowCorners/macOS_26_SDK, red the same at
  9d08993c8 itself (#3949, macOS 27). The nogui run of the package was
  not reached.
- The whole GUI suite: started at 24fd4a250 on WSL (magpie-desktop),
  stopped about halfway (3,915 results) to rebase; 68 reds in 28 files.
  Those 28 files with quit-ask, old-webkit and i18n-keys at 9d08993c8+this
  on mote: 74 reds in 7 files, none in this change's files. The 7 alone
  at origin/main 9d08993c8: the same 6 files red (73), and
  gateway-caller-keys red at main when run alone (1 of 4). All filed:
  balance-fix #4682 #4683, key-replace #4126 #3476, agent-panel-name-width
  #4203 (red on macOS too, commented), context-map #3488, header-centre
  #3479, gateway-key-models #4616, gateway-caller-keys #3797.
- Not run: go test ./... in full (mote at load 140-160 with others' full
  suites, WSL with two GUI suites), and the GUI suite to its end.

Broken by hand, each red:
- api.go's ask skipped (false &&): TestWindowQuitAsksFirst "the window's
  Quit didn't ask (AskQuit never ran)".
- askingQuit without RemoveMenuItem: TestCommandQAsksFirst "the app menu
  still has the Quit role".
- quitNow as asked == 0 ||: TestQuitNow "connected, never asked: quitNow
  = true, want false".
- The return after a failed disconnect removed: quit-ask 5/25 chromium
  red (the failed-disconnect test in every language).
- app.js's ?ask=quit line removed: 20/25 webkit red.

Windows, for real (xiaomi-gpu, sandbox HOME/APPDATA under
C:\Users\yeton\quitask-sb, MAGPIE_ADDR 127.0.0.1:3471, MAGPIE_NO_ACCOUNTS,
a -H windowsgui build of this branch, launched in the desktop session):
`magpie codex fakeq/m1` wired the sandbox Codex to
http://127.0.0.1:3471/backend-api/codex; WM_CLOSE on the window left
the process alive with no visible window and the gateway listening.

Not tried:
- The tray's Quit and the sheet on real Windows: WebView2's CDP port
  never listened and UI Automation didn't find the tray icon, so the
  sheet was tried in Playwright only.
- A real Codex run against the sandbox gateway before and after a quit.
- The Dock's Quit (not covered by design).
2026-11-01 21:16:35 +08:00

170 lines
9.7 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// Aisiverto on X: Codex was wired to magpie, magpie was quit, and Codex
// failed with "502 Bad Gateway" five times with nothing to say why. A Quit
// the user chooses while agents go through magpie now asks first, in the
// app's own sheet (quitask.js; AskQuit in quitask_app.go opens the window
// on /?ask=quit or calls window.askQuit): it names each agent cut off,
// says that closing the window keeps magpie running (the menu bar on a
// Mac, the system tray elsewhere), and offers Quit, Disconnect and quit,
// and Cancel. Cancel posts nothing; Quit posts window/quit?now=1, which
// quits without asking again; Disconnect and quit disconnects each agent
// in turn and then quits, and a disconnect that fails keeps magpie open.
// With nothing connected any more it quits at once. In every language and
// 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 two = [
{ id: "codex", name: "Codex", icon: "generic" },
{ id: "claude", name: "Claude Code", icon: "generic" },
];
const keys = [
"Quit magpie?",
"{agent} goes through magpie, so it stops working while magpie is closed.",
"These agents go through magpie, so they stop working while magpie is closed.",
"Closing the window keeps magpie running in the menu bar.",
"Closing the window keeps magpie running in the system tray.",
"Disconnect and quit",
"Puts back each agent's own settings first, so they work without magpie",
"Quit",
"Cancel",
];
// until waits for f to hold (the posts the page makes), at most 5s
const until = async (f) => { for (let i = 0; i < 250 && !f(); i++) await new Promise((r) => setTimeout(r, 20)); };
function server(lang, posts, o) {
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data, status = 200) => route.fulfill({ status, json: data });
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
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(state);
if (url.pathname === "/api/quit") return json({ agents: o.agents });
if (req.method() === "POST" && url.pathname.startsWith("/api/agents/disconnect/")) {
posts.push(url.pathname);
if (o.fail === url.pathname.split("/").pop()) return json({ error: "config is locked" }, 500);
return json(state);
}
if (req.method() === "POST" && url.pathname === "/api/window/quit") { posts.push(url.pathname + url.search); return json({}); }
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 });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
const open = async (t, o, platform = "Win32", url = "/?ask=quit", width = 980) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 560 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], posts = [], dialogs = [];
page.on("pageerror", (e) => errors.push(e.message));
page.on("dialog", (d) => { dialogs.push(d.message()); d.dismiss(); });
await page.addInitScript((p) => Object.defineProperty(navigator, "platform", { get: () => p }), platform);
await page.route("**/*", server(lang, posts, o));
await page.goto("http://magpie.test" + url);
const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]);
t.after(() => { assert.deepEqual(errors, []); assert.deepEqual(dialogs, [], "no native dialog"); });
return { page, posts, tr };
};
test(`${engine} ${lang}: a Quit with agents connected names them and asks`, async (t) => {
const { page, posts, tr } = await open(t, { agents: two });
if (lang !== "en") {
const missing = await page.evaluate(([lang, keys]) => keys.filter((k) => !I18N[lang][k]), [lang, keys]);
assert.deepEqual(missing, [], "every string has its " + lang);
}
const ask = page.locator(".editor.quit-ask");
await ask.waitFor();
assert.equal(new URL(page.url()).searchParams.get("ask"), null, "the ask is spent, a reload doesn't ask again");
assert.equal((await ask.locator(".ehead b").textContent()).trim(), await tr("Quit magpie?"));
assert.deepEqual(await ask.locator(".quit-agents li").allTextContents(), ["Codex", "Claude Code"]);
const text = await ask.textContent();
assert.ok(text.includes(await tr("These agents go through magpie, so they stop working while magpie is closed.")));
assert.ok(text.includes(await tr("Closing the window keeps magpie running in the system tray.")), "off the Mac, the tray");
const quit = ask.locator(".bar button.primary");
assert.equal((await quit.textContent()).trim(), await tr("Quit"));
assert.ok(await quit.evaluate((b) => b === document.activeElement), "Quit has the focus");
assert.ok(await ask.locator(".bar button", { hasText: await tr("Disconnect and quit") }).getAttribute("title"), "it says what it does");
// Cancel posts nothing
await ask.locator(".bar button", { hasText: await tr("Cancel") }).click();
await ask.waitFor({ state: "detached" });
assert.deepEqual(posts, []);
// asked again (the window was up), Escape is a Cancel too
await page.evaluate(() => window.askQuit());
await ask.waitFor();
await page.keyboard.press("Escape");
await ask.waitFor({ state: "detached" });
assert.deepEqual(posts, []);
// Quit quits, without asking again
await page.evaluate(() => window.askQuit());
await ask.waitFor();
await quit.click();
await until(() => posts.length);
assert.deepEqual(posts, ["/api/window/quit?now=1"]);
});
test(`${engine} ${lang}: Disconnect and quit puts each agent back, then quits`, async (t) => {
const { page, posts, tr } = await open(t, { agents: two }, "MacIntel", "/", 420);
await page.locator("#status").waitFor({ state: "attached" });
await page.evaluate(() => window.askQuit());
const ask = page.locator(".editor.quit-ask");
await ask.waitFor();
assert.ok((await ask.textContent()).includes(await tr("Closing the window keeps magpie running in the menu bar.")), "on a Mac, the menu bar");
// narrow: the bar's buttons stay inside the sheet
const [box, bar] = await Promise.all([ask.boundingBox(), ask.locator(".bar").boundingBox()]);
assert.ok(bar.x >= box.x - 1 && bar.x + bar.width <= box.x + box.width + 1, "the bar fits a narrow window");
await ask.locator(".bar button", { hasText: await tr("Disconnect and quit") }).click();
await until(() => posts.length >= 3);
assert.deepEqual(posts, ["/api/agents/disconnect/codex", "/api/agents/disconnect/claude", "/api/window/quit?now=1"]);
});
test(`${engine} ${lang}: a disconnect that fails keeps magpie open`, async (t) => {
const { page, posts, tr } = await open(t, { agents: two, fail: "codex" });
const ask = page.locator(".editor.quit-ask");
await ask.waitFor();
const off = ask.locator(".bar button", { hasText: await tr("Disconnect and quit") });
await off.click();
await page.locator("#status.err").waitFor();
assert.match(await page.locator("#status").textContent(), /^Codex: /);
assert.deepEqual(posts, ["/api/agents/disconnect/codex"], "nothing after the failed one, no quit");
assert.equal(await ask.count(), 1, "the sheet stays");
assert.ok(await off.isEnabled(), "and can be tried again");
});
test(`${engine} ${lang}: one agent is named in the sentence`, async (t) => {
const { page, tr } = await open(t, { agents: two.slice(0, 1) }, "Linux x86_64");
const ask = page.locator(".editor.quit-ask");
await ask.waitFor();
const text = await ask.textContent();
assert.ok(text.includes(await tr("{agent} goes through magpie, so it stops working while magpie is closed.", { agent: "Codex" })));
assert.ok(text.includes(await tr("Closing the window keeps magpie running in the system tray.")));
});
test(`${engine} ${lang}: nothing connected any more quits at once`, async (t) => {
const { page, posts } = await open(t, { agents: [] });
await until(() => posts.length);
assert.deepEqual(posts, ["/api/window/quit?now=1"]);
assert.equal(await page.locator(".editor.quit-ask").count(), 0);
});
}
}