diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 5d57a6644..4f0591f63 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -819,6 +819,41 @@ See `TestWindowQuitAsksFirst`, `TestQuitListsWiredAgents`, `TestQuitDontAskAgain`, `TestSetQuitNoAsk`, `TestQuitNoAskKeptUnlessSent`, `quit-ask.test.cjs` and `quit-ask-setting.test.cjs`. +### Pausing the gateway + +Disconnect and quit was the only way to stop the gateway, and it quits +magpie too (me2seeks on X). Pause does the same without the quit: the +tray's Pause Gateway (Resume Gateway while paused), Settings › General › +Gateway (`#gatewayPauseRow`, On/Paused, the app's only) and the Gateway +page's Resume gateway, all through `POST /api/gateway/pause {"on": bool}` +([`gatewaypause.go`](../../internal/gui/gatewaypause.go)). + +- `pauseGateway` disconnects each wired agent as its row's Disconnect does + (its own settings put back), writes the ids to `gateway-paused.json` in + the config folder, then stops the gateway this process serves + (`stopServedLocked`, requests in flight drained). An agent that can't be + disconnected keeps the gateway serving, those before it connected again, + and is named in the status line. +- While the file is there `serveGatewayLocked` serves nothing, so neither + the 15 s watch, a port change nor a handover starts it; a magpie started + again stays paused. A file that can't be read or parsed counts as a pause + (a failed read is unknown). The file is this computer's alone: backup and + sync don't carry it. Only the app pauses (`pausable`); `magpie web` and + `magpie serve` never read it. +- `resumeGateway` removes the file and serves again (`startHere`). A port + held by something else keeps the pause and says what holds it + (`gatewayFixSays`). Then each agent named in the file that is still + there and not connected is connected again. +- The Gateway page's Start or Restart (`orResume`, outside `gatewayMu`) + resumes, and so does connecting an agent or picking one of magpie's + models for it (`resumeOnWire`): it would otherwise point at nothing. + An agent wired from the CLI while the app is paused + does not resume it. + +See `TestGatewayPauseAndResume`, `TestGatewayPauseRollsBack`, +`TestGatewayResumesOnWire`, `TestGatewayPauseFileUnreadable`, +`TestTrayMenuLabels` and `gateway-pause.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 b59064ef9..198fc58d0 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -453,7 +453,9 @@ type settingsJSON struct { // it is served by magpie web, where the mode can be set GatewayOn bool `json:"gatewayOn,omitempty"` GatewayWhy string `json:"gatewayWhy,omitempty"` - Web bool `json:"web,omitempty"` + // GatewayPaused: the user paused the gateway (gatewaypause.go) + GatewayPaused bool `json:"gatewayPaused,omitempty"` + Web bool `json:"web,omitempty"` // the proxy vendor requests go through now, and where it came from: // settings, environment, system, off or none ProxyNow string `json:"proxyNow"` @@ -834,6 +836,7 @@ func settingsState() settingsJSON { s.WSL = runtime.GOOS == "windows" s.Web = webPage.Load() s.GatewayOn, s.GatewayWhy = gatewayMode(s.Web) + s.GatewayPaused = pausedNow() s.LANKey = "" // the retained credential belongs on disk, not in UI state // the GitHub token, masked, and where the library's requests take one // from: Settings, or the environment variable named @@ -1240,6 +1243,9 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { fail(rw, err) return } + if !wired { + resumeOnWire(a) + } s := state() if a.Notice != nil && (!f.Live || !wired && a.Wired()) { s.Notice = a.Notice() @@ -1448,6 +1454,9 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { var c agent.Connection c, err = a.ConnectHow() how = &c + if err == nil { + resumeOnWire(a) + } case "disconnect": err = a.Disconnect() default: @@ -1535,6 +1544,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { cliBehindRoutes(mux) configRepairRoutes(mux, !isWeb(w)) gatewayFixRoutes(mux) + gatewayPauseRoutes(mux) gatewayModeRoutes(mux) if !isWeb(w) { appPageRoutes(mux) diff --git a/internal/gui/app.go b/internal/gui/app.go index 9cbe9acef..7f386ea8c 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -361,6 +361,7 @@ func Run(version string, showMain bool, link string) error { // magpie before, which hands it the gateway (handover.go). startExe, _ = update.Executable() handoverHost.Store(true) + pausable.Store(true) // the gateway paused from its menu (gatewaypause.go) before := 0 if startExe != "" { before = takeOver(startExe) @@ -516,10 +517,27 @@ func Run(version string, showMain bool, link string) error { onFonts = h.fontsChanged // the menu in the page's language, relabelled when that changes (#301) - labels := trayMenuLabels(trayLang(settings.Load().Lang, systemLang), version, "") + labels := trayMenuLabels(trayLang(settings.Load().Lang, systemLang), version, "", pausedNow()) menu := h.app.NewMenu() open := menu.Add(labels.open).OnClick(func(*application.Context) { h.ShowMain("") }) menu.AddSeparator() + // the gateway paused, or resumed, without quitting (gatewaypause.go); + // what couldn't be done opens the window on Settings, which says it + pause := menu.Add(labels.pause).OnClick(func(*application.Context) { + go func() { + var r pauseJSON + if pausedNow() { + r = resumeGateway() + } else { + r = pauseGateway() + } + if r.Error != "" || r.Fix != nil { + log.Printf("gateway pause: %s %s", r.Agent, r.Error) + h.ShowMain("settings") + } + }() + }) + menu.AddSeparator() ver := menu.Add(labels.version).SetEnabled(false) restart := menu.Add(labels.restart).SetHidden(true) restart.OnClick(func(*application.Context) { @@ -536,11 +554,12 @@ func Run(version string, showMain bool, link string) error { 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) + l := trayMenuLabels(trayLang(settings.Load().Lang, systemLang), version, ready, pausedNow()) if waiting, b := updates.waitingFor(); waiting && ready != "" { l.restart = trayRestartNow(trayLang(settings.Load().Lang, systemLang), b) } open.SetLabel(l.open) + pause.SetLabel(l.pause) ver.SetLabel(l.version) restart.SetLabel(l.restart) quit.SetLabel(l.quit) @@ -550,6 +569,7 @@ func Run(version string, showMain bool, link string) error { } } onLang = func() { application.InvokeSync(relabel) } + onPaused = onLang updates.onReady = func(v string) { application.InvokeSync(func() { ready = v diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 393b878eb..e9291f55b 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -19522,6 +19522,16 @@ function renderLoginAllow(s) { sub.replaceChildren(t("Switched off in System Settings’ Login Items, so magpie won’t open at login"), " ", open); } +// setGatewayPaused pauses the gateway or resumes it, from Settings or the +// Gateway page, and says which agent stood in the way; the pages are read +// again either way, the agents' rows with them +async function setGatewayPaused(on) { + let out; + try { out = await api("gateway/pause", { on }); } catch (e) { out = { error: e.message }; } + if (out?.fix) status(gatewayFixSays(out.fix), "err"); + else if (out?.error) status(on && out.agent ? t("{agent} couldn't be disconnected: {error}", { agent: out.agent, error: out.error }) : out.error, "err"); + await Promise.allSettled([loadSettings(), loadProviders(), load(true)]); +} async function loadSettings() { const since = prefsWrites; if (fontList === null && !fontListError) loadFonts(); @@ -19951,6 +19961,10 @@ function renderSettings() { ? "Keeps this computer and its screen awake while magpie runs tasks" : "Keeps this computer awake while magpie runs tasks"; awakeSub.textContent = t(awakeSub.dataset.en); + // the gateway paused (me2seeks on X): agents disconnected and nothing + // listening, without quitting magpie (gatewaypause.go) + $("#gatewayPauseSegs").replaceChildren(segs([["on", t("On")], ["paused", t("Paused")]], s.gatewayPaused ? "paused" : "on", + (v) => setGatewayPaused(v === "paused"))); // quitask.js's question $("#quitAskSegs").replaceChildren(segs([["off", t("Off")], ["on", t("On")]], s.quitNoAsk ? "off" : "on", (v) => savePrefs({ ...keep, quitNoAsk: v === "off" }))); // WSL's distros, looked in on Windows unless turned off (#1264) diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index dbfff8d5b..fbe38c44b 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4,6 +4,10 @@ // works. {name} slots are filled by t(str, vars). const I18N = { zh: { + "paused": "已暂停", + "Resume gateway": "恢复网关", + "Paused, agents are disconnected and use their own settings": "暂停时各 agent 断开连接,用回它们自己的配置", + "{agent} couldn't be disconnected: {error}": "{agent} 断开失败:{error}", "Codex service tier": "Codex 服务层级", "As Codex asks": "按 Codex 的请求", "/fast in Codex": "Codex 里的 /fast", @@ -4931,6 +4935,10 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "这份报告已经不在了:magpie 只保留最近 5 份。", }, "zh-TW": { + "paused": "已暫停", + "Resume gateway": "恢復閘道", + "Paused, agents are disconnected and use their own settings": "暫停時各 agent 中斷連線,改用它們自己的設定", + "{agent} couldn't be disconnected: {error}": "{agent} 中斷連線失敗:{error}", "Codex service tier": "Codex 服務層級", "As Codex asks": "依 Codex 的請求", "/fast in Codex": "Codex 裡的 /fast", @@ -9843,6 +9851,10 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "這份報告已經不在了:magpie 只保留最近 5 份。", }, ja: { + "paused": "一時停止中", + "Resume gateway": "ゲートウェイを再開", + "Paused, agents are disconnected and use their own settings": "一時停止中はエージェントの接続を解除し、それぞれ元の設定を使います", + "{agent} couldn't be disconnected: {error}": "{agent} の接続を解除できませんでした: {error}", "Codex service tier": "Codex のサービスティア", "As Codex asks": "Codex の指定どおり", "/fast in Codex": "Codex の /fast", @@ -14757,6 +14769,10 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "このレポートはもう残っていません。magpie は最新の 5 件だけを保存します。", }, de: { + "paused": "pausiert", + "Resume gateway": "Zugangspunkt fortsetzen", + "Paused, agents are disconnected and use their own settings": "Pausiert werden Agenten getrennt und nutzen ihre eigenen Einstellungen", + "{agent} couldn't be disconnected: {error}": "{agent} konnte nicht getrennt werden: {error}", "Codex service tier": "Codex-Servicestufe", "As Codex asks": "Wie Codex es anfragt", "/fast in Codex": "/fast in Codex", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 79a7cc00c..dbc356345 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -235,6 +235,10 @@
Open at login
+
+
Gateway
Paused, agents are disconnected and use their own settings
+
+
Ask before quitting
While agents go through magpie, Quit names them and asks first
diff --git a/internal/gui/assets/plugins/gateway/client.js b/internal/gui/assets/plugins/gateway/client.js index 20a3bba19..2d8501d1f 100644 --- a/internal/gui/assets/plugins/gateway/client.js +++ b/internal/gui/assets/plugins/gateway/client.js @@ -137,6 +137,19 @@ function renderGatewayOwn() { let gatewayFix = { busy: false, err: "", when: "" }; const gatewayFixWhen = (g) => [g.running, g.mine, g.version || ""].join("|"); function gatewayFixButton(g, older) { + // paused (gatewaypause.go): resumed, its agents connected again + if (g.paused) { + const b = el("button", "text action gw-fix", t("Resume gateway")); + b.disabled = gatewayFix.busy; + b.onclick = async () => { + gatewayFix = { busy: true, err: "", when: gatewayFixWhen(g) }; + b.disabled = true; + await setGatewayPaused(false); + gatewayFix = { busy: false, err: "", when: "" }; + renderGateway(); + }; + return b; + } if (g.running && !g.mine && !older) return null; // bordered: a plain text button read as words on the card in dark mode const b = el("button", "text action gw-fix"); @@ -263,12 +276,15 @@ function renderGateway() { const name = el("div", "name", t("Gateway")); name.append(el("span", "state", older ? t("running · served by magpie {v}, older than this one", { v: g.version }) + : g.paused ? t("paused") : t(g.running ? (g.mine ? "running" : "running · served by another magpie") : "not running"))); const routed = new Set(); for (const p of providers.providers) for (const a of p.agents) if (a.current) routed.add(a.id); const n = routed.size; if (older) { who.append(name, el("div", "sub old", t("Agents' requests go through magpie {v} and are sent as it sends them, without this version's fixes. Quit it here and this one serves the gateway at once.", { v: g.version }))); + } else if (g.paused) { + who.append(name, el("div", "sub", t("Paused, agents are disconnected and use their own settings"))); } else who.append(name, el("div", "sub", g.running ? [t(g.models === 1 ? "{n} model" : "{n} models", { n: g.models }), n ? t(n === 1 ? "{n} agent routed through it" : "{n} agents routed through it", { n }) : t("no agent routed through it yet"), t("five APIs, one URL")].join(" · ") : t("start it with magpie serve, or open magpie at login"))); diff --git a/internal/gui/backend.go b/internal/gui/backend.go index ad7555df4..852b3fd3a 100644 --- a/internal/gui/backend.go +++ b/internal/gui/backend.go @@ -136,6 +136,10 @@ func serveGateway() *gateway.Server { } func serveGatewayLocked() *gateway.Server { + // paused by the user (gatewaypause.go): nothing serves it until resumed + if pausedNow() { + return nil + } // handing over, the one there is this one's predecessor, which lets go // once this one listens beside it // so is the one that handed this one its socket, still finishing its diff --git a/internal/gui/gateway_takeover.go b/internal/gui/gateway_takeover.go index a64715749..1f38d589e 100644 --- a/internal/gui/gateway_takeover.go +++ b/internal/gui/gateway_takeover.go @@ -44,13 +44,25 @@ type gatewayFixJSON struct { func gatewayFixRoutes(mux *http.ServeMux) { mux.HandleFunc("POST /api/gateway/take-over", func(rw http.ResponseWriter, r *http.Request) { - writeJSON(rw, takeOverGateway()) + writeJSON(rw, orResume(takeOverGateway)) }) mux.HandleFunc("POST /api/gateway/restart", func(rw http.ResponseWriter, r *http.Request) { - writeJSON(rw, restartGateway()) + writeJSON(rw, orResume(restartGateway)) }) } +// orResume is fix, or with the gateway paused (gatewaypause.go) its +// resume: a Start while paused brings back the agents the pause took off. +func orResume(fix func() gatewayFixJSON) gatewayFixJSON { + if !pausedNow() { + return fix() + } + if r := resumeGateway(); r.Fix != nil { + return *r.Fix + } + return gatewayFixJSON{OK: true} +} + // How long a magpie asked to quit is given before it is ended at once, // that again, and the gateway here to answer; vars for the tests. var ( diff --git a/internal/gui/gatewaypause.go b/internal/gui/gatewaypause.go new file mode 100644 index 000000000..fdbfa70a2 --- /dev/null +++ b/internal/gui/gatewaypause.go @@ -0,0 +1,242 @@ +package gui + +import ( + "encoding/json" + "errors" + "fmt" + "io/fs" + "log" + "net/http" + "os" + "path/filepath" + "sync" + "sync/atomic" + + "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/settings" +) + +// Pausing the gateway (me2seeks on X): told the gateway runs while magpie +// does, the user quit magpie with Disconnect and quit to have it stopped, +// and asked for a switch. Pause, from the tray's menu, Settings › General +// or the Gateway page, does what Disconnect and quit does without the +// quit: each connected agent is disconnected as its row's Disconnect does +// (its own settings put back, so it works without magpie), then the +// gateway stops listening. Resume serves it again and connects the agents +// that were connected at the pause. The pause is kept in +// gateway-paused.json, this computer's alone (no backup or sync carries +// it), so a magpie started again, or one updated, stays paused, and +// nothing starts the gateway meanwhile (serveGatewayLocked): not the +// watch for a gateway gone, a port change, the Gateway page's Start +// (which resumes) nor a handover. Connecting an agent, or picking one of +// magpie's models for it, while paused resumes: the agent would otherwise +// point at a gateway that isn't there, the 502s of quitask.go. It is the +// app's own: magpie web is a server whose job is the gateway. + +// pausable says this process may pause its gateway: the app's (Run). +var pausable atomic.Bool + +// pauseMu keeps one pause or resume at a time. +var pauseMu sync.Mutex + +// onPaused tells the tray's menu the gateway was paused or resumed; set +// by the process that has the tray. +var onPaused func() + +// pauseFile is gateway-paused.json: the agents connected at the pause, +// which a resume connects again. +type pauseFile struct { + Agents []string `json:"agents"` +} + +func pausePath() string { return filepath.Join(settings.Dir(), "gateway-paused.json") } + +// gatewayPaused says whether this process's gateway is paused, and the +// agents to connect again on resume. A file that is there but can't be +// read or parsed is a pause whose agents aren't known: only magpie writes +// it, and a gateway started on a bad read would serve agents put back on +// their own settings. +func gatewayPaused() (bool, []string) { + if !pausable.Load() { + return false, nil + } + b, err := os.ReadFile(pausePath()) + if errors.Is(err, fs.ErrNotExist) { + return false, nil + } + var f pauseFile + if err == nil { + err = json.Unmarshal(b, &f) + } + if err != nil { + log.Println("gateway pause:", err) + } + return true, f.Agents +} + +// pausedNow is gatewayPaused's first answer. +func pausedNow() bool { p, _ := gatewayPaused(); return p } + +// pauseJSON is how a pause or resume went: Paused is the state after it; +// Agent and Error say which agent couldn't be disconnected, or connected +// again, and why; Fix is a resume's gateway that couldn't listen. +type pauseJSON struct { + Paused bool `json:"paused"` + Agents []string `json:"agents,omitempty"` + Agent string `json:"agent,omitempty"` + Error string `json:"error,omitempty"` + Fix *gatewayFixJSON `json:"fix,omitempty"` +} + +// pause hooks, vars for the tests: the agents connected now, whether one +// is, and an agent's Disconnect and connect. +var ( + pauseWired = func() []*agent.Agent { return wiredOf(agent.Detected()) } + pauseIsWired = func(a *agent.Agent) bool { return a.Wired() } + pauseDisconnect = func(a *agent.Agent) error { return a.Disconnect() } + pauseConnect = func(a *agent.Agent) error { _, err := a.ConnectHow(); return err } + pauseFind = agent.Find +) + +// wiredOf is those of as with magpie in their config. +func wiredOf(as []*agent.Agent) []*agent.Agent { + var out []*agent.Agent + for _, a := range as { + if a.Wired() { + out = append(out, a) + } + } + return out +} + +// pauseGateway disconnects every connected agent and stops the gateway +// this process serves. An agent that can't be disconnected leaves the +// gateway serving, with those disconnected before it connected again. +func pauseGateway() pauseJSON { + pauseMu.Lock() + defer pauseMu.Unlock() + if p, ids := gatewayPaused(); p { + return pauseJSON{Paused: true, Agents: ids} + } + if !pausable.Load() { + return pauseJSON{Error: "only the app pauses its gateway"} + } + var done []*agent.Agent + ids := []string{} + for _, a := range pauseWired() { + if err := pauseDisconnect(a); err != nil { + for _, b := range done { + if err := pauseConnect(b); err != nil { + log.Printf("gateway pause: %s not connected again: %v", b.ID, err) + } + } + return pauseJSON{Agent: a.Name, Error: err.Error()} + } + done = append(done, a) + ids = append(ids, a.ID) + } + b, _ := json.Marshal(pauseFile{Agents: ids}) + err := os.MkdirAll(filepath.Dir(pausePath()), 0o755) + if err == nil { + err = edit.WriteAtomic(pausePath(), b) + } + if err != nil { + for _, b := range done { + _ = pauseConnect(b) + } + return pauseJSON{Error: err.Error()} + } + gatewayMu.Lock() + stopServedLocked() + gatewayMu.Unlock() + log.Printf("gateway: paused; %d agents disconnected", len(ids)) + if onPaused != nil { + onPaused() + } + return pauseJSON{Paused: true, Agents: ids} +} + +// stopServedLocked stops the gateway this process serves and waits until +// it has; under gatewayMu. +func stopServedLocked() { + gw := served.Load() + if gw == nil { + return + } + if servedRun.stop != nil { + servedRun.stop() + <-servedRun.done + } + served.CompareAndSwap(gw, nil) +} + +// resumeGateway serves the gateway again and connects the agents the pause +// disconnected. A gateway that can't listen keeps the pause, with what +// holds the port. An agent that can't be connected is said; the rest are. +func resumeGateway() pauseJSON { + pauseMu.Lock() + defer pauseMu.Unlock() + p, ids := gatewayPaused() + if !p { + return pauseJSON{} + } + if err := os.Remove(pausePath()); err != nil && !errors.Is(err, fs.ErrNotExist) { + return pauseJSON{Paused: true, Agents: ids, Error: err.Error()} + } + gatewayMu.Lock() + out := startHere() + gatewayMu.Unlock() + if !out.OK { + b, _ := json.Marshal(pauseFile{Agents: ids}) + _ = edit.WriteAtomic(pausePath(), b) + return pauseJSON{Paused: true, Agents: ids, Fix: &out} + } + res := pauseJSON{Agents: ids} + var errs []error + for _, id := range ids { + a, err := pauseFind(id) + if err != nil || pauseIsWired(a) { + continue // gone since, or connected by hand meanwhile + } + if err := pauseConnect(a); err != nil { + errs = append(errs, fmt.Errorf("%s: %w", a.Name, err)) + if res.Agent == "" { + res.Agent = a.Name + } + } + } + if len(errs) > 0 { + res.Error = errors.Join(errs...).Error() + } + log.Printf("gateway: resumed; %d agents connected again", len(ids)-len(errs)) + if onPaused != nil { + onPaused() + } + return res +} + +// resumeOnWire resumes a paused gateway once an agent was put on it. +func resumeOnWire(a *agent.Agent) { + if a != nil && pausedNow() && pauseIsWired(a) { + resumeGateway() + } +} + +// gatewayPauseRoutes: POST /api/gateway/pause {"on": true|false}. +func gatewayPauseRoutes(mux *http.ServeMux) { + mux.HandleFunc("POST /api/gateway/pause", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + On bool `json:"on"` + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if in.On { + writeJSON(rw, pauseGateway()) + } else { + writeJSON(rw, resumeGateway()) + } + }) +} diff --git a/internal/gui/gatewaypause_test.go b/internal/gui/gatewaypause_test.go new file mode 100644 index 000000000..3ba60badb --- /dev/null +++ b/internal/gui/gatewaypause_test.go @@ -0,0 +1,223 @@ +package gui + +import ( + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + + "github.com/yetone/magpie/internal/agent" +) + +// pauseSandbox gives a test its own HOME, a gateway port of its own and +// fake agents: wired says which are connected, and the hooks' disconnects +// and connects change it and are counted. The gateway is served before +// the test and stopped after it. +func pauseSandbox(t *testing.T, ids ...string) (port int, wired map[string]bool, calls *[]string) { + t.Helper() + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("APPDATA", filepath.Join(h, "AppData")) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + port = freePort(t) + t.Setenv("MAGPIE_ADDR", "127.0.0.1:"+strconv.Itoa(port)) + was := pausable.Load() + pausable.Store(true) + agents := map[string]*agent.Agent{} + wired = map[string]bool{} + for _, id := range ids { + agents[id] = &agent.Agent{ID: id, Name: strings.ToUpper(id)} + wired[id] = true + } + calls = &[]string{} + hooks := []any{pauseWired, pauseIsWired, pauseDisconnect, pauseConnect, pauseFind, onPaused} + pauseWired = func() []*agent.Agent { + var out []*agent.Agent + for _, id := range ids { + if wired[id] { + out = append(out, agents[id]) + } + } + return out + } + pauseIsWired = func(a *agent.Agent) bool { return wired[a.ID] } + pauseDisconnect = func(a *agent.Agent) error { + *calls = append(*calls, "off "+a.ID) + wired[a.ID] = false + return nil + } + pauseConnect = func(a *agent.Agent) error { + *calls = append(*calls, "on "+a.ID) + wired[a.ID] = true + return nil + } + pauseFind = func(id string) (*agent.Agent, error) { + if a := agents[id]; a != nil { + return a, nil + } + return nil, errors.New("no agent " + id) + } + onPaused = nil + served.Store(nil) + t.Cleanup(func() { + gatewayMu.Lock() + stopServedLocked() + gatewayMu.Unlock() + pausable.Store(was) + pauseWired = hooks[0].(func() []*agent.Agent) + pauseIsWired = hooks[1].(func(*agent.Agent) bool) + pauseDisconnect = hooks[2].(func(*agent.Agent) error) + pauseConnect = hooks[3].(func(*agent.Agent) error) + pauseFind = hooks[4].(func(string) (*agent.Agent, error)) + onPaused = hooks[5].(func()) + }) + gatewayMu.Lock() + out := startHere() + gatewayMu.Unlock() + if !out.OK || !answers(port) { + t.Fatalf("gateway not served: %+v", out) + } + return port, wired, calls +} + +// me2seeks on X: quitting magpie with Disconnect and quit was the only way +// to stop its gateway. Pause disconnects every connected agent and stops +// the listener with the app still running; nothing serves it meanwhile; +// Resume serves it again and connects those agents again. +func TestGatewayPauseAndResume(t *testing.T) { + port, wired, calls := pauseSandbox(t, "codex", "claude") + told := 0 + onPaused = func() { told++ } + + out := pauseGateway() + if !out.Paused || out.Error != "" || !slices.Equal(out.Agents, []string{"codex", "claude"}) { + t.Fatalf("pause: %+v", out) + } + if wired["codex"] || wired["claude"] { + t.Fatalf("agents still connected: %v", wired) + } + if served.Load() != nil || answers(port) { + t.Fatal("the gateway still serves while paused") + } + if _, err := os.Stat(pausePath()); err != nil { + t.Fatalf("the pause isn't kept: %v", err) + } + if !providersState().Gateway.Paused || !settingsState().GatewayPaused { + t.Fatal("the pages aren't told of the pause") + } + if l := trayMenuLabels("en", "1", "", pausedNow()); l.pause != "Resume Gateway" { + t.Fatalf("tray reads %q", l.pause) + } + // nothing starts it meanwhile: the watch for a gateway gone, a port + // change, a handover + gatewayMu.Lock() + gw := serveGatewayLocked() + gatewayMu.Unlock() + if gw != nil || served.Load() != nil || answers(port) { + t.Fatal("served while paused") + } + // a second pause changes nothing + if again := pauseGateway(); !again.Paused || len(*calls) != 2 { + t.Fatalf("pause again: %+v, %v", again, *calls) + } + + // the Gateway page's Start resumes + mux := http.NewServeMux() + gatewayFixRoutes(mux) + gatewayPauseRoutes(mux) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest("POST", "/api/gateway/restart", strings.NewReader("{}"))) + if !strings.Contains(rec.Body.String(), `"ok":true`) { + t.Fatalf("restart while paused: %s", rec.Body) + } + if pausedNow() || served.Load() == nil || !answers(port) { + t.Fatal("not resumed") + } + if !wired["codex"] || !wired["claude"] { + t.Fatalf("agents not connected again: %v", wired) + } + if !slices.Equal(*calls, []string{"off codex", "off claude", "on codex", "on claude"}) { + t.Fatalf("calls: %v", *calls) + } + if told != 2 { + t.Fatalf("the tray was told %d times", told) + } + + // and the route pauses and resumes + for _, on := range []string{"true", "false"} { + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest("POST", "/api/gateway/pause", strings.NewReader(`{"on":`+on+`}`))) + if rec.Code != 200 || pausedNow() != (on == "true") || answers(port) == (on == "true") { + t.Fatalf("pause %s: %d %s", on, rec.Code, rec.Body) + } + } +} + +// An agent that can't be disconnected leaves the gateway serving, and those +// disconnected before it are connected again: a pause never leaves an +// agent pointed at a gateway that isn't there. +func TestGatewayPauseRollsBack(t *testing.T) { + port, wired, calls := pauseSandbox(t, "codex", "claude") + off := pauseDisconnect + pauseDisconnect = func(a *agent.Agent) error { + if a.ID == "claude" { + return errors.New("config is read-only") + } + return off(a) + } + out := pauseGateway() + if out.Paused || out.Agent != "CLAUDE" || out.Error != "config is read-only" { + t.Fatalf("pause: %+v", out) + } + if pausedNow() || served.Load() == nil || !answers(port) { + t.Fatal("the gateway stopped though an agent stayed on it") + } + if !wired["codex"] || !slices.Equal(*calls, []string{"off codex", "on codex"}) { + t.Fatalf("codex not connected again: %v %v", wired, *calls) + } +} + +// Connecting an agent while paused resumes: it would otherwise point at a +// gateway that isn't there. +func TestGatewayResumesOnWire(t *testing.T) { + port, wired, _ := pauseSandbox(t, "codex") + if out := pauseGateway(); !out.Paused { + t.Fatalf("pause: %+v", out) + } + a, _ := pauseFind("codex") + resumeOnWire(a) // not connected: stays paused + if !pausedNow() { + t.Fatal("resumed with no agent connected") + } + wired["codex"] = true + resumeOnWire(a) + if pausedNow() || !answers(port) { + t.Fatal("not resumed once an agent was connected") + } +} + +// A pause file that can't be read is a pause, not a gateway to start; a +// process that isn't the app (magpie web, the CLI) is never paused. +func TestGatewayPauseFileUnreadable(t *testing.T) { + pauseSandbox(t) + if err := os.MkdirAll(filepath.Dir(pausePath()), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(pausePath(), []byte("{"), 0o644); err != nil { + t.Fatal(err) + } + if p, ids := gatewayPaused(); !p || ids != nil { + t.Fatalf("half-written file: %v %v", p, ids) + } + pausable.Store(false) + if pausedNow() { + t.Fatal("paused outside the app") + } +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index d877647b9..177ac0f14 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -626,8 +626,10 @@ type gatewayJSON struct { // callers from elsewhere, a container's host among them, need one OnNetwork bool `json:"onNetwork,omitempty"` Running bool `json:"running"` - Mine bool `json:"mine"` // this process serves it - Window bool `json:"window"` // the magpie serving it shows its routing + Mine bool `json:"mine"` // this process serves it + // Paused: the user paused it (gatewaypause.go), and nothing serves it + Paused bool `json:"paused,omitempty"` + Window bool `json:"window"` // the magpie serving it shows its routing // Version is another magpie's, serving it, and Older says it is older // than this one: agents' requests are then sent as that version sends // them, without this one's fixes (#506) @@ -1353,6 +1355,7 @@ func providersState() providersJSON { } s.Gateway.Groups = append(s.Gateway.Groups, g) } + s.Gateway.Paused = pausedNow() if gw := served.Load(); gw != nil { s.Gateway.Running, s.Gateway.Mine, s.Gateway.Window = true, true, true // the calls without their bodies, which only an opened row reads diff --git a/internal/gui/quitask.go b/internal/gui/quitask.go index 4d34c0963..506fbf660 100644 --- a/internal/gui/quitask.go +++ b/internal/gui/quitask.go @@ -41,10 +41,8 @@ var quitAgents = func() []quitAgentJSON { // 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}) - } + for _, a := range wiredOf(as) { + out = append(out, quitAgentJSON{ID: a.ID, Name: a.Name, Icon: a.Icon}) } return out } diff --git a/internal/gui/tests/gateway-pause.test.cjs b/internal/gui/tests/gateway-pause.test.cjs new file mode 100644 index 000000000..a370100c1 --- /dev/null +++ b/internal/gui/tests/gateway-pause.test.cjs @@ -0,0 +1,122 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Pausing the gateway (me2seeks on X: the gateway could be stopped only by +// quitting magpie with Disconnect and quit). Settings → General has a +// Gateway row, On or Paused: Paused asks the backend to pause (agents +// disconnected, the listener stopped), and the row reads Paused once it +// says so. An agent that couldn't be disconnected is named in the status +// line. The Gateway page's card then reads paused, with Resume gateway, +// which asks to resume and leaves it running. In every language, both +// engines, wide and narrow; what is clicked stays put on screen, nothing runs off +// it sideways. 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 } = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); + +const words = { + en: { on: "On", paused: "Paused", state: "paused", resume: "Resume gateway", restart: "Restart gateway", failed: "Codex couldn't be disconnected: config is read-only" }, + zh: { on: "开启", paused: "已暂停", state: "已暂停", resume: "恢复网关", restart: "重启网关", failed: "Codex 断开失败:config is read-only" }, + "zh-TW": { on: "開啟", paused: "已暫停", state: "已暫停", resume: "恢復閘道", restart: "重啟閘道", failed: "Codex 中斷連線失敗:config is read-only" }, + ja: { on: "オン", paused: "一時停止中", state: "一時停止中", resume: "ゲートウェイを再開", restart: "ゲートウェイを再起動", failed: "Codex の接続を解除できませんでした: config is read-only" }, + de: { on: "An", paused: "Pausiert", state: "pausiert", resume: "Zugangspunkt fortsetzen", restart: "Zugangspunkt neu starten", failed: "Codex konnte nicht getrennt werden: config is read-only" }, +}; + +function serve(lang, world) { + const settings = () => ({ lang, theme: "light", searchVendors: [], searchAPIs: [], gatewayPaused: world.paused }); + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/gateway/pause") { + const { on } = JSON.parse(r.request().postData()); + world.posts.push(on); + if (on && world.refuse) return json({ paused: false, agent: "Codex", error: "config is read-only" }); + world.paused = on; + return json({ paused: on, agents: ["codex"] }); + } + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: settings() }); + if (url.pathname === "/api/settings") return json(settings()); + if (url.pathname === "/api/providers") return json({ + providers: [], presets: [], excluded: [], + gateway: world.paused + ? { running: false, mine: false, paused: true, window: true, url: "http://127.0.0.1:3999", calls: [], groups: [], models: 0 } + : { running: true, mine: true, window: true, url: "http://127.0.0.1:3999", calls: [], groups: [], models: 3 }, + }); + if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/gateway/trace") return json({ mine: false, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + 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 r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) for (const width of [1000, 420]) { + const w = words[lang]; + test(`${engine} ${lang} ${width}px: the gateway pauses from Settings and resumes from its page`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch()); + t.after(() => browser.close()); + const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => { if (engine === "webkit" && /due to access control checks/.test(e.message)) return; errors.push(e.message); }); // a goto in WebKit can cut off a fetch (#1350) + const world = { paused: false, posts: [], refuse: true }; + await page.route("**/*", serve(lang, world)); + await watchSettingsReads(page); + await page.goto("http://magpie.test/?view=settings&tab=general"); + await settingsDrawn(page); + const row = page.locator("#gatewayPauseRow"); + await row.locator(".opt.on").waitFor(); + assert.equal(await row.isVisible(), true, "the row is hidden in the app"); + assert.deepEqual(await row.locator(".opt").allInnerTexts(), [w.on, w.paused]); + assert.equal(await row.locator(".opt.on").innerText(), w.on); + // what the reader clicks stays put on screen (gui-shell.md, "A click + // never moves"); the view's scrollTop may change around it + const top = (l) => l.evaluate((e) => Math.round(e.getBoundingClientRect().top)); + + // an agent that can't be disconnected: named, and the row stays On + await row.locator(".opt", { hasText: w.paused }).click(); + await page.waitForFunction((m) => document.querySelector("#status")?.textContent === m, w.failed); + assert.deepEqual(world.posts, [true]); + await page.waitForFunction((on) => document.querySelector("#gatewayPauseRow .opt.on")?.textContent === on, w.on); + + // paused: the row, in sight since the click, stays put + const before = await top(row); + world.refuse = false; + await row.locator(".opt", { hasText: w.paused }).click(); + await page.waitForFunction((p) => document.querySelector("#gatewayPauseRow .opt.on")?.textContent === p, w.paused); + assert.deepEqual(world.posts, [true, true]); + assert.equal(await top(row), before, "the click moved the row"); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, "the page scrolls sideways"); + + // the Gateway page says so, and resumes it + await page.goto("http://magpie.test/?view=gateway"); + const fix = page.locator("#gateway .gw-fix"); + await fix.waitFor(); + assert.equal((await page.locator("#gateway .state").textContent()).trim(), w.state); + assert.equal((await fix.textContent()).trim(), w.resume); + assert.equal(await page.locator("#gateway .sub.err").count(), 0); + // the card's own text changes length, so the page's scroll is what + // holds here + const scrolls = () => page.evaluate(() => [...document.querySelectorAll(".view, html, body")].map((e) => e.scrollTop).join(",")); + const gwBefore = await scrolls(); + await fix.click(); + await page.waitForFunction((r) => document.querySelector("#gateway .gw-fix")?.textContent.trim() === r, w.restart); + assert.deepEqual(world.posts, [true, true, false]); + assert.notEqual((await page.locator("#gateway .state").textContent()).trim(), w.state); + assert.equal(await scrolls(), gwBefore, "the click scrolled the page"); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, "the page scrolls sideways"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/settings-general.test.cjs b/internal/gui/tests/settings-general.test.cjs index 3e61331ab..29b2dc53a 100644 --- a/internal/gui/tests/settings-general.test.cjs +++ b/internal/gui/tests/settings-general.test.cjs @@ -34,7 +34,7 @@ const system = { en: "System", zh: "跟随系统", "zh-TW": "跟隨系統", ja: // the rows whose name says enough, found by the control they hold const bare = ["#themeSegs", "#colorblindSegs", "#reduceMotionSegs", "#birdSegs", "#langPick", "#textSizeSegs", "#traySegs", "#plainNamesSegs", "#loginSegs", "#dockSegs"]; // the rows that keep a line, one each -const kept = ["#lightweightSegs", "#keepAwakeSegs", "#quitAskSegs", "#sessionTerminalRow .sess-pick"]; +const kept = ["#lightweightSegs", "#keepAwakeSegs", "#gatewayPauseSegs", "#quitAskSegs", "#sessionTerminalRow .sess-pick"]; function serve(lang, posted, st) { const settings = () => ({ lang, theme: "light", searchVendors: [], searchAPIs: [], ...st }); diff --git a/internal/gui/traymenu.go b/internal/gui/traymenu.go index 8746d2d60..2e36a5c6b 100644 --- a/internal/gui/traymenu.go +++ b/internal/gui/traymenu.go @@ -18,6 +18,9 @@ var trayZh = map[string]string{ "Quit magpie": "退出 magpie", "Restart Now to Update": "立即重启以更新", "Restart Now to Update (%d in flight)": "立即重启以更新(%d 个进行中)", + // the gateway paused from the menu (gatewaypause.go) + "Pause Gateway": "暂停网关", + "Resume Gateway": "恢复网关", // the tray icon's tooltip (trayusage.go; yi_time on Discord) "%s used": "已用 %s", "%s left": "剩余 %s", @@ -50,6 +53,9 @@ var trayZhTW = map[string]string{ "Quit magpie": "結束 magpie", "Restart Now to Update": "立即重新啟動以更新", "Restart Now to Update (%d in flight)": "立即重新啟動以更新(%d 個進行中)", + // the gateway paused from the menu (gatewaypause.go) + "Pause Gateway": "暫停閘道", + "Resume Gateway": "恢復閘道", // the tray icon's tooltip (trayusage.go; yi_time on Discord) "%s used": "已用 %s", "%s left": "剩餘 %s", @@ -82,6 +88,9 @@ var trayJa = map[string]string{ "Quit magpie": "magpie を終了", "Restart Now to Update": "今すぐ再起動してアップデート", "Restart Now to Update (%d in flight)": "今すぐ再起動してアップデート(%d 件処理中)", + // the gateway paused from the menu (gatewaypause.go) + "Pause Gateway": "ゲートウェイを一時停止", + "Resume Gateway": "ゲートウェイを再開", // the tray icon's tooltip (trayusage.go; yi_time on Discord) "%s used": "使用済み %s", "%s left": "残り %s", @@ -114,6 +123,9 @@ var trayDe = map[string]string{ "Quit magpie": "magpie beenden", "Restart Now to Update": "Jetzt neu starten und aktualisieren", "Restart Now to Update (%d in flight)": "Jetzt neu starten und aktualisieren (%d laufend)", + // the gateway paused from the menu (gatewaypause.go) + "Pause Gateway": "Zugangspunkt pausieren", + "Resume Gateway": "Zugangspunkt fortsetzen", // the tray icon's tooltip (trayusage.go; yi_time on Discord) "%s used": "%s verbraucht", "%s left": "%s übrig", @@ -202,14 +214,16 @@ func trayText(lang, key string, args ...any) string { return fmt.Sprintf(key, args...) } -// trayLabels are the tray menu's lines: open, version, restart and quit. -type trayLabels struct{ open, version, restart, quit string } +// trayLabels are the tray menu's lines: open, pause (the gateway's, or +// its resume), version, restart and quit. +type trayLabels struct{ open, pause, version, restart, quit string } // trayMenuLabels are the lines in the language; update is the version -// waiting for a restart, if there is one. -func trayMenuLabels(lang, version, update string) trayLabels { +// waiting for a restart, if there is one; paused, the gateway is. +func trayMenuLabels(lang, version, update string, paused bool) trayLabels { l := trayLabels{ open: trayText(lang, "Open magpie"), + pause: trayText(lang, "Pause Gateway"), version: trayText(lang, "Version %s", version), restart: trayText(lang, "Restart to Update"), quit: trayText(lang, "Quit magpie"), @@ -217,6 +231,9 @@ func trayMenuLabels(lang, version, update string) trayLabels { if update != "" { l.restart = trayText(lang, "Restart to Update to %s", update) } + if paused { + l.pause = trayText(lang, "Resume Gateway") + } return l } diff --git a/internal/gui/traymenu_test.go b/internal/gui/traymenu_test.go index 3df74355f..450d302a1 100644 --- a/internal/gui/traymenu_test.go +++ b/internal/gui/traymenu_test.go @@ -46,8 +46,8 @@ func TestTrayMenuLabels(t *testing.T) { t.Errorf("trayLang(%q, %s) = %s, want %s", c.pref, c.sys(), got, c.want) } } - de := trayMenuLabels("de", "0.1.500", "0.1.501") - if de != (trayLabels{"magpie öffnen", "Version 0.1.500", "Zum Aktualisieren auf 0.1.501 neu starten", "magpie beenden"}) { + de := trayMenuLabels("de", "0.1.500", "0.1.501", false) + if de != (trayLabels{"magpie öffnen", "Zugangspunkt pausieren", "Version 0.1.500", "Zum Aktualisieren auf 0.1.501 neu starten", "magpie beenden"}) { t.Errorf("de: %+v", de) } for lang, want := range map[string]string{"de": "en", "en": "en", "zh": "zh", "zh-TW": "zh"} { @@ -55,23 +55,29 @@ func TestTrayMenuLabels(t *testing.T) { t.Errorf("notesLang(%q) = %q, want %q", lang, got, want) } } - zh := trayMenuLabels("zh", "0.1.500", "") - if zh != (trayLabels{"打开 magpie", "版本 0.1.500", "重启以更新", "退出 magpie"}) { + zh := trayMenuLabels("zh", "0.1.500", "", false) + if zh != (trayLabels{"打开 magpie", "暂停网关", "版本 0.1.500", "重启以更新", "退出 magpie"}) { t.Errorf("zh: %+v", zh) } - if tw := trayMenuLabels("zh-TW", "0.1.500", "0.1.501"); tw != (trayLabels{"開啟 magpie", "版本 0.1.500", "重新啟動以更新到 0.1.501", "結束 magpie"}) { + if tw := trayMenuLabels("zh-TW", "0.1.500", "0.1.501", false); tw != (trayLabels{"開啟 magpie", "暫停閘道", "版本 0.1.500", "重新啟動以更新到 0.1.501", "結束 magpie"}) { t.Errorf("zh-TW: %+v", tw) } - if ja := trayMenuLabels("ja", "0.1.500", ""); ja != (trayLabels{"magpie を開く", "バージョン 0.1.500", "再起動してアップデート", "magpie を終了"}) { + if ja := trayMenuLabels("ja", "0.1.500", "", false); ja != (trayLabels{"magpie を開く", "ゲートウェイを一時停止", "バージョン 0.1.500", "再起動してアップデート", "magpie を終了"}) { t.Errorf("ja: %+v", ja) } - if l := trayMenuLabels("zh", "0.1.500", "0.1.501"); l.restart != "重启以更新到 0.1.501" { + if l := trayMenuLabels("zh", "0.1.500", "0.1.501", false); l.restart != "重启以更新到 0.1.501" { t.Errorf("zh restart: %q", l.restart) } - en := trayMenuLabels("en", "0.1.500", "0.1.501") - if en != (trayLabels{"Open magpie", "Version 0.1.500", "Restart to Update to 0.1.501", "Quit magpie"}) { + en := trayMenuLabels("en", "0.1.500", "0.1.501", false) + if en != (trayLabels{"Open magpie", "Pause Gateway", "Version 0.1.500", "Restart to Update to 0.1.501", "Quit magpie"}) { t.Errorf("en: %+v", en) } + // paused, the menu's line resumes the gateway (me2seeks on X) + for lang, want := range map[string]string{"en": "Resume Gateway", "zh": "恢复网关", "zh-TW": "恢復閘道", "ja": "ゲートウェイを再開", "de": "Zugangspunkt fortsetzen"} { + if l := trayMenuLabels(lang, "0.1.500", "", true); l.pause != want { + t.Errorf("%s paused: %q, want %q", lang, l.pause, want) + } + } env := map[string]string{"LC_ALL": "C", "LANG": "zh_CN.UTF-8"} if got := envLang(func(k string) string { return env[k] }); got != "zh_CN.UTF-8" { t.Errorf("envLang skips C: %q", got) @@ -113,7 +119,7 @@ func TestSettingsLangRelabelsTray(t *testing.T) { if calls != 1 { t.Fatalf("relabelled %d times after en → zh, want 1", calls) } - if l := trayMenuLabels(trayLang(settings.Load().Lang, systemLang), "1", ""); l.quit != "退出 magpie" { + if l := trayMenuLabels(trayLang(settings.Load().Lang, systemLang), "1", "", false); l.quit != "退出 magpie" { t.Fatalf("after the change the menu reads %+v", l) } }