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.
279 lines
7.5 KiB
Go
279 lines
7.5 KiB
Go
package gui
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/appdir"
|
|
"github.com/yetone/magpie/internal/backup"
|
|
"github.com/yetone/magpie/internal/davsync"
|
|
"github.com/yetone/magpie/internal/edit"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
// backupRoutes are the Settings page's Export and Import, and the WebDAV
|
|
// sync set up there.
|
|
func backupRoutes(mux *http.ServeMux, w Windows) {
|
|
mux.HandleFunc("POST /api/backup/export", func(rw http.ResponseWriter, r *http.Request) {
|
|
var in struct {
|
|
Pass string
|
|
Keys bool
|
|
Library *bool // nil is yes
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
b, err := backup.Collect(in.Keys, Version)
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
if in.Library != nil && !*in.Library {
|
|
b.Library = nil
|
|
}
|
|
data, err := backup.Seal(b, in.Pass)
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
dir := downloads()
|
|
name := filepath.Join(dir, "magpie-"+time.Now().Format("2006-01-02")+backup.Ext)
|
|
for i := 2; ; i++ { // never over an earlier one
|
|
if _, err := os.Stat(name); err != nil {
|
|
break
|
|
}
|
|
name = filepath.Join(dir, fmt.Sprintf("magpie-%s-%d%s", time.Now().Format("2006-01-02"), i, backup.Ext))
|
|
}
|
|
if err := edit.WriteAtomic(name, data); err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
os.Chmod(name, 0o600)
|
|
_ = w.OpenFolder(dir) // saved either way; the path is in the answer
|
|
writeJSON(rw, map[string]any{"path": tilde(name), "providers": len(b.Providers), "profiles": len(b.Profiles), "agents": len(b.Agents), "library": b.Library != nil})
|
|
})
|
|
mux.HandleFunc("POST /api/backup/import", func(rw http.ResponseWriter, r *http.Request) {
|
|
var in struct {
|
|
Data string
|
|
Pass string
|
|
Agents bool
|
|
Library *bool // nil is yes
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
data, err := base64.StdEncoding.DecodeString(in.Data)
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
b, err := backup.Open(data, in.Pass)
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
parts := backup.All
|
|
parts.Agents = in.Agents
|
|
parts.Library = in.Library == nil || *in.Library
|
|
res, err := backup.Restore(b, parts)
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
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())
|
|
})
|
|
mux.HandleFunc("POST /api/davsync/{action}", func(rw http.ResponseWriter, r *http.Request) {
|
|
// no time limit: a large backup on a slow line takes minutes (#657),
|
|
// and davsync ends a request that stops moving
|
|
ctx := r.Context()
|
|
var err error
|
|
var brought []string
|
|
switch r.PathValue("action") {
|
|
case "save": // and sync at once, so a wrong address or password shows now
|
|
var c davsync.Config
|
|
if err = json.NewDecoder(r.Body).Decode(&c); err == nil {
|
|
err = davsync.Configure(c)
|
|
}
|
|
if err != nil { // said in the form, what was typed in it kept
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
err = busy(davsync.SyncNow(ctx)) // how it went is in the status
|
|
case "now":
|
|
err = busy(davsync.SyncNow(ctx))
|
|
case "off":
|
|
err = davsync.Off()
|
|
case "dismiss":
|
|
err = davsync.Dismiss()
|
|
case "auto": // how often it syncs by itself, or never (#847)
|
|
var in struct{ Minutes int }
|
|
if err = json.NewDecoder(r.Body).Decode(&in); err == nil {
|
|
err = davsync.SetAuto(in.Minutes)
|
|
}
|
|
case "restore": // the server's setup over this computer's, which is kept
|
|
brought, err = davsync.Restore(ctx)
|
|
case "undo":
|
|
_, err = davsync.Undo()
|
|
case "upload": // this computer's setup over a server file that isn't a backup, kept first
|
|
err = davsync.Upload(ctx)
|
|
case "follow": // the agent fields kept on this computer follow the others again
|
|
err = busy(davsync.Follow(ctx))
|
|
case "reveal":
|
|
err = w.OpenFolder(filepath.Join(settings.Dir(), "sync"))
|
|
default:
|
|
http.NotFound(rw, r)
|
|
return
|
|
}
|
|
v := davsync.Status()
|
|
switch {
|
|
case errors.Is(err, davsync.ErrBusy):
|
|
// nothing ran to put it in the status: it is said there all the same
|
|
v.Error = err.Error()
|
|
case err != nil:
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
if r.PathValue("action") == "restore" { // and what it brought in: nothing when it was the same
|
|
writeJSON(rw, struct {
|
|
davsync.View
|
|
Brought []string `json:"brought"`
|
|
}{v, brought})
|
|
return
|
|
}
|
|
writeJSON(rw, v)
|
|
})
|
|
}
|
|
|
|
// 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 {
|
|
if errors.Is(err, davsync.ErrBusy) {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// downloads is where an export is saved: the Downloads folder the system
|
|
// keeps (appdir.Downloads: Windows' known folder, the XDG one on Linux,
|
|
// which 1Shin on Discord had moved off home\Downloads), else
|
|
// home\Downloads, else home when there is none.
|
|
func downloads() string {
|
|
home, _ := os.UserHomeDir()
|
|
for _, d := range []string{appdir.Downloads(), filepath.Join(home, "Downloads")} {
|
|
if d != "" && isDir(d) {
|
|
return d
|
|
}
|
|
}
|
|
return home
|
|
}
|
|
|
|
func isDir(p string) bool {
|
|
fi, err := os.Stat(p)
|
|
return err == nil && fi.IsDir()
|
|
}
|