diff --git a/docs/subsystems/sync-backup.md b/docs/subsystems/sync-backup.md index 25f46a9c2..35b31d03c 100644 --- a/docs/subsystems/sync-backup.md +++ b/docs/subsystems/sync-backup.md @@ -126,6 +126,40 @@ fields reuse a saved credential only for its matching account; GitHub restricts reuse to the same owner/repo. Branch or prefix changes within that repository can keep the token. The branch is part of the sync state key. +## Backups by themselves + +[`auto.go`](../../internal/backup/auto.go) writes the setup into a folder on +this computer on a schedule (jwaitq on Discord). `RunAuto` runs while the +gateway serves (`gateway.WhileServing`, wired in `internal/cli/main.go`) and +calls `AutoTick` every few minutes; tests call `AutoTick` with their own +clock. + +- **Config:** `autobackup.json` beside the settings holds only what the user + set (`Off`, `Hours`, `Keep`, `Dir`). Missing means on, every 24 hours, + keeping 7, in `settings.Dir()/auto-backups` (not `backups`, which the + library prunes). A config that can't be read or parsed makes no backup and + shows the error; it is never read as the defaults. +- **Content:** `Collect(false, app)`, the manual export without keys, with + the proxy settings blanked too, since nothing seals it: no passphrase is + there on a schedule. Files are 0600 in a 0700 folder. +- **Format:** `magpie-YYYYMMDD-HHMMSS[-n]-{auto,restore}.json`, holding the + bundle and its sha256. Each is written to a `.magpie-backup-*.tmp` and + renamed into place. A file whose sum doesn't match, a temp file or a name + that doesn't match is never listed, restored or pruned. +- **Schedule:** a backup is due `Hours` after the newest, so a restart + doesn't make one early; one whose bundle equals the newest's is not + written. After a write the oldest `-auto` files past `Keep` are removed + (and `-restore` ones past `Keep` after a restore), with its own temp files + over an hour old; other files in the folder are never touched. +- **Restore:** `AutoRestore(name)` first writes a `-restore` backup of what + is here (and stops if that fails), then `Restore(bundle, All)`, which is + additive: providers added since stay, each keeps its local key. Restoring + the `-restore` file undoes it. +- **API:** `GET /api/autobackup`; `POST /api/autobackup/{set,choose,now, + reveal,restore}`. `set` changes only the fields sent; `dir ""` is the + default folder. Settings draws it under Sync's Export and Import from the + lazy [`autobackup.js`](../../internal/gui/assets/autobackup.js). + ## GitHub constraints and errors - The repository must exist and be private: `prepare` refuses one whose diff --git a/internal/backup/auto.go b/internal/backup/auto.go new file mode 100644 index 000000000..c1f0f74a9 --- /dev/null +++ b/internal/backup/auto.go @@ -0,0 +1,527 @@ +package backup + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/settings" +) + +// Backups made by themselves (jwaitq on Discord, who got their setup back +// on Windows only from an export in Downloads): every so often the setup is +// written to a folder on this computer, the last few kept, and any of them +// can be put back from Settings › Sync and backup. +// +// What goes in is what an export without the API keys holds, by the same +// Collect(false): no key, no key-like header, no gateway key, no token, no +// sign-in (and no proxy, autoCollect). There is no passphrase to seal with +// here, so nothing that needs one is written; the file is the bundle as JSON, 0600 in a 0700 folder. +// A restore of one is the export's import (Restore, every part): a provider +// that came without a key keeps the one it has here, so going back to a +// version never takes a key away. + +// AutoConfig is how backups are made by themselves. It is this computer's +// own, in autobackup.json beside the settings, never in a bundle or a sync. +// The zero value is the default, so a field the user never set follows it +// and one they set is kept as set. +type AutoConfig struct { + Off bool `json:"off,omitempty"` // turned off by the user; on unless so + Hours int `json:"hours,omitempty"` // between backups; 0 is DefaultHours + Keep int `json:"keep,omitempty"` // backups kept of each kind; 0 is DefaultKeep + Dir string `json:"dir,omitempty"` // the folder; "" is AutoDefaultDir +} + +// On by default: losing the setup is what this is for, and a user who +// never found the switch is the one it saves. Once a day, deduplicated (a +// day with no change makes none), so the last week of changes is kept. +const ( + DefaultHours = 24 + DefaultKeep = 7 +) + +// AutoHours and AutoKeeps are what Settings offers. +var ( + AutoHours = []int{1, 6, 24, 168} + AutoKeeps = []int{3, 7, 14, 30} +) + +const autoFormat = "magpie-auto-backup" + +// Reasons a backup was made: by the schedule (or Back up now), or as what +// was here before a restore, to undo it. +const ( + ReasonAuto = "auto" + ReasonRestore = "restore" +) + +func autoPath() string { return filepath.Join(settings.Dir(), "autobackup.json") } + +// AutoDefaultDir is where backups go unless the user picked a folder. Not +// settings.Dir()/backups: that is the library's, which prunes it. +func AutoDefaultDir() string { return filepath.Join(settings.Dir(), "auto-backups") } + +func (c AutoConfig) every() time.Duration { + if c.Hours > 0 { + return time.Duration(c.Hours) * time.Hour + } + return DefaultHours * time.Hour +} + +func (c AutoConfig) keep() int { + if c.Keep > 0 { + return c.Keep + } + return DefaultKeep +} + +func (c AutoConfig) dir() string { + if c.Dir != "" { + return c.Dir + } + return AutoDefaultDir() +} + +// LoadAuto reads the setup. A file that isn't there is the defaults; one +// that can't be read or parsed is an error, never the defaults: the user may +// have turned backups off in it. +func LoadAuto() (AutoConfig, error) { + var c AutoConfig + data, err := os.ReadFile(autoPath()) + if errors.Is(err, os.ErrNotExist) { + return c, nil + } + if err != nil { + return c, err + } + if len(strings.TrimSpace(string(edit.TrimBOM(data)))) == 0 { + return c, nil + } + if err := json.Unmarshal(edit.TrimBOM(data), &c); err != nil { + return c, fmt.Errorf("%s: %w", autoPath(), err) + } + return c, nil +} + +// SaveAuto writes the setup, after checking it is one Settings offers. +func SaveAuto(c AutoConfig) error { + if c.Hours != 0 && !slices.Contains(AutoHours, c.Hours) { + return fmt.Errorf("backups can be made every %v hours, not %d", AutoHours, c.Hours) + } + if c.Keep < 0 || c.Keep > 100 { + return fmt.Errorf("keep between 1 and 100 backups, not %d", c.Keep) + } + if c.Dir != "" && !filepath.IsAbs(c.Dir) { + return fmt.Errorf("the backup folder must be a full path, not %q", c.Dir) + } + data, err := json.MarshalIndent(c, "", " ") + if err != nil { + return err + } + if err := os.MkdirAll(settings.Dir(), 0o755); err != nil { + return err + } + autoMu.Lock() + defer autoMu.Unlock() + autoChecked = time.Time{} // a new folder or interval is looked at anew + return edit.WriteAtomic(autoPath(), append(data, '\n')) +} + +// AutoBackup is one backup in the folder. +type AutoBackup struct { + Name string `json:"name"` + Made time.Time `json:"made"` + Reason string `json:"reason"` + App string `json:"app,omitempty"` + Size int64 `json:"size"` + Providers int `json:"providers"` + Library bool `json:"library"` + sum string +} + +// autoFile is a backup as written: what it is and when, then the bundle, +// with a hash of the bundle's bytes so a file damaged after it was written +// is never offered. +type autoFile struct { + Format string `json:"format"` + Version int `json:"version"` + Reason string `json:"reason"` + Made time.Time `json:"made"` + App string `json:"app,omitempty"` + Providers int `json:"providers"` + Library bool `json:"library"` + Sum string `json:"sum"` + Bundle json.RawMessage `json:"bundle"` +} + +// autoName is a backup's file name; anything else in the folder (the +// temporary file one is written to, the user's own files) is never listed, +// put back or removed. +var autoName = regexp.MustCompile(`^magpie-(\d{8}-\d{6})(?:-\d+)?-(auto|restore)\.json$`) + +const autoTemp = ".magpie-backup-*.tmp" + +// autoRename puts a written backup at its name: a var so a test can stop +// a write there. +var autoRename = os.Rename + +var ( + autoMu sync.Mutex + autoChecked time.Time // when the schedule last looked and found its backup made or not needed + autoErr string // why the last scheduled backup failed, "" once one goes + // what was read of each file, by name, while its size and time stay + autoSeen = map[string]autoSeenFile{} +) + +type autoSeenFile struct { + size int64 + mod time.Time + b AutoBackup + ok bool +} + +// bundleBytes is the bundle as a backup holds it, with what changes on +// every collect (when, by which magpie) taken out, so the same setup is the +// same bytes and makes no new backup. +func bundleBytes(b Bundle) ([]byte, string, error) { + b.Created, b.App = time.Time{}, "" + raw, err := json.Marshal(b) + if err != nil { + return nil, "", err + } + s := sha256.Sum256(raw) + return raw, hex.EncodeToString(s[:]), nil +} + +// writeAuto writes b into dir as a backup made at now for reason, through +// a temporary file renamed into place, so a backup cut short (the machine +// going off mid-write) is never at a backup's name. +func writeAuto(dir, reason string, b Bundle, now time.Time) (AutoBackup, error) { + raw, sum, err := bundleBytes(b) + if err != nil { + return AutoBackup{}, err + } + f := autoFile{Format: autoFormat, Version: 1, Reason: reason, Made: now.UTC(), App: b.App, + Providers: len(b.Providers), Library: b.Library != nil, Sum: sum, Bundle: raw} + data, err := json.Marshal(f) + if err != nil { + return AutoBackup{}, err + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return AutoBackup{}, err + } + tmp, err := os.CreateTemp(dir, autoTemp) + if err != nil { + return AutoBackup{}, err + } + gone := func(err error) (AutoBackup, error) { + tmp.Close() + os.Remove(tmp.Name()) + return AutoBackup{}, err + } + if _, err := tmp.Write(data); err != nil { + return gone(err) + } + if err := tmp.Sync(); err != nil { + return gone(err) + } + if err := tmp.Close(); err != nil { + return gone(err) + } + os.Chmod(tmp.Name(), 0o600) + stamp := now.UTC().Format("20060102-150405") + name := "magpie-" + stamp + "-" + reason + ".json" + for i := 2; ; i++ { // never over another + if _, err := os.Lstat(filepath.Join(dir, name)); errors.Is(err, os.ErrNotExist) { + break + } + name = fmt.Sprintf("magpie-%s-%d-%s.json", stamp, i, reason) + } + if err := autoRename(tmp.Name(), filepath.Join(dir, name)); err != nil { + os.Remove(tmp.Name()) + return AutoBackup{}, err + } + return AutoBackup{Name: name, Made: f.Made, Reason: reason, App: f.App, Size: int64(len(data)), + Providers: f.Providers, Library: f.Library, sum: sum}, nil +} + +// readAuto reads one backup whole, checking its hash. +func readAuto(path string) (AutoBackup, autoFile, error) { + data, err := os.ReadFile(path) + if err != nil { + return AutoBackup{}, autoFile{}, err + } + var f autoFile + if err := json.Unmarshal(data, &f); err != nil || f.Format != autoFormat { + return AutoBackup{}, f, ErrCorrupt + } + if f.Version != 1 { + return AutoBackup{}, f, errors.New("this backup was made by a newer magpie; update magpie to open it") + } + s := sha256.Sum256(f.Bundle) + if hex.EncodeToString(s[:]) != f.Sum || (f.Reason != ReasonAuto && f.Reason != ReasonRestore) { + return AutoBackup{}, f, ErrCorrupt + } + return AutoBackup{Name: filepath.Base(path), Made: f.Made, Reason: f.Reason, App: f.App, Size: int64(len(data)), + Providers: f.Providers, Library: f.Library, sum: f.Sum}, f, nil +} + +// listAuto is the backups in dir, newest first: only files at a backup's +// name that read whole and match their hash. A folder that isn't there has +// none. Each file is read once while it stays as it was. +func listAuto(dir string) ([]AutoBackup, error) { + es, err := os.ReadDir(dir) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var out []AutoBackup + for _, e := range es { + if !e.Type().IsRegular() || !autoName.MatchString(e.Name()) { + continue + } + fi, err := e.Info() + if err != nil { + continue + } + p := filepath.Join(dir, e.Name()) + seen, ok := autoSeen[p] + if !ok || seen.size != fi.Size() || !seen.mod.Equal(fi.ModTime()) { + b, _, err := readAuto(p) + seen = autoSeenFile{size: fi.Size(), mod: fi.ModTime(), b: b, ok: err == nil} + if len(autoSeen) > 1000 { + clear(autoSeen) + } + autoSeen[p] = seen + } + if seen.ok { + out = append(out, seen.b) + } + } + slices.SortFunc(out, func(a, b AutoBackup) int { + if c := b.Made.Compare(a.Made); c != 0 { + return c + } + return strings.Compare(b.Name, a.Name) + }) + return out, nil +} + +// pruneAuto removes the backups made for reason past the newest keep, and +// temporary files an earlier write left an hour or more ago. +func pruneAuto(dir, reason string, keep int, now time.Time) { + list, err := listAuto(dir) + if err != nil { + return + } + n := 0 + for _, b := range list { + if b.Reason != reason { + continue + } + if n++; n > keep { + os.Remove(filepath.Join(dir, b.Name)) + } + } + tmps, _ := filepath.Glob(filepath.Join(dir, autoTemp)) + for _, p := range tmps { + if fi, err := os.Stat(p); err == nil && now.Sub(fi.ModTime()) > time.Hour { + os.Remove(p) + } + } +} + +// autoCollect is the setup as an export without keys holds it, and the +// proxy taken out too: it may name a password, the file isn't sealed, and +// a restore keeps this computer's own proxy (KeepOwn) anyway. +func autoCollect(app string) (Bundle, error) { + b, err := Collect(false, app) + if err == nil && b.Settings != nil { + s := *b.Settings + s.Proxy, s.ProxyCustom = "", "" + b.Settings = &s + } + return b, err +} + +// AutoTick makes a backup if one is due at now: on, the interval gone by +// since the last one (or the clock gone back before it), and the setup +// changed since the newest scheduled backup. It says the backup made, or +// nothing. A setup that can't be read whole makes none (Collect's error). +func AutoTick(now time.Time, app string) (*AutoBackup, error) { + autoMu.Lock() + defer autoMu.Unlock() + c, err := LoadAuto() + if err != nil { + return nil, err + } + if c.Off { + return nil, nil + } + dir := c.dir() + list, err := listAuto(dir) + if err != nil { + return nil, err + } + var newest *AutoBackup + if i := slices.IndexFunc(list, func(b AutoBackup) bool { return b.Reason == ReasonAuto }); i >= 0 { + newest = &list[i] + } + last := autoChecked + if newest != nil && newest.Made.After(last) { + last = newest.Made + } + if !last.IsZero() && !now.Before(last) && now.Sub(last) < c.every() { + return nil, nil + } + b, err := autoCollect(app) + if err != nil { + return nil, err + } + if _, sum, err := bundleBytes(b); err == nil && newest != nil && newest.sum == sum { + autoChecked = now // nothing changed: none made, looked at again in an interval + return nil, nil + } + made, err := writeAuto(dir, ReasonAuto, b, now) + if err != nil { + return nil, err + } + autoChecked = now + pruneAuto(dir, ReasonAuto, c.keep(), now) + return &made, nil +} + +// AutoNow makes a scheduled backup at once, changed or not (Back up now). +func AutoNow(app string) (AutoBackup, error) { + autoMu.Lock() + defer autoMu.Unlock() + c, err := LoadAuto() + if err != nil { + return AutoBackup{}, err + } + b, err := autoCollect(app) + if err != nil { + return AutoBackup{}, err + } + now := time.Now() + made, err := writeAuto(c.dir(), ReasonAuto, b, now) + if err != nil { + return made, err + } + autoChecked, autoErr = now, "" + pruneAuto(c.dir(), ReasonAuto, c.keep(), now) + return made, nil +} + +// AutoRestore puts the backup by name back, every part, as an import does. +// What is here now is backed up first (reason restore), so a restore is +// undone by restoring that one; if it can't be, nothing is put back. +func AutoRestore(name, app string) (Result, AutoBackup, error) { + autoMu.Lock() + defer autoMu.Unlock() + if !autoName.MatchString(name) { + return Result{}, AutoBackup{}, errors.New("not a backup's name") + } + c, err := LoadAuto() + if err != nil { + return Result{}, AutoBackup{}, err + } + dir := c.dir() + _, f, err := readAuto(filepath.Join(dir, name)) + if err != nil { + return Result{}, AutoBackup{}, err + } + var b Bundle + if err := json.Unmarshal(f.Bundle, &b); err != nil { + return Result{}, AutoBackup{}, ErrCorrupt + } + b.Created, b.App = f.Made, f.App + cur, err := autoCollect(app) + if err != nil { + return Result{}, AutoBackup{}, fmt.Errorf("couldn't back up the setup here first, so nothing was put back: %w", err) + } + now := time.Now() + before, err := writeAuto(dir, ReasonRestore, cur, now) + if err != nil { + return Result{}, AutoBackup{}, fmt.Errorf("couldn't back up the setup here first, so nothing was put back: %w", err) + } + pruneAuto(dir, ReasonRestore, c.keep(), now) + r, err := Restore(b, All) + return r, before, err +} + +// AutoView is what Settings shows. +type AutoView struct { + On bool `json:"on"` + Hours int `json:"hours"` + Keep int `json:"keep"` + Dir string `json:"dir"` + Custom bool `json:"custom"` // a folder the user picked + Error string `json:"error,omitempty"` + Backups []AutoBackup `json:"backups"` +} + +// AutoStatus is the setup and the backups in its folder. +func AutoStatus() AutoView { + c, err := LoadAuto() + v := AutoView{On: !c.Off, Hours: int(c.every() / time.Hour), Keep: c.keep(), Dir: c.dir(), Custom: c.Dir != "", Backups: []AutoBackup{}} + if err != nil { + v.On, v.Error = false, err.Error() + return v + } + autoMu.Lock() + defer autoMu.Unlock() + if v.On { + v.Error = autoErr + } + list, err := listAuto(v.Dir) + if err != nil && v.Error == "" { + v.Error = err.Error() + } + if list != nil { + v.Backups = list + } + return v +} + +// autoPoll is how often RunAuto looks whether a backup is due, and +// autoFirst how soon after it starts: a var for tests. +var autoPoll, autoFirst = 10 * time.Minute, 2 * time.Minute + +// RunAuto makes backups on their schedule until ctx ends. A failure is +// logged once and shown in Settings, not on every try. +func RunAuto(ctx context.Context) { + t := time.NewTimer(autoFirst) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + } + t.Reset(autoPoll) + _, err := AutoTick(time.Now(), "magpie") + autoMu.Lock() + if msg := fmt.Sprint(err); err != nil && msg != autoErr { + log.Printf("backing up by itself: %s", msg) + autoErr = msg + } else if err == nil { + autoErr = "" + } + autoMu.Unlock() + } +} diff --git a/internal/backup/auto_test.go b/internal/backup/auto_test.go new file mode 100644 index 000000000..aadf97975 --- /dev/null +++ b/internal/backup/auto_test.go @@ -0,0 +1,365 @@ +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) + } +} diff --git a/internal/cli/main.go b/internal/cli/main.go index 08ed3e8d7..ba9e58a73 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -15,6 +15,7 @@ import ( "github.com/yetone/magpie/internal/agent" "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/backup" "github.com/yetone/magpie/internal/browsermcp" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/claudebridge" @@ -399,6 +400,8 @@ func run(args []string) error { gateway.CodexDesktopChanged = agent.SyncCatalogSoon // the setup kept the same on every computer, by whichever serves gateway.WhileServing = append(gateway.WhileServing, davsync.Run) + // and the setup backed up into a folder here by itself (jwaitq) + gateway.WhileServing = append(gateway.WhileServing, backup.RunAuto) // and dsh's patch lists, which dsh reads live: a route left behind by // something else writing the file fails every session there until // magpie writes its own list again diff --git a/internal/cli/settings_parity_test.go b/internal/cli/settings_parity_test.go index ed868d051..2a985fced 100644 --- a/internal/cli/settings_parity_test.go +++ b/internal/cli/settings_parity_test.go @@ -235,6 +235,8 @@ var notYet = map[string]string{ "POST /api/usage/arrange": W, // api.go "POST /api/warm-now": A, // api.go "POST /api/window/{action}": W, // api.go + "GET /api/autobackup": S2, // backup.go: Back up by itself + "POST /api/autobackup/{action}": S2, // backup.go "GET /api/archive": S2, // archive.go "GET /api/archive/file": S2, // archive.go "POST /api/archive/export": S2, // archive.go diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index b20e37da9..51de58529 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -4230,6 +4230,12 @@ body.panel .modal { padding: 16px 12px; } .editor .fname { flex: 1; min-width: 0; font-size: 12.5px; color: var(--fg-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .editor.sync-form .done { grid-column: 1 / -1; font-size: 12.5px; color: var(--fg-2); user-select: text; -webkit-user-select: text; } .editor.sync-form .bar { grid-column: 1 / -1; } +/* Back up by itself (autobackup.js): a control too wide for the row goes + under its name, at the right, as Agents' rows do */ +.prefs .row.pref.auto-backup { flex-wrap: wrap; row-gap: 8px; } +.prefs .row.pref.auto-backup .who { flex: 1 1 200px; } +.prefs .row.pref.auto-backup .sub { white-space: normal; } +.prefs .row.pref.auto-backup .val { margin-left: auto; max-width: 100%; } /* the usual context windows under the field, one click each (#120) */ .cxpicks { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 6px; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 1e95bb5fb..060e60c50 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -20028,11 +20028,7 @@ async function renderSync(v) { // "Synced" in the same grey it read as part of a sync that went fine // (#1259) if (v.on && !v.error && v.usageError) sub.after(el("div", "sub bad wraps sync-usage-err", t("Couldn't share usage: {error}", { error: v.usageError }))); - // subscriptions whose settings sync brought with no account here: sync - // carries no sign-in, and they are listed once signed in to here. It says - // the synced settings are why they are named, and that one not used here - // needs nothing (悠悠哥 on Discord asked why sync said ChatGPT wasn't - // signed in) + // subscriptions synced with no account here (悠悠哥 on Discord) if (v.on && v.signIn?.length) sub.after(el("div", "sub wraps sync-sign-in", t("Your synced settings use {names}, which isn't signed in on this computer. Sync carries settings, not sign-ins: to use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.", { names: subNames(v.signIn) }))); // the server's file isn't a backup a sync can read, and is a file: this // computer's setup can go up in its place, the user choosing it @@ -20086,6 +20082,9 @@ async function renderSync(v) { if (syncOpen === "export") box.append(exportForm()); row(t("Import"), t("Bring in a file exported from magpie"), btn(t(syncOpen === "import" ? "Close" : "Import…"), toggle("import"))); if (syncOpen === "import") box.append(importForm()); + // Back up by itself (jwaitq), in autobackup.js + const ab = box.appendChild(el("div")); + if (window.autoBackupFill) autoBackupFill(ab); else import("./autobackup.js").then(() => autoBackupFill(ab), () => {}); } // askRestore asks before the server's setup replaces this computer's diff --git a/internal/gui/assets/autobackup.js b/internal/gui/assets/autobackup.js new file mode 100644 index 000000000..17e365391 --- /dev/null +++ b/internal/gui/assets/autobackup.js @@ -0,0 +1,142 @@ +// Settings › Sync's Back up by itself (jwaitq on Discord: 定期自动备份, +// 支持回退选择版本): the setup backed up into a folder on this computer on a +// schedule, the last few kept, and any of them put back, what is here being +// backed up first so that can be undone. app.js imports this when Settings +// draws Sync, so it weighs nothing on the core. + +// the server's view, kept over Settings' redraws and read again when it is +// half a minute old; the read under way, which a redraw while it is out +// draws with too; what the last restore came to, said once under the +// versions +let autoBackupView = null; +let autoBackupAt = 0; +let autoBackupLoad = null; +let autoBackupSaid = null; + +// autoBackupFill puts the rows in place of at, the empty element renderSync +// leaves at the end of Sync's list: rows, so the list's lines run between +// them as between Sync's own. +window.autoBackupFill = function (at) { + let drawn = [at]; + const draw = () => { + if (!drawn[0].isConnected) return; + const rows = autoBackupRows(autoBackupView); + drawn[0].before(...rows); + for (const r of drawn) r.remove(); + drawn = rows; + }; + if (autoBackupView) draw(); + if (Date.now() - autoBackupAt >= 30000) { + autoBackupAt = Date.now(); + const load = api("autobackup").then((v) => { autoBackupView = v; }, (e) => { autoBackupView = { error: e.message, backups: [] }; }); + autoBackupLoad = load; + load.then(() => { if (autoBackupLoad === load) autoBackupLoad = null; }); + } + autoBackupLoad?.then(draw); +}; + +// autoBackupDo posts one action and draws Sync again with what it says +async function autoBackupDo(action, body, b) { + b?.classList.add("busy"); + try { + autoBackupView = await api("autobackup/" + action, body || {}); + autoBackupAt = Date.now(); + } catch (e) { + statusErr(e); + } + renderSync(); +} + +function autoBackupRows(v) { + const rows = []; + const row = (name, sub, ...tools) => { + const r = el("div", "row pref auto-backup"); + const who = el("div", "who"); + const s = el("div", "sub", sub); + who.append(el("div", "name", name), s); + const val = el("div", "val"); + val.append(...tools); + r.append(who, val); + rows.push(r); + return r; + }; + const btn = (label, fn) => { const b = el("button", "text", label); b.type = "button"; b.onclick = (e) => fn(b, e); return b; }; + const on = !!v.on; + const head = row(t("Back up by itself"), v.error ? t("Couldn't back up: {error}", { error: v.error }) + : on ? t("Your providers, settings and profiles, without API keys or sign-ins, into a folder on this computer") : t("Off: no backups are made by themselves"), + segs([[0, t("Off")], [1, t("1 hour")], [6, t("6 hours")], [24, t("1 day")], [168, t("1 week")]], on ? v.hours : 0, + (h) => autoBackupDo("set", h ? { on: true, hours: h } : { on: false }))); + if (v.error) head.querySelector(".sub").classList.add("bad", "wraps"); + if (on) { + row(t("Versions kept"), t("The oldest is removed when a new one is made; one is made only when something changed"), + segs([3, 7, 14, 30].map((n) => [n, String(n)]), v.keep, (n) => autoBackupDo("set", { keep: n }))); + } + if (on || v.backups?.length) { + const tools = [btn(t("Change…"), (b) => autoBackupDo("choose", {}, b)), btn(t("Show"), () => api("autobackup/reveal", {}).catch(statusErr))]; + if (v.custom) tools.push(btn(t("Default"), (b) => autoBackupDo("set", { dir: "" }, b))); + row(t("Backup folder"), v.dir || "", ...tools).querySelector(".sub").classList.add("wraps", "auto-backup-dir"); + } + const list = v.backups || []; + const sub = row(t("Versions"), list.length ? t("{n} backups · newest {when}", { n: list.length, when: syncWhen(list[0].made) }) : t("None yet"), + btn(t("Back up now"), (b) => autoBackupDo("now", {}, b))).querySelector(".sub"); + if (autoBackupSaid) { + sub.after(...autoBackupSaid.map((l) => el("div", "sub wraps auto-backup-said", l))); + autoBackupSaid = null; + } + for (const b of list) { + const when = autoBackupWhen(b.made); + const what = [t(b.providers === 1 ? "1 provider" : "{n} providers", { n: b.providers })]; + if (b.reason === "restore") what.unshift(t("What was here before a restore")); + row(when, what.join(" · "), btn(t("Restore…"), () => autoBackupAsk(b, when))).classList.add("auto-backup-version"); + } + return rows; +} + +// autoBackupWhen names a version by when it was made, as its row does +const autoBackupWhen = (made) => new Date(made).toLocaleString(intlLang(), { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }); + +// autoBackupAsk asks before a version is put back, in the app's own +// dialog, saying what changes and that what is here is backed up first. +function autoBackupAsk(b, when) { + const ed = el("div", "editor restore-ask auto-backup-ask"); + const head = el("div", "ehead"); + head.append(el("b", "", t("Restore the backup of {when}?", { when }))); + ed.append(head); + ed.append(el("p", "lib-confirm", t("Your providers, settings, profiles and agents' models become this backup's. Providers added since are kept, and each keeps its API keys here."))); + ed.append(el("p", "lib-confirm", t("What is here now is backed up first: restore that one to undo this."))); + const err = el("p", "editor-error", ""); + ed.append(err); + const bar = el("div", "bar"); + const go = el("button", "text primary danger-fill", t("Restore")); + go.onclick = async (e) => { + e.stopPropagation(); + go.disabled = true; + go.classList.add("busy"); + try { + const r = await api("autobackup/restore", { name: b.name }); + closeConfirmAsk(); + autoBackupView = r.view; + autoBackupAt = Date.now(); + const x = r.result || {}; + const lines = [t("Restored the backup of {when}", { when }) + " · " + t("Providers: {added} added, {replaced} replaced; {profiles} profiles; {agents} agent settings changed", { added: x.Added, replaced: x.Replaced, profiles: x.Profiles, agents: x.Agents })]; + if (x.NeedKey?.length) lines.push(t("Needs a key: {names}", { names: x.NeedKey.join(", ") })); + const before = r.view?.backups?.find((k) => k.name === r.before); + if (before) lines.push(t("What was here before is the version of {when}: restore it to undo.", { when: autoBackupWhen(before.made) })); + autoBackupSaid = lines; + renderSync(); + refreshAfterSync(); + } catch (x) { + go.disabled = false; + go.classList.remove("busy"); + err.textContent = x.message; + } + }; + const cancel = el("button", "text", t("Cancel")); + cancel.onclick = cancelAsk; + bar.append(el("span", "grow"), cancel, go); + ed.append(bar); + confirmAsk = ed; + openModal(ed); + $("#modal").classList.add("lib"); + cancel.focus(NO_SCROLL); +} diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index ca6a71bf0..ed833c862 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2726,6 +2726,28 @@ const I18N = { "This computer's setup from before is kept in the sync folder.": "本机恢复前的配置已备份在 sync 文件夹。", "Undo": "撤销", "Sync by itself": "自动同步", + "Back up by itself": "自动备份", + "1 week": "1 周", + "6 hours": "6 小时", + "Back up now": "立即备份", + "Backup folder": "备份文件夹", + "Change…": "更改…", + "Couldn't back up: {error}": "无法备份:{error}", + "None yet": "暂无", + "Off: no backups are made by themselves": "已关闭,不会自动备份", + "Restore the backup of {when}?": "恢复 {when} 的备份?", + "Restored the backup of {when}": "已恢复 {when} 的备份", + "The oldest is removed when a new one is made; one is made only when something changed": "有新备份时删除最旧的一份;只有配置有变化时才会新建备份", + "Versions": "版本", + "Versions kept": "保留份数", + "What is here now is backed up first: restore that one to undo this.": "当前配置会先备份一份:恢复那一份即可撤销本次操作。", + "What was here before a restore": "恢复前的配置", + "What was here before is the version of {when}: restore it to undo.": "恢复前的配置已备份为 {when} 的版本:恢复它即可撤销。", + "Your providers, settings and profiles, without API keys or sign-ins, into a folder on this computer": "提供商、设置和配置方案(不含 API 密钥和登录信息),备份到本机的文件夹", + "Your providers, settings, profiles and agents' models become this backup's. Providers added since are kept, and each keeps its API keys here.": "提供商、设置、配置方案和各 agent 的模型将变为这份备份中的内容。之后新加的提供商会保留,每个提供商在本机的 API 密钥也保持不变。", + "{n} backups · newest {when}": "{n} 份备份 · 最新 {when}", + "1 provider": "1 个提供商", + "{n} providers": "{n} 个提供商", "Every {n} minutes while magpie runs": "magpie 运行时每 {n} 分钟同步一次", "Off: only Sync now syncs": "已关闭,仅在点「立即同步」时同步", "3 min": "3 分钟", @@ -7090,6 +7112,28 @@ const I18N = { "This computer's setup from before is kept in the sync folder.": "本機恢復前的設定已備份在 sync 資料夾。", "Undo": "復原", "Sync by itself": "自動同步", + "Back up by itself": "自動備份", + "1 week": "1 週", + "6 hours": "6 小時", + "Back up now": "立即備份", + "Backup folder": "備份資料夾", + "Change…": "更改…", + "Couldn't back up: {error}": "無法備份:{error}", + "None yet": "尚無", + "Off: no backups are made by themselves": "已關閉,不會自動備份", + "Restore the backup of {when}?": "還原 {when} 的備份?", + "Restored the backup of {when}": "已還原 {when} 的備份", + "The oldest is removed when a new one is made; one is made only when something changed": "有新備份時刪除最舊的一份;只有設定有變化時才會新建備份", + "Versions": "版本", + "Versions kept": "保留份數", + "What is here now is backed up first: restore that one to undo this.": "目前的設定會先備份一份:還原那一份即可復原本次操作。", + "What was here before a restore": "還原前的設定", + "What was here before is the version of {when}: restore it to undo.": "還原前的設定已備份為 {when} 的版本:還原它即可復原。", + "Your providers, settings and profiles, without API keys or sign-ins, into a folder on this computer": "供應商、設定與設定檔(不含 API 金鑰與登入資訊),備份到本機的資料夾", + "Your providers, settings, profiles and agents' models become this backup's. Providers added since are kept, and each keeps its API keys here.": "供應商、設定、設定檔與各 agent 的模型將變為這份備份中的內容。之後新增的供應商會保留,每個供應商在本機的 API 金鑰也維持不變。", + "{n} backups · newest {when}": "{n} 份備份 · 最新 {when}", + "1 provider": "1 個供應商", + "{n} providers": "{n} 個供應商", "Every {n} minutes while magpie runs": "magpie 執行時每 {n} 分鐘同步一次", "Off: only Sync now syncs": "已關閉,僅在點「立即同步」時同步", "3 min": "3 分鐘", @@ -11464,6 +11508,28 @@ const I18N = { "This computer's setup from before is kept in the sync folder.": "復元前のこのコンピューターの設定は同期フォルダーに保存されています。", "Undo": "取り消す", "Sync by itself": "自動同期", + "Back up by itself": "自動バックアップ", + "1 week": "1 週間", + "6 hours": "6 時間", + "Back up now": "今すぐバックアップ", + "Backup folder": "バックアップフォルダ", + "Change…": "変更…", + "Couldn't back up: {error}": "バックアップできませんでした:{error}", + "None yet": "まだありません", + "Off: no backups are made by themselves": "オフ:自動ではバックアップしません", + "Restore the backup of {when}?": "{when} のバックアップを復元しますか?", + "Restored the backup of {when}": "{when} のバックアップを復元しました", + "The oldest is removed when a new one is made; one is made only when something changed": "新しいバックアップを作ると最も古いものを削除します。変更があったときだけ作ります", + "Versions": "バージョン", + "Versions kept": "残す数", + "What is here now is backed up first: restore that one to undo this.": "いまの設定を先にバックアップします。それを復元すれば元に戻せます。", + "What was here before a restore": "復元前の設定", + "What was here before is the version of {when}: restore it to undo.": "復元前の設定は {when} のバージョンとして残っています。それを復元すれば元に戻せます。", + "Your providers, settings and profiles, without API keys or sign-ins, into a folder on this computer": "プロバイダ、設定、プロファイルを(API キーとサインインを除いて)このコンピュータのフォルダへ", + "Your providers, settings, profiles and agents' models become this backup's. Providers added since are kept, and each keeps its API keys here.": "プロバイダ、設定、プロファイル、各エージェントのモデルがこのバックアップのものになります。その後に追加したプロバイダは残り、各プロバイダのこのコンピュータの API キーもそのままです。", + "{n} backups · newest {when}": "バックアップ {n} 件 · 最新 {when}", + "1 provider": "プロバイダ 1 件", + "{n} providers": "プロバイダ {n} 件", "Every {n} minutes while magpie runs": "magpie の実行中、{n} 分ごとに同期", "Off: only Sync now syncs": "オフ:「今すぐ同期」を押したときだけ同期", "3 min": "3 分", @@ -15849,6 +15915,28 @@ const I18N = { "This computer's setup from before is kept in the sync folder.": "Die Einrichtung dieses Computers von vorher liegt im Sync-Ordner.", "Undo": "Rückgängig", "Sync by itself": "Selbst synchronisieren", + "Back up by itself": "Selbst sichern", + "1 week": "1 Woche", + "6 hours": "6 Stunden", + "Back up now": "Jetzt sichern", + "Backup folder": "Sicherungsordner", + "Change…": "Ändern…", + "Couldn't back up: {error}": "Sichern fehlgeschlagen: {error}", + "None yet": "Noch keine", + "Off: no backups are made by themselves": "Aus: Es wird nicht selbst gesichert", + "Restore the backup of {when}?": "Die Sicherung vom {when} wiederherstellen?", + "Restored the backup of {when}": "Sicherung vom {when} wiederhergestellt", + "The oldest is removed when a new one is made; one is made only when something changed": "Mit jeder neuen wird die älteste entfernt; eine neue entsteht nur, wenn sich etwas geändert hat", + "Versions": "Versionen", + "Versions kept": "Behaltene Versionen", + "What is here now is backed up first: restore that one to undo this.": "Was jetzt hier ist, wird zuerst gesichert: Diese Sicherung wiederherstellen macht es rückgängig.", + "What was here before a restore": "Stand vor einer Wiederherstellung", + "What was here before is the version of {when}: restore it to undo.": "Der Stand von vorher ist die Version vom {when}: Sie wiederherzustellen macht es rückgängig.", + "Your providers, settings and profiles, without API keys or sign-ins, into a folder on this computer": "Anbieter, Einstellungen und Profile, ohne API-Schlüssel und Anmeldungen, in einen Ordner auf diesem Computer", + "Your providers, settings, profiles and agents' models become this backup's. Providers added since are kept, and each keeps its API keys here.": "Anbieter, Einstellungen, Profile und die Modelle der Agenten werden die dieser Sicherung. Seitdem hinzugefügte Anbieter bleiben, und jeder behält seine API-Schlüssel hier.", + "{n} backups · newest {when}": "{n} Sicherungen · neueste {when}", + "1 provider": "1 Anbieter", + "{n} providers": "{n} Anbieter", "Every {n} minutes while magpie runs": "Alle {n} Minuten, solange magpie läuft", "Off: only Sync now syncs": "Aus: nur „Jetzt synchronisieren“ synchronisiert", "3 min": "3 Min.", diff --git a/internal/gui/backup.go b/internal/gui/backup.go index abefd5dca..1600ed1de 100644 --- a/internal/gui/backup.go +++ b/internal/gui/backup.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "net/http" "os" "path/filepath" @@ -91,6 +92,81 @@ func backupRoutes(mux *http.ServeMux, w Windows) { writeJSON(rw, res) }) + // backups made by themselves into a folder here, and putting one back + // (jwaitq on Discord) + mux.HandleFunc("GET /api/autobackup", func(rw http.ResponseWriter, r *http.Request) { + writeJSON(rw, autoView()) + }) + mux.HandleFunc("POST /api/autobackup/{action}", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + On *bool + Hours *int + Keep *int + Dir *string // "" is the default folder + Name string + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil && !errors.Is(err, io.EOF) { + fail(rw, err) + return + } + set := func(f func(*backup.AutoConfig)) error { + c, err := backup.LoadAuto() + if err != nil { + return err + } + f(&c) + return backup.SaveAuto(c) + } + var err error + switch r.PathValue("action") { + case "set": // only what was sent: the rest stays as the user set it + err = set(func(c *backup.AutoConfig) { + if in.On != nil { + c.Off = !*in.On + } + if in.Hours != nil { + c.Hours = *in.Hours + } + if in.Keep != nil { + c.Keep = *in.Keep + } + if in.Dir != nil && *in.Dir == "" { + c.Dir = "" + } + }) + case "choose": // a folder from the system's picker, checked writable + var dir string + if dir, err = w.ChooseFolder("Choose a folder for backups"); err == nil && dir != "" { + if err = writable(dir); err == nil { + err = set(func(c *backup.AutoConfig) { c.Dir = dir }) + } + } + case "now": + _, err = backup.AutoNow(Version) + case "reveal": + dir := backup.AutoStatus().Dir + if err = os.MkdirAll(dir, 0o700); err == nil { + err = w.OpenFolder(dir) + } + case "restore": // what is here is backed up first, to undo it + res, before, err := backup.AutoRestore(in.Name, Version) + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, map[string]any{"view": autoView(), "result": res, "before": before.Name}) + return + default: + http.NotFound(rw, r) + return + } + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, autoView()) + }) + mux.HandleFunc("GET /api/davsync", func(rw http.ResponseWriter, r *http.Request) { writeJSON(rw, davsync.Status()) }) @@ -156,6 +232,23 @@ func backupRoutes(mux *http.ServeMux, w Windows) { }) } +// autoView is backup.AutoStatus with the folder as the page shows it. +func autoView() backup.AutoView { + v := backup.AutoStatus() + v.Dir = tilde(v.Dir) + return v +} + +// writable says whether a file can be made in dir. +func writable(dir string) error { + f, err := os.CreateTemp(dir, ".magpie-backup-*.tmp") + if err != nil { + return err + } + f.Close() + return os.Remove(f.Name()) +} + // busy is what of a sync's failure the status doesn't hold: that it waited // its time out for another magpie's. The rest is in the status. func busy(err error) error { diff --git a/internal/gui/backup_test.go b/internal/gui/backup_test.go index ff4d8fbda..9560f6569 100644 --- a/internal/gui/backup_test.go +++ b/internal/gui/backup_test.go @@ -125,3 +125,66 @@ func TestExportGoesToTheSystemsDownloads(t *testing.T) { 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) + } +} diff --git a/internal/gui/tests/agent-prefs.test.cjs b/internal/gui/tests/agent-prefs.test.cjs index 4fcf90a3c..d8b70f84e 100644 --- a/internal/gui/tests/agent-prefs.test.cjs +++ b/internal/gui/tests/agent-prefs.test.cjs @@ -119,6 +119,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // none in Settings; its search says where they are await page.goto("http://magpie.test/?view=settings"); await page.locator("#setQ").waitFor(); + // #setQ is in the page before Settings is drawn, and Long + // conversations with it: wait for the drawing to take it out + await page.waitForFunction(() => !document.querySelector("#view-settings #fullContextRow")).catch(() => {}); for (const id of CODEX) assert.equal(await page.locator(`#view-settings #${id}`).count(), 0, `${lang}: ${id} not in Settings`); assert.equal(await page.locator(".agent-pref-link").first().isVisible(), false, "no link rows till searching"); await page.locator("#setQ").fill(w.titles); diff --git a/internal/gui/tests/auto-backup.test.cjs b/internal/gui/tests/auto-backup.test.cjs new file mode 100644 index 000000000..04d89e92e --- /dev/null +++ b/internal/gui/tests/auto-backup.test.cjs @@ -0,0 +1,219 @@ +// 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