Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
whatsnew: Settings' What's new can show this version and the 10, 20, 50 or 100 before it (Linka)
yetone761904b5ab29
diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.cssindex 3fc7d4754..c426a8a43 100644--- a/internal/gui/assets/app.css+++ b/internal/gui/assets/app.css@@ -3600,6 +3600,7 @@ html.theming, html.theming *, html.theming *::before, html.theming *::after {.whatsnew .wn-ver { display: flex; align-items: center; gap: 8px; font-size: 13px; }.whatsnew .wn-ver b { font-weight: 600; }.whatsnew .wn-since { margin-left: 10px; font-size: 12px; color: var(--muted); }+.whatsnew .wn-range { max-width: min(220px, 55%); }.whatsnew .wn-notes { font-size: 12.5px; line-height: 1.55; color: var(--fg-2); overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; }.whatsnew .wn-h { margin: 10px 0 2px; font-size: 12px; font-weight: 600; color: var(--fg); }.whatsnew .wn-h1, .whatsnew .wn-h2 { font-size: 12.5px; }diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex bcc2396ea..127124192 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -4365,13 +4365,34 @@ async function whatsNewOnce() {// waiting update (pending), which the app puts first. The notes that// couldn't be had (the site failing, #661) say so, with a retry and the// release page, apart from a version that has none.-async function openWhatsNew(b) {+// last: the range picked (wnRange), "" since the last update; a failed ask+// keeps the notes last shown (wnKept).+let wnKept = null;+async function openWhatsNew(b, last = "") {if (b) { b.disabled = true; b.classList.add("busy"); }- const w = await api(updatePath("whatsnew?all=1")).catch(() => null);+ const w = await api(updatePath("whatsnew?all=1" + (last && "&last=" + last))).catch(() => null);if (b) { b.disabled = false; b.classList.remove("busy"); }- const list = w?.releases || [];+ let list = w?.releases || [], failed = !w || !!w.error;+ if (!failed) wnKept = list;+ else if (!list.length && wnKept) list = wnKept;if (!list.length && !w?.current) return status(t("Couldn't load the release notes"), "err");- showWhatsNew(list, false, { failed: !w || !!w.error, current: w?.current, url: w?.url, retry: () => openWhatsNew() });+ showWhatsNew(list, false, { failed, current: w?.current, url: w?.url, last, retry: () => openWhatsNew(null, last) });+}++// wnRange is Settings' pick of which notes (Linka): since the last update,+// or this version and 10, 20, 50 or 100 before it+function wnRange(last) {+ const name = (v) => v ? t("This version and {n} before", { n: v }) : t("Since the last update");+ const b = el("button", "sess-pick wn-range");+ b.type = "button";+ b.setAttribute("aria-haspopup", "menu");+ b.append(el("span", "", name(last)), svg(CHEV, 11, 1.6));+ b.onclick = (e) => {+ e.stopPropagation();+ if (b.classList.contains("open")) return closeProtoMenu();+ openProtoMenu(b, ["", "10", "20", "50", "100"].map((v) => ({ v, name: name(v), note: "", literalName: true })), last, (v) => v !== last && openWhatsNew(b, v), "Release notes shown", "sess-menu", "right");+ };+ return b;}// auto: shown by itself after an update, with "Don't show again today"@@ -4383,6 +4404,7 @@ function showWhatsNew(releases, auto, more = {}) {const ed = el("div", "editor whatsnew");const head = el("div", "ehead");head.append(el("b", "", t("What's new in {v}", { v: "v" + (releases[0]?.version || more.current) })));+ if (!auto) head.append(el("span", "grow"), wnRange(more.last || ""));ed.append(head);for (const r of releases) {const sec = el("section", "wn-rel");@@ -4410,7 +4432,7 @@ function showWhatsNew(releases, auto, more = {}) {}if (more.url) acts.append(noteLink(t("Open the release page"), more.url));sec.append(h, p, acts);- ed.append(sec);+ head.after(sec); // above the notes kept from before}const bar = el("div", "bar");const ok = el("button", "text primary", t("Close"));@@ -7188,62 +7210,6 @@ function renderArchive() {} else err?.remove();}-// What was read back from the archive, by "<date>/<id>": the archive's-// copy, or {busy} while it is read, or {error}.-const archivedCalls = new Map();--function headersPanel(label, first, headers) {- const panel = el("section", "call-body");- const head = el("div", "call-body-head");- const lines = [first, ...Object.keys(headers || {}).sort().flatMap((k) => headers[k].map((v) => `${k}: ${v}`))].filter(Boolean);- head.append(el("span", "call-body-label", label), el("span", "grow"), copyBtn(lines.join("\n"), label));- const pre = el("pre");- pre.append(el("code", "", lines.join("\n")));- panel.append(head, pre);- return panel;-}--// The archived file, whole, however large: to the browser in magpie web,-// to Downloads in the app (#447).-async function downloadArchive(name, b) {- const [date, aid] = name.split("/");- const q = `date=${encodeURIComponent(date)}&id=${encodeURIComponent(aid)}`;- if (web) {- const a = el("a");- a.href = "/api/archive/file?" + q;- a.download = "";- a.click();- return;- }- b.classList.add("busy");- b.disabled = true;- try {- const r = await api("archive/export?" + q, {});- status(t("Saved to {path}", { path: r.path }), "ok");- } catch (e) {- status(t(e.message), "err");- } finally {- b.classList.remove("busy");- b.disabled = false;- }-}--// one body read back from the archive: shown, or, past 256 KB, only its-// size — the server leaves it out — for the file to be downloaded whole-function archiveBodyPanel(label, part, id, key = id) {- if (part.omitted) {- const panel = el("section", "call-body");- const head = el("div", "call-body-head");- head.append(el("span", "call-body-label", t(label)), el("span", "call-body-count", fmtBytes(part.size)));- panel.append(head, el("p", "call-archive-big", t("Too long to show here. Download the archive to read it whole.")));- return panel;- }- // cut where the archive stops: its limit, or 256 KB in one from before #447- const cut = part.truncated && (part.size ? t("first {n} of {size}", { n: fmtBytes(new Blob([part.body]).size), size: fmtBytes(part.size) }) : true);- return callBodyPanel(label, part.body, cut, id, key);-}--// An agent's model field, and whether any of its options come from provider p.function modelField(a) {const agent = state.agents.find((x) => x.id === a.id);diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex 256695f08..be209c088 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -3015,6 +3015,9 @@ const I18N = {"What's new in {v}": "{v} 更新内容","What changed since {v}": "自 {v} 以来的更新内容","Not installed yet": "尚未安装",+ "Since the last update": "上次更新以来",+ "This version and {n} before": "当前版本及之前 {n} 个版本",+ "Release notes shown": "显示的更新说明","Don't show again today": "今天不再弹出","Couldn't load the release notes": "无法获取更新说明","No release notes provided.": "这个版本没有更新说明。",@@ -6946,6 +6949,9 @@ const I18N = {"What's new in {v}": "{v} 更新內容","What changed since {v}": "自 {v} 以來的更新內容","Not installed yet": "尚未安裝",+ "Since the last update": "上次更新以來",+ "This version and {n} before": "目前版本及之前 {n} 個版本",+ "Release notes shown": "顯示的更新說明","Don't show again today": "今天不再彈出","Couldn't load the release notes": "無法取得更新說明","No release notes provided.": "這個版本沒有更新說明。",@@ -10889,6 +10895,9 @@ const I18N = {"What's new in {v}": "{v} の新機能","What changed since {v}": "{v} からの変更点","Not installed yet": "まだインストールされていません",+ "Since the last update": "前回のアップデート以降",+ "This version and {n} before": "このバージョンと前の {n} 件",+ "Release notes shown": "表示するリリースノート","Don't show again today": "今日はもう表示しない","Couldn't load the release notes": "リリースノートを読み込めませんでした","No release notes provided.": "リリースノートはありません。",@@ -14842,6 +14851,9 @@ const I18N = {"What's new in {v}": "Neu in {v}","What changed since {v}": "Was sich seit {v} geändert hat","Not installed yet": "Noch nicht installiert",+ "Since the last update": "Seit dem letzten Update",+ "This version and {n} before": "Diese Version und {n} davor",+ "Release notes shown": "Angezeigte Versionshinweise","Don't show again today": "Heute nicht mehr anzeigen","Couldn't load the release notes": "Versionshinweise konnten nicht geladen werden","No release notes provided.": "Keine Versionshinweise vorhanden.",diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.jsindex da85aaea3..b4934c1b7 100644--- a/internal/gui/assets/plugins/usage/page.js+++ b/internal/gui/assets/plugins/usage/page.js@@ -2,6 +2,62 @@// app.js, whose helpers and state it shares, and before start.js shows the// first page.let usageHidOpen = false; // the hidden agents shown under their line++// What was read back from the archive, by "<date>/<id>": the archive's+// copy, or {busy} while it is read, or {error}.+const archivedCalls = new Map();++function headersPanel(label, first, headers) {+ const panel = el("section", "call-body");+ const head = el("div", "call-body-head");+ const lines = [first, ...Object.keys(headers || {}).sort().flatMap((k) => headers[k].map((v) => `${k}: ${v}`))].filter(Boolean);+ head.append(el("span", "call-body-label", label), el("span", "grow"), copyBtn(lines.join("\n"), label));+ const pre = el("pre");+ pre.append(el("code", "", lines.join("\n")));+ panel.append(head, pre);+ return panel;+}++// The archived file, whole, however large: to the browser in magpie web,+// to Downloads in the app (#447).+async function downloadArchive(name, b) {+ const [date, aid] = name.split("/");+ const q = `date=${encodeURIComponent(date)}&id=${encodeURIComponent(aid)}`;+ if (web) {+ const a = el("a");+ a.href = "/api/archive/file?" + q;+ a.download = "";+ a.click();+ return;+ }+ b.classList.add("busy");+ b.disabled = true;+ try {+ const r = await api("archive/export?" + q, {});+ status(t("Saved to {path}", { path: r.path }), "ok");+ } catch (e) {+ status(t(e.message), "err");+ } finally {+ b.classList.remove("busy");+ b.disabled = false;+ }+}++// one body read back from the archive: shown, or, past 256 KB, only its+// size — the server leaves it out — for the file to be downloaded whole+function archiveBodyPanel(label, part, id, key = id) {+ if (part.omitted) {+ const panel = el("section", "call-body");+ const head = el("div", "call-body-head");+ head.append(el("span", "call-body-label", t(label)), el("span", "call-body-count", fmtBytes(part.size)));+ panel.append(head, el("p", "call-archive-big", t("Too long to show here. Download the archive to read it whole.")));+ return panel;+ }+ // cut where the archive stops: its limit, or 256 KB in one from before #447+ const cut = part.truncated && (part.size ? t("first {n} of {size}", { n: fmtBytes(new Blob([part.body]).size), size: fmtBytes(part.size) }) : true);+ return callBodyPanel(label, part.body, cut, id, key);+}+// A call the archive kept, by "<date>/<id>": read back when asked, and its// file downloaded, drawn again by redraw as it is read — under a request's// row on the Usage page, and under a Routing trace's (plugins/routing drawsdiff --git a/internal/gui/tests/whats-new-range.test.cjs b/internal/gui/tests/whats-new-range.test.cjsnew file mode 100644index 000000000..f4351247c--- /dev/null+++ b/internal/gui/tests/whats-new-range.test.cjs@@ -0,0 +1,215 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// Settings › About › What's new picks which notes it shows (Linka on+// Discord): since the last update, as before and by default, or this+// version and the 10, 20, 50 or 100 before it. The pick is the app's own+// menu (a pill in the dialog's head), never a native <select>, and only in+// the dialog Settings opens, not the one shown by itself after an update.+// The page asks the app for the range picked (?last=); a pick that fails+// keeps the notes it showed, says it failed above them, and Try again asks+// for the same range. No click moves the page, nothing leaves the dialog+// sideways at a narrow window, no left-border accent. In all five+// languages, Chromium and WebKit; 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 CURRENT = "0.1.1410";+// magpie-releases' shape: newest first, 0.1.1407 never released+const ALL = [];+for (let v = 1410; v >= 1290; v--) if (v !== 1407) ALL.push({ version: "0.1." + v, notes: `## Bug Fixes\n\n- fix ${v}` });+const back = (n) => ALL.slice(0, n + 1);++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: CURRENT, 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 },+ };+}++// ctl.down: the site failing for a range; ctl.asked: each Settings ask's+// last ("" for the default)+function serve(lang, ctl) {+ 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: { lang, theme: "light" } });+ if (url.pathname === "/api/settings") return json(settingsPayload(lang));+ if (url.pathname === "/api/plugins") return json({ plugins: [] });+ if (url.pathname === "/api/groups") return json({ groups: [], models: [] });+ if (url.pathname === "/api/usage/quotas") return json([]);+ if (url.pathname === "/api/update") return json({ state: "latest", current: CURRENT });+ if (url.pathname === "/api/whatsnew") {+ if (!url.searchParams.has("all")) return json({ show: false, current: CURRENT, releases: [] });+ const last = url.searchParams.get("last") || "";+ ctl.asked.push(last);+ const base = { show: false, current: CURRENT, url: "https://github.com/yetone/magpie-releases/releases/tag/v" + CURRENT };+ if (last && ctl.down) return json({ ...base, releases: [], error: "release notes: 503 Service Unavailable" });+ return json({ ...base, releases: last ? back(+last) : back(1) });+ }+ 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 words = {+ en: { open: "Open", since: "Since the last update", back: (n) => `This version and ${n} before`, head: "Release notes shown", failed: "Couldn't load the release notes", retry: "Try again" },+ zh: { open: "打开", since: "上次更新以来", back: (n) => `当前版本及之前 ${n} 个版本`, head: "显示的更新说明", failed: "无法获取更新说明", retry: "重试" },+ "zh-TW": { open: "開啟", since: "上次更新以來", back: (n) => `目前版本及之前 ${n} 個版本`, head: "顯示的更新說明", failed: "無法取得更新說明", retry: "重試" },+ ja: { open: "開く", since: "前回のアップデート以降", back: (n) => `このバージョンと前の ${n} 件`, head: "表示するリリースノート", failed: "リリースノートを読み込めませんでした", retry: "再試行" },+ de: { open: "Öffnen", since: "Seit dem letzten Update", back: (n) => `Diese Version und ${n} davor`, head: "Angezeigte Versionshinweise", failed: "Versionshinweise konnten nicht geladen werden", retry: "Erneut versuchen" },+};++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ for (const lang of Object.keys(words)) {+ const w = words[lang];+ test(`${engine} ${lang}: What's new picks since the last update or this version and 10 to 100 before (Linka)`, async (t) => {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ t.after(async () => browser.close());+ const context = await browser.newContext({ viewport: { width: 900, height: 700 }, reducedMotion: "reduce" });+ const ctl = { asked: [], down: false };+ const page = await context.newPage();+ page.setDefaultTimeout(5000);+ const errors = [];+ page.on("pageerror", (e) => errors.push(e.message));+ page.on("dialog", (d) => { errors.push("dialog: " + d.message()); d.dismiss(); });+ await page.route("**/*", serve(lang, ctl));+ await watchSettingsReads(page);+ await page.goto("http://magpie.test/?view=settings&tab=about");+ await settingsDrawn(page);+ const dialog = page.locator("#modal .editor.whatsnew");+ const view = page.locator("#view-settings");+ const open = page.locator("#about .row.pref.whatsnew-row").getByRole("button", { name: w.open, exact: true });+ await open.waitFor();+ await page.mouse.move(450, 400);+ for (let i = 0; i < 60; i++) {+ const b = await open.boundingBox();+ if (b && b.y > 80 && b.y + b.height < 640) break;+ await page.mouse.wheel(0, !b || b.y > 80 ? 120 : -120);+ await page.waitForTimeout(30);+ }+ await page.waitForTimeout(200);+ const at = await view.evaluate((v) => v.scrollTop);+ const still = async (what) => assert.equal(await view.evaluate((v) => v.scrollTop), at, what + " moved the page");+ const shown = () => dialog.locator(".wn-rel:not(.wn-none) .wn-ver b").allTextContents();+ const vs = (list) => list.map((r) => "v" + r.version);+ const pill = dialog.locator(".ehead .wn-range");+ const pick = async (name) => {+ await pill.click();+ const menu = page.locator(".pop.proto-menu");+ await menu.waitFor();+ assert.equal(await menu.locator(".pm-head").textContent(), w.head);+ assert.deepEqual(await menu.locator(".pm-name").allTextContents(), [w.since, ...[10, 20, 50, 100].map(w.back)]);+ await menu.locator(".pm-item", { hasText: name }).click();+ };++ // the default, as before: since the last update, nothing else asked+ await open.click();+ await dialog.waitFor();+ await still("Open");+ assert.equal(await pill.textContent(), w.since);+ assert.equal(await pill.getAttribute("aria-haspopup"), "menu");+ assert.deepEqual(await shown(), vs(back(1)));+ assert.deepEqual(ctl.asked, [""]);+ assert.equal(await page.locator("select").count(), 0, "no native select");++ // this version and the 10 before it: eleven, newest first+ await pick(w.back(10));+ await dialog.locator(".wn-rel").nth(10).waitFor();+ assert.deepEqual(ctl.asked, ["", "10"]);+ assert.deepEqual(await shown(), vs(back(10)));+ assert.equal(await pill.textContent(), w.back(10));+ await still("a pick");+ // picking what is shown asks nothing+ await pick(w.back(10));+ await page.waitForTimeout(150);+ assert.deepEqual(ctl.asked, ["", "10"]);++ // 100: past the 40 the default stops at+ await pick(w.back(100));+ await dialog.locator(".wn-rel").nth(100).waitFor();+ assert.deepEqual(await shown(), vs(back(100)));++ // a range that fails keeps the notes shown, says so above them, and+ // Try again asks for the same range+ ctl.down = true;+ await pick(w.back(50));+ await dialog.locator(".wn-failed").waitFor();+ assert.equal(await pill.textContent(), w.back(50));+ assert.equal(await dialog.locator(".wn-failed .wn-msg").textContent(), w.failed);+ assert.deepEqual(await shown(), vs(back(100)), "the notes shown before are kept");+ const firstRel = await dialog.locator(".wn-rel").first().getAttribute("class");+ assert.match(firstRel, /wn-failed/, "the failure is said above the kept notes");+ ctl.down = false;+ await dialog.getByRole("button", { name: w.retry }).click();+ await page.waitForFunction(() => !document.querySelector("#modal .wn-failed") && document.querySelectorAll("#modal .wn-rel").length === 51);+ assert.deepEqual(ctl.asked.slice(-2), ["50", "50"]);+ assert.deepEqual(await shown(), vs(back(50)));+ await still("Try again");++ const border = await page.evaluate(() => [...document.querySelectorAll("#modal .whatsnew, #modal .whatsnew *")].map((e) => getComputedStyle(e).borderLeftWidth).filter((b) => parseFloat(b) > 1));+ assert.deepEqual(border, [], "no left-border accent");+ if (process.env.ARTIFACT_DIR) {+ await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });+ await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-whatsnew-range.png`) });+ }+ await page.keyboard.press("Escape");+ await page.locator("#modal").waitFor({ state: "hidden" });++ // opened again: the default, as before+ await open.click();+ await dialog.waitFor();+ assert.equal(await pill.textContent(), w.since);+ assert.equal(ctl.asked.at(-1), "");++ // a narrow window: the head's pill stays inside the dialog+ await page.setViewportSize({ width: 440, height: 700 });+ await page.waitForTimeout(200);+ const fit = await page.evaluate(() => {+ const ed = document.querySelector("#modal .whatsnew"), p = ed.querySelector(".wn-range");+ const e = ed.getBoundingClientRect(), b = p.getBoundingClientRect();+ return { inside: b.left >= e.left - 0.5 && b.right <= e.right + 0.5, sideways: ed.scrollWidth > ed.clientWidth + 1 };+ });+ assert.deepEqual(fit, { inside: true, sideways: false });+ await page.keyboard.press("Escape");+ assert.deepEqual(errors, []);+ });+ }+}++// The dialog shown by itself after an update has no pick: it lists what came+// since the last update, as it always did.+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ test(`${engine}: the dialog after an update has no range pick`, async (t) => {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ t.after(async () => browser.close());+ const page = await (await browser.newContext({ viewport: { width: 900, height: 700 }, reducedMotion: "reduce" })).newPage();+ page.setDefaultTimeout(5000);+ const ctl = { asked: [] };+ const base = serve("en", ctl);+ await page.route("**/*", (route) => {+ const url = new URL(route.request().url());+ if (url.pathname === "/api/whatsnew" && !url.searchParams.has("all")) return route.fulfill({ json: { show: true, current: CURRENT, releases: back(1) } });+ if (url.pathname === "/api/whatsnew/seen") return route.fulfill({ status: 204 });+ return base(route);+ });+ await page.goto("http://magpie.test/");+ const dialog = page.locator("#modal .editor.whatsnew");+ await dialog.waitFor();+ assert.equal(await dialog.locator(".wn-range").count(), 0);+ assert.deepEqual(ctl.asked, []);+ });+}diff --git a/internal/gui/whatsnew.go b/internal/gui/whatsnew.goindex f2ca70973..a79948c06 100644--- a/internal/gui/whatsnew.go+++ b/internal/gui/whatsnew.go@@ -8,6 +8,7 @@ import ("os""path/filepath""slices"+ "strconv""strings""sync""time"@@ -39,6 +40,14 @@ type whatsNew struct {quiet bool // the upgrade was the user's own restart to update: not shown by itselfshown bool // a page has shown themnotes map[string][]update.Note // by language+ back map[string]backNotes // Settings' "this version and n before it", by language+}++// backNotes is the longest "this version and n before it" asked for in a+// language: a shorter one is cut from it, a longer one asked for again.+type backNotes struct {+ n int+ list []update.Note}var news = &whatsNew{}@@ -185,6 +194,57 @@ func (n *whatsNew) get(ctx context.Context, all bool, lang string) whatsNewJSONreturn j}+// before is Settings' other ranges (Linka on Discord): this version's notes+// and those of the count releases before it, newest first. They are asked+// of the site once per language for the longest count asked so far, and+// kept while magpie runs, as the releases up to this one don't change. A+// failed ask is said (Error), with the notes of a shorter range asked+// before, if any, so a page keeps what it had.+func (n *whatsNew) before(ctx context.Context, count int, lang string) whatsNewJSON {+ j := whatsNewJSON{Current: Version, Releases: []update.Note{}}+ if !update.Released(Version) {+ return j+ }+ j.URL = update.ReleasePage(Version)+ n.mu.Lock()+ got, ok := n.back[lang]+ n.mu.Unlock()+ if !ok || got.n < count {+ ctx, cancel := context.WithTimeout(ctx, 15*time.Second)+ list, err := update.NotesBack(ctx, Version, count, lang)+ cancel()+ if err != nil {+ log.Println("release notes:", err)+ j.Error = err.Error()+ } else {+ got, ok = backNotes{count, list}, true+ n.mu.Lock()+ if n.back == nil {+ n.back = map[string]backNotes{}+ }+ if n.back[lang].n < count {+ n.back[lang] = got+ }+ n.mu.Unlock()+ }+ }+ if ok {+ j.Releases = update.Back(got.list, Version, count)+ }+ return j+}++// backCount is the range a page asks for (?last=10, 20, 50 or 100), 0 for+// the notes since the last update.+func backCount(r *http.Request) int {+ for _, c := range update.BackCounts {+ if r.URL.Query().Get("last") == strconv.Itoa(c) {+ return c+ }+ }+ return 0+}+// withWaiting puts first, in Settings' What's new while an update waits,// the notes of every release after this one up to it, marked not installed// yet. Only the update's own notes were (小八 on Discord: on 0.1.1398 with@@ -275,6 +335,10 @@ func askedLang(r *http.Request) string {func whatsNewRoutes(mux *http.ServeMux) {mux.HandleFunc("GET /api/whatsnew", func(rw http.ResponseWriter, r *http.Request) {all, lang := r.URL.Query().Get("all") != "", pageLang(r)+ if c := backCount(r); all && c > 0 {+ writeJSON(rw, news.before(r.Context(), c, lang))+ return+ }j := news.get(r.Context(), all, lang)if all {j.Releases = withWaiting(r.Context(), j.Releases, updates.jsonIn(askedLang(r)), lang)diff --git a/internal/gui/whatsnew_back_test.go b/internal/gui/whatsnew_back_test.gonew file mode 100644index 000000000..a59f725f2--- /dev/null+++ b/internal/gui/whatsnew_back_test.go@@ -0,0 +1,174 @@+package gui++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "slices"+ "strconv"+ "sync"+ "testing"++ "github.com/yetone/magpie/internal/update"+)++// Settings' What's new offers, besides the notes since the last update,+// this version and the 10, 20, 50 or 100 before it (Linka on Discord). The+// site is asked for that many alone, once per language and longest range:+// a shorter range, or the same again, is cut from what was had. A failed+// ask is said, with the shorter range had before; a range magpie doesn't+// offer is the default. The site's list is magpie-releases' shape, with+// 0.1.1407 never released and each note's Install section.+func TestWhatsNewBackRanges(t *testing.T) {+ home := t.TempDir()+ t.Setenv("XDG_CONFIG_HOME", home)+ var list []update.Note+ for v := 1420; v >= 1290; v-- {+ if v == 1407 {+ continue+ }+ s := strconv.Itoa(v)+ list = append(list, update.Note{+ Version: "0.1." + s,+ Notes: "## Bug Fixes\n\n- fix " + s + "\n\n## Install\n\n- macOS: [magpie-0.1." + s + "-mac-arm64.dmg](https://github.com/yetone/magpie-releases/releases/download/v0.1." + s + "/magpie-0.1." + s + "-mac-arm64.dmg)",+ })+ }+ var mu sync.Mutex+ var asked []string+ down := false+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mu.Lock()+ asked = append(asked, r.URL.RawQuery)+ failing := down+ mu.Unlock()+ if failing {+ http.Error(w, `{"error":"no releases"}`, http.StatusServiceUnavailable)+ return+ }+ // as the site answers: up to upto, newest first, at most limit+ var out []update.Note+ upto := r.URL.Query().Get("upto")+ limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))+ for _, n := range list {+ if !update.Newer(n.Version, upto) && (limit <= 0 || len(out) < limit) {+ out = append(out, n)+ }+ }+ json.NewEncoder(w).Encode(map[string]any{"releases": out})+ }))+ defer srv.Close()+ t.Setenv("MAGPIE_NOTES_FEED", srv.URL)+ t.Setenv("MAGPIE_UPDATE_FEED", "http://127.0.0.1:1/")+ oldV, oldNews, oldUp := Version, news, updates+ t.Cleanup(func() { Version, news, updates = oldV, oldNews, oldUp })+ Version = "0.1.1410"+ news = &whatsNew{after: "0.1.1408", pending: true, shown: true}+ updates = &updater{state: "latest", notesIn: "en"}+ mux := http.NewServeMux()+ whatsNewRoutes(mux)+ ask := func(q string) (whatsNewJSON, []string) {+ mu.Lock()+ asked = nil+ mu.Unlock()+ rec := httptest.NewRecorder()+ mux.ServeHTTP(rec, httptest.NewRequest("GET", "/api/whatsnew?all=1&lang=en"+q, nil))+ var j whatsNewJSON+ if err := json.Unmarshal(rec.Body.Bytes(), &j); err != nil {+ t.Fatal(rec.Code, rec.Body.String(), err)+ }+ mu.Lock()+ defer mu.Unlock()+ return j, slices.Clone(asked)+ }+ versions := func(j whatsNewJSON) []string {+ out := []string{}+ for _, r := range j.Releases {+ out = append(out, r.Version)+ }+ return out+ }+ // the n releases before 0.1.1410, newest first, 0.1.1407 skipped+ before := func(n int) []string {+ out := []string{}+ for _, r := range list {+ if !update.Newer(r.Version, Version) && len(out) < n+1 {+ out = append(out, r.Version)+ }+ }+ return out+ }++ // the default is as it was: the notes since the last update+ j, _ := ask("")+ if got := versions(j); !slices.Equal(got, []string{"0.1.1410", "0.1.1409"}) {+ t.Fatalf("default: %v", got)+ }+ // 10 before: eleven releases, from the site's 11 alone, Install out+ j, got := ask("&last=10")+ if !slices.Equal(got, []string{"lang=en&limit=11&upto=0.1.1410"}) {+ t.Fatalf("10 asked the site %q", got)+ }+ if !slices.Equal(versions(j), before(10)) || j.Error != "" {+ t.Fatalf("10: %v (%q), want %v", versions(j), j.Error, before(10))+ }+ if j.Releases[0].Notes != "## Bug Fixes\n\n- fix 1410" {+ t.Fatalf("10: Install kept: %q", j.Releases[0].Notes)+ }+ // the same again: not asked again+ if j, got = ask("&last=10"); len(got) != 0 || len(j.Releases) != 11 {+ t.Fatalf("10 again asked %q, %d releases", got, len(j.Releases))+ }+ // 100, past MaxNotes: asked once, 101 releases; then 20 and 50 are cut+ // from it, without asking+ if j, got = ask("&last=100"); len(got) != 1 || !slices.Equal(versions(j), before(100)) {+ t.Fatalf("100 asked %q, got %v", got, versions(j))+ }+ for _, n := range []int{20, 50, 10} {+ if j, got = ask("&last=" + strconv.Itoa(n)); len(got) != 0 || !slices.Equal(versions(j), before(n)) {+ t.Fatalf("%d after 100 asked %q, got %v", n, got, versions(j))+ }+ }+ // a range magpie doesn't offer: the default, the site not asked for it+ for _, q := range []string{"&last=7", "&last=x", "&last=1000"} {+ if j, _ = ask(q); !slices.Equal(versions(j), []string{"0.1.1410", "0.1.1409"}) {+ t.Fatalf("%s: %v", q, versions(j))+ }+ }++ // a fresh run: the site failing says so, keeping+ // the shorter range had before+ news = &whatsNew{}+ if j, _ = ask("&last=20"); len(j.Releases) != 21 {+ t.Fatalf("fresh 20: %d", len(j.Releases))+ }+ mu.Lock()+ down = true+ mu.Unlock()+ j, got = ask("&last=50")+ if len(got) != 1 || j.Error == "" {+ t.Fatalf("50 with the site down: asked %q, error %q", got, j.Error)+ }+ if !slices.Equal(versions(j), before(20)) {+ t.Fatalf("50 with the site down: %v, want the 20 had", versions(j))+ }+ // and once it answers, asked again: the 50+ mu.Lock()+ down = false+ mu.Unlock()+ if j, got = ask("&last=50"); len(got) != 1 || j.Error != "" || !slices.Equal(versions(j), before(50)) {+ t.Fatalf("50 back: asked %q, error %q, %v", got, j.Error, versions(j))+ }+ // nothing had at all and the site failing: an error, no notes+ news = &whatsNew{}+ mu.Lock()+ down = true+ mu.Unlock()+ if j, _ = ask("&last=10"); j.Error == "" || len(j.Releases) != 0 || j.URL == "" {+ t.Fatalf("down from the start: %+v", j)+ }+ // a build from source has no releases to list+ Version = "dev"+ if j, got = ask("&last=10"); len(got) != 0 || len(j.Releases) != 0 {+ t.Fatalf("dev: asked %q, %v", got, versions(j))+ }+}diff --git a/internal/update/notes.go b/internal/update/notes.goindex 26084e48c..3e08f4dad 100644--- a/internal/update/notes.go+++ b/internal/update/notes.go@@ -10,6 +10,7 @@ import ("regexp""slices""sort"+ "strconv""strings")@@ -45,6 +46,31 @@ func NotesBetween(ctx context.Context, after, upto, lang string) ([]Note, error)if after != "" {q.Set("after", after)}+ notes, err := askNotes(ctx, q, lang)+ if err != nil {+ return nil, err+ }+ return Between(notes, after, upto), nil+}++// BackCounts are the ranges Settings' What's new offers besides the notes+// since the last update: this version and that many before it (Linka on+// Discord).+var BackCounts = []int{10, 20, 50, 100}++// NotesBack asks the site for the notes of upto and the n releases before+// it, newest first, in lang. The site is asked for those alone (limit); one+// from before it took a limit sends them all, and Back keeps n+1.+func NotesBack(ctx context.Context, upto string, n int, lang string) ([]Note, error) {+ notes, err := askNotes(ctx, url.Values{"upto": {upto}, "limit": {strconv.Itoa(n + 1)}}, lang)+ if err != nil {+ return nil, err+ }+ return Back(notes, upto, n), nil+}++// askNotes is the site's list for q, each release's notes in lang.+func askNotes(ctx context.Context, q url.Values, lang string) ([]Note, error) {if lang != "" {q.Set("lang", lang)}@@ -69,7 +95,7 @@ func NotesBetween(ctx context.Context, after, upto, lang string) ([]Note, error)for i := range out.Releases {out.Releases[i].Notes = InLang(out.Releases[i].Notes, lang)}- return Between(out.Releases, after, upto), nil+ return out.Releases, nil}// zhMarker is where a release's notes turn from English to Chinese: the@@ -144,6 +170,35 @@ func Between(notes []Note, after, upto string) []Note {return out}+// Back keeps upto and the n releases before it, newest first: n+1+// releases counted before any is dropped, so a release whose notes are+// empty once its Install section is out still counts as one. A release+// newer than upto, or one listed twice, isn't counted.+func Back(notes []Note, upto string, n int) []Note {+ var keep []Note+ seen := map[string]bool{}+ for _, r := range notes {+ v := strings.TrimPrefix(strings.TrimSpace(r.Version), "v")+ if parse(v) == nil || seen[v] || Newer(v, upto) {+ continue+ }+ seen[v] = true+ r.Version = v+ keep = append(keep, r)+ }+ sort.SliceStable(keep, func(i, j int) bool { return Newer(keep[i].Version, keep[j].Version) })+ if len(keep) > n+1 {+ keep = keep[:n+1]+ }+ out := []Note{}+ for _, r := range keep {+ if r.Notes = StripInstall(r.Notes); strings.TrimSpace(r.Notes) != "" {+ out = append(out, r)+ }+ }+ return out+}+var heading = regexp.MustCompile(`^(#{1,6})\s+(.*?)\s*#*\s*$`)// installHeadings are the Install section's heading in each language thediff --git a/internal/update/notes_test.go b/internal/update/notes_test.goindex 6219ed937..7ada0eb7f 100644--- a/internal/update/notes_test.go+++ b/internal/update/notes_test.go@@ -3,6 +3,7 @@ package updateimport ("context""encoding/json"+ "fmt""net/http""net/http/httptest""reflect"@@ -118,3 +119,63 @@ func TestNotesBetween(t *testing.T) {t.Error("no error offline")}}++// Settings' What's new can show this version and the 10, 20, 50 or 100+// before it (Linka on Discord): the site is asked for that many alone, and+// a site that sends more (from before it took a limit) is cut to them.+func TestNotesBack(t *testing.T) {+ versions := func(ns []Note) []string {+ out := []string{}+ for _, n := range ns {+ out = append(out, n.Version)+ }+ return out+ }+ var asked []string+ var list []Note+ for v := 660; v >= 590; v-- {+ if v == 607 {+ continue // never released+ }+ list = append(list, Note{Version: fmt.Sprintf("0.1.%d", v), Notes: fmt.Sprintf("- %d\n\n## Install\n\nDownload it.", v)})+ }+ list[660-617].Notes = "## Install\n\nonly links" // 0.1.617: nothing left once Install is out+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ asked = append(asked, r.URL.RawQuery)+ // a site from before limit: every release, whatever was asked+ json.NewEncoder(w).Encode(map[string]any{"releases": list})+ }))+ defer srv.Close()+ t.Setenv("MAGPIE_NOTES_FEED", srv.URL)+ got, err := NotesBack(context.Background(), "0.1.612", 10, "zh")+ if err != nil {+ t.Fatal(err)+ }+ if want := []string{"lang=zh&limit=11&upto=0.1.612"}; !reflect.DeepEqual(asked, want) {+ t.Errorf("asked %q, want %q", asked, want)+ }+ // 0.1.612 and the ten before it, 0.1.607 never released+ want := []string{"0.1.612", "0.1.611", "0.1.610", "0.1.609", "0.1.608", "0.1.606", "0.1.605", "0.1.604", "0.1.603", "0.1.602", "0.1.601"}+ if !reflect.DeepEqual(versions(got), want) {+ t.Errorf("got %v, want %v", versions(got), want)+ }+ if got[0].Notes != "- 612" {+ t.Errorf("Install kept: %q", got[0].Notes)+ }+ // newer than upto isn't counted; an empty one counts but isn't shown+ if got, want := versions(Back(list, "0.1.619", 3)), []string{"0.1.619", "0.1.618", "0.1.616"}; !reflect.DeepEqual(got, want) {+ t.Errorf("back 3 from 0.1.619: %v, want %v", got, want)+ }+ // fewer than asked: what there is+ if got, want := versions(Back(list, "0.1.592", 10)), []string{"0.1.592", "0.1.591", "0.1.590"}; !reflect.DeepEqual(got, want) {+ t.Errorf("short list: %v, want %v", got, want)+ }+ // more than MaxNotes: the 100 asked for are all kept+ if got := Back(list, "0.1.660", 100); len(got) != len(list)-1 {+ t.Errorf("back 100: %d releases, want %d", len(got), len(list)-1)+ }+ srv.Close()+ if _, err := NotesBack(context.Background(), "0.1.612", 10, ""); err == nil {+ t.Error("no error offline")+ }+}diff --git a/site/worker.js b/site/worker.jsindex cafbb2896..91c7595fd 100644--- a/site/worker.js+++ b/site/worker.js@@ -3,7 +3,7 @@// download links that never go stale.//// /api/latest {version, notes, url, published, assets: {name: {url, size, sha256}}}-// /api/notes?after=&upto= {releases: [{version, notes, url, published}]}, newest+// /api/notes?after=&upto=&limit= {releases: [{version, notes, url, published}]}, newest// first: what changed since the version an app last ran// Both take ?lang=zh for the notes in Chinese, where a// release has them (below its <!-- lang:zh --> marker);@@ -91,8 +91,12 @@ export default {if (!got) return json({ error: "no releases" }, 503, NO_STORE);const after = url.searchParams.get("after"), upto = url.searchParams.get("upto");const lang = url.searchParams.get("lang");+ // limit: the newest that many alone (Settings' "this version and the+ // 10 before it", Linka), so an app asking for 11 isn't sent 100+ const limit = parseInt(url.searchParams.get("limit"), 10);const pick = got.list.filter((r) => (!after || newer(r.version, after)) && (!upto || !newer(r.version, upto)))+ .slice(0, limit > 0 ? limit : undefined).map((r) => ({ ...r, notes: inLang(r.notes, lang) }));return json({ releases: pick }, 200, cacheFor(got));}diff --git a/site/worker.test.mjs b/site/worker.test.mjsindex 4c882727c..ed9501257 100644--- a/site/worker.test.mjs+++ b/site/worker.test.mjs@@ -104,6 +104,16 @@ test("notes: each release in the language, English where it has no Chinese", asyassert.equal(again[0].notes, ZH);});+test("notes: limit keeps the newest that many up to upto", async () => {+ const two = (await get("/api/notes?upto=0.1.3&limit=2")).body.releases;+ assert.deepEqual(two.map((r) => r.version), ["0.1.3", "0.1.2"]);+ const one = (await get("/api/notes?upto=0.1.2&limit=1")).body.releases;+ assert.deepEqual(one.map((r) => r.version), ["0.1.2"]);+ for (const q of ["", "&limit=0", "&limit=x", "&limit=-1"]) {+ assert.equal((await get("/api/notes?upto=0.1.3" + q)).body.releases.length, 3, q);+ }+});+test("i18n: every string the home page marks has its Chinese, and no other", async () => {const { readFile } = await import("node:fs/promises");const { LANGS } = await import("./i18n.js");