diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 4cd273685..cba44c638 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -4467,10 +4467,7 @@ function updatePath(p) { } // renderUpdateBadge shows the header's Update pill once a newer magpie is -// downloaded (a click restarts into it) or, where magpie can't replace -// itself, out (a click opens the release page). The user may keep it away: -// for good (Settings), or for this version (its ×, or a right-click), until -// a newer one is out. magpie still downloads it and puts it in on quitting. +// 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); @@ -4511,7 +4508,7 @@ async function renderUpdateBadge() { delete b.dataset.pulling; return restart(); } - label.textContent = downloadingText(u); + b.title = label.textContent = downloadingText(u); setTimeout(renderUpdateBadge, 700); return; } @@ -4563,14 +4560,16 @@ async function renderUpdateBadge() { }; } -// downloadingText is the pill's word while an update downloads: its -// percent once there is one. The answer leaves done out while it is 0, and -// total too while the size isn't known yet, so the first reads have none — -// they said "NaN%" (inaction on Discord). +// 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) +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; - return Number.isFinite(p) ? t("Downloading… {p}%", { p: Math.min(100, Math.max(0, p)) }) : t("Downloading…"); + const p = u?.total > 0 ? Math.floor(((u.done || 0) / u.total) * 100) : NaN, s = UPDATE_STEPS[u?.step]; + if (s && u.step !== "retry") return t(s); + return (s ? t(s) : Number.isFinite(p) ? t("Downloading… {p}%", { p: Math.min(100, Math.max(0, p)) }) : t("Downloading…")) + (u?.speed ? " · " + speedText(u.speed) : ""); } +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) { @@ -22461,8 +22460,7 @@ async function renderUpdate(r, u) { break; } case "found": { - // downloads wait for a click (Settings' Download updates - // automatically off, #2296): what is out, and how big it is + // downloads wait for a click (#2296): what is out, and its size sub.textContent = t("{v} is out", { v: u.latest }) + (u.size ? " · " + t("{done} MB", { done: (u.size / 1e6).toFixed(1) }) : ""); const get = btn(t("Download update"), async () => { if (updateBusy) return; @@ -22483,9 +22481,16 @@ async function renderUpdate(r, u) { if (!web) page(); break; case "downloading": + if (UPDATE_STEPS[u.step] && u.step !== "retry") { + sub.textContent = t("{v} is downloaded", { v: u.latest }) + " · " + t(UPDATE_STEPS[u.step]); + again(700); + break; + } sub.textContent = t("Downloading {v}…", { v: u.latest }); - if (u.total) sub.textContent += " " + Math.floor((u.done / u.total) * 100) + "% · " + t("{done} of {total} MB", { done: (u.done / 1e6).toFixed(1), total: (u.total / 1e6).toFixed(1) }); + if (u.total) sub.textContent += " " + Math.floor(((u.done || 0) / u.total) * 100) + "% · " + t("{done} of {total} MB", { done: ((u.done || 0) / 1e6).toFixed(1), total: (u.total / 1e6).toFixed(1) }); else if (u.done) sub.textContent += " " + t("{done} MB", { done: (u.done / 1e6).toFixed(1) }); + if (u.step === "retry") sub.textContent += " · " + t("Reconnecting…"); + else if (u.speed) sub.textContent += " · " + speedText(u.speed); page(); again(700); break; @@ -22501,15 +22506,11 @@ async function renderUpdate(r, u) { case "error": // the reason in sight: "timed out" says try a proxy, a 404 says wait sub.textContent = t(u.latest ? "Couldn't download {v}" : "Couldn't check for updates", { v: u.latest }) + (u.error ? " · " + u.error.replace(/^Get "[^"]*": /, "") : ""); - // the network broke it off, after the tries download makes by itself - // (AIMetaPhD on X: an EOF from GitHub's asset host, with its whole - // signed address): what happened and what to do, in the app's words + // the network broke it off (AIMetaPhD on X): said in the app's words if (u.network && u.latest) sub.textContent = t("{v}'s download broke off, a network problem. Click Check to try again, or download it from the release page", { v: u.latest }); sub.title = u.error || ""; if (u.error) sub.classList.add("wraps"); - // through a mirror (#893): it's the mirror's failing — it didn't - // answer, or sent a file that isn't the release's, never installed — - // and GitHub itself is offered, which also takes the mirror away + // through a mirror (#893): the mirror's failing; GitHub is offered 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 "[^"]*": /, "") : ""); @@ -22531,9 +22532,7 @@ async function renderUpdate(r, u) { if (u.latest) page(); break; case "blocked": { - // the new version didn't start on this computer (#894) and this one - // runs on: why, and what the user can do. The clock doesn't download - // it again; Check tries it once more. + // the new version didn't start here (#894): why, and what to do const b = u.blocked || {}; sub.textContent = b.policy ? t("{v} didn't start on this computer: Windows' Smart App Control (or another app control policy) blocked the new version, which isn't signed. magpie stays on {cur}. Download it and run it yourself, or turn Smart App Control off and check again", { v: u.latest || b.version, cur: u.current }) diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 716cff882..f3a5f1f57 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3606,6 +3606,12 @@ const I18N = { "{done} MB": "{done} MB", "Downloading…": "正在下载…", "Downloading… {p}%": "正在下载… {p}%", + "Reconnecting…": "正在重新连接…", + "Verifying…": "正在校验…", + "Unpacking…": "正在解压…", + "Checking signature…": "正在检查签名…", + "{n} MB/s": "{n} MB/s", + "{n} KB/s": "{n} KB/s", "Click to try again": "点击重试", "Click to open the download page.": "点击打开下载页面。", "macOS is running magpie from a temporary copy, so it can't update itself; move magpie to Applications and open it from there.": "macOS 正从临时副本运行 magpie,无法自动更新;请将 magpie 移到「应用程序」文件夹后从那里打开。", @@ -8238,6 +8244,12 @@ const I18N = { "{done} MB": "{done} MB", "Downloading…": "正在下載…", "Downloading… {p}%": "正在下載… {p}%", + "Reconnecting…": "正在重新連線…", + "Verifying…": "正在驗證…", + "Unpacking…": "正在解壓縮…", + "Checking signature…": "正在檢查簽章…", + "{n} MB/s": "{n} MB/s", + "{n} KB/s": "{n} KB/s", "Click to try again": "點選重試", "Click to open the download page.": "點選開啟下載頁面。", "macOS is running magpie from a temporary copy, so it can't update itself; move magpie to Applications and open it from there.": "macOS 正從臨時副本執行 magpie,無法自動更新;請將 magpie 移到「應用程式」資料夾後從那裡開啟。", @@ -12881,6 +12893,12 @@ const I18N = { "{done} MB": "{done} MB", "Downloading…": "ダウンロード中…", "Downloading… {p}%": "ダウンロード中… {p}%", + "Reconnecting…": "再接続中…", + "Verifying…": "検証中…", + "Unpacking…": "展開中…", + "Checking signature…": "署名を確認中…", + "{n} MB/s": "{n} MB/s", + "{n} KB/s": "{n} KB/s", "Click to try again": "クリックして再試行", "Click to open the download page.": "クリックするとダウンロードページを開きます。", "macOS is running magpie from a temporary copy, so it can't update itself; move magpie to Applications and open it from there.": "macOS が magpie を一時的なコピーから実行しているため、自動アップデートできません。magpie を「アプリケーション」フォルダに移動し、そこから開いてください。", @@ -17535,6 +17553,12 @@ const I18N = { "{done} MB": "{done} MB", "Downloading…": "Wird heruntergeladen…", "Downloading… {p}%": "Wird heruntergeladen… {p} %", + "Reconnecting…": "Verbindung wird neu aufgebaut…", + "Verifying…": "Wird geprüft…", + "Unpacking…": "Wird entpackt…", + "Checking signature…": "Signatur wird geprüft…", + "{n} MB/s": "{n} MB/s", + "{n} KB/s": "{n} KB/s", "Click to try again": "Zum erneuten Versuch klicken", "Click to open the download page.": "Klicken, um die Download-Seite zu öffnen.", "macOS is running magpie from a temporary copy, so it can't update itself; move magpie to Applications and open it from there.": "macOS führt magpie aus einer temporären Kopie aus, daher kann es sich nicht selbst aktualisieren; verschieben Sie magpie in „Programme“ und öffnen Sie es von dort.", diff --git a/internal/gui/tests/update-download-steps.test.cjs b/internal/gui/tests/update-download-steps.test.cjs new file mode 100644 index 000000000..b4abbf4d0 --- /dev/null +++ b/internal/gui/tests/update-download-steps.test.cjs @@ -0,0 +1,142 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// An update's download never sits on a still percent (esir_tech on Discord: +// "17%" for minutes). The header's Update pill and Settings' Version row say +// how fast the bytes come, "Reconnecting…" while a broken download waits to +// try again, and then each step after the bytes (verifying, unpacking, +// checking the signature) instead of a stale 100%. Every language, a wide +// and a narrow window: the pill's text fits, or its tooltip carries it where +// the tight header hides the word. No NaN, no scroll, no left border; 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 assets = path.resolve(__dirname, "../assets"); + +const words = { + en: { half: "Downloading… 50%", retry: "Reconnecting…", verify: "Verifying…", unpack: "Unpacking…", signature: "Checking signature…", ready: "0.1.401 is downloaded" }, + zh: { half: "正在下载… 50%", retry: "正在重新连接…", verify: "正在校验…", unpack: "正在解压…", signature: "正在检查签名…", ready: "0.1.401 已下载" }, + "zh-TW": { half: "正在下載… 50%", retry: "正在重新連線…", verify: "正在驗證…", unpack: "正在解壓縮…", signature: "正在檢查簽章…", ready: "0.1.401 已下載" }, + ja: { half: "ダウンロード中… 50%", retry: "再接続中…", verify: "検証中…", unpack: "展開中…", signature: "署名を確認中…", ready: "0.1.401 をダウンロードしました" }, + de: { half: "Wird heruntergeladen… 50 %", retry: "Verbindung wird neu aufgebaut…", verify: "Wird geprüft…", unpack: "Wird entpackt…", signature: "Signatur wird geprüft…", ready: "0.1.401 ist heruntergeladen" }, +}; + +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: "", + 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) { + return async (route) => { + const url = new URL(route.request().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: settingsPayload(lang), fx: settingsPayload(lang).fx }); + if (url.pathname === "/api/settings") return json(settingsPayload(lang)); + if (url.pathname === "/api/update/install" || url.pathname === "/api/update") return json({ ...ctl.update }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + 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: "" }); } + }; +} + +const at = (extra) => ({ state: "downloading", current: "0.1.400", latest: "0.1.401", total: 30_000_000, ...extra }); +const scrolls = (page) => page.evaluate(() => [window.scrollY, document.scrollingElement.scrollTop, ...[...document.querySelectorAll(".view")].map((v) => v.scrollTop)].join(",")); + +async function open(browser, lang, ctl, width, url) { + const errors = []; + const page = await (await browser.newContext({ viewport: { width, height: 640 }, 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 page.goto(url); + return { page, errors }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": an update's download says its speed, then each step after it", async (t) => { + 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, 420]) { + await t.test(`${lang} at ${width}px: the pill`, async () => { + const ctl = { update: { state: "error", retry: true, current: "0.1.400", latest: "0.1.401", error: "timed out" } }; + const { page, errors } = await open(browser, lang, ctl, width, "http://magpie.test/"); + const pill = page.locator("#update"), label = pill.locator("span").first(); + await pill.waitFor({ state: "visible" }); + const seen = []; + await page.exposeFunction("__seen", (s) => seen.push(s)); + await label.evaluate((l) => new MutationObserver(() => window.__seen(l.textContent)).observe(l, { childList: true, characterData: true, subtree: true })); + + ctl.update = at({ done: 15_000_000, step: "download", speed: 1_500_000 }); + const before = await scrolls(page); + await pill.click(); + assert.equal(await scrolls(page), before, "the click must not scroll the page"); + const says = async (want) => { + await page.waitForFunction((s) => document.querySelector("#update span").textContent.trim() === s, want); + // the word fits the pill, or the tight header hides it and the tooltip carries it + const fit = await pill.evaluate((b) => { + const s = b.querySelector("span"), shown = getComputedStyle(s).display !== "none"; + return { shown, fits: s.scrollWidth <= s.clientWidth + 1 && b.scrollWidth <= b.clientWidth + 1, title: b.title }; + }); + assert.ok(fit.shown ? fit.fits : fit.title === want, `${want}: ${JSON.stringify(fit)}`); + }; + await says(w.half + " · 1.5 MB/s"); + ctl.update = at({ done: 15_000_000, step: "download", speed: 42_000 }); + await says(w.half + " · 42 KB/s"); + ctl.update = at({ done: 15_000_000, step: "retry" }); + await says(w.retry); + for (const step of ["verify", "unpack", "signature"]) { + ctl.update = at({ done: 30_000_000, step }); + await says(w[step]); + } + assert.deepEqual(seen.filter((s) => /NaN|undefined|Infinity/.test(s)), [], "the pill said " + seen.join(" | ")); + assert.equal(await pill.evaluate((e) => getComputedStyle(e).borderLeftWidth === "0px" || getComputedStyle(e).borderLeftColor === getComputedStyle(e).borderTopColor), true); + assert.deepEqual(errors, []); + await page.context().close(); + }); + + await t.test(`${lang} at ${width}px: Settings' Version row`, async () => { + const ctl = { update: at({ done: 15_000_000, step: "download", speed: 1_500_000 }) }; + const { page, errors } = await open(browser, lang, ctl, width, "http://magpie.test/?view=settings&tab=about"); + const sub = page.locator("#about .row.pref .sub", { hasText: "0.1.401" }).first(); + await sub.waitFor(); + await page.waitForFunction(() => /50%|50 %/.test([...document.querySelectorAll("#about .row.pref .sub")].map((s) => s.textContent).join("|"))); + assert.match(await sub.textContent(), /15\.0.*30\.0.* · 1\.5 MB\/s$/); + ctl.update = at({ done: 15_000_000, step: "retry" }); + await sub.filter({ hasText: w.retry }).waitFor(); + assert.ok((await sub.textContent()).endsWith(" · " + w.retry)); + for (const step of ["verify", "unpack", "signature"]) { + ctl.update = at({ done: 30_000_000, step }); + await sub.filter({ hasText: w[step] }).waitFor(); + const text = await sub.textContent(); + assert.ok(text.endsWith(" · " + w[step]), text); + assert.ok(text.startsWith(w.ready), text); + assert.doesNotMatch(text, /NaN|undefined|Infinity|100%/); + } + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "the page scrolls sideways"); + assert.deepEqual(errors, []); + await page.context().close(); + }); + } + } + }); +} diff --git a/internal/gui/update.go b/internal/gui/update.go index b3f113833..48d91d583 100644 --- a/internal/gui/update.go +++ b/internal/gui/update.go @@ -61,6 +61,8 @@ type updater struct { asked time.Time // when the feed was last asked, by the clock or a click done int64 // downloading: bytes so far, of total (0 when unknown) total int64 + step string // downloading: the step under way (update.StepDownload, …) + rate []progMark // downloading: the last few seconds' progress, for its speed onReady func(version string) // the waiting update's notes follow the pages' language (freecss on // Discord): the one they last asked in, else the app's @@ -114,6 +116,12 @@ type updateJSON struct { Network bool `json:"network,omitempty"` Error string `json:"error,omitempty"` Done int64 `json:"done,omitempty"` // downloading: bytes so far + // downloading: the step under way, "" before the first + // (update.StepDownload, StepRetry, StepVerify, StepUnpack, + // StepSignature), and how fast the bytes came over the last seconds, + // per second, left out while too little is known + Step string `json:"step,omitempty"` + Speed int64 `json:"speed,omitempty"` // blocked: the version this computer wouldn't start, and why (#894) Blocked *update.Blocked `json:"blocked,omitempty"` Total int64 `json:"total,omitempty"` @@ -475,11 +483,17 @@ func (u *updater) run() { } // an older download is replaced by this one: until it is in, there is // nothing to install - u.state, u.done, u.total, u.staged = "downloading", 0, 0, "" + u.state, u.done, u.total, u.staged, u.step, u.rate = "downloading", 0, 0, "", "", nil u.mu.Unlock() ctx = update.WithProgress(ctx, func(done, total int64) { u.mu.Lock() u.done, u.total = done, total + u.rate = marked(u.rate, done, time.Now()) + u.mu.Unlock() + }) + ctx = update.WithStep(ctx, func(step string) { + u.mu.Lock() + u.step = step u.mu.Unlock() }) var staged string @@ -619,7 +633,10 @@ func (u *updater) jsonIn(lang string) updateJSON { } } if u.state == "downloading" { - j.Done, j.Total = u.done, u.total + j.Done, j.Total, j.Step = u.done, u.total, u.step + if u.step == update.StepDownload { + j.Speed = speedOf(u.rate, u.done, time.Now()) + } } if u.state == "blocked" { j.Blocked = u.blocked @@ -876,3 +893,44 @@ func mainShown(w Windows) bool { s, ok := w.(interface{ MainShown() bool }) return ok && s.MainShown() } + +// progMark is how many bytes a download had at a moment. +type progMark struct { + at time.Time + done int64 +} + +// rateSpan is how far back a download's speed looks. +const rateSpan = 5 * time.Second + +// marked is marks with done at now added, at most one each quarter +// second, those older than rateSpan dropped but the newest of them, and +// all of them when done went back (a host that sent the whole file again). +func marked(marks []progMark, done int64, now time.Time) []progMark { + if n := len(marks); n > 0 && done < marks[n-1].done { + marks = nil + } + if n := len(marks); n > 0 && now.Sub(marks[n-1].at) < 250*time.Millisecond { + return marks + } + i := 0 + for i+1 < len(marks) && now.Sub(marks[i+1].at) >= rateSpan { + i++ + } + return append(marks[i:], progMark{now, done}) +} + +// speedOf is the bytes a second a download came at over about the last +// rateSpan, done the bytes it has now: 0 while under a second is known. +// A stalled download's falls to 0 as the seconds pass without bytes. +func speedOf(marks []progMark, done int64, now time.Time) int64 { + for _, m := range marks { + if d := now.Sub(m.at); d <= rateSpan+time.Second { + if d < time.Second || done < m.done { + return 0 + } + return int64(float64(done-m.done) / d.Seconds()) + } + } + return 0 +} diff --git a/internal/gui/update_progress_test.go b/internal/gui/update_progress_test.go new file mode 100644 index 000000000..328c750fa --- /dev/null +++ b/internal/gui/update_progress_test.go @@ -0,0 +1,127 @@ +package gui + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "github.com/yetone/magpie/internal/update" +) + +// esir_tech on Discord: after Update, the pill said 17% and sat there. +// While a download goes on, /api/update says its step and how fast the +// bytes come, so the pill and Settings' row show it moving. +func TestUpdateDownloadSaysStepAndSpeed(t *testing.T) { + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + + const chunk, chunks = 8 << 10, 40 + body := make([]byte, chunk*chunks) + for i := range body { + body[i] = byte(i * 7) + } + sum := sha256.Sum256(body) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/asset" { + for i := 0; i < chunks; i++ { + if _, err := w.Write(body[i*chunk : (i+1)*chunk]); err != nil { + return + } + w.(http.Flusher).Flush() + time.Sleep(60 * time.Millisecond) + } + return + } + json.NewEncoder(w).Encode(update.Release{Version: "0.1.11", Assets: map[string]update.Asset{ + update.BinaryAsset(): {URL: "http://" + r.Host + "/asset", Size: int64(len(body)), SHA256: hex.EncodeToString(sum[:])}, + }}) + })) + defer srv.Close() + t.Setenv("MAGPIE_UPDATE_FEED", srv.URL) + oldV := Version + Version = "0.1.10" + defer func() { Version = oldV }() + exe, err := update.Executable() + if err != nil { + t.Fatal(err) + } + u := &updater{exe: exe} + u.self, _ = os.Stat(exe) + defer func() { + u.mu.Lock() + staged := u.staged + u.mu.Unlock() + if staged != "" { + os.Remove(staged) + } + }() + if !u.begin() { + t.Fatal("no check began") + } + ran := make(chan struct{}) + go func() { u.run(); close(ran) }() + + var moving []updateJSON + deadline := time.After(time.Minute) + for watching := true; watching; { + select { + case <-ran: + watching = false + case <-deadline: + t.Fatalf("still downloading: %+v", u.json()) + case <-time.After(20 * time.Millisecond): + if j := u.json(); j.State == "downloading" && j.Step == update.StepDownload && j.Speed > 0 { + moving = append(moving, j) + } + } + } + if j := u.json(); j.State != "ready" { + t.Fatalf("after the download: %+v", j) + } + if len(moving) == 0 { + t.Fatal("the download never said how fast it went") + } + for _, j := range moving { + // at most every byte in the shortest span speedOf takes, a second + if j.Done <= 0 || j.Total != int64(len(body)) || j.Speed > j.Total { + t.Fatalf("while downloading: %+v", j) + } + } +} + +// A download's speed is over its last seconds: none until a second is +// known, and falling to 0 while no bytes come. +func TestUpdateSpeedFallsWhenStalled(t *testing.T) { + t0 := time.Unix(1_800_000_000, 0) + var marks []progMark + for i := range 41 { // 100 KB every 100ms for 4s + marks = marked(marks, int64(i)*100_000, t0.Add(time.Duration(i)*100*time.Millisecond)) + } + at := t0.Add(4 * time.Second) + if s := speedOf(marks, 4_000_000, at); s < 900_000 || s > 1_100_000 { + t.Fatalf("speed = %d, want about 1 MB/s", s) + } + if s := speedOf(marked(nil, 5, t0), 5, t0.Add(500*time.Millisecond)); s != 0 { + t.Fatalf("speed after half a second = %d, want none yet", s) + } + // stalled: the bytes stay at 4 MB + if s := speedOf(marks, 4_000_000, at.Add(3*time.Second)); s <= 0 || s >= 900_000 { + t.Fatalf("speed 3s into a stall = %d, want falling", s) + } + if s := speedOf(marks, 4_000_000, at.Add(10*time.Second)); s != 0 { + t.Fatalf("speed 10s into a stall = %d, want 0", s) + } + // a host that sent the file again from its start: the marks before go + if m := marked(marks, 1000, at.Add(time.Second)); len(m) != 1 { + t.Fatalf("marks after the bytes went back = %d, want 1", len(m)) + } +} diff --git a/internal/update/download_test.go b/internal/update/download_test.go index aa28c298c..c5dce902b 100644 --- a/internal/update/download_test.go +++ b/internal/update/download_test.go @@ -5,6 +5,7 @@ import ( "context" "crypto/sha256" "encoding/hex" + "errors" "fmt" "net/http" "net/http/httptest" @@ -13,6 +14,8 @@ import ( "slices" "strconv" "strings" + "sync" + "sync/atomic" "testing" "time" ) @@ -197,3 +200,95 @@ func TestDownloadNotFoundIsNotRetried(t *testing.T) { t.Fatalf("err = %v after %d tries, want one 404", err, tries) } } + +// A connection that goes silent part way, its bytes held back with the +// connection kept open (what left esir_tech's update at 17% on Discord), +// is broken off after stallAfter and tried again from where it stopped, +// and the steps say so: the download, the wait to try again, the rest, +// then the checksum. +func TestDownloadStallIsTriedAgain(t *testing.T) { + quickRetries(t) + old := stallAfter + stallAfter = 300 * time.Millisecond + t.Cleanup(func() { stallAfter = old }) + body := make([]byte, 600<<10) + for i := range body { + body[i] = byte(i * 13) + } + sum := sha256.Sum256(body) + cut := len(body) * 17 / 100 + var mu sync.Mutex + var ranges []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + ranges = append(ranges, r.Header.Get("Range")) + first := len(ranges) == 1 + mu.Unlock() + if first { + w.Header().Set("Content-Length", strconv.Itoa(len(body))) + w.Write(body[:cut]) + w.(http.Flusher).Flush() + <-r.Context().Done() // silent, the connection open, until the client goes + return + } + from, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(r.Header.Get("Range"), "bytes="), "-")) + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", from, len(body)-1, len(body))) + w.Header().Set("Content-Length", strconv.Itoa(len(body)-from)) + w.WriteHeader(http.StatusPartialContent) + w.Write(body[from:]) + })) + defer srv.Close() + + var steps []string + var done, total int64 + ctx := WithProgress(context.Background(), func(d, t int64) { done, total = d, t }) + ctx = WithStep(ctx, func(s string) { + if len(steps) == 0 || steps[len(steps)-1] != s { + steps = append(steps, s) + } + }) + // the update's own bound, far over the stall's, is what the old code + // waited out + ctx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + path := filepath.Join(t.TempDir(), "magpie.new") + start := time.Now() + if err := download(ctx, Asset{URL: srv.URL, Size: int64(len(body)), SHA256: hex.EncodeToString(sum[:])}, path); err != nil { + t.Fatalf("after %s at %d of %d bytes: %v", time.Since(start).Round(time.Millisecond), done, total, err) + } + mu.Lock() + defer mu.Unlock() + if want := []string{"", fmt.Sprintf("bytes=%d-", cut)}; !slices.Equal(ranges, want) { + t.Fatalf("ranges asked = %q, want %q", ranges, want) + } + if b, _ := os.ReadFile(path); !bytes.Equal(b, body) { + t.Fatalf("file has %d bytes, not the release's", len(b)) + } + if want := []string{StepDownload, StepRetry, StepDownload, StepVerify}; !slices.Equal(steps, want) { + t.Fatalf("steps = %q, want %q", steps, want) + } +} + +// A stall that never ends is the network's, said so: tried every time +// retryWaits allows, and the error names what happened. +func TestDownloadStallEveryTimeSaysSo(t *testing.T) { + quickRetries(t) + old := stallAfter + stallAfter = 50 * time.Millisecond + t.Cleanup(func() { stallAfter = old }) + var tries atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + tries.Add(1) + <-r.Context().Done() // no answer at all + })) + defer srv.Close() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + err := download(ctx, Asset{URL: srv.URL, SHA256: "00"}, filepath.Join(t.TempDir(), "magpie.new")) + if err == nil || !Network(err) || !errors.Is(err, errStalled) || ctx.Err() != nil { + t.Fatalf("err = %v, want a stall", err) + } + if n := int(tries.Load()); n != len(retryWaits)+1 { + t.Fatalf("tries = %d, want %d", n, len(retryWaits)+1) + } +} diff --git a/internal/update/update.go b/internal/update/update.go index cf67a886e..922f76035 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -298,6 +298,7 @@ func Stage(ctx context.Context, rel *Release, bundle string) (string, error) { return "", err } out := filepath.Join(dir, "unzip") + step(ctx, StepUnpack) if b, err := proc.CommandContext(ctx, "ditto", "-x", "-k", zip, out).CombinedOutput(); err != nil { os.RemoveAll(dir) return "", fmt.Errorf("unzip: %v: %s", err, b) @@ -314,6 +315,7 @@ func Stage(ctx context.Context, rel *Release, bundle string) (string, error) { } os.Remove(out) unregister(unzipped) // in case it looked in that moment + step(ctx, StepSignature) if err := sameSigner(ctx, bundle, app); err != nil { os.RemoveAll(dir) return "", err @@ -1070,6 +1072,42 @@ func WithProgress(ctx context.Context, f func(done, total int64)) context.Contex return context.WithValue(ctx, progressKey{}, f) } +type stepKey struct{} + +// The steps an update made under WithStep's ctx goes through, in order. +// After the download its percent says nothing, and a Mac's unpack and +// signature check take seconds: each says its name instead (esir_tech on +// Discord, a percent that sat still). +const ( + StepDownload = "download" // the bytes coming in + StepRetry = "retry" // the connection broke off or stalled: waiting to try again + StepVerify = "verify" // the file checked against its SHA-256 + StepUnpack = "unpack" // the Mac's zip unpacked + StepSignature = "signature" // the Mac app's signature checked +) + +// WithStep has an update made under ctx say each step it starts. +func WithStep(ctx context.Context, f func(step string)) context.Context { + return context.WithValue(ctx, stepKey{}, f) +} + +func step(ctx context.Context, s string) { + if f, ok := ctx.Value(stepKey{}).(func(string)); ok { + f(s) + } +} + +// stallAfter is how long a download waits for its next byte. A +// connection that sends nothing for that long (GitHub's asset host from +// some networks holds one open with no data) is broken off and tried +// again from where it stopped, as one that drops is; before, the download +// sat at its percent until the update's 10 minutes ran out (esir_tech on +// Discord, at 17%). A var for tests. +var stallAfter = 30 * time.Second + +// errStalled is a try that got no byte for stallAfter. +var errStalled = errors.New("no data came for a while") + // retryWaits are the pauses before each try after the first: a // connection that drops at the start or part way (GitHub's asset host from // some networks: AIMetaPhD on X, "EOF" at 0.1.1618) is tried again, from @@ -1092,12 +1130,14 @@ func download(ctx context.Context, a Asset, path string) error { var err error for try := 0; try <= len(retryWaits); try++ { if try > 0 { + step(ctx, StepRetry) select { case <-ctx.Done(): return err case <-time.After(retryWaits[try-1]): } } + step(ctx, StepDownload) if err = fetch(ctx, a, path); err == nil || ctx.Err() != nil || !Network(err) { break } @@ -1196,10 +1236,22 @@ func fetch(ctx context.Context, a Asset, path string) error { } have = 0 } + // a try that hears nothing for stallAfter, from the ask to the last + // byte, is broken off as the network's (errStalled) + tctx, cancel := context.WithCancelCause(ctx) + defer cancel(nil) + idle := time.AfterFunc(stallAfter, func() { cancel(errStalled) }) + defer idle.Stop() + netErr := func(err error) error { + if errors.Is(context.Cause(tctx), errStalled) { + err = errStalled + } + return &NetError{File: name, Err: err} + } var res *http.Response flag := os.O_WRONLY | os.O_CREATE | os.O_TRUNC for restarted := false; ; restarted = true { - req, err := http.NewRequestWithContext(ctx, "GET", u, nil) + req, err := http.NewRequestWithContext(tctx, "GET", u, nil) if err != nil { return err } @@ -1211,7 +1263,7 @@ func fetch(ctx context.Context, a Asset, path string) error { if ctx.Err() != nil { return fail(err) } - return fail(&NetError{File: name, Err: err}) + return fail(netErr(err)) } if res.StatusCode == http.StatusRequestedRangeNotSatisfiable && have > 0 && !restarted { // what was kept isn't the start of the file the host has (it @@ -1240,7 +1292,8 @@ func fetch(ctx context.Context, a Asset, path string) error { } // a read that fails is the network's; a write that fails (a full // disk) is not, and isn't tried again - in := &readErr{r: res.Body} + idle.Reset(stallAfter) + in := &readErr{r: res.Body, idle: idle} var body io.Reader = in if report, ok := ctx.Value(progressKey{}).(func(done, total int64)); ok { total := res.ContentLength @@ -1258,11 +1311,13 @@ func fetch(ctx context.Context, a Asset, path string) error { } if err != nil { if ctx.Err() == nil && in.err != nil { - err = &NetError{File: name, Err: err} + err = netErr(err) } return fail(err) } + idle.Stop() // the whole file, what earlier tries kept included, against the feed's + step(ctx, StepVerify) if !strings.EqualFold(fileHash(path), a.SHA256) { err = fmt.Errorf("%s does not match its checksum", name) if u != a.URL { @@ -1273,14 +1328,19 @@ func fetch(ctx context.Context, a Asset, path string) error { return nil } -// readErr keeps the error its reader returned, io.EOF aside. +// readErr keeps the error its reader returned, io.EOF aside, and puts +// idle off again with each byte. type readErr struct { - r io.Reader - err error + r io.Reader + err error + idle *time.Timer } func (r *readErr) Read(p []byte) (int, error) { n, err := r.r.Read(p) + if n > 0 && r.idle != nil { + r.idle.Reset(stallAfter) + } if err != nil && err != io.EOF { r.err = err }