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.
191 lines
6.4 KiB
Go
191 lines
6.4 KiB
Go
package gui
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/agentenv"
|
|
"github.com/yetone/magpie/internal/library"
|
|
)
|
|
|
|
// folderOnly is the app's windows as far as an export needs them.
|
|
type folderOnly struct{ Windows }
|
|
|
|
func (folderOnly) OpenFolder(string) error { return nil }
|
|
|
|
// sandboxHome gives the test a machine of its own: no agents, no magpie files.
|
|
func sandboxHome(t *testing.T) string {
|
|
t.Helper()
|
|
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"))
|
|
t.Setenv("PATH", "")
|
|
for _, v := range agentenv.Vars {
|
|
t.Setenv(v, "")
|
|
}
|
|
t.Setenv("APPDATA", "")
|
|
t.Setenv("LOCALAPPDATA", "")
|
|
return h
|
|
}
|
|
|
|
// The Settings page's Export and Import carry the library, and leave it
|
|
// when its box is unticked.
|
|
func TestBackupLibraryRoundTrip(t *testing.T) {
|
|
h := sandboxHome(t)
|
|
text := "Be brief."
|
|
if _, err := library.SaveInstructions(library.InstructionsChange{Shared: &text}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
mux := http.NewServeMux()
|
|
backupRoutes(mux, folderOnly{})
|
|
post := func(path string, body any) map[string]any {
|
|
t.Helper()
|
|
b, _ := json.Marshal(body)
|
|
w := httptest.NewRecorder()
|
|
mux.ServeHTTP(w, httptest.NewRequest("POST", path, strings.NewReader(string(b))))
|
|
if w.Code != 200 {
|
|
t.Fatalf("%s: %d %s", path, w.Code, w.Body)
|
|
}
|
|
var out map[string]any
|
|
json.Unmarshal(w.Body.Bytes(), &out)
|
|
return out
|
|
}
|
|
export := func(lib bool) []byte {
|
|
t.Helper()
|
|
out := post("/api/backup/export", map[string]any{"pass": "pw", "keys": true, "library": lib})
|
|
if out["library"] != lib {
|
|
t.Fatalf("export: %v", out)
|
|
}
|
|
p, _ := out["path"].(string)
|
|
data, err := os.ReadFile(filepath.Join(h, strings.TrimPrefix(p, "~")))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return data
|
|
}
|
|
with, without := export(true), export(false)
|
|
|
|
sandboxHome(t) // another machine
|
|
enc := base64.StdEncoding.EncodeToString
|
|
if out := post("/api/backup/import", map[string]any{"data": enc(without), "pass": "pw", "agents": true, "library": true}); out["Library"] != false {
|
|
t.Fatalf("a file without it: %v", out)
|
|
}
|
|
if out := post("/api/backup/import", map[string]any{"data": enc(with), "pass": "pw", "agents": true, "library": false}); out["Library"] != false {
|
|
t.Fatalf("unticked: %v", out)
|
|
}
|
|
if iv, _ := library.ReadInstructions(); iv.Shared != "" {
|
|
t.Fatalf("the library came in unticked: %q", iv.Shared)
|
|
}
|
|
if out := post("/api/backup/import", map[string]any{"data": enc(with), "pass": "pw", "agents": true, "library": true}); out["Library"] != true {
|
|
t.Fatalf("import: %v", out)
|
|
}
|
|
if iv, _ := library.ReadInstructions(); iv.Shared != "Be brief." {
|
|
t.Fatalf("instructions: %q", iv.Shared)
|
|
}
|
|
}
|
|
|
|
// 1Shin on Discord: an export joined $HOME/Downloads. On a Linux desktop in
|
|
// Chinese, Downloads is ~/下载 (user-dirs.dirs); the export goes there, and
|
|
// to home\Downloads when the folder named there isn't one.
|
|
func TestExportGoesToTheSystemsDownloads(t *testing.T) {
|
|
if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
|
|
t.Skip("user-dirs.dirs is read on Linux and the BSDs (appdir's tests fake Windows' known folder)")
|
|
}
|
|
h := sandboxHome(t)
|
|
os.MkdirAll(filepath.Join(h, ".config"), 0o700)
|
|
os.WriteFile(filepath.Join(h, ".config", "user-dirs.dirs"), []byte("XDG_DOWNLOAD_DIR=\"$HOME/下载\"\n"), 0o600)
|
|
mux := http.NewServeMux()
|
|
backupRoutes(mux, folderOnly{})
|
|
export := func() string {
|
|
t.Helper()
|
|
w := httptest.NewRecorder()
|
|
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/backup/export", strings.NewReader(`{"pass":"pw"}`)))
|
|
if w.Code != 200 {
|
|
t.Fatalf("export: %d %s", w.Code, w.Body)
|
|
}
|
|
var out struct{ Path string }
|
|
json.Unmarshal(w.Body.Bytes(), &out)
|
|
return filepath.Dir(filepath.Join(h, strings.TrimPrefix(out.Path, "~")))
|
|
}
|
|
os.MkdirAll(filepath.Join(h, "Downloads"), 0o700)
|
|
if got, want := export(), filepath.Join(h, "Downloads"); got != want {
|
|
t.Errorf("~/下载 not made yet: saved in %s, want %s", got, want)
|
|
}
|
|
os.MkdirAll(filepath.Join(h, "下载"), 0o700)
|
|
if got, want := export(), filepath.Join(h, "下载"); got != want {
|
|
t.Errorf("saved in %s, want %s", got, want)
|
|
}
|
|
}
|
|
|
|
// pickFolder is the app's windows with the system's folder picker answering
|
|
// dir.
|
|
type pickFolder struct {
|
|
folderOnly
|
|
dir string
|
|
}
|
|
|
|
func (p pickFolder) ChooseFolder(string) (string, error) { return p.dir, nil }
|
|
|
|
// Settings' Back up by itself (jwaitq on Discord): a change sends only what
|
|
// it changes, so the rest stays as the user set it; Change… takes a folder
|
|
// from the picker; a backup made now is listed, and restoring it says which
|
|
// backup of what was here undoes it.
|
|
func TestAutoBackupRoutes(t *testing.T) {
|
|
sandboxHome(t)
|
|
picked := t.TempDir()
|
|
mux := http.NewServeMux()
|
|
backupRoutes(mux, pickFolder{dir: picked})
|
|
call := func(path, body string) map[string]any {
|
|
t.Helper()
|
|
w := httptest.NewRecorder()
|
|
method := "POST"
|
|
if body == "-" {
|
|
method, body = "GET", ""
|
|
}
|
|
mux.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))
|
|
if w.Code != 200 {
|
|
t.Fatalf("%s: %d %s", path, w.Code, w.Body)
|
|
}
|
|
var out map[string]any
|
|
json.Unmarshal(w.Body.Bytes(), &out)
|
|
return out
|
|
}
|
|
if v := call("/api/autobackup", "-"); v["on"] != true || v["hours"] != 24.0 || v["keep"] != 7.0 || v["custom"] != false {
|
|
t.Fatalf("the defaults: %v", v)
|
|
}
|
|
call("/api/autobackup/set", `{"hours":168}`)
|
|
call("/api/autobackup/set", `{"keep":14}`)
|
|
if v := call("/api/autobackup/set", `{"on":false}`); v["on"] != false || v["hours"] != 168.0 || v["keep"] != 14.0 {
|
|
t.Fatalf("off kept the rest? %v", v)
|
|
}
|
|
if v := call("/api/autobackup/choose", ""); v["custom"] != true || v["dir"] != tilde(picked) {
|
|
t.Fatalf("chosen: %v", v)
|
|
}
|
|
v := call("/api/autobackup/now", "")
|
|
list, _ := v["backups"].([]any)
|
|
if len(list) != 1 {
|
|
t.Fatalf("after Back up now: %v", v)
|
|
}
|
|
name := list[0].(map[string]any)["name"].(string)
|
|
if _, err := os.Stat(filepath.Join(picked, name)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
r := call("/api/autobackup/restore", `{"name":"`+name+`"}`)
|
|
before, _ := r["before"].(string)
|
|
if !strings.HasSuffix(before, "-restore.json") || len(r["view"].(map[string]any)["backups"].([]any)) != 2 {
|
|
t.Fatalf("restore: %v", r)
|
|
}
|
|
if v := call("/api/autobackup/set", `{"dir":""}`); v["custom"] != false || v["hours"] != 168.0 {
|
|
t.Fatalf("back to the default folder: %v", v)
|
|
}
|
|
}
|