diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 319c10361..4f72e516d 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -24,6 +24,7 @@ three. | The app's log | `runGUI` and `runPanel` (so `magpie`, `app`, `tray`, `panel`, a window view and a `magpie:` link) call `startLog` before `gui.Run`: `applog.Start` sends the standard logger, which the gateway, the plugin host and Wails' error handler write to, to `app.log` in `appdir.Logs` as well as stderr (`quiet`, which never fails, first, since io.MultiWriter stops at a failed writer and an app opened from Explorer has no stderr), and points `debug.SetCrashOutput` at it, so a panic is in it. Opened from the Finder, the Dock or the Start menu the app has no terminal, and wrote its log nowhere (rayem1w on X, 0.1.2330). The folder is `~/Library/Logs/magpie` on macOS (beside the launch agent's `serve.log`, which launchd writes for `magpie serve`: the two processes never share a file), `%LOCALAPPDATA%\magpie\logs` on Windows, `$XDG_STATE_HOME/magpie` (`~/.local/state/magpie`) elsewhere, and `logs` in a portable data folder. The file is 0600. At 5 MiB (`Limit`) it becomes `app.old.log`; when another magpie (an update's new process) rotated it already (`os.SameFile` of the open file and the path differs), it is only opened again, and when it can't be moved it is emptied. Each line goes through `scrub`, which masks bearer and basic credentials, key and token query parameters, and `sk-`, `AIza`, `gh?_` and JWT shapes, though nothing logged is meant to carry one. Settings › About's Log row (`#logRow`, `settingsJSON.Log` from `applog.Current`, so `magpie web`, which writes no file, shows none) has its path and an Open (`POST /api/settings/log/reveal`) that shows its folder; `magpie log` prints where every log is, `-n` the last lines, `-f` follows across a rotation (`TestTheAppWritesItsLog`, `TestLogFollows`). | [`internal/applog/applog.go`](../../internal/applog/applog.go), [`gui_on.go`](../../internal/cli/gui_on.go), [`log_cli.go`](../../internal/cli/log_cli.go) | | No GUI build | `-tags nogui` builds magpie without the GUI: `hasGUI` is false and `runGUI` says to use `magpie tui`. The files of `internal/gui` that need Wails build under `!nogui`. | [`gui_off.go`](../../internal/cli/gui_off.go) | | The terminal quitting | `magpie tui` that served the gateway with an agent connected hands the gateway on as it quits, on Linux where nothing opens magpie at login (a WSL distro, a server over SSH; zaidu259434 on X): `keepGateway` starts magpie's service when it is installed, installs it (`daemon.Install`) when the user never removed it (`daemon.Removed`, a mark `magpie daemon uninstall` leaves), and otherwise starts `magpie serve` in its own session (`serveInBackground`, log in magpie's cache). Elsewhere, with nothing connected, or where magpie opens at login, it only says the gateway stopped. | [`keep.go`](../../internal/tui/keep.go) | +| The app quitting | A Quit the user chooses (the tray's Quit, the panel's and window's Quit, Command-Q on the Mac) while agents are connected to the gateway this process serves asks first (see [A Quit asks while agents go through magpie](#a-quit-asks-while-agents-go-through-magpie)). Closing the window only hides it: magpie stays in the menu bar or the system tray and the gateway keeps serving, on Windows too. | [`quitask.go`](../../internal/gui/quitask.go), [`quitask_app.go`](../../internal/gui/quitask_app.go), [`quitask.js`](../../internal/gui/assets/quitask.js) | ## Runtime path @@ -581,6 +582,41 @@ never empty: `OwnerTrace` says so with its second result). See `TestGatewayTraceIsLoopbackOnly` in [`trace_peer_test.go`](../../internal/gateway/trace_peer_test.go). +### A Quit asks while agents go through magpie + +Quitting magpie ends the gateway, and each agent wired to it fails until +magpie runs again with nothing to say why: Codex retried "502 Bad Gateway" +on `/backend-api/codex/responses` five times and gave up, and its user +found magpie's `openai_base_url` in config.toml only after a long search +(Aisiverto on X). So a Quit the user chooses asks first when +`quitAgents` (`agent.Detected()` filtered by `Wired`) names any agent and +this process serves the gateway (`served`; when another magpie serves it, +that one keeps serving the agents and the Quit goes on). + +- The tray's Quit and the page's Quit (`POST /api/window/quit` without + `now`, on a host that is a `quitAsker`) call `AskQuit`. On the Mac, + `askingQuit` puts magpie's own Command-Q item in place of the app menu's + Quit role. `AskQuit` brings the window up on the question: it opens + `/?ask=quit` when the window is gone or loading, else runs + `window.askQuit()` in the loaded page. +- `quitask.js` (lazy-loaded, so it adds nothing to the core) reads + `GET /api/quit` and draws the sheet: the agents, the sentence that they + stop while magpie is closed, a note that closing the window keeps magpie + running (the menu bar on a Mac, the system tray elsewhere), and Disconnect + and quit, Cancel, and Quit (focused). Quit posts `window/quit?now=1`. + Disconnect and quit disconnects each agent in turn, as its row's + Disconnect does, and a failure leaves magpie open, named in the status + line. With nothing connected any more it quits without drawing. +- A second Quit within a minute of the question (`quitNow`, `quitAgain`) + quits, so a window that can't show the question doesn't trap the user. +- Not asked: a restart to update, Uninstall, a browser's page (`magpie + web`), logging out or shutting down, and the Dock's Quit (AppKit's + `terminate:`). + +See `TestWindowQuitAsksFirst`, `TestQuitListsWiredAgents`, +`TestQuitAPIListsAgents`, `TestQuitNow`, `TestCommandQAsksFirst` and +`quit-ask.test.cjs`. + ### A restart to update hands the gateway over On a Mac and on Linux, a restart into a downloaded update (the Update pill, diff --git a/internal/gui/api.go b/internal/gui/api.go index 2373d13c8..966b43bb7 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -2511,6 +2511,10 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { } rw.WriteHeader(http.StatusNoContent) }) + // the agents a quit would cut off, for its question (quitask.go) + mux.HandleFunc("GET /api/quit", func(rw http.ResponseWriter, r *http.Request) { + writeJSON(rw, map[string]any{"agents": quitAgents()}) + }) mux.HandleFunc("POST /api/window/{action}", func(rw http.ResponseWriter, r *http.Request) { switch r.PathValue("action") { case "hide": @@ -2518,7 +2522,13 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { case "main": w.ShowMain(mainView(r.URL.Query())) case "quit": - w.Quit() + // the user's Quit asks first while agents are connected + // (quitask.go); the question's own Quit is now=1 + if a, ok := w.(quitAsker); ok && r.URL.Query().Get("now") == "" { + go a.AskQuit() + } else { + w.Quit() + } case "fit": if h, g, ok := parseFit(r.URL.Query()); ok { w.FitPanel(h, g) diff --git a/internal/gui/app.go b/internal/gui/app.go index 81db129df..6569fcc20 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -100,6 +100,10 @@ type host struct { // screen; it is hidden once it has closing atomic.Bool + // quitAt is when a Quit the user chose last asked first (AskQuit, unix + // nanoseconds) + quitAt atomic.Int64 + ready chan struct{} // closed once the main window can be shown readyOnce sync.Once @@ -457,6 +461,7 @@ func Run(version string, showMain bool, link string) error { if !webView2Check(h.app) { return nil } + var appQuit *application.MenuItem // the Mac's app menu's Quit // Wails' default Learn More replaces the current window with wails.io. // Keep the native menus, but open magpie's help in the system browser. // macOS only: it is the one that shows a menu bar unasked; on Linux a @@ -466,6 +471,10 @@ func Run(version string, showMain bool, link string) error { help := appMenu.FindByRole(application.HelpMenu).GetSubmenu() help.Clear() help.Add("Learn More").OnClick(func(*application.Context) { _ = h.OpenURL("https://usemagpie.ai") }) + // Command-Q asks first while agents are connected (quitask.go). The + // role's item sends terminate:, which logging out and shutting down + // send too, so it is replaced rather than the app's ShouldQuit set + appQuit = askingQuit(appMenu, trayText(trayLang(settings.Load().Lang, systemLang), "Quit magpie"), func() { go h.AskQuit() }) h.app.Menu.Set(appMenu) } if Started != nil { @@ -506,7 +515,7 @@ func Run(version string, showMain bool, link string) error { } updates.restartAsked(now) }) - quit := menu.Add(labels.quit).OnClick(func(*application.Context) { h.app.Quit() }) + quit := menu.Add(labels.quit).OnClick(func(*application.Context) { go h.AskQuit() }) var ready string // the version waiting for a restart; on the main thread relabel := func() { l := trayMenuLabels(trayLang(settings.Load().Lang, systemLang), version, ready) @@ -518,6 +527,9 @@ func Run(version string, showMain bool, link string) error { restart.SetLabel(l.restart) quit.SetLabel(l.quit) menu.Update() + if appQuit != nil { + appQuit.SetLabel(l.quit) + } } onLang = func() { application.InvokeSync(relabel) } updates.onReady = func(v string) { diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 51c64fb0e..3c1e4b899 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -4636,6 +4636,11 @@ body.window .row + .row.agent.conn > .who { min-height: 41px; } /* the line abov .ag-diff-loading { padding: 14px 0; font-size: 12px; color: var(--muted); } .disconnect-ask .ag-note { grid-column: 1 / -1; margin: 0 0 10px; font-size: 12px; color: var(--muted); } .ag-bar-note { font-size: 12px; color: var(--muted); } +/* a Quit's question: the agents it cuts off, a row each (quitask.js) */ +.quit-ask .quit-agents { grid-column: 1 / -1; list-style: none; margin: 2px 0 10px; padding: 0; display: grid; gap: 6px; } +.quit-ask .quit-agents li { display: flex; align-items: center; gap: 8px; min-width: 0; font-size: 13px; } +.quit-ask .quit-agents li > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.quit-ask .ag-note { grid-column: 1 / -1; margin: 0 0 10px; font-size: 12px; color: var(--muted); } @media (max-width: 600px) { body.window .row.agent.conn { display: flex; } /* the name beside its logo; the link and the switch wrap under it when short of room */ diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 524ae5b0a..bde1ec44b 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -1066,18 +1066,12 @@ function profileDetail(p, footed) { return d; } -// driftNote: under the name of an agent whose config something else -// rewrote since magpie set it — the row still shows a magpie model while the -// agent no longer reaches magpie, or it was put back on a model of its own — -// what happened, and the one click that sets it again. -// driftFix is the one thing a drifted agent shows: an amber pill after its -// name that sets magpie's settings again. What is off is its tooltip; taking -// the config as it is now is in the row's menu. -// An agent whose config is right but whose address doesn't answer (#1013) -// has nothing to set again: its pill says what has to listen there, unless -// WSL now reaches Windows at another address, which it moves the config to. -// Likewise one whose requests for magpie go through a proxy that doesn't -// pass them on (proxied: Codex, Muma102kMichael on X). +// driftFix: an amber pill after a drifted agent's name (its config was +// rewritten since magpie set it) that sets magpie's settings again; what is +// off is its tooltip. With the config right but its address not answering +// (#1013), or its requests through a proxy that drops them (Codex, +// Muma102kMichael on X), it says what must listen there, or moves a WSL +// config to Windows' new address. function driftFix(a, label = "Apply again") { const d = a.drift, f = a.fields.find((x) => x.key === d.field); const want = (f && optionFor(f, d.want)?.label) || d.want; @@ -18077,6 +18071,8 @@ async function askReset(q) { try { await import("./resetask.js"); } catch (err) { return statusErr(err); } askResetSheet(q); } +// a Quit's question (quitask.js); unloaded, it quits +window.askQuit = () => import("./quitask.js").then(() => askQuitSheet(), () => api("window/quit?now=1", {})); // closes a confirmation, nothing more (its Cancel, or an OK that only dismisses) function cancelAsk(e) { e.stopPropagation(); closeConfirmAsk(); } // THIRD_PARTY_NOTICES, which every build carries @@ -24459,4 +24455,5 @@ if (mode === "window" && params.get("import")) { if (providers && view === "providers") renderProviders(); }).catch(() => {}); } +if (mode === "window" && params.get("ask") === "quit") { params.delete("ask"); history.replaceState(null, "", "?" + params); askQuit(); } if (mode === "window" && params.get("view") === "providers" && params.get("edit")) editing = params.get("edit"); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 3a8390c6c..8bf710c7c 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -611,6 +611,13 @@ const I18N = { "Take out everything magpie wrote into {agent}'s config and put back what it had before": "移除 magpie 写入 {agent} 配置的内容,还原接入前的设置", "put back what {agent} had before magpie": "还原 {agent} 接入 magpie 之前的设置", "Disconnect {agent} from magpie?": "断开 {agent} 和 magpie?", + "Quit magpie?": "退出 magpie?", + "{agent} goes through magpie, so it stops working while magpie is closed.": "{agent} 通过 magpie 连接,magpie 关闭期间它将无法使用。", + "These agents go through magpie, so they stop working while magpie is closed.": "这些 Agent 通过 magpie 连接,magpie 关闭期间它们将无法使用。", + "Closing the window keeps magpie running in the menu bar.": "关闭窗口时 magpie 会继续在菜单栏中运行。", + "Closing the window keeps magpie running in the system tray.": "关闭窗口时 magpie 会继续在系统托盘中运行。", + "Disconnect and quit": "断开并退出", + "Puts back each agent's own settings first, so they work without magpie": "先恢复每个 Agent 自己的设置,让它们不经过 magpie 也能使用", "magpie takes out everything it wrote into {agent}'s config — its endpoint, key, models and effort — and puts back the settings {agent} had before. magpie's providers and accounts stay as they are.": "移除 magpie 写入 {agent} 配置的所有内容(接口地址、密钥、模型和推理强度),还原 {agent} 之前的设置。magpie 的供应商和账号不受影响。", "Disconnect": "断开", "Not connected · {agent} uses its own settings": "未接入 · 用 {agent} 自己的设置", @@ -4969,6 +4976,13 @@ const I18N = { "Take out everything magpie wrote into {agent}'s config and put back what it had before": "移除 magpie 寫入 {agent} 設定的內容,還原接入前的設定", "put back what {agent} had before magpie": "還原 {agent} 接入 magpie 之前的設定", "Disconnect {agent} from magpie?": "斷開 {agent} 和 magpie?", + "Quit magpie?": "退出 magpie?", + "{agent} goes through magpie, so it stops working while magpie is closed.": "{agent} 透過 magpie 連線,magpie 關閉期間它將無法使用。", + "These agents go through magpie, so they stop working while magpie is closed.": "這些 Agent 透過 magpie 連線,magpie 關閉期間它們將無法使用。", + "Closing the window keeps magpie running in the menu bar.": "關閉視窗時 magpie 會繼續在選單列中執行。", + "Closing the window keeps magpie running in the system tray.": "關閉視窗時 magpie 會繼續在系統匣中執行。", + "Disconnect and quit": "斷開並退出", + "Puts back each agent's own settings first, so they work without magpie": "先還原每個 Agent 自己的設定,讓它們不經過 magpie 也能使用", "magpie takes out everything it wrote into {agent}'s config — its endpoint, key, models and effort — and puts back the settings {agent} had before. magpie's providers and accounts stay as they are.": "移除 magpie 寫入 {agent} 設定的所有內容(介面位址、金鑰、模型和推理強度),還原 {agent} 之前的設定。magpie 的供應商和帳號不受影響。", "Disconnect": "斷開", "Not connected · {agent} uses its own settings": "未接入 · 用 {agent} 自己的設定", @@ -9292,6 +9306,13 @@ const I18N = { "Take out everything magpie wrote into {agent}'s config and put back what it had before": "magpie が {agent} の設定に書き込んだ内容をすべて削除し、以前の設定に戻します", "put back what {agent} had before magpie": "{agent} を magpie 接続前の設定に戻す", "Disconnect {agent} from magpie?": "{agent} を magpie から切断しますか?", + "Quit magpie?": "magpie を終了しますか?", + "{agent} goes through magpie, so it stops working while magpie is closed.": "{agent} は magpie を経由しているため、magpie を閉じている間は動作しません。", + "These agents go through magpie, so they stop working while magpie is closed.": "これらのエージェントは magpie を経由しているため、magpie を閉じている間は動作しません。", + "Closing the window keeps magpie running in the menu bar.": "ウインドウを閉じても magpie はメニューバーで動作し続けます。", + "Closing the window keeps magpie running in the system tray.": "ウインドウを閉じても magpie はシステムトレイで動作し続けます。", + "Disconnect and quit": "切断して終了", + "Puts back each agent's own settings first, so they work without magpie": "まず各エージェント自身の設定に戻し、magpie なしでも動作するようにします", "magpie takes out everything it wrote into {agent}'s config — its endpoint, key, models and effort — and puts back the settings {agent} had before. magpie's providers and accounts stay as they are.": "magpie は {agent} の設定に書き込んだ内容(エンドポイント、キー、モデル、推論レベル)をすべて削除し、{agent} を以前の設定に戻します。magpie のプロバイダとアカウントはそのままです。", "Disconnect": "切断", "Not connected · {agent} uses its own settings": "未接続 · {agent} は独自の設定を使用", @@ -13633,6 +13654,13 @@ const I18N = { "Take out everything magpie wrote into {agent}'s config and put back what it had before": "Alles entfernen, was magpie in die Konfiguration von {agent} geschrieben hat, und den vorherigen Stand wiederherstellen", "put back what {agent} had before magpie": "Stand von {agent} vor magpie wiederherstellen", "Disconnect {agent} from magpie?": "{agent} von magpie trennen?", + "Quit magpie?": "magpie beenden?", + "{agent} goes through magpie, so it stops working while magpie is closed.": "{agent} läuft über magpie und funktioniert nicht, solange magpie geschlossen ist.", + "These agents go through magpie, so they stop working while magpie is closed.": "Diese Agenten laufen über magpie und funktionieren nicht, solange magpie geschlossen ist.", + "Closing the window keeps magpie running in the menu bar.": "Wenn du das Fenster schließt, läuft magpie in der Menüleiste weiter.", + "Closing the window keeps magpie running in the system tray.": "Wenn du das Fenster schließt, läuft magpie im Infobereich weiter.", + "Disconnect and quit": "Trennen und beenden", + "Puts back each agent's own settings first, so they work without magpie": "Stellt zuerst die eigenen Einstellungen jedes Agenten wieder her, damit er ohne magpie funktioniert", "magpie takes out everything it wrote into {agent}'s config — its endpoint, key, models and effort — and puts back the settings {agent} had before. magpie's providers and accounts stay as they are.": "magpie entfernt alles, was es in die Konfiguration von {agent} geschrieben hat — Endpunkt, Schlüssel, Modelle und Reasoning-Effort — und stellt die vorherigen Einstellungen von {agent} wieder her. Anbieter und Konten in magpie bleiben unverändert.", "Disconnect": "Trennen", "Not connected · {agent} uses its own settings": "Nicht verbunden · {agent} nutzt eigene Einstellungen", diff --git a/internal/gui/assets/quitask.js b/internal/gui/assets/quitask.js new file mode 100644 index 000000000..a96cc9e10 --- /dev/null +++ b/internal/gui/assets/quitask.js @@ -0,0 +1,71 @@ +// The question a Quit the user chose puts while agents are connected to +// magpie's gateway (quitask.go; Aisiverto on X: Codex failed with 502s +// after magpie was quit, and nothing said why). It names the agents that +// stop working, says that closing the window keeps magpie running, and +// offers Quit, Disconnect and quit (each agent's own settings put back, +// as its row's Disconnect does), or Cancel. app.js imports this when the +// question is put, so it weighs nothing on the core. +window.askQuitSheet = async function () { + let agents; + try { ({ agents } = await api("quit")); } catch { agents = null; } + // nothing connected any more (disconnected meanwhile): the Quit goes on + if (agents && !agents.length) return api("window/quit?now=1", {}); + const ed = el("div", "editor quit-ask"); + const head = el("div", "ehead"); + head.append(el("b", "", t("Quit magpie?"))); + ed.append(head); + const one = agents?.length === 1; + ed.append(el("p", "lib-confirm", one + ? t("{agent} goes through magpie, so it stops working while magpie is closed.", { agent: agents[0].name }) + : t("These agents go through magpie, so they stop working while magpie is closed."))); + if (agents) { + const list = el("ul", "quit-agents"); + for (const a of agents) { + const li = el("li"); + li.append(icon(a.icon), el("span", "", a.name)); + list.append(li); + } + ed.append(list); + } + const mac = document.body.classList.contains("mac"); + ed.append(el("p", "ag-note", mac ? t("Closing the window keeps magpie running in the menu bar.") + : t("Closing the window keeps magpie running in the system tray."))); + const bar = el("div", "bar"); + const quit = el("button", "text primary", t("Quit")); + const off = el("button", "text", t("Disconnect and quit")); + off.title = t("Puts back each agent's own settings first, so they work without magpie"); + const cancel = el("button", "text", t("Cancel")); + const busy = (b, on) => { + for (const x of [quit, off, cancel]) x.disabled = on; + b.classList.toggle("busy", on); + }; + quit.onclick = async (e) => { + e.stopPropagation(); + busy(quit, true); + try { await api("window/quit?now=1", {}); } catch (err) { busy(quit, false); statusErr(err); } + }; + // each agent put back as its row's Disconnect puts it back; one that + // can't be leaves magpie open, with the rest still listed + off.onclick = async (e) => { + e.stopPropagation(); + busy(off, true); + for (const a of agents || []) { + try { + state = await api("agents/disconnect/" + a.id, {}); + } catch (err) { + busy(off, false); + status(a.name + ": " + t(err.message), "err"); + return; + } + } + try { await api("window/quit?now=1", {}); } catch (err) { busy(off, false); statusErr(err); } + }; + cancel.onclick = cancelAsk; + if (agents) bar.append(off); + bar.append(el("span", "grow"), cancel, quit); + ed.append(bar); + confirmAsk = ed; + openModal(ed); + $("#modal").classList.add("lib"); + quit.focus(NO_SCROLL); +}; diff --git a/internal/gui/quitask.go b/internal/gui/quitask.go new file mode 100644 index 000000000..cc7282dbc --- /dev/null +++ b/internal/gui/quitask.go @@ -0,0 +1,68 @@ +package gui + +import ( + "time" + + "github.com/yetone/magpie/internal/agent" +) + +// Quitting magpie ends the gateway, and every agent connected to it fails +// until magpie is opened again, with nothing to say why: Codex retried +// "unexpected status 502 Bad Gateway: Unknown error" five times and gave +// up, and its user found magpie's line in ~/.codex/config.toml only after +// a long search (Aisiverto on X). So a Quit the user chooses (the tray's +// menu, the panel's Quit, Command-Q on the Mac) while agents are connected +// opens the window on a question first, naming them (quitask.js): Quit, +// Disconnect and quit (each one's own settings put back, as its row's +// Disconnect does), or Cancel. A quit magpie makes itself (a restart to +// update, Uninstall) and the system's own (logging out, shutting down, +// the Dock's Quit) don't ask. + +// quitAgentJSON is an agent a quit would cut off, for the question. +type quitAgentJSON struct { + ID string `json:"id"` + Name string `json:"name"` + Icon string `json:"icon"` +} + +// quitAgents lists the agents connected to the gateway this process +// serves: none when another magpie serves it, which goes on serving them. +// A var so tests can say. +var quitAgents = func() []quitAgentJSON { + if served.Load() == nil { + return nil + } + return wiredAgents(agent.Detected()) +} + +// wiredAgents is the agents of as with magpie in their config. +func wiredAgents(as []*agent.Agent) []quitAgentJSON { + out := []quitAgentJSON{} + for _, a := range as { + if a.Wired() { + out = append(out, quitAgentJSON{ID: a.ID, Name: a.Name, Icon: a.Icon}) + } + } + return out +} + +// quitAsker is a host that asks before a quit the user chose (the app's); +// a browser's page (magpie web) quits at once. +type quitAsker interface { + // AskQuit quits, or first asks in the window when agents are connected + AskQuit() +} + +// quitAgain is how long after the question is put a second Quit quits +// without it. +const quitAgain = time.Minute + +// quitNow says whether a Quit chosen at now quits without asking: with no +// agent connected (wired), or within quitAgain of the question put at +// asked (unix nanoseconds; 0 when it never was). +func quitNow(asked int64, now time.Time, wired int) bool { + if wired == 0 { + return true + } + return asked != 0 && now.Sub(time.Unix(0, asked)) < quitAgain +} diff --git a/internal/gui/quitask_app.go b/internal/gui/quitask_app.go new file mode 100644 index 000000000..5b673fa8f --- /dev/null +++ b/internal/gui/quitask_app.go @@ -0,0 +1,52 @@ +//go:build !nogui + +package gui + +import ( + "time" + + "github.com/wailsapp/wails/v3/pkg/application" +) + +// askQuitJS has the window's page put the question; askQuitURL opens a +// window made again on it. +const ( + askQuitJS = "window.askQuit?.()" + askQuitURL = "/?ask=quit" +) + +// AskQuit is a Quit the user chose: at once while no agent is connected to +// the gateway this process serves, else the window comes up and asks +// (quitask.go). A second Quit within quitAgain of the question quits: the +// user has been told, and it is the way out should the window not show it. +func (h *host) AskQuit() { + if quitNow(h.quitAt.Load(), time.Now(), len(quitAgents())) { + h.app.Quit() + return + } + h.quitAt.Store(time.Now().UnixNano()) + application.InvokeSync(func() { + if h.main == nil || h.loading[h.main] { + h.openMain(askQuitURL + h.query) + return + } + h.openMain("") + h.main.ExecJS(askQuitJS) + }) +} + +// askingQuit puts an item of label in place of the Quit item of menu's +// app menu, with Command-Q, that calls ask; nil when menu has none. +func askingQuit(menu *application.Menu, label string, ask func()) *application.MenuItem { + app := menu.FindByRole(application.AppMenu) + if app == nil || app.GetSubmenu() == nil { + return nil + } + sub := app.GetSubmenu() + old := sub.FindByRole(application.Quit) + if old == nil { + return nil + } + sub.RemoveMenuItem(old) + return sub.Add(label).SetAccelerator("CmdOrCtrl+q").OnClick(func(*application.Context) { ask() }) +} diff --git a/internal/gui/quitask_darwin_test.go b/internal/gui/quitask_darwin_test.go new file mode 100644 index 000000000..fa926d756 --- /dev/null +++ b/internal/gui/quitask_darwin_test.go @@ -0,0 +1,59 @@ +//go:build darwin && cgo && !nogui + +package gui + +import ( + "fmt" + "os" + "strings" + "testing" + "time" + + "github.com/wailsapp/wails/v3/pkg/application" +) + +// Command-Q on the Mac is the app menu's Quit, which AppKit sends to +// terminate: and which never reached magpie's question (Aisiverto on X). +// askingQuit puts magpie's own item in its place, with Command-Q, and no +// item with the Quit role is left to send terminate:. +func TestCommandQAsksFirst(t *testing.T) { + out, err := runAppKit(t, 30*time.Second, []string{"MAGPIE_TEST_QUIT_MENU=1"}) + if err != nil || !strings.Contains(string(out), "quit menu: ok") { + t.Fatalf("quit menu: %v\n%s", err, out) + } +} + +func init() { + if os.Getenv("MAGPIE_TEST_QUIT_MENU") != "1" { + return + } + fail := func(format string, a ...any) { + fmt.Printf("quit menu: "+format+"\n", a...) + os.Exit(1) + } + application.New(application.Options{Name: "magpie"}) + menu := application.DefaultApplicationMenu() + if menu.FindByRole(application.Quit) == nil { + fail("the default app menu has no Quit to replace; the cause isn't what this test is about") + } + item := askingQuit(menu, "Quit magpie", func() {}) + if item == nil { + fail("no item was put in the app menu") + } + if menu.FindByRole(application.Quit) != nil { + fail("the app menu still has the Quit role, which sends terminate: past the question") + } + if item.Label() != "Quit magpie" || item.GetAccelerator() == "" { + fail("the item is %q with accelerator %q, want Quit magpie with Command-Q", item.Label(), item.GetAccelerator()) + } + sub := menu.FindByRole(application.AppMenu).GetSubmenu() + var last *application.MenuItem + for i := 0; sub.ItemAt(i) != nil; i++ { + last = sub.ItemAt(i) + } + if last != item { + fail("the item isn't last in the app menu, where Quit was") + } + fmt.Println("quit menu: ok") + os.Exit(0) +} diff --git a/internal/gui/quitask_test.go b/internal/gui/quitask_test.go new file mode 100644 index 000000000..a068eb4ee --- /dev/null +++ b/internal/gui/quitask_test.go @@ -0,0 +1,130 @@ +package gui + +import ( + "encoding/json" + "net/http/httptest" + "testing" + "time" + + "github.com/yetone/magpie/internal/agent" +) + +// A Quit the user chose while agents go through magpie asks first +// (Aisiverto on X: Codex's 502s after magpie was quit, with nothing to +// say why). The window's Quit reaches AskQuit; the question's own Quit +// (now=1) quits; a browser's page (magpie web) has no window to ask in +// and quits. +func TestWindowQuitAsksFirst(t *testing.T) { + quits := 0 + asked := make(chan struct{}, 4) + h := Handler(askingHost{webHost{quit: func() { quits++ }}, asked}, nil) + post := func(url string) { + t.Helper() + r := httptest.NewRecorder() + h.ServeHTTP(r, httptest.NewRequest("POST", url, nil)) + if r.Code != 204 { + t.Fatalf("%s: %d %s", url, r.Code, r.Body) + } + } + + post("/api/window/quit") + select { + case <-asked: + case <-time.After(5 * time.Second): + t.Fatal("the window's Quit didn't ask (AskQuit never ran)") + } + if quits != 0 { + t.Fatalf("the window's Quit quit %d times without asking", quits) + } + + post("/api/window/quit?now=1") + if quits != 1 { + t.Fatalf("the question's Quit (now=1) quit %d times, want 1", quits) + } + select { + case <-asked: + t.Fatal("the question's own Quit asked again") + default: + } + + web := Handler(webHost{quit: func() { quits++ }}, nil) + r := httptest.NewRecorder() + web.ServeHTTP(r, httptest.NewRequest("POST", "/api/window/quit", nil)) + if quits != 2 { + t.Fatalf("a browser's Quit quit %d times, want at once", quits-1) + } +} + +// askingHost is a host that asks, as the app's does. +type askingHost struct { + webHost + asked chan struct{} +} + +func (h askingHost) AskQuit() { h.asked <- struct{}{} } + +// The question names the agents magpie is in, and only those. +func TestQuitListsWiredAgents(t *testing.T) { + yes := func() bool { return true } + got := wiredAgents([]*agent.Agent{ + {ID: "codex", Name: "Codex", Icon: "openai", Joined: yes}, + {ID: "claude", Name: "Claude Code", Icon: "claude"}, + {ID: "hermes", Name: "Hermes", Icon: "hermes", Beside: yes}, + }) + want := []quitAgentJSON{{ID: "codex", Name: "Codex", Icon: "openai"}, {ID: "hermes", Name: "Hermes", Icon: "hermes"}} + if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] { + t.Fatalf("wired agents = %+v, want %+v", got, want) + } + // none is an empty list, which the page reads as "quit at once" + if b, _ := json.Marshal(wiredAgents(nil)); string(b) != "[]" { + t.Fatalf("no agents marshal as %s, want []", b) + } +} + +// GET /api/quit is what the question reads. +func TestQuitAPIListsAgents(t *testing.T) { + old := quitAgents + t.Cleanup(func() { quitAgents = old }) + quitAgents = func() []quitAgentJSON { return []quitAgentJSON{{ID: "codex", Name: "Codex", Icon: "openai"}} } + r := httptest.NewRecorder() + Handler(webHost{}, nil).ServeHTTP(r, httptest.NewRequest("GET", "/api/quit", nil)) + var got struct{ Agents []quitAgentJSON } + if err := json.Unmarshal(r.Body.Bytes(), &got); err != nil || len(got.Agents) != 1 || got.Agents[0].ID != "codex" { + t.Fatalf("GET /api/quit = %d %s (%v)", r.Code, r.Body, err) + } +} + +// With no gateway served here (another magpie serves it, and goes on +// serving the agents) a Quit cuts nobody off. +func TestQuitAgentsNoneWithoutGateway(t *testing.T) { + if served.Load() != nil { + t.Skip("a gateway is served in this test binary") + } + if got := quitAgents(); len(got) != 0 { + t.Fatalf("with no gateway served here, a Quit cuts off %+v", got) + } +} + +// With agents connected the first Quit asks; a second within a minute of +// the question quits (the user was told, and it is the way out should the +// window not show the question); later, it asks again. +func TestQuitNow(t *testing.T) { + now := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC) + asked := now.Add(-10 * time.Second).UnixNano() + for _, c := range []struct { + name string + asked int64 + wired int + want bool + }{ + {"nothing connected", 0, 0, true}, + {"nothing connected, asked before", asked, 0, true}, + {"connected, never asked", 0, 2, false}, + {"connected, asked 10s ago", asked, 1, true}, + {"connected, asked 2m ago", now.Add(-2 * time.Minute).UnixNano(), 1, false}, + } { + if got := quitNow(c.asked, now, c.wired); got != c.want { + t.Errorf("%s: quitNow = %v, want %v", c.name, got, c.want) + } + } +} diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index 3680db218..cd1cd2c19 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -150,9 +150,9 @@ test("compat.js is the first of the page's own scripts", async () => { // the pointer comes over the sidebar, whatsnew.js when release notes // open, claudemode.js when a Claude provider's editor opens, ctxtext.js // when a context window part is opened, resetask.js when a Codex reset's - // Use is pressed, quotaall.js when a provider has two accounts; the - // checks above still read them - for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); + // Use is pressed, quotaall.js when a provider has two accounts, + // quitask.js when a Quit asks first; the checks above still read them + for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/gui/tests/quit-ask.test.cjs b/internal/gui/tests/quit-ask.test.cjs new file mode 100644 index 000000000..d22784b1f --- /dev/null +++ b/internal/gui/tests/quit-ask.test.cjs @@ -0,0 +1,169 @@ +// 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); + }); + } +}