Files
magpie/internal/backup/auto_test.go
T
yetone 52195b6b07 backup: the setup is backed up into a folder by itself, and any version put back (jwaitq)
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.
2026-11-02 18:24:38 +08:00

366 lines
11 KiB
Go

package backup
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"runtime"
"slices"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/profile"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// autoHome is a machine of its own with the setup setUp makes, and the
// schedule's memory of an earlier test forgotten.
func autoHome(t *testing.T) {
t.Helper()
home(t)
setUp(t)
autoMu.Lock()
autoChecked, autoErr = time.Time{}, ""
clear(autoSeen)
autoMu.Unlock()
}
func autoList(t *testing.T) []AutoBackup {
t.Helper()
v := AutoStatus()
if v.Error != "" {
t.Fatal(v.Error)
}
return v.Backups
}
func setTheme(t *testing.T, theme string) {
t.Helper()
s := settings.Load()
s.Theme = theme
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
}
var t0 = time.Date(2026, 11, 2, 9, 30, 0, 0, time.UTC)
// On with nothing set, a backup is made at once, then again only once the
// interval has gone by, and only when the setup changed (jwaitq on Discord).
func TestAutoBackupOnSchedule(t *testing.T) {
autoHome(t)
tick := func(at time.Time, want bool) {
t.Helper()
b, err := AutoTick(at, "test")
if err != nil {
t.Fatal(err)
}
if (b != nil) != want {
t.Fatalf("at %v: made %+v, wanted one: %v", at, b, want)
}
}
tick(t0, true)
if l := autoList(t); len(l) != 1 || l[0].Reason != ReasonAuto || !l[0].Made.Equal(t0) || l[0].Providers != 2 {
t.Fatalf("after the first: %+v", l)
}
setTheme(t, "light")
tick(t0.Add(time.Hour), false)
tick(t0.Add(23*time.Hour+59*time.Minute), false)
tick(t0.Add(24*time.Hour), true)
// a day with no change makes none, and pushes nothing out
tick(t0.Add(48*time.Hour), false)
setTheme(t, "dark")
tick(t0.Add(49*time.Hour), false) // looked at 48h: the next look is a day after
tick(t0.Add(72*time.Hour), true)
if l := autoList(t); len(l) != 3 {
t.Fatalf("want 3 backups, have %+v", l)
}
// the clock set back before the last backup: due, not waited out
setTheme(t, "light")
tick(t0.Add(-time.Hour), true)
}
// A magpie that starts again goes by the newest backup in the folder, not
// a fresh start: no backup at every launch.
func TestAutoBackupAfterRestartWaits(t *testing.T) {
autoHome(t)
if _, err := AutoTick(t0, "test"); err != nil {
t.Fatal(err)
}
setTheme(t, "light")
autoMu.Lock()
autoChecked = time.Time{}
clear(autoSeen)
autoMu.Unlock()
if b, err := AutoTick(t0.Add(2*time.Hour), "test"); err != nil || b != nil {
t.Fatalf("made %+v, %v two hours after the last", b, err)
}
}
// The user's own choice is kept: off stays off, and a setup that can't be
// read is unknown, so nothing is made.
func TestAutoBackupOffOrUnreadable(t *testing.T) {
autoHome(t)
if err := SaveAuto(AutoConfig{Off: true}); err != nil {
t.Fatal(err)
}
if b, err := AutoTick(t0, "test"); err != nil || b != nil {
t.Fatalf("off made %+v, %v", b, err)
}
if v := AutoStatus(); v.On || v.Hours != DefaultHours || v.Keep != DefaultKeep {
t.Fatalf("off reads %+v", v)
}
if err := os.WriteFile(autoPath(), []byte(`{"off":tr`), 0o600); err != nil {
t.Fatal(err)
}
if b, err := AutoTick(t0, "test"); err == nil || b != nil {
t.Fatalf("unreadable setup made %+v, %v", b, err)
}
if v := AutoStatus(); v.On || v.Error == "" {
t.Fatalf("unreadable setup reads %+v", v)
}
if _, err := os.Stat(AutoDefaultDir()); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("a backup folder was made: %v", err)
}
if err := SaveAuto(AutoConfig{Hours: 5}); err == nil {
t.Fatal("an interval Settings doesn't offer was saved")
}
if err := SaveAuto(AutoConfig{Dir: "relative/dir"}); err == nil {
t.Fatal("a relative folder was saved")
}
}
// Only the newest of each kind are kept, and nothing else in the folder is
// touched: the user may have picked one with their own files in it.
func TestAutoBackupPrunes(t *testing.T) {
autoHome(t)
dir := filepath.Join(t.TempDir(), "My backups")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := SaveAuto(AutoConfig{Keep: 3, Dir: dir, Hours: 1}); err != nil {
t.Fatal(err)
}
mine := []string{"notes.txt", "magpie-2026-11-01.magpie-backup", "magpie-20200101-000000-auto.json.bak"}
for _, f := range mine {
if err := os.WriteFile(filepath.Join(dir, f), []byte("mine"), 0o644); err != nil {
t.Fatal(err)
}
}
var made []string
for i := range 5 {
if err := profile.Save("work", profile.Profile{Fields: map[string]string{"claude.model": fmt.Sprint("acme/m", i)}}); err != nil {
t.Fatal(err)
}
b, err := AutoTick(t0.Add(time.Duration(i)*time.Hour), "test")
if err != nil || b == nil {
t.Fatalf("tick %d: %+v %v", i, b, err)
}
made = append(made, b.Name)
}
l := autoList(t)
if len(l) != 3 || l[0].Name != made[4] || l[1].Name != made[3] || l[2].Name != made[2] {
t.Fatalf("kept %+v, made %v", l, made)
}
for _, f := range mine {
if _, err := os.Stat(filepath.Join(dir, f)); err != nil {
t.Fatalf("the user's %s: %v", f, err)
}
}
if fi, err := os.Stat(filepath.Join(dir, made[4])); err != nil {
t.Fatal(err)
} else if runtime.GOOS != "windows" && fi.Mode().Perm()&0o077 != 0 {
t.Fatalf("a backup others can read: %v", fi.Mode())
}
}
// What a backup holds is what an export without keys holds, the proxy
// left out too: nothing secret is in the file.
func TestAutoBackupHoldsNoSecrets(t *testing.T) {
autoHome(t)
s := settings.Load()
s.GitHubToken, s.LANKey, s.Proxy = "ghp_SYNTHETIC_PRIVATE_TOKEN", "lan-SYNTHETIC-KEY", "http://user:proxy-SYNTHETIC-pass@10.0.0.1:8080"
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
b, err := AutoTick(t0, "test")
if err != nil || b == nil {
t.Fatal(b, err)
}
data, err := os.ReadFile(filepath.Join(AutoDefaultDir(), b.Name))
if err != nil {
t.Fatal(err)
}
for _, secret := range []string{"sk-acme", "balance-acme", "AK-acme", "SK-acme", "hdr-secret", "SYNTHETIC"} {
if strings.Contains(string(data), secret) {
t.Fatalf("%q in the backup", secret)
}
}
var f autoFile
if err := json.Unmarshal(data, &f); err != nil {
t.Fatal(err)
}
var got Bundle
if err := json.Unmarshal(f.Bundle, &got); err != nil {
t.Fatal(err)
}
// the export's own keyless collect, through JSON as a file carries it
want, err := Collect(false, "test")
if err != nil {
t.Fatal(err)
}
ws := *want.Settings
ws.Proxy, ws.ProxyCustom = "", ""
want.Settings, want.Created, want.App = &ws, time.Time{}, ""
raw, _ := json.Marshal(want)
var wantBack Bundle
json.Unmarshal(raw, &wantBack)
if !reflect.DeepEqual(got, wantBack) {
t.Fatalf("the backup is not the keyless export:\n%s\n%s", f.Bundle, raw)
}
}
// A restore puts the version back, keeps the keys here, and first backs up
// what was here, so restoring that one undoes it.
func TestAutoRestoreRoundTripAndUndo(t *testing.T) {
autoHome(t)
a, err := AutoTick(t0, "test")
if err != nil || a == nil {
t.Fatal(a, err)
}
// then the setup changes: another address, theme and profile
p, _ := provider.Find("acme")
p.Chat = "https://changed.example.com/v1"
if err := provider.Save(*p); err != nil {
t.Fatal(err)
}
setTheme(t, "light")
if err := profile.Save("work", profile.Profile{Fields: map[string]string{"claude.model": "beta/m2"}}); err != nil {
t.Fatal(err)
}
r, before, err := AutoRestore(a.Name, "test")
if err != nil {
t.Fatal(err)
}
if r.Replaced != 2 || !r.Settings || r.Profiles != 1 || before.Reason != ReasonRestore {
t.Fatalf("restore: %+v, before %+v", r, before)
}
p, _ = provider.Find("acme")
if p.Chat != "https://acme.example.com/v1" || p.Key != "sk-acme" || p.BalanceToken != "balance-acme" || p.Headers["X-Api-Key"] != "hdr-secret" {
t.Fatalf("acme after the restore: %+v", p)
}
if s := settings.Load(); s.Theme != "dark" {
t.Fatalf("theme %q", s.Theme)
}
if ps, _ := profile.Load(); ps["work"].Fields["claude.model"] != "acme/m1" {
t.Fatalf("profile %+v", ps["work"])
}
l := autoList(t)
if len(l) != 2 || !slices.ContainsFunc(l, func(b AutoBackup) bool { return b.Name == before.Name }) {
t.Fatalf("list after the restore: %+v", l)
}
// undo: the backup of what was here before it
if _, _, err := AutoRestore(before.Name, "test"); err != nil {
t.Fatal(err)
}
p, _ = provider.Find("acme")
if p.Chat != "https://changed.example.com/v1" || p.Key != "sk-acme" {
t.Fatalf("acme after the undo: %+v", p)
}
if s := settings.Load(); s.Theme != "light" {
t.Fatalf("theme after the undo %q", s.Theme)
}
if ps, _ := profile.Load(); ps["work"].Fields["claude.model"] != "beta/m2" {
t.Fatalf("profile after the undo %+v", ps["work"])
}
}
// A setup here that can't be read can't be backed up first, so nothing is
// put back over it.
func TestAutoRestoreNeedsTheBackupFirst(t *testing.T) {
autoHome(t)
a, err := AutoTick(t0, "test")
if err != nil || a == nil {
t.Fatal(a, err)
}
p, _ := provider.Find("acme")
p.Chat = "https://changed.example.com/v1"
if err := provider.Save(*p); err != nil {
t.Fatal(err)
}
// settings.json there but not readable (a folder at its name: the same
// on every system, where a file's mode isn't)
if err := os.Remove(settings.Path()); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(settings.Path(), 0o700); err != nil {
t.Fatal(err)
}
if _, _, err := AutoRestore(a.Name, "test"); err == nil {
t.Fatal("restored with no backup of what was here")
}
if p, _ := provider.Find("acme"); p.Chat != "https://changed.example.com/v1" {
t.Fatalf("acme put back anyway: %+v", p)
}
if _, _, err := AutoRestore("../settings.json", "test"); err == nil {
t.Fatal("a name outside the backups was read")
}
}
// A backup cut short, damaged, or still being written is never listed or
// put back, and a write that stops before its rename leaves nothing at a
// backup's name.
func TestAutoHalfWrittenNeverListed(t *testing.T) {
autoHome(t)
good, err := AutoTick(t0, "test")
if err != nil || good == nil {
t.Fatal(good, err)
}
dir := AutoDefaultDir()
whole, err := os.ReadFile(filepath.Join(dir, good.Name))
if err != nil {
t.Fatal(err)
}
cut := "magpie-20261101-000000-auto.json"
if err := os.WriteFile(filepath.Join(dir, cut), whole[:len(whole)/2], 0o600); err != nil {
t.Fatal(err)
}
changed := "magpie-20261101-000001-auto.json"
if err := os.WriteFile(filepath.Join(dir, changed), []byte(strings.Replace(string(whole), `"theme":"dark"`, `"theme":"pink"`, 1)), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, ".magpie-backup-123.tmp"), whole, 0o600); err != nil {
t.Fatal(err)
}
if l := autoList(t); len(l) != 1 || l[0].Name != good.Name {
t.Fatalf("listed %+v", l)
}
for _, n := range []string{cut, changed} {
if _, _, err := AutoRestore(n, "test"); !errors.Is(err, ErrCorrupt) {
t.Fatalf("restored %s: %v", n, err)
}
}
// the write stops after the temporary file is full, before its rename
autoRename = func(string, string) error { return errors.New("the machine went off") }
t.Cleanup(func() { autoRename = os.Rename })
setTheme(t, "light")
if b, err := AutoNow("test"); err == nil {
t.Fatalf("made %+v", b)
}
if l := autoList(t); len(l) != 1 || l[0].Name != good.Name {
t.Fatalf("listed after a stopped write %+v", l)
}
tmps, _ := filepath.Glob(filepath.Join(dir, autoTemp))
if len(tmps) != 1 { // the test's own, not the stopped write's
t.Fatalf("temporary files left: %v", tmps)
}
}