jwaitq (Discord) nearly lost their setup on Windows and got it back only
from a Downloads\data folder they happened to have. They asked for
backups made on a schedule into a folder, with a version to go back to.
What changed
- internal/backup/auto.go: Settings › Sync › "Back up by itself". On by
default: once every 24 hours, the last 7 kept, into
<config dir>/auto-backups. Interval (1 hour, 6 hours, 1 day, 1 week, or Off), keep (3,
7, 14, 30) and the folder are the user's to change. autobackup.json holds
only what the user set; a field they never touched follows the default,
so a later default never overrides their own value. An unreadable
autobackup.json makes no backup and says so, never "off" or a default.
- What goes in is the export without API keys (backup.Collect(false)),
the same bundle and the same handling of secrets as the manual no-keys
export, with the proxy URL blanked as well (it can carry a password).
Not sealed, so it opens without a passphrase. Files are 0600 in a 0700
folder, written to a temp file, fsynced and renamed, and listed only
when they parse and their sha256 matches, so a half-written file is
never a version. A temp file over an hour old is removed.
- A backup is made only when the setup changed since the newest one, so
a quiet week keeps a week of versions, not seven copies of one day.
The loop runs inside the gateway (WhileServing), first 2 minutes after
launch, then every 10 minutes it checks whether one is due by the
newest file's time, so a restart doesn't make an extra one.
- Restore puts a version back the way Import does (additive), after
first writing the current setup as a "-restore" backup. If that
backup can't be written, nothing is put back. The row says when the
undo copy was made, and restoring it undoes the restore. "-restore"
backups are pruned past Keep like the rest.
- internal/gui/backup.go: GET /api/autobackup and POST
/api/autobackup/{set,choose,now,reveal,restore}. internal/cli
settings_parity_test names the two routes in notYet (S2).
- GUI: autobackup.js, imported lazily when Sync is drawn, so app.js and
the core budget are not raised. The app's own segmented controls and
menus (no <select>), the folder row with Change…/Show/Default, Back up
now, and the versions list with Restore behind a confirm. Strings in
en, zh, zh-TW, ja, de (22 keys each).
- docs/subsystems/sync-backup.md: "Backups by themselves".
- Tests touched beside it: sync-sign-in's "last row" is now the last of
Sync's own rows (the new rows come after Import); usage-computers
scrolls its tick to the middle, since in WebKit the sticky Settings
tabs covered it at the page's end; agent-prefs waits for Settings'
first draw instead of reading the static index.html's rows.
Tests
- internal/backup/auto_test.go: TestAutoBackupOnSchedule (injected
clock, no sleeps), TestAutoBackupAfterRestartWaits,
TestAutoBackupOffOrUnreadable, TestAutoBackupPrunes,
TestAutoBackupHoldsNoSecrets, TestAutoRestoreRoundTripAndUndo,
TestAutoRestoreNeedsTheBackupFirst, TestAutoHalfWrittenNeverListed.
- internal/gui/backup_test.go: TestAutoBackupRoutes.
- internal/gui/tests/auto-backup.test.cjs: chromium and webkit, 1100px
and 420px, en/zh/zh-TW/ja/de; plus "Sync redrawn while the backups are
being read still shows them", which found a real bug (the rows were
dropped when Sync redrew during the first read) and is red on the old
code.
Broken by hand, each test red, then put back: dedup off (OnSchedule),
interval check off (OnSchedule, AfterRestartWaits), keep+1
(Prunes), proxy left in (HoldsNoSecrets), no backup before a restore
(RoundTripAndUndo), restore going on after a failed backup
(NeedsTheBackupFirst), unreadable config read as default
(OffOrUnreadable), checksum not checked (HalfWrittenNeverListed),
os.Rename without the temp step (HalfWrittenNeverListed). And the
redraw fix, reverted: the redraw GUI test red in both engines.
Run on mote (macOS 27) at this change on c9af34446; rebased then onto
019b308f1 (internal/provider only) and built and vetted again, then onto
70b96126e (app.js/app.css editor sizing): TestCoreScriptBudget and
TestAutoBackupRoutes ok on mote; auto-backup, old-webkit, i18n-keys,
sync-sign-in and editor-roomy 152/152 on WSL. The earlier runs:
gofmt -l clean; GOOS=linux go vet -tags nogui and GOOS=windows go vet
of backup, gui, cli ok; go build ./... ok; go test -timeout 45m
./internal/backup ./internal/davsync ok, ./internal/cli and
./internal/gui red only on known reds: TestEveryRouteHasACommandOrIsNamed
for POST /api/usage/checkin-account (#4826) and
TestMainWindowCorners/macOS_26_SDK (#3949).
GUI on Linux (WSL magpie-desktop, Playwright 1.62.0, chromium and
webkit) at 0dd8901a7, whose only difference from this head is Go files
outside this change: auto-backup, gui-de, gui-ja, gui-zh-tw, i18n-keys,
old-webkit, settings-general, settings-lines-wrap, settings-search,
settings-sections, settings-tabs-stick, sync-auto-restore,
sync-not-backup, sync-note-show, sync-other-kind, sync-own-fields,
sync-sign-in, sync-spin, sync-usage-error, webdav-settings-refresh,
github-sync, s3-sync, import-row, menu-scroll, agent-prefs,
usage-computers, account-eye: green. Red the same at origin/main
1aca55909 in the same run: segs-press-redraw searchAllRow (#4566),
balance-fix Sub2API (#4683), agent-panel-name-width (#4203), click-scroll
webkit wheel (#4385), codex-auto-reset webkit de (#4790),
codex-predictions webkit (#2624), codex-credits-first webkit (#4908,
filed now).
Not tried: the whole GUI suite (on WSL at concurrency 4 it ran past 5
hours beside other sessions' runs; I stopped my own run and ran the
files a Settings/Sync change can reach, plus the ones it had shown red);
a real Windows install (jwaitq's system) or the real app with a real
HOME; a restore of a real user's backup.
Asked for by jwaitq on Discord.
220 lines
14 KiB
JavaScript
220 lines
14 KiB
JavaScript
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||
// Settings › Sync's Back up by itself (jwaitq on Discord: 定期自动备份,支持
|
||
// 回退选择版本). Its rows come after Export and Import, in the list's own
|
||
// rows (a line between each): the interval and Versions kept as the app's
|
||
// segmented control (no <select>), the folder with Change…, Show and, once
|
||
// one is picked, Default, Back up now, and each version with Restore….
|
||
// Picking Off posts on:false and the row says none are made; 1 week posts
|
||
// hours 168; 14 posts keep 14; Default posts dir "". Restore… asks in the
|
||
// app's own dialog, saying what is here is backed up first; Cancel posts
|
||
// nothing, Restore posts the version's name, and the list then says what
|
||
// was put back and which version undoes it. In all five languages, at 1100
|
||
// and 420px, Chromium and WebKit, with nothing wider than the window. The
|
||
// API is faked; nothing is backed up.
|
||
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 { openPart } = require("./reader.cjs");
|
||
const { strings } = require("./strings.cjs");
|
||
|
||
const assets = path.resolve(__dirname, "../assets");
|
||
const { I18N } = strings();
|
||
const tr = (lang, k, vars = {}) => {
|
||
const s = lang === "en" ? k : I18N[lang][k];
|
||
assert.equal(typeof s, "string", `${lang} has ${JSON.stringify(k)}`);
|
||
return s.replace(/\{(\w+)\}/g, (_, v) => vars[v]);
|
||
};
|
||
|
||
const hourAgo = new Date(Date.now() - 3600e3).toISOString();
|
||
const dayAgo = new Date(Date.now() - 86400e3).toISOString();
|
||
const backups = [
|
||
{ name: "magpie-20261102-010000-auto.json", made: hourAgo, reason: "auto", providers: 3, size: 900 },
|
||
{ name: "magpie-20261101-010000-restore.json", made: dayAgo, reason: "restore", providers: 1, size: 700 },
|
||
];
|
||
|
||
function serve(lang, posts) {
|
||
const settings = {
|
||
theme: "light", lang, tray: "panel", version: "test", dir: "/tmp/magpie",
|
||
gateway: "http://127.0.0.1:3425", visionModels: [], imageGenModels: [],
|
||
fx: { rate: 7.2, stale: false },
|
||
};
|
||
let view = { on: true, hours: 24, keep: 7, dir: "~/Library/Application Support/magpie/auto-backups-with-a-long-folder-name-to-wrap", custom: true, backups };
|
||
return async (route) => {
|
||
const request = route.request();
|
||
const pathname = new URL(request.url()).pathname;
|
||
const json = (data) => route.fulfill({ json: data });
|
||
if (pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
|
||
if (pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||
if (pathname === "/api/state") return json({ agents: [], profiles: [], settings });
|
||
if (pathname === "/api/settings") return json(settings);
|
||
if (pathname === "/api/usage/quotas") return json([]);
|
||
if (pathname === "/api/groups") return json({ groups: [], models: [] });
|
||
if (pathname === "/api/plugins") return json({ plugins: [] });
|
||
if (pathname === "/api/davsync") return json({ on: false });
|
||
if (pathname === "/api/autobackup") return json(view);
|
||
if (pathname.startsWith("/api/autobackup/")) {
|
||
const action = pathname.slice("/api/autobackup/".length);
|
||
const body = request.postDataJSON();
|
||
posts.push({ action, body });
|
||
if (action === "set") {
|
||
if (body.on !== undefined) view = { ...view, on: body.on };
|
||
if (body.hours) view = { ...view, hours: body.hours };
|
||
if (body.keep) view = { ...view, keep: body.keep };
|
||
if (body.dir === "") view = { ...view, custom: false, dir: "~/Library/Application Support/magpie/auto-backups" };
|
||
}
|
||
if (action === "restore") {
|
||
const before = { name: "magpie-20261102-020000-restore.json", made: new Date().toISOString(), reason: "restore", providers: 3, size: 900 };
|
||
view = { ...view, backups: [before, ...view.backups] };
|
||
return json({ view, before: before.name, result: { Added: 0, Replaced: 2, Profiles: 1, Agents: 0, Settings: true } });
|
||
}
|
||
return json(view);
|
||
}
|
||
if (pathname.startsWith("/api/")) return json({});
|
||
const file = path.join(assets, pathname === "/" ? "index.html" : pathname);
|
||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||
return route.fulfill({ body: await fs.readFile(file), contentType });
|
||
};
|
||
}
|
||
|
||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||
for (const width of [1100, 420]) {
|
||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||
const w = (k, vars) => tr(lang, k, vars);
|
||
test(`${engine} ${width}px ${lang}: Back up by itself is set, and a version restored after asking`, async (t) => {
|
||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
|
||
const errors = [], posts = [];
|
||
page.on("pageerror", (e) => errors.push(e.message));
|
||
await page.route("**/*", serve(lang, posts));
|
||
t.after(async () => {
|
||
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}-${width}-${lang}-auto-backup.png`), fullPage: true });
|
||
}
|
||
await browser.close();
|
||
});
|
||
page.setDefaultTimeout(5000);
|
||
page.setDefaultNavigationTimeout(60000);
|
||
|
||
await page.goto("http://magpie.test/");
|
||
await page.locator("#prefs").click();
|
||
await openPart(page, "sync");
|
||
const list = page.locator("#syncList");
|
||
const exact = (s) => new RegExp("^" + s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "$");
|
||
const rowNamed = (name) => list.locator(".row.pref").filter({ has: page.locator(".name", { hasText: exact(name) }) });
|
||
const auto = rowNamed(w("Back up by itself"));
|
||
await auto.waitFor({ state: "visible" });
|
||
const sub = (r) => r.locator(".who > .sub").first().textContent();
|
||
|
||
// after Export and Import, as rows of the list's own
|
||
const names = await list.locator(":scope > .row.pref > .who > .name").allTextContents();
|
||
assert.ok(names.indexOf(w("Back up by itself")) > names.indexOf(w("Import")), names.join(" | "));
|
||
assert.equal(await list.locator(":scope > div:not(.row):not(.editor)").count(), 0, "no wrapper left in the list");
|
||
assert.equal(await list.locator("select").count(), 0, "no native select");
|
||
assert.equal(await sub(auto), w("Your providers, settings and profiles, without API keys or sign-ins, into a folder on this computer"));
|
||
assert.equal(await auto.locator(".segs .opt.on").textContent(), w("1 day"));
|
||
const kept = rowNamed(w("Versions kept"));
|
||
assert.equal(await kept.locator(".segs .opt.on").textContent(), "7");
|
||
const folder = rowNamed(w("Backup folder"));
|
||
assert.match(await sub(folder), /auto-backups-with-a-long/);
|
||
for (const b of ["Change…", "Show", "Default"]) await folder.locator("button", { hasText: w(b) }).waitFor();
|
||
const versions = rowNamed(w("Versions"));
|
||
assert.ok((await sub(versions)).startsWith(w("{n} backups · newest {when}", { n: 2, when: "" }).trim().replace(/\s*$/, "")), await sub(versions));
|
||
assert.equal(await list.locator(".auto-backup-version").count(), 2);
|
||
assert.ok((await sub(list.locator(".auto-backup-version").nth(1))).startsWith(w("What was here before a restore")));
|
||
assert.ok((await sub(list.locator(".auto-backup-version").first())).includes(w("{n} providers", { n: 3 })));
|
||
|
||
// nothing wider than the window, the long folder wrapping
|
||
const wide = await page.evaluate(() => {
|
||
const out = [];
|
||
if (document.scrollingElement.scrollWidth > innerWidth) out.push("page " + document.scrollingElement.scrollWidth);
|
||
for (const r of document.querySelectorAll("#syncList .row.pref")) {
|
||
const b = r.getBoundingClientRect();
|
||
if (b.right > innerWidth + 0.5 || r.scrollWidth > r.clientWidth + 1) out.push(r.querySelector(".name")?.textContent + " " + b.right + "/" + r.scrollWidth + ">" + r.clientWidth);
|
||
}
|
||
return out;
|
||
});
|
||
assert.deepEqual(wide, [], "rows wider than the window");
|
||
|
||
// the interval, Off, the count, the default folder
|
||
await auto.locator(".segs .opt", { hasText: w("1 week") }).click();
|
||
await page.waitForFunction(() => document.querySelectorAll("#syncList .row.pref.auto-backup").length > 0);
|
||
assert.deepEqual(posts.at(-1), { action: "set", body: { on: true, hours: 168 } });
|
||
await rowNamed(w("Versions kept")).locator(".segs .opt", { hasText: "14" }).click();
|
||
await page.waitForFunction(() => [...document.querySelectorAll("#syncList .auto-backup .segs .opt.on")].some((o) => o.textContent === "14"));
|
||
assert.deepEqual(posts.at(-1), { action: "set", body: { keep: 14 } });
|
||
await rowNamed(w("Backup folder")).locator("button", { hasText: w("Default") }).click();
|
||
await page.waitForFunction(() => [...document.querySelectorAll("#syncList .auto-backup-dir")].some((s) => s.textContent.endsWith("/auto-backups")));
|
||
assert.deepEqual(posts.at(-1), { action: "set", body: { dir: "" } });
|
||
assert.equal(await rowNamed(w("Backup folder")).locator("button", { hasText: w("Default") }).count(), 0, "Default is gone with the default folder");
|
||
await rowNamed(w("Back up by itself")).locator(".segs .opt", { hasText: w("Off") }).click();
|
||
await page.waitForFunction((s) => [...document.querySelectorAll("#syncList .auto-backup .sub")].some((x) => x.textContent === s), w("Off: no backups are made by themselves"));
|
||
assert.deepEqual(posts.at(-1), { action: "set", body: { on: false } });
|
||
assert.equal(await rowNamed(w("Versions kept")).count(), 0, "no count while off");
|
||
// off, the versions there are still listed to restore
|
||
assert.equal(await list.locator(".auto-backup-version").count(), 2);
|
||
await rowNamed(w("Versions")).locator("button", { hasText: w("Back up now") }).click();
|
||
for (let i = 0; i < 250 && !posts.some((p) => p.action === "now"); i++) await page.waitForTimeout(20);
|
||
assert.deepEqual(posts.at(-1), { action: "now", body: {} });
|
||
|
||
// Restore asks first; Cancel posts nothing
|
||
const restores = () => posts.filter((p) => p.action === "restore").length;
|
||
await list.locator(".auto-backup-version").first().locator("button", { hasText: w("Restore…") }).click();
|
||
const ask = page.locator(".auto-backup-ask");
|
||
await ask.waitFor({ state: "visible" });
|
||
assert.ok((await ask.textContent()).includes(w("What is here now is backed up first: restore that one to undo this.")));
|
||
await ask.locator("button", { hasText: w("Cancel") }).click();
|
||
await ask.waitFor({ state: "detached" });
|
||
assert.equal(restores(), 0);
|
||
await list.locator(".auto-backup-version").first().locator("button", { hasText: w("Restore…") }).click();
|
||
await ask.waitFor({ state: "visible" });
|
||
await ask.locator("button.primary").click();
|
||
await page.locator(".auto-backup-said").first().waitFor({ state: "visible" });
|
||
assert.deepEqual(posts.filter((p) => p.action === "restore"), [{ action: "restore", body: { name: backups[0].name } }]);
|
||
const said = (await page.locator(".auto-backup-said").allTextContents()).join("\n");
|
||
assert.ok(said.includes(w("Providers: {added} added, {replaced} replaced; {profiles} profiles; {agents} agent settings changed", { added: 0, replaced: 2, profiles: 1, agents: 0 })), said);
|
||
const undo = lang === "en" ? "What was here before is the version of {when}: restore it to undo." : I18N[lang]["What was here before is the version of {when}: restore it to undo."];
|
||
for (const part of undo.split("{when}")) assert.ok(said.includes(part), part + " in " + said);
|
||
assert.equal(await list.locator(".auto-backup-version").count(), 3, "the backup made first is listed, to undo with");
|
||
assert.deepEqual(errors, []);
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
// Sync drawn again while the first read of Back up by itself is still out
|
||
// (a sync's tick, a form opened): its rows are drawn when the read comes
|
||
// back, not left out until the next read half a minute on, which also
|
||
// shortened the page under a reader scrolled to its end.
|
||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||
test(`${engine}: Sync redrawn while the backups are being read still shows them`, async (t) => {
|
||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||
t.after(() => browser.close());
|
||
const page = await (await browser.newContext({ viewport: { width: 900, height: 800 }, reducedMotion: "reduce" })).newPage();
|
||
const errors = [];
|
||
page.on("pageerror", (e) => errors.push(e.message));
|
||
let release;
|
||
const held = new Promise((r) => { release = r; });
|
||
const inner = serve("en", []);
|
||
await page.route("**/*", async (route) => {
|
||
if (new URL(route.request().url()).pathname === "/api/autobackup") await held;
|
||
return inner(route);
|
||
});
|
||
page.setDefaultTimeout(5000);
|
||
page.setDefaultNavigationTimeout(60000);
|
||
await page.goto("http://magpie.test/");
|
||
await page.locator("#prefs").click();
|
||
await openPart(page, "sync");
|
||
await page.locator("#syncList .row.pref").first().waitFor({ state: "visible" });
|
||
await page.waitForFunction(() => typeof window.autoBackupFill === "function");
|
||
await page.evaluate(() => { renderSync(); renderSync(); });
|
||
release();
|
||
await page.locator("#syncList .row.pref.auto-backup-version").first().waitFor({ state: "visible" });
|
||
assert.equal(await page.locator("#syncList .row.pref.auto-backup-version").count(), 2);
|
||
assert.equal(await page.locator("#syncList .row.pref.auto-backup").filter({ has: page.locator(".name", { hasText: /^Back up by itself$/ }) }).count(), 1);
|
||
assert.deepEqual(errors, []);
|
||
});
|
||
}
|