diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index fbb6064f4..7f110251f 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -1346,6 +1346,33 @@ and the old one quitting only after its stream) and socket passing in [`handoff_test.go`](../../internal/handoff/handoff_test.go), and `update-wait.test.cjs`. +### Restart magpie, with no update + +What a user changes is meant to apply live, and most of it does; a restart +is the way out for what doesn't yet, without quitting and opening magpie by +hand (yansheng1003 on X: "请在刷新旁边增加一个重启按钮"). Settings › Version +has **Restart** beside Check while no update is on offer: not once one is +found, downloading, downloaded (its Restart to update is the only one) or +blocked, nor with a newer version named or a download failed, whose own +buttons fill a narrow row (`renderUpdate`), and the tray's +restart item is always there: *Restart magpie*, *Restart to Update* once +one is ready (`trayMenuLabels`). + +Both go through `restartSelfNow` in [`restart.go`](../../internal/gui/restart.go), +the updater's restart with nothing to install: `beginHandover` on a Mac and +Linux, so the gateway's requests carry on, else `update.Relaunch` or +`relaunchBinary` once this magpie has exited (Windows; requests in flight +there are cut). An update ready is installed on the way (`restartToUpdate`). +The page's `POST /api/restart {view}` answers 204 and quits (`leave`); a +relaunch that can't be arranged answers 400 and magpie runs on, the row +saying "Couldn't restart magpie". A browser on the app's page restarts the +app; `magpie web` runs again in its place (`webReexec`). `/api/update` +carries `run`, when this run started, and a browser's page reloads once a +run other than the one it restarted answers (`restartSelf` in +versionrow.js, imported when Restart is pressed). See +`TestRestartStartsMagpieAgain`, `TestUpdateSaysItsRun`, +`TestTrayMenuLabels` and `version-restart.test.cjs`. + ### Where Windows installs magpie There is no installer: the Windows exe opened from Downloads, the Desktop diff --git a/internal/cli/settings_parity_test.go b/internal/cli/settings_parity_test.go index 017b757bc..a0f2e1491 100644 --- a/internal/cli/settings_parity_test.go +++ b/internal/cli/settings_parity_test.go @@ -258,6 +258,7 @@ var notYet = map[string]string{ "POST /api/appearance/wallpaper": W, // appearance.go: the picture comes from the window's file picker "GET /api/quit": W, // api.go: the window's Quit question "POST /api/quit/disconnect": W, // api.go: the Quit question's Disconnect and quit, which quits the app + "POST /api/restart": W, // restart.go: the app starting itself again, as the tray's Restart magpie does "POST /api/page-away": W, // api.go: the page says it went from view, so its caches can go "GET /api/remote": W, // remote.go: another magpie opened in a window of the app "POST /api/remote": W, // remote.go diff --git a/internal/gui/api.go b/internal/gui/api.go index 94d006d95..eb70e8905 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -1707,6 +1707,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { sessionManageRoutes(mux, w) backupRoutes(mux, w) dataFolderRoutes(mux, w) + restartRoutes(mux, w) mtlsRoutes(mux, w) joinRoutes(mux) httpsRoutes(mux, w) diff --git a/internal/gui/app.go b/internal/gui/app.go index 8429299d2..0f2ed29d8 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -551,9 +551,20 @@ func Run(version string, showMain bool, link string) error { }) menu.AddSeparator() ver := menu.Add(labels.version).SetEnabled(false) - restart := menu.Add(labels.restart).SetHidden(true) + var ready string // the version waiting for a restart; on the main thread + restart := menu.Add(labels.restart) restart.OnClick(func(*application.Context) { // the window comes back if it was open; the tray alone if not + if updates.json().State != "ready" { + // no update: magpie as it is (restart.go), its requests + // handed over where the gateway can be + go func() { + if restartSelfNow(false, h.MainShown(), "") { + leave(h.app.Quit) + } + }() + return + } now := func() bool { if restartToUpdate(false, h.MainShown(), "") { leave(h.app.Quit) @@ -564,7 +575,6 @@ func Run(version string, showMain bool, link string) error { updates.restartAsked(now) }) 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.Shared().Lang, systemLang), version, ready, pausedNow()) if waiting, b := updates.waitingFor(); waiting && ready != "" { @@ -585,7 +595,6 @@ func Run(version string, showMain bool, link string) error { updates.onReady = func(v string) { application.InvokeSync(func() { ready = v - restart.SetHidden(false) relabel() }) } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index c15f05e34..0456a7b98 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -22693,19 +22693,7 @@ async function renderUpdate(r, u) { if (u.mirror) { sub.textContent = t("Couldn't download {v} through the mirror {mirror}; it may be down or sent a file that doesn't match the release, which isn't installed", { v: u.latest, mirror: u.mirror }) + (u.error ? " · " + u.error.replace("through the mirror " + u.mirror + ": ", "").replace(/^Get "[^"]*": /, "") : ""); - btn(t("Download from GitHub"), async () => { - if (updateBusy) return; - dim(); - try { - prefs = await writingPrefs(api("settings/update-mirror", { mirror: "" })); - await api(updatePath("update/install"), installFrom()); - updateLast = null; - renderSettings(); // the source row says GitHub, this one the download - } catch (e) { - statusTErr(e); - renderUpdate(r); - } - }); + btn(t("Download from GitHub"), () => import("./versionrow.js").then(() => fromGitHub(r))); } btn(t("Check"), check); if (u.latest) page(); @@ -22729,6 +22717,10 @@ async function renderUpdate(r, u) { default: // built from source sub.textContent = ""; } + // magpie started again as it is (yansheng1003 on X), in versionrow.js; + // not beside an update on offer, whose own path restarts, nor past a + // narrow row's room + if (!/^(ready|downloading|found|available|blocked)$/.test(u.state) && !u.newest && !(u.state === "error" && u.latest)) btn(t("Restart"), () => import("./versionrow.js").then(() => restartSelf(r, u)), u.state === "checking"); if (kept && !pageShown) kept.remove(); } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index b303eac3e..3f5f5ce8a 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4217,6 +4217,7 @@ const I18N = { "Automatic updates are off": "自动更新已关闭", "Restart to update to {v}": "重启以更新到 {v}", "Restarting…": "正在重启…", + "Couldn't restart magpie": "无法重启 magpie", "{n} in flight": "{n} 个请求进行中", "{n} awaiting tool results": "{n} 个工具调用待返回", "restarts once the gateway is idle": "网关空闲后自动重启", @@ -9653,6 +9654,7 @@ const I18N = { "Automatic updates are off": "自動更新已關閉", "Restart to update to {v}": "重啟以更新到 {v}", "Restarting…": "正在重啟…", + "Couldn't restart magpie": "無法重啟 magpie", "{n} in flight": "{n} 個請求進行中", "{n} awaiting tool results": "{n} 個工具呼叫待返回", "restarts once the gateway is idle": "閘道空閒後自動重啟", @@ -15102,6 +15104,7 @@ const I18N = { "Automatic updates are off": "自動アップデートはオフです", "Restart to update to {v}": "再起動して {v} にアップデート", "Restarting…": "再起動中…", + "Couldn't restart magpie": "magpie を再起動できませんでした", "{n} in flight": "{n} 件のリクエストを処理中", "{n} awaiting tool results": "{n} 件がツール結果待ち", "restarts once the gateway is idle": "ゲートウェイがアイドルになったら再起動します", @@ -20564,6 +20567,7 @@ const I18N = { "Automatic updates are off": "Automatische Updates sind ausgeschaltet", "Restart to update to {v}": "Neu starten, um auf {v} zu aktualisieren", "Restarting…": "Neustart…", + "Couldn't restart magpie": "magpie konnte nicht neu gestartet werden", "{n} in flight": "{n} laufend", "{n} awaiting tool results": "{n} warten auf Tool-Ergebnisse", "restarts once the gateway is idle": "startet neu, sobald der Zugangspunkt frei ist", diff --git a/internal/gui/assets/versionrow.js b/internal/gui/assets/versionrow.js new file mode 100644 index 000000000..92c50e771 --- /dev/null +++ b/internal/gui/assets/versionrow.js @@ -0,0 +1,53 @@ +// Settings › Version's rarer buttons, imported from renderUpdate (app.js) +// when one is pressed, so they weigh nothing on the core: Restart +// (yansheng1003 on X: "请在刷新旁边增加一个重启按钮"), magpie started again +// as it is (restart.go), and a failing mirror's Download from GitHub (#893). + +// the row's parts, as renderUpdate drew them +const parts = (r) => { + const val = r.querySelector(".val"); + const dim = () => { for (const b of val.querySelectorAll("button")) { b.disabled = true; b.classList.add("busy"); } }; + return { val, sub: r.querySelector(".who .sub"), dim }; +}; + +// restartSelf asks for the restart, and says in the row what came of it. +// The app's window closes with the app, and the new one opens its own; a +// browser's page (magpie web, or a browser on the app's page) reloads once +// another run, of the same version, answers /api/update (its run). +window.restartSelf = async function (r, u) { + const { val, sub, dim } = parts(r); + const mine = seqOf(r) + 1; + updateSeq.set(r, mine); // stops timers: their redraw would drop the line + dim(); + try { + await api("restart", installFrom()); + } catch (e) { + if (!r.isConnected || seqOf(r) !== mine) return; + sub.textContent = t("Couldn't restart magpie") + (e.message ? " · " + e.message : ""); + sub.classList.add("wraps"); + for (const b of val.querySelectorAll("button")) { b.disabled = false; b.classList.remove("busy"); } + return; + } + sub.textContent = t("Restarting…"); + if (!web || !u.run) return; + for (let i = 0; i < 180; i++) { + await new Promise((res) => setTimeout(res, 1000)); + const n = await fetch("/api/update").then((x) => (x.ok ? x.json() : null)).catch(() => null); + if (n && n.run && n.run !== u.run) return location.reload(); + } +}; + +// fromGitHub drops the mirror that failed and downloads from GitHub +window.fromGitHub = async function (r) { + if (updateBusy) return; + parts(r).dim(); + try { + prefs = await writingPrefs(api("settings/update-mirror", { mirror: "" })); + await api(updatePath("update/install"), installFrom()); + updateLast = null; + renderSettings(); // the source row says GitHub, this one the download + } catch (e) { + statusTErr(e); + renderUpdate(r); + } +}; diff --git a/internal/gui/restart.go b/internal/gui/restart.go new file mode 100644 index 000000000..8afa582bc --- /dev/null +++ b/internal/gui/restart.go @@ -0,0 +1,95 @@ +package gui + +import ( + "encoding/json" + "errors" + "log" + "net/http" + "time" + + "github.com/yetone/magpie/internal/update" +) + +// A restart of magpie as it is, asked for from the tray menu or Settings' +// version row (yansheng1003 on X: "请在刷新旁边增加一个重启按钮"). What a +// user changes is meant to apply live, and most of it does; this is the +// way out for what doesn't yet, without quitting and opening magpie by +// hand. It goes the way the updater's restart goes: on a Mac or Linux the +// new magpie takes the gateway over while this one finishes its requests +// (handover.go); elsewhere it opens once this one has exited. + +// runStarted is when this run of magpie started: /api/update's run. +var runStarted = time.Now().UnixNano() + +// restartSelfNow arranges for this magpie to start again once it is gone; +// the caller then quits (leave). An update staged is installed on the way, +// as the updater's restart would. magpie web runs again in its own place +// (Web.Wait). False when it can't: the caller runs on. +func restartSelfNow(web, window bool, view string) bool { + if pending.Load() != nil { + return false // a handover under way restarts already + } + if updates.json().State == "ready" { + return restartToUpdate(web, window, view) + } + unmarkQuietRestart() // one asked for comes to the front + if web { + webReexec.Store(true) + return true + } + bundle := bundleOf() + exe := "" + if bundle == "" { + var err error + if exe, err = executable(); err != nil { + log.Println("restart:", err) + return false + } + } + // the Mac's always opens its window, as the updater's asked restart does + if bundle != "" { + window = true + } + if beginHandover(bundle, exe, window, view, false) { + return true + } + var err error + if bundle != "" { + err = update.Relaunch(bundle, window, false) + } else { + err = relaunchBinary(exe, "", window, view) + } + if err != nil { + // nothing would open it again: it runs on, and the page says so + log.Println("restart:", err) + return false + } + return true +} + +// restartAppFrom is restartSelfNow for a page: the app's, a browser's on +// the app's page (the app restarts, its window back if it was up), or +// magpie web's (it runs again in its place). view is the tab the window's +// page is on, to come back to it. +func restartAppFrom(w Windows, view string) (Windows, bool) { + if a, ok := w.(appWebHost); ok { + return a.app, restartSelfNow(false, mainShown(a.app), "") + } + return w, restartSelfNow(ownWeb(w), view != "" || mainShown(w), view) +} + +func restartRoutes(mux *http.ServeMux, w Windows) { + mux.HandleFunc("POST /api/restart", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + View string `json:"view"` + } + _ = json.NewDecoder(r.Body).Decode(&in) // nothing sent: no tab to come back to + app, ok := restartAppFrom(w, in.View) + if !ok { + fail(rw, errors.New("magpie couldn't start again: quit it and open it again")) + return + } + rw.WriteHeader(http.StatusNoContent) + go leave(app.Quit) + }) +} diff --git a/internal/gui/restart_test.go b/internal/gui/restart_test.go new file mode 100644 index 000000000..58de4df80 --- /dev/null +++ b/internal/gui/restart_test.go @@ -0,0 +1,121 @@ +package gui + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// quitSays is a window that says when it quits. +type quitSays struct { + folderOnly + quit chan struct{} +} + +func (q quitSays) Quit() { q.quit <- struct{}{} } + +// TestRestartStartsMagpieAgain (yansheng1003 on X: "请在刷新旁边增加一个重启 +// 按钮"): Settings' Restart starts this magpie again with no update +// waiting, as it is, back on the tab the window was on, and the app quits +// for it. A relaunch that can't be arranged leaves it running and says so. +// magpie web runs again in its own place; a browser on the app's page +// restarts the app. +func TestRestartStartsMagpieAgain(t *testing.T) { + sandboxHome(t) + oldBundle, oldExe, oldRelaunch, oldHands := bundleOf, executable, relaunchBinary, handsOver + t.Cleanup(func() { + bundleOf, executable, relaunchBinary, handsOver = oldBundle, oldExe, oldRelaunch, oldHands + webReexec.Store(false) + }) + bundleOf = func() string { return "" } + executable = func() (string, error) { return "/opt/magpie/magpie", nil } + handsOver = func() bool { return false } // Windows': opened once this one has exited + if s := updates.json().State; s == "ready" { + t.Fatalf("an update is staged in the test: %q", s) + } + type relaunch struct { + exe, aside, view string + window bool + } + var got []relaunch + var fail error + relaunchBinary = func(exe, aside string, window bool, view string) error { + got = append(got, relaunch{exe, aside, view, window}) + return fail + } + post := func(w Windows, body string) *httptest.ResponseRecorder { + t.Helper() + mux := http.NewServeMux() + restartRoutes(mux, w) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest("POST", "/api/restart", strings.NewReader(body))) + return rec + } + quits := func(q quitSays) bool { + select { + case <-q.quit: + return true + case <-time.After(2 * time.Second): + return false + } + } + + app := quitSays{quit: make(chan struct{}, 1)} + if rec := post(app, `{"view":"settings"}`); rec.Code != http.StatusNoContent { + t.Fatalf("restart: %d %s", rec.Code, rec.Body) + } + if len(got) != 1 || got[0] != (relaunch{"/opt/magpie/magpie", "", "settings", true}) { + t.Fatalf("relaunched %+v, want this binary again on Settings", got) + } + if !quits(app) { + t.Fatal("the app didn't quit for the restart") + } + + got, fail = nil, errors.New("no helper to open it again") + if rec := post(app, `{}`); rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "couldn't start again") { + t.Fatalf("a relaunch that failed: %d %s", rec.Code, rec.Body) + } + if quits(app) { + t.Fatal("the app quit with nothing to open it again") + } + fail = nil + + // a browser on the app's page: the app restarts and quits + got = nil + inner := quitSays{quit: make(chan struct{}, 1)} + if rec := post(appWebHost{webHost{}, inner}, `{"view":"usage"}`); rec.Code != http.StatusNoContent { + t.Fatalf("from a browser: %d %s", rec.Code, rec.Body) + } + if len(got) != 1 || got[0].view != "" { + t.Fatalf("from a browser relaunched %+v: the app, not a tab of the browser's", got) + } + if !quits(inner) { + t.Fatal("the app didn't quit for a browser's restart") + } + + // magpie web: run again in its place, nothing relaunched + got = nil + quit := make(chan struct{}, 1) + if rec := post(webHost{quit: func() { quit <- struct{}{} }}, `{}`); rec.Code != http.StatusNoContent { + t.Fatalf("magpie web: %d %s", rec.Code, rec.Body) + } + if len(got) != 0 || !webReexec.Load() { + t.Fatalf("magpie web relaunched %+v, re-exec %v", got, webReexec.Load()) + } + select { + case <-quit: + case <-time.After(2 * time.Second): + t.Fatal("magpie web didn't end for its re-exec") + } +} + +// TestUpdateSaysItsRun: a page that restarted magpie with no update +// reloads once another run answers; /api/update says which run it is. +func TestUpdateSaysItsRun(t *testing.T) { + if j := updates.json(); j.Run == 0 || j.Run != runStarted { + t.Fatalf("run %d, want %d", j.Run, runStarted) + } +} diff --git a/internal/gui/tests/update-check.test.cjs b/internal/gui/tests/update-check.test.cjs index fbc25f1c0..76f2ba17b 100644 --- a/internal/gui/tests/update-check.test.cjs +++ b/internal/gui/tests/update-check.test.cjs @@ -143,7 +143,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await button.evaluate((b) => { const fn = b.onclick; fn(); fn(); }); await page.waitForTimeout(50); assert.equal(ctl.posts, 1, "a second click must not ask again"); - assert.equal(await row.locator("button").count(), 1); + assert.equal(await row.locator("button", { hasText: w.check }).count(), 1); // and Restart beside it (version-restart) // a read that left while the check ran, answered "checking" only after // the check itself has answered — it must not be drawn over that @@ -164,7 +164,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", ctl.releaseGets(); await page.waitForTimeout(1200); assert.equal((await row.locator(".sub").textContent()).trim(), w.latest, "a late checking read must not replace the answer"); - assert.equal(await row.locator("button").count(), 1); + assert.equal(await row.locator("button", { hasText: w.check }).count(), 1); // and Restart beside it (version-restart) assert.equal(await button.isEnabled(), true); assert.equal(ctl.posts, 1); assert.deepEqual(errors, []); @@ -182,7 +182,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.evaluate(() => renderSettings()); const again = rowOf(page, w.version); await again.locator("button", { hasText: w.check }).waitFor(); - assert.equal(await again.locator("button").isDisabled(), true, "the new row keeps the button while the check runs"); + assert.equal(await again.locator("button", { hasText: w.check }).isDisabled(), true, "the new row keeps the button while the check runs"); + assert.equal(await again.locator("button", { hasNotText: w.check }).isDisabled(), true, "and Restart beside it dimmed with it"); assert.equal((await again.locator(".sub").textContent()).trim(), w.checking); assert.equal(ctl.posts, 1); ctl.update = { state: "latest", current: "0.1.400" }; diff --git a/internal/gui/tests/version-restart.test.cjs b/internal/gui/tests/version-restart.test.cjs new file mode 100644 index 000000000..7a7a13118 --- /dev/null +++ b/internal/gui/tests/version-restart.test.cjs @@ -0,0 +1,163 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Settings › About's Version row restarts magpie as it is (yansheng1003 on +// X: "请在刷新旁边增加一个重启按钮"): +// - up to date, the row has Restart beside Check, on one line at 400px +// too; a click posts /api/restart with the tab the window is on and says +// Restarting…; +// - in a browser (magpie web), the page reloads once another run of +// magpie answers /api/update, of the same version; +// - a restart that can't be arranged says so and gives the buttons back; +// - an update downloaded has its own Restart to update, and no second +// Restart. +// Every language, 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 { watchSettingsReads, settingsDrawn } = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const words = { + en: { version: "Version", latest: "Up to date", check: "Check", restart: "Restart", restarting: "Restarting…", failed: "Couldn't restart magpie", update: "Restart to update" }, + zh: { version: "版本", latest: "已是最新", check: "检查", restart: "重启", restarting: "正在重启…", failed: "无法重启 magpie", update: "重启以更新" }, + "zh-TW": { version: "版本", latest: "已是最新", check: "檢查", restart: "重啟", restarting: "正在重啟…", failed: "無法重啟 magpie", update: "重啟以更新" }, + ja: { version: "バージョン", latest: "最新です", check: "確認", restart: "再起動", restarting: "再起動中…", failed: "magpie を再起動できませんでした", update: "再起動してアップデート" }, + de: { version: "Version", latest: "Aktuell", check: "Prüfen", restart: "Neu starten", restarting: "Neustart…", failed: "magpie konnte nicht neu gestartet werden", update: "Zum Aktualisieren neu starten" }, +}; + +function server(lang, ctl) { + const settings = { + theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", proxy: "", redact: false, redactWords: [], + version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425", proxyNow: "none", proxySource: "none", + visionModels: [], imageGenModels: [], workbuddyCheckins: [], lanURLs: [], fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, + }; + return async (route) => { + const req = route.request(); + const url = new URL(req.url()); + const json = (data, status) => route.fulfill({ json: data, status: status || 200 }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${!!ctl.web}};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, fx: settings.fx }); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/update") return json(ctl.update || { state: "latest", current: "0.1.400", run: ctl.run }); + if (url.pathname === "/api/restart" && req.method() === "POST") { + ctl.posts.push(req.postDataJSON()); + if (ctl.fail) return json({ error: "magpie couldn't start again: quit it and open it again" }, 400); + return route.fulfill({ status: 204, body: "" }); + } + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + if (!/^\/[\w./-]*$/.test(url.pathname) || url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +async function open(browser, lang, ctl, width) { + const errors = []; + const page = await (await browser.newContext({ viewport: { width, height: 700 } })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => { if (!/^ResizeObserver loop completed with undelivered notifications/.test(e.message)) errors.push(e.message); }); + await page.route("**/*", server(lang, ctl)); + await watchSettingsReads(page); + await page.goto("http://magpie.test/?view=settings&tab=about"); + await settingsDrawn(page); + return { page, errors }; +} + +const versionRow = (page, lang) => page.locator("#about .row.pref", { has: page.locator(".name", { hasText: words[lang].version }) }).first(); +const buttons = (row) => row.locator(".val button").evaluateAll((bs) => bs.map((b) => b.textContent)); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": the Version row restarts magpie as it is", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of Object.keys(words)) { + const w = words[lang]; + + for (const width of [900, 400]) { + await t.test(`${lang} ${width}px: Restart beside Check, and a click restarts`, async () => { + const ctl = { posts: [], run: 111 }; + const { page, errors } = await open(browser, lang, ctl, width); + const row = versionRow(page, lang); + await row.locator(".sub", { hasText: w.latest }).waitFor(); + assert.deepEqual(await buttons(row), [w.check, w.restart]); + const tops = await row.locator(".val button").evaluateAll((bs) => bs.map((b) => Math.round(b.getBoundingClientRect().top))); + assert.equal(new Set(tops).size, 1, `the buttons wrap: tops ${tops}`); + const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert.ok(over <= 0, `the page scrolls sideways by ${over}px`); + await row.locator(".val button", { hasText: w.restart }).click(); + await row.locator(".sub", { hasText: w.restarting }).waitFor(); + assert.deepEqual(ctl.posts, [{ view: "settings" }]); + assert.ok(await row.locator(".val button").evaluateAll((bs) => bs.every((b) => b.disabled)), "the buttons stay live while it restarts"); + assert.deepEqual(errors, []); + await page.context().close(); + }); + } + + await t.test(lang + ": in a browser, the page reloads once the next run answers", async () => { + const ctl = { posts: [], run: 111, web: true }; + const { page, errors } = await open(browser, lang, ctl, 900); + const row = versionRow(page, lang); + await row.locator(".sub", { hasText: w.latest }).waitFor(); + let loads = 0; + page.on("load", () => loads++); + await row.locator(".val button", { hasText: w.restart }).click(); + await row.locator(".sub", { hasText: w.restarting }).waitFor(); + assert.equal(ctl.posts.length, 1); // the tab it names is the server's to ignore (restartAppFrom) + await page.waitForTimeout(1500); // the same run still answers: no reload + assert.equal(loads, 0, "reloaded while the same run answered"); + ctl.run = 222; + await page.waitForEvent("load", { timeout: 5000 }); + assert.deepEqual(errors, []); + await page.context().close(); + }); + + await t.test(lang + ": a restart that can't be arranged says so", async () => { + const ctl = { posts: [], run: 111, fail: true }; + const { page, errors } = await open(browser, lang, ctl, 900); + const row = versionRow(page, lang); + await row.locator(".sub", { hasText: w.latest }).waitFor(); + await row.locator(".val button", { hasText: w.restart }).click(); + await row.locator(".sub", { hasText: w.failed }).waitFor(); + assert.ok(await row.locator(".val button").evaluateAll((bs) => bs.every((b) => !b.disabled)), "the buttons weren't given back"); + assert.deepEqual(errors, []); + await page.context().close(); + }); + + // an update on offer restarts by its own path, and a narrow row has + // no room for a third button (update-download's 420px) + await t.test(lang + ": no Restart beside an update on offer", async () => { + for (const update of [ + { state: "found", current: "0.1.400", latest: "0.1.401", size: 3e7 }, + { state: "available", current: "0.1.400", latest: "0.1.401" }, + { state: "latest", current: "0.1.400", channel: "stable", newest: "0.1.401" }, + { state: "error", current: "0.1.400", latest: "0.1.401", error: "timed out" }, + ]) { + const ctl = { posts: [], update: { ...update, run: 111 } }; + const { page, errors } = await open(browser, lang, ctl, 400); + const row = versionRow(page, lang); + await row.locator(".val button").first().waitFor(); + assert.ok(!(await buttons(row)).includes(w.restart), update.state + ": " + (await buttons(row)).join(", ")); + assert.deepEqual(errors, []); + await page.context().close(); + } + }); + + await t.test(lang + ": an update downloaded has no second Restart", async () => { + const ctl = { posts: [], update: { state: "ready", current: "0.1.400", latest: "0.1.401", run: 111 } }; + const { page, errors } = await open(browser, lang, ctl, 900); + const row = versionRow(page, lang); + await row.locator(".val button", { hasText: w.update }).waitFor(); + assert.deepEqual(await buttons(row), [w.update]); + assert.deepEqual(errors, []); + await page.context().close(); + }); + } + }); +} diff --git a/internal/gui/traymenu.go b/internal/gui/traymenu.go index f901a7399..848405784 100644 --- a/internal/gui/traymenu.go +++ b/internal/gui/traymenu.go @@ -11,6 +11,7 @@ import ( // (i18n.js), and these few are all the menu and the icon's tooltip show // (#301). var trayZh = map[string]string{ + "Restart magpie": "重启 magpie", "Open magpie": "打开 magpie", "Version %s": "版本 %s", "Restart to Update": "重启以更新", @@ -46,6 +47,7 @@ var trayZh = map[string]string{ // trayZhTW is the tray menu in Traditional Chinese, with Taiwan's words. var trayZhTW = map[string]string{ + "Restart magpie": "重新啟動 magpie", "Open magpie": "開啟 magpie", "Version %s": "版本 %s", "Restart to Update": "重新啟動以更新", @@ -81,6 +83,7 @@ var trayZhTW = map[string]string{ // trayJa is the tray menu in Japanese. var trayJa = map[string]string{ + "Restart magpie": "magpie を再起動", "Open magpie": "magpie を開く", "Version %s": "バージョン %s", "Restart to Update": "再起動してアップデート", @@ -116,6 +119,7 @@ var trayJa = map[string]string{ // trayDe is the tray menu in German. var trayDe = map[string]string{ + "Restart magpie": "magpie neu starten", "Open magpie": "magpie öffnen", "Version %s": "Version %s", "Restart to Update": "Zum Aktualisieren neu starten", @@ -199,7 +203,8 @@ func trayMenuLabels(lang, version, update string, paused bool) trayLabels { open: trayText(lang, "Open magpie"), pause: trayText(lang, "Pause Gateway"), version: trayText(lang, "Version %s", version), - restart: trayText(lang, "Restart to Update"), + // no update waiting: magpie restarts as it is (restart.go) + restart: trayText(lang, "Restart magpie"), quit: trayText(lang, "Quit magpie"), } if update != "" { diff --git a/internal/gui/traymenu_test.go b/internal/gui/traymenu_test.go index 41a9ac721..5101d162a 100644 --- a/internal/gui/traymenu_test.go +++ b/internal/gui/traymenu_test.go @@ -56,13 +56,13 @@ func TestTrayMenuLabels(t *testing.T) { } } zh := trayMenuLabels("zh", "0.1.500", "", false) - if zh != (trayLabels{"打开 magpie", "暂停网关", "版本 0.1.500", "重启以更新", "退出 magpie"}) { + if zh != (trayLabels{"打开 magpie", "暂停网关", "版本 0.1.500", "重启 magpie", "退出 magpie"}) { t.Errorf("zh: %+v", zh) } 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", "", false); ja != (trayLabels{"magpie を開く", "ゲートウェイを一時停止", "バージョン 0.1.500", "再起動してアップデート", "magpie を終了"}) { + if ja := trayMenuLabels("ja", "0.1.500", "", false); ja != (trayLabels{"magpie を開く", "ゲートウェイを一時停止", "バージョン 0.1.500", "magpie を再起動", "magpie を終了"}) { t.Errorf("ja: %+v", ja) } if l := trayMenuLabels("zh", "0.1.500", "0.1.501", false); l.restart != "重启以更新到 0.1.501" { diff --git a/internal/gui/update.go b/internal/gui/update.go index 039d40624..71180961b 100644 --- a/internal/gui/update.go +++ b/internal/gui/update.go @@ -128,6 +128,10 @@ type updateJSON struct { Notes string `json:"notes,omitempty"` URL string `json:"url,omitempty"` Stuck string `json:"stuck,omitempty"` // available: why it can't update itself + // Run tells this run of magpie from the next, of the same version: + // a page whose restart asked for no update reloads once it changes + // (restart.go) + Run int64 `json:"run,omitempty"` // available, stuck "not-writable": the folder magpie may not write to StuckDir string `json:"stuckDir,omitempty"` // available, stuck "package": the package manager that installed @@ -799,7 +803,7 @@ func (u *updater) jsonIn(lang string) updateJSON { go u.relang(u.latest.Version, lang) } } - j := updateJSON{State: u.state, Current: Version, Error: u.err, Retry: u.retry} + j := updateJSON{State: u.state, Current: Version, Run: runStarted, Error: u.err, Retry: u.retry} if u.channel != "" && u.latest != nil { j.Channel = u.channel if u.state == "latest" {