diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 4f0591f63..c3336695f 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -998,6 +998,28 @@ while the new version starts (#4521). See `TestUpdateInATerminalRestartsTheAppWi [`restart_test.go`](../../internal/gateway/restart_test.go) and `TestUpdateAsksTheRunningMagpieToRestart`. +A restart magpie makes by itself (Settings' Restart automatically, +`magpie update` from a terminal, a Remote magpie's ask, another copy +replacing this one's binary) also waits while the user is using one of +magpie's own windows (BESTLJP0412 on X: the window closed and came back +in the middle of adding a provider, the gateway idle). Every page (the +window, the tray panel, a browser on `magpie web`) posts +`/api/update/using` on a press, a key, typing or the wheel, at most +every 20 s and at once when the dialog (`#modal`) opens or closes, with +whether it is open (app.js, beside `renderUpdateBadge`). `inUseAt` in +[`update_wait.go`](../../internal/gui/update_wait.go) counts the user +as using magpie for `usingFor` (2 minutes) after that input, or +`openFor` (15 minutes) while a dialog was open, which may hold a form +half filled in; `waitFor` waits through it when the wait wasn't asked +for (`waitAsked`), and `restartBeside` doesn't restart at once. The +post writes nothing, so `held` keeps what it holds. The wait says so +(`using` in `/api/update`; Settings › Version and the Update pill add +"waiting while you use magpie"). A restart the user asked for (the pill, +Settings › Version, the tray) never waits for it. A window left open +and unused for longer is not in use, so the restart still comes. See +`TestAutoRestartWaitsWhileTheWindowIsUsed`, +`TestTerminalUpdateWaitsWhileTheWindowIsUsed` and `update-using.test.cjs`. + The app and `magpie web` open together each have an updater of their own over the same program, and the gateway's ask reaches only the one serving the gateway (visamzh on X: one restarted to update, and the other ran on diff --git a/internal/cli/settings_parity_test.go b/internal/cli/settings_parity_test.go index 4d9380769..0268fe32c 100644 --- a/internal/cli/settings_parity_test.go +++ b/internal/cli/settings_parity_test.go @@ -489,6 +489,7 @@ var notYet = map[string]string{ "POST /api/usage/requests/export": U, // usage.go "POST /api/usage/trae-checkin": U, // usage.go "GET /api/update/notes": W, // update.go + "POST /api/update/using": W, // update.go "GET /api/whatsnew": W, // whatsnew.go "POST /api/whatsnew/seen": W, // whatsnew.go "POST /api/whatsnew/today": W, // whatsnew.go diff --git a/internal/gui/api.go b/internal/gui/api.go index 198fc58d0..74d002457 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -2963,9 +2963,9 @@ func held(h http.Handler) http.Handler { // 5x the CPU. defer tightenGC()() } - if !(api && r.Method == http.MethodGet) { + if !(api && r.Method == http.MethodGet) && r.URL.Path != "/api/update/using" { // anything that may have written drops what was held, once it - // has answered with it + // has answered with it (a page's word of input writes nothing) defer provider.Changed() } h.ServeHTTP(rw, r) diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 18d3f8278..d52f2a884 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -4352,31 +4352,36 @@ function recoveredOnce() { : t("{file} was damaged (the computer likely stopped mid-write), so magpie restored it from its backup. A change made after that may be missing; the damaged file is kept beside it.", { file: files }), "warn", 20000); } -// installFrom is what a restart to update tells the app: the window's tab, -// for the new version to open its window there (Windows, Linux). +// installFrom: the window's tab, for the new version to open on (Windows, Linux) function installFrom() { return mode === "window" ? { view } : {}; } -// updateBusy says what a restart would cut short (#577): the agents' -// requests in flight through the gateway, the Claude Code turns waiting on -// their tool results. -function updateBusyText(b) { - const parts = []; +// updateBusy: what a restart would cut short (#577), and the window in use +function updateBusyText(b, using) { + const parts = using ? [t("waiting while you use magpie")] : []; if (b?.requests) parts.push(t("{n} in flight", { n: b.requests })); if (b?.tools) parts.push(t("{n} awaiting tool results", { n: b.tools })); return parts.join(" · "); } -// updatePath asks for the update's state or the release notes in the -// page's language: the notes follow Settings' language, Chinese where a -// release has it (freecss on Discord). +// updatePath: the update's state or notes in the page's language (freecss on Discord) function updatePath(p) { return p + (p.includes("?") ? "&" : "?") + "lang=" + encodeURIComponent(locale); } +// input: in use, so an update waits (inUseAt) +let usedAt = 0, usedOpen; +for (const k of "pointerdown keydown input wheel".split(" ")) addEventListener(k, () => { + const open = $("#modal")?.hidden === false, now = Date.now(); + if (now - usedAt < 2e4 && open === usedOpen) return; + usedAt = now, usedOpen = open; + api("update/using", { open }).catch(() => {}); +}, true); + // renderUpdateBadge shows the header's Update pill once a newer magpie is // downloaded or out; Settings or its × keeps it away. + async function renderUpdateBadge() { const b = $("#update"), label = b.querySelector("span"); const u = await api(updatePath("update")).catch(() => null); @@ -4427,7 +4432,7 @@ async function renderUpdateBadge() { // click, not as "now" if (u.state === "ready" && u.waiting) { label.textContent = t("Waiting to update"); - const a = { v: u.latest, busy: updateBusyText(u.busy) || "…" }; + const a = { v: u.latest, busy: updateBusyText(u.busy, u.using) || "…" }; b.title = u.handover ? t("magpie restarts to update to {v} once the replies through a Claude subscription have finished: {busy}. Other requests carry on across the restart. Click to restart now.", a) : t("magpie restarts to update to {v} once the agents' requests through the gateway have finished: {busy}. Click to restart now.", a); b.onclick = () => { if (Date.now() - (+b.dataset.armed || 0) < 1500) return; @@ -4469,9 +4474,8 @@ async function renderUpdateBadge() { }; } -// downloadingText is the pill's word while an update downloads: its percent -// (none while the size is unknown: "NaN%", inaction on Discord) and speed, -// then the step after the bytes, never still (esir_tech on Discord) +// downloadingText: the pill's percent (none for an unknown size, inaction on +// Discord) and speed, then the step after the bytes (esir_tech on Discord) const UPDATE_STEPS = { retry: "Reconnecting…", verify: "Verifying…", unpack: "Unpacking…", signature: "Checking signature…" }; function downloadingText(u) { const p = u?.total > 0 ? Math.floor(((u.done || 0) / u.total) * 100) : NaN, s = UPDATE_STEPS[u?.step]; @@ -4480,14 +4484,12 @@ function downloadingText(u) { } const speedText = (b) => (b >= 1e6 ? t("{n} MB/s", { n: (b / 1e6).toFixed(1) }) : t("{n} KB/s", { n: Math.max(1, Math.round(b / 1e3)) })); -// updatePillOff is whether the user keeps the Update pill away for v. function updatePillOff(v) { const s = state?.settings || {}; return !!s.noUpdatePill || (!!v && s.updateSkip === v); } -// skipUpdate hides the Update pill until a version newer than v is out -// ("" shows it again), and says where it can be brought back. +// skipUpdate hides the pill until a version newer than v ("" shows it again) async function skipUpdate(v) { $("#update").hidden = true; try { @@ -4513,9 +4515,8 @@ async function backAsNew(was) { } } -// servedAnew reloads, once, a browser's page that another version of -// magpie now answers for (visamzh on X): its magpie restarted into an -// update put in elsewhere. The badge and the Version row both ask. +// servedAnew reloads, once, a page another magpie version now answers for +// (visamzh on X); the badge and the Version row ask let reloadingAnew = false; function servedAnew(u) { if (!web || !pageVersion || !u?.current || u.current === pageVersion) return false; @@ -4523,9 +4524,8 @@ function servedAnew(u) { return true; } -// updateStuck says why this magpie can't replace itself where it is: off -// the Mac, a folder it may not write to, such as C:\ (#1277), or a -// container, whose image is what gets updated. +// updateStuck: why magpie can't replace itself: a folder it may not write +// to off the Mac (C:\, #1277), or a container, whose image gets updated function updateStuck(u) { const p = u.packaged; if (p) return p.command ? t("{manager} installed magpie ({pkg}), so {manager} updates it, not magpie: {cmd}", { manager: p.manager, pkg: p.package, cmd: p.command }) : t("{manager} installed magpie, so {manager} updates it, not magpie.", { manager: p.manager }); @@ -22455,7 +22455,7 @@ async function renderUpdate(r, u) { sub.textContent = t("Restarting…"); backAsNew(u.current); }; - const busyNow = updateBusyText(u.busy); + const busyNow = updateBusyText(u.busy, u.using); if (u.waiting) { sub.textContent += " · " + (u.handover ? t("restarts once the Claude subscription's replies have finished") : t("restarts once the gateway is idle")) + (busyNow ? " · " + busyNow : ""); btn(t("Restart now"), () => install("now")); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index d7aa4432f..b54b64093 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3785,6 +3785,7 @@ const I18N = { "{n} in flight": "{n} 个请求进行中", "{n} awaiting tool results": "{n} 个工具调用待返回", "restarts once the gateway is idle": "网关空闲后自动重启", + "waiting while you use magpie": "正在使用 magpie,稍后再重启", "restarts once the Claude subscription's replies have finished": "Claude 订阅的回复结束后自动重启", "magpie restarts to update to {v} once the replies through a Claude subscription have finished: {busy}. Other requests carry on across the restart. Click to restart now.": "Claude 订阅的回复结束后,magpie 将重启以更新到 {v}:{busy}。其他请求不受重启影响。点击立即重启。", "Restart now": "立即重启", @@ -8697,6 +8698,7 @@ const I18N = { "{n} in flight": "{n} 個請求進行中", "{n} awaiting tool results": "{n} 個工具呼叫待返回", "restarts once the gateway is idle": "閘道空閒後自動重啟", + "waiting while you use magpie": "正在使用 magpie,稍後再重啟", "restarts once the Claude subscription's replies have finished": "Claude 訂閱的回覆結束後自動重啟", "magpie restarts to update to {v} once the replies through a Claude subscription have finished: {busy}. Other requests carry on across the restart. Click to restart now.": "Claude 訂閱的回覆結束後,magpie 將重啟以更新到 {v}:{busy}。其他請求不受重啟影響。點選立即重啟。", "Restart now": "立即重啟", @@ -13620,6 +13622,7 @@ const I18N = { "{n} in flight": "{n} 件のリクエストを処理中", "{n} awaiting tool results": "{n} 件がツール結果待ち", "restarts once the gateway is idle": "ゲートウェイがアイドルになったら再起動します", + "waiting while you use magpie": "magpie の使用中は待機します", "restarts once the Claude subscription's replies have finished": "Claude サブスクリプションの応答が終わると再起動します", "magpie restarts to update to {v} once the replies through a Claude subscription have finished: {busy}. Other requests carry on across the restart. Click to restart now.": "Claude サブスクリプションの応答が終わると、magpie は再起動して {v} にアップデートします:{busy}。ほかのリクエストは再起動をまたいで続きます。クリックすると今すぐ再起動します。", "Restart now": "今すぐ再起動", @@ -18554,6 +18557,7 @@ const I18N = { "{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", + "waiting while you use magpie": "wartet, solange du magpie benutzt", "restarts once the Claude subscription's replies have finished": "startet neu, sobald die Antworten des Claude-Abos fertig sind", "magpie restarts to update to {v} once the replies through a Claude subscription have finished: {busy}. Other requests carry on across the restart. Click to restart now.": "magpie startet für das Update auf {v} neu, sobald die Antworten über das Claude-Abo fertig sind: {busy}. Andere Anfragen laufen über den Neustart hinweg weiter. Klicken, um jetzt neu zu starten.", "Restart now": "Jetzt neu starten", diff --git a/internal/gui/tests/update-using.test.cjs b/internal/gui/tests/update-using.test.cjs new file mode 100644 index 000000000..8ebcfe25c --- /dev/null +++ b/internal/gui/tests/update-using.test.cjs @@ -0,0 +1,133 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// BESTLJP0412 on X: a restart by itself (Settings › Restart automatically) +// came while the user was adding a provider. The page tells the app of the +// user's input (POST /api/update/using, at most every 20s, at once when a +// dialog opens or closes), and the wait it holds says so in Settings › +// Version and on the Update pill. Every language, both engines; no backend, +// the API is faked. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { watchSettingsReads, settingsDrawn } = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); + +const words = { + en: { version: "Version", using: "waiting while you use magpie", idle: "restarts once the gateway is idle", pill: "Waiting to update" }, + zh: { version: "版本", using: "正在使用 magpie,稍后再重启", idle: "网关空闲后自动重启", pill: "等待更新" }, + "zh-TW": { version: "版本", using: "正在使用 magpie,稍後再重啟", idle: "閘道空閒後自動重啟", pill: "等待更新" }, + ja: { version: "バージョン", using: "magpie の使用中は待機します", idle: "ゲートウェイがアイドルになったら再起動します", pill: null }, + de: { version: "Version", using: "wartet, solange du magpie benutzt", idle: "startet neu, sobald der Zugangspunkt frei ist", pill: null }, +}; + +function settingsPayload(lang) { + return { + theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", + dock: false, dockWindow: false, proxy: "", redact: false, redactPersonal: false, redactWords: [], + codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "", workbuddyCheckin: false, noStats: false, + trayUsage: "", trayUsageEvery: 3, vision: "", imageGen: "", autoRestart: true, + version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425", + proxyNow: "none", proxySource: "none", login: false, + visionModels: [], imageGenModels: [], workbuddyCheckins: [], lanURLs: [], + fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, + }; +} + +function server(lang, ctl) { + const cur = settingsPayload(lang); + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: cur, fx: cur.fx }); + if (url.pathname === "/api/settings") return json(cur); + if (url.pathname === "/api/update") return json({ ...ctl.update }); + if (url.pathname === "/api/update/using") { + ctl.used.push(req.postDataJSON()); + return route.fulfill({ status: 204 }); + } + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + 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 }); + }; +} + +const fresh = () => ({ + update: { state: "ready", current: "0.1.400", latest: "0.1.401", waiting: true, using: true }, + used: [], +}); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a restart by itself waits while magpie is used", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const open = async (lang, ctl, query, width) => { + const errors = []; + const page = await (await browser.newContext({ viewport: { width, height: 560 }, reducedMotion: "reduce" })).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/" + query); + return { page, errors }; + }; + + await t.test("input is told, at most every 20s, and at once when a dialog opens or closes", async () => { + const ctl = fresh(); + const { page, errors } = await open("en", ctl, "?view=settings&tab=about", 900); + await settingsDrawn(page); + assert.deepEqual(ctl.used, [], "loading the page is no input"); + const told = async (n) => { + for (let i = 0; i < 100 && ctl.used.length < n; i++) await page.waitForTimeout(20); + assert.equal(ctl.used.length, n); + }; + await page.keyboard.press("Shift"); + await told(1); + assert.deepEqual(ctl.used[0], { open: false }); + await page.mouse.click(5, 300); + await page.mouse.wheel(0, 40); + await page.keyboard.press("Shift"); + await page.waitForTimeout(200); + assert.equal(ctl.used.length, 1, "more input within 20s says nothing new"); + await page.evaluate(() => { document.querySelector("#modal").hidden = false; }); + await page.keyboard.press("Shift"); + await told(2); + assert.deepEqual(ctl.used[1], { open: true }); + await page.evaluate(() => { document.querySelector("#modal").hidden = true; }); + await page.mouse.click(5, 300); + await told(3); + assert.deepEqual(ctl.used[2], { open: false }); + assert.deepEqual(errors, []); + }); + + for (const [lang, w] of Object.entries(words)) { + await t.test(lang + ": Settings › Version and the pill say the restart waits for the user", async () => { + const ctl = fresh(); + const { page, errors } = await open(lang, ctl, "?view=settings&tab=about", 900); + await settingsDrawn(page); + const row = page.locator("#about .row.pref", { has: page.locator(".name", { hasText: w.version }) }).first(); + await page.waitForFunction((t) => [...document.querySelectorAll("#about .row.pref .sub")].some((s) => s.textContent.includes(t)), w.using); + const sub = (await row.locator(".sub").textContent()).trim(); + assert.ok(sub.endsWith(" · " + w.idle + " · " + w.using), sub); + if (lang === "en") assert.equal(sub, "0.1.401 is downloaded · restarts once the gateway is idle · waiting while you use magpie"); + const panel = await open(lang, fresh(), "?mode=panel", 420); + const pill = panel.page.locator("#update"); + await pill.waitFor({ state: "visible" }); + await panel.page.waitForFunction(() => (document.querySelector("#update")?.title || "").length > 0); + if (w.pill) assert.equal((await pill.locator("span").first().textContent()).trim(), w.pill); + assert.ok((await pill.getAttribute("title")).includes(w.using), await pill.getAttribute("title")); + if (lang === "en") assert.equal(await pill.getAttribute("title"), "magpie restarts to update to 0.1.401 once the agents' requests through the gateway have finished: waiting while you use magpie. Click to restart now."); + assert.deepEqual(errors, []); + assert.deepEqual(panel.errors, []); + }); + } + }); +} diff --git a/internal/gui/update.go b/internal/gui/update.go index ed218d4d0..81705a1a1 100644 --- a/internal/gui/update.go +++ b/internal/gui/update.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "io" "log" "net/http" "os" @@ -147,6 +148,9 @@ type updateJSON struct { // (handover.go): Busy is then the Claude subscription's turns alone, // every other request finishing as the new version takes the next Handover bool `json:"handover,omitempty"` + // Using, a restart by itself waits for the user to stop using a + // window (inUseAt) + Using bool `json:"using,omitempty"` } var updates = &updater{} @@ -683,6 +687,7 @@ func (u *updater) jsonIn(lang string) updateJSON { } if j.State == "ready" || u.waiting { j.Waiting, j.GaveUp = u.waiting, u.gaveUp && !u.waiting + j.Using = u.waiting && !u.waitAsked && inUseAt(time.Now()) j.Handover = handover if busy.Any() { j.Busy = &busy @@ -725,6 +730,16 @@ func (u *updater) relang(version, lang string) { } func updateRoutes(mux *http.ServeMux, w Windows) { + // a page's word of the user's input, which a restart by itself waits + // for to end (inUseAt); open: a dialog is open + mux.HandleFunc("POST /api/update/using", func(rw http.ResponseWriter, r *http.Request) { + var b struct { + Open bool `json:"open"` + } + json.NewDecoder(io.LimitReader(r.Body, 1<<10)).Decode(&b) + noteUse(b.Open, time.Now()) + rw.WriteHeader(http.StatusNoContent) + }) mux.HandleFunc("GET /api/update", func(rw http.ResponseWriter, r *http.Request) { if r.URL.Query().Get("fresh") == "1" { // the Version row updates.refreshLatest(settings.Load()) diff --git a/internal/gui/update_autorestart_test.go b/internal/gui/update_autorestart_test.go index c37cf6680..123fc83be 100644 --- a/internal/gui/update_autorestart_test.go +++ b/internal/gui/update_autorestart_test.go @@ -2,8 +2,11 @@ package gui import ( "encoding/json" + "fmt" "net/http" "net/http/httptest" + "os" + "path/filepath" "strings" "sync/atomic" "testing" @@ -95,3 +98,78 @@ func TestAutoRestartCalledOff(t *testing.T) { updates.autoTick(on) eventually(t, "a newer version wasn't restarted into", func() bool { return restarts.Load() == 1 }) } + +// BESTLJP0412 on X: a restart by itself came while the user was adding a +// provider in the window, the gateway idle. It waits while a page tells of +// input, longer with a dialog open, and comes once that has stopped; a +// restart the user asked for doesn't wait for it. +func TestAutoRestartWaitsWhileTheWindowIsUsed(t *testing.T) { + busy := &fakeBusy{} + busy.set(gateway.Busy{Last: time.Now().Add(-time.Hour)}) + old := updates + updates = &updater{state: "ready", latest: &update.Release{Version: "0.1.999"}} + t.Cleanup(func() { updates = old }) + quick(t, busy, updates) + oldUsing, oldOpen := usingFor, openFor + usingFor, openFor = 100*time.Millisecond, time.Minute + t.Cleanup(func() { usingFor, openFor = oldUsing, oldOpen }) + var restarts atomic.Int32 + updates.autoRestart = func() bool { restarts.Add(1); return true } + mux := http.NewServeMux() + updateRoutes(mux, &quitCount{}) + using := func(open bool) { + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest("POST", "/api/update/using", strings.NewReader(fmt.Sprintf(`{"open":%t}`, open)))) + if rec.Code != http.StatusNoContent { + t.Fatalf("using: %d %s", rec.Code, rec.Body) + } + } + + using(true) // typing in the Add provider dialog + updates.autoTick(settings.Settings{AutoRestart: true}) + if w, _ := updates.waitingFor(); !w { + t.Fatal("no restart waits") + } + time.Sleep(300 * time.Millisecond) // three times usingFor: the dialog holds it + if n := restarts.Load(); n != 0 { + t.Fatal("restarted while the user had a dialog open") + } + if j := updates.json(); !j.Using || !j.Waiting { + t.Fatalf("the wait doesn't say it is for the user: %+v", j) + } + using(false) // the dialog closed + eventually(t, "never restarted once the window was left", func() bool { return restarts.Load() == 1 }) + + // a restart the user asked for doesn't wait for them + using(true) + updates.waitIdle(func() bool { restarts.Add(1); return true }, true) + eventually(t, "a restart asked for waited for the window", func() bool { return restarts.Load() == 2 }) +} + +// magpie update run in a terminal (an agent's) restarts the app as +// AutoRestart does, so it waits for the user's window too. +func TestTerminalUpdateWaitsWhileTheWindowIsUsed(t *testing.T) { + busy := &fakeBusy{} + busy.set(gateway.Busy{Last: time.Now().Add(-time.Hour)}) + exe := filepath.Join(t.TempDir(), "magpie") + if err := os.WriteFile(exe, []byte("v0.1.1"), 0o755); err != nil { + t.Fatal(err) + } + u := &updater{state: "latest", exe: exe} + u.self, _ = os.Stat(exe) + quick(t, busy, u) + oldUsing := usingFor + usingFor = 150 * time.Millisecond + t.Cleanup(func() { usingFor = oldUsing }) + var restarts atomic.Int32 + u.autoRestart = func() bool { restarts.Add(1); return true } + if err := os.WriteFile(exe, []byte("v0.1.2 is longer"), 0o755); err != nil { + t.Fatal(err) + } + + noteUse(false, time.Now()) + if r := u.restartBeside("v0.1.2"); r.State != "waiting" { + t.Fatalf("restarted with the window in use: %+v", r) + } + eventually(t, "never restarted once the window was left", func() bool { return restarts.Load() == 1 }) +} diff --git a/internal/gui/update_beside.go b/internal/gui/update_beside.go index 4034414d6..10e52f6a6 100644 --- a/internal/gui/update_beside.go +++ b/internal/gui/update_beside.go @@ -40,7 +40,9 @@ func (u *updater) restartBeside(version string) gateway.RestartReply { return gateway.RestartReply{State: "unsupported"} } reply := gateway.RestartReply{Handover: handsOver()} - if waiting, _ := u.waitingFor(); !waiting && u.idle() { + // nor while the user is using a window (inUseAt): the terminal's + // command isn't theirs in the window + if waiting, _ := u.waitingFor(); !waiting && u.idle() && !inUseAt(time.Now()) { reply.State = "restarting" go restart() // after the answer: the restart lets this request finish return reply diff --git a/internal/gui/update_wait.go b/internal/gui/update_wait.go index da8cb8f88..2063426ae 100644 --- a/internal/gui/update_wait.go +++ b/internal/gui/update_wait.go @@ -1,6 +1,7 @@ package gui import ( + "sync/atomic" "time" "github.com/yetone/magpie/internal/gateway" @@ -25,6 +26,46 @@ var ( waitTick = time.Second ) +// A restart by itself (Settings' AutoRestart) also waits while the user +// is using one of magpie's own windows (BESTLJP0412 on X: the window +// closed and came back mid-way through adding a provider). Each page +// tells the app of the user's input (`POST /api/update/using`, a press, a +// key, typing or the wheel, at most every 20s), and whether a dialog is +// open (#modal); the app counts it in use for usingFor after that input, +// or openFor with a dialog open, which may hold a form half filled in. +// A restart the user asked for (a click, `magpie update`) doesn't wait +// for it: they are the one using magpie. +var ( + usingFor = 2 * time.Minute + openFor = 15 * time.Minute +) + +// usedAt is when a page last told of input (Unix nanoseconds), usedOpen +// whether a dialog was open then. +var ( + usedAt atomic.Int64 + usedOpen atomic.Bool +) + +// noteUse is a page's word of the user's input at now. +func noteUse(open bool, now time.Time) { + usedOpen.Store(open) + usedAt.Store(now.UnixNano()) +} + +// inUseAt is whether the user was using a window lately enough at now. +func inUseAt(now time.Time) bool { + at := usedAt.Load() + if at == 0 { + return false + } + gap, most := now.Sub(time.Unix(0, at)), usingFor + if usedOpen.Load() { + most = openFor + } + return gap < most +} + // gatewayBusy is what the gateway this process serves has in flight; // nothing when another magpie serves it, which a restart here leaves be. var gatewayBusy = func() gateway.Busy { @@ -127,6 +168,12 @@ func (u *updater) waitFor(gen int) { continue } u.mu.Lock() + asked := u.waitAsked + u.mu.Unlock() + if !asked && inUseAt(time.Now()) { + continue + } + u.mu.Lock() // another magpie put the update in (restartBeside): that is what // the restart goes into, whatever the feed answers now in := u.replaced() @@ -135,9 +182,6 @@ func (u *updater) waitFor(gen int) { case in: case st == "ready": // a newer version out since is downloaded first, and waited for - u.mu.Lock() - asked := u.waitAsked - u.mu.Unlock() waitRecheck(u, asked) if u.asking() || u.json().State != "ready" { continue @@ -167,7 +211,8 @@ func (u *updater) waitFor(gen int) { // autoTick, with Settings' AutoRestart on (and automatic updates), has a // downloaded update restarted into once the gateway is idle (#2096). The -// wait is waitIdle's, so a restart never cuts a request short; one that +// wait is waitIdle's, so a restart never cuts a request short, nor comes +// while the user is using a window (inUseAt); one that // ran out (gaveUp) is waited for again on the next tick, and one the user // called off isn't, for that version. func (u *updater) autoTick(s settings.Settings) { diff --git a/internal/gui/update_wait_test.go b/internal/gui/update_wait_test.go index b1ae9a59d..6fd615002 100644 --- a/internal/gui/update_wait_test.go +++ b/internal/gui/update_wait_test.go @@ -41,10 +41,13 @@ func quick(t *testing.T, busy *fakeBusy, u *updater) { oldBusy, oldSettle, oldMost, oldTick, oldRecheck := gatewayBusy, idleSettle, waitMost, waitTick, waitRecheck gatewayBusy, idleSettle, waitMost, waitTick = busy.get, 80*time.Millisecond, time.Minute, 5*time.Millisecond waitRecheck = func(*updater, bool) {} + oldAt, oldOpen := usedAt.Swap(0), usedOpen.Swap(false) // no window used t.Cleanup(func() { u.cancelWait() u.loops.Wait() gatewayBusy, idleSettle, waitMost, waitTick, waitRecheck = oldBusy, oldSettle, oldMost, oldTick, oldRecheck + usedAt.Store(oldAt) + usedOpen.Store(oldOpen) }) }