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.
This commit is contained in:
yetone
2026-11-02 18:24:38 +08:00
parent 70b96126ef
commit 52195b6b07
16 changed files with 1558 additions and 9 deletions
+34
View File
@@ -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
+527
View File
@@ -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()
}
}
+365
View File
@@ -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)
}
}
+3
View File
@@ -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
+2
View File
@@ -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
+6
View File
@@ -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; }
+4 -5
View File
@@ -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
+142
View File
@@ -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);
}
+88
View File
@@ -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.",
+93
View File
@@ -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 {
+63
View File
@@ -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)
}
}
+3
View File
@@ -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);
+219
View File
@@ -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 <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, []);
});
}
+3 -2
View File
@@ -152,8 +152,9 @@ test("compat.js is the first of the page's own scripts", async () => {
// when a context window part is opened, resetask.js when a Codex reset's
// Use is pressed, quotaall.js when a provider has two accounts,
// quitask.js when a Quit asks first, checkinnow.js when Settings' Check
// in now for one account is pressed; the checks above still read them
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
// in now for one account is pressed, autobackup.js when Settings draws
// Sync; the checks above still read them
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
});
test("the styles hold up in Safari 15.0", async () => {
+3 -2
View File
@@ -88,8 +88,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const fit = await line.evaluate((e) => ({ sw: e.scrollWidth, cw: e.clientWidth, right: e.getBoundingClientRect().right }));
assert.ok(fit.sw <= fit.cw + 1 && fit.right <= width, `the line is shown whole: ${JSON.stringify(fit)}`);
// the import's result
const open = page.locator("#syncList .row.pref").last().locator("button");
// the import's result: Import is the last of Sync's own rows,
// Back up by itself's come after it
const open = page.locator("#syncList .row.pref:not(.auto-backup)").last().locator("button");
await reach(page, open);
await open.click();
const form = page.locator("#syncList .sync-form");
@@ -196,6 +196,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await box(lang === "zh" ? "口令" : "Passphrase").fill("correct horse");
await toEnd();
const tick = form.locator("label.tick", { hasText: w.tick });
// Back up by itself's rows under the form put the tick, at the
// page's end, under Settings' held tabs: bring it into the open
await tick.evaluate((e) => e.scrollIntoView({ block: "center" }));
assert.equal(await tick.locator("input").isChecked(), false, "off unless picked");
const top = () => p.locator("#view-settings").evaluate((v) => v.scrollTop);
const at = await top();