From 459d668b352c204b6ad8f92f9dcf49a0c9cafd36 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 13 Nov 2026 21:05:58 +0800 Subject: [PATCH] sync: pick what syncs, preview a sync, undo the last one (#6428) jinpwng (#6428, on X) syncs two computers and wants only Library and memory to go between them: each keeps its own providers, settings and models. They also want to see what a sync would change before it applies, and to roll the last one back. What syncs: providers, settings and profiles now have switches like agents' models, library and memory (Config.Providers/Settings/Profiles, *bool, nil = synced as before, so an existing setup syncs exactly what it did). The sync form shows Providers (and its API keys), Settings and Agents' models up front; Profiles, usage and sign-ins sit under Advanced, closed unless one is set away from its default. The form sends a part's choice only when it is or was off. A part left out stays as it is here and on the server; turning it back on joins it like a first sync (st.Off, rejoin). The sync's line says which parts each computer keeps ("Stays as it is on each computer: ..."). The setup text and the CLI carry it: magpie set providers=no settings=no profiles=no. Preview: davsync.Preview (plan.go) says, per part, what syncing now would bring in, send up, or leave; library items and memory files by name, sign-ins and plugins gone. Preview... in Settings > Sync shows it, and Sync now from there runs SyncPreviewed(token): if the server or this computer changed since, it says so and shows the new plan instead of syncing something else. CLI: magpie preview. Undo: a sync that brings parts in records them (st.Applied) and keeps a sealed copy of this computer first (keepSealed, as Restore does). Undo the last sync puts those parts back from that copy, on this computer only (st.Local, so the next sync sends it up rather than fetching the server's again). If one of them changed here since, it asks first (409 changed, Undo anyway). CLI: magpie undo-sync [anyway]. Restore's own Undo is unchanged. docs/subsystems/sync-backup.md and the site's sync docs (en, zh, ja) have a section on it. i18n: zh, zh-TW, ja, de. Run (worktree at base 48e394146): - go test -count=1 . ./internal/davsync ./internal/cli: ok (mote). Broken by hand, each went red: syncs() forced true (scope tests), rejoin's again forced false, UndoSync without the st.Local update. - go test -count=1 ./internal/gui: TestCoreScriptBudget was over by 85 bytes; the sync-left line moved into syncfiles.js, now ok. - go vet ./internal/gui, GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok. gofmt -l: nothing. - node --check app.js, syncfiles.js, sync-scope.test.cjs: ok. - GUI (mica), every test file that opens Settings > Sync or calls davsync (22 files) plus i18n-keys, Chromium and WebKit, 1100 and 420px, en/zh/zh-TW/ja/de: 453 of 454 pass. The red is s3-sync webkit en "picking S3 must not scroll the page" (0 !== 98), the same on origin/main 52c9880cb (#3413, #2448). An earlier run also had library-new-skill chromium en 420 red, the same on main (#6539). sync-scope.test.cjs is new: on the old code there is no Providers switch, Preview or Undo, so it fails at once. - Rebased on origin/main 7eecbcc56 (app.js and i18n.js changed there): TestCoreScriptBudget, go test . ./internal/davsync, node --check, and i18n-keys, sync-scope, webdav-settings-refresh (both engines): ok. - The full go test ./... was started through mote's suite lock when this was pushed; its result goes on #6428. Not tried: a real WebDAV, S3 or GitHub server (the tests use fakes); the real app on Linux WebKitGTK. "Save and sync" from the form, after a preview, syncs without the preview's token check. --- docs/subsystems/sync-backup.md | 55 ++- internal/cli/webdav_cli.go | 147 +++++- internal/cli/webdav_cli_test.go | 13 + internal/davsync/davsync.go | 150 ++++++- internal/davsync/plan.go | 425 ++++++++++++++++++ internal/davsync/restore.go | 84 +++- internal/davsync/scope_test.go | 313 +++++++++++++ internal/davsync/setuptext.go | 28 +- internal/davsync/setuptext_test.go | 20 + internal/gui/assets/app.css | 9 +- internal/gui/assets/app.js | 15 +- internal/gui/assets/i18n.js | 143 +++++- internal/gui/assets/syncfiles.js | 223 ++++++++- internal/gui/backup.go | 37 ++ internal/gui/tests/github-sync.test.cjs | 2 +- internal/gui/tests/s3-sync.test.cjs | 6 +- internal/gui/tests/sync-scope.test.cjs | 222 +++++++++ internal/gui/tests/sync-signins.test.cjs | 3 + internal/gui/tests/usage-computers.test.cjs | 9 +- .../tests/webdav-settings-refresh.test.cjs | 6 +- internal/provider/signins_carry.go | 9 + site/public/docs/ja/sync.html | 6 + site/public/docs/sync.html | 6 + site/public/docs/zh/sync.html | 6 + 24 files changed, 1850 insertions(+), 87 deletions(-) create mode 100644 internal/davsync/plan.go create mode 100644 internal/davsync/scope_test.go create mode 100644 internal/gui/tests/sync-scope.test.cjs diff --git a/docs/subsystems/sync-backup.md b/docs/subsystems/sync-backup.md index 5fa1b9c6a..7f1916aed 100644 --- a/docs/subsystems/sync-backup.md +++ b/docs/subsystems/sync-backup.md @@ -21,8 +21,11 @@ clone a working tree or synchronize arbitrary files. branch or using the repository's default. - [`backup.go`](../../internal/backup/backup.go) owns bundle contents and sealing. Sync divides the setup into providers, settings, profiles, agents - and library. Provider keys, agent models, library and usage have their own - inclusion switches. + and library. Each part, provider keys, memory, usage and sign-ins have + their own inclusion switches (`Config.syncs`). +- [`plan.go`](../../internal/davsync/plan.go) previews a sync (`Preview`, + `PreviewWith`), runs the one previewed (`SyncPreviewed`) and undoes the + last sync that brought parts in (`UndoSync`). - [`usage.go`](../../internal/davsync/usage.go) shares separately sealed usage and quota files through a remote's `files` interface. - [`restore.go`](../../internal/davsync/restore.go) replaces local parts from @@ -196,6 +199,54 @@ 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. +## What syncs, preview and undo + +#6428 (jinpwng on X): sync only the library and memory, keep each +computer's providers, settings and models, see what a sync changes before +it does, and take it back. + +- **What syncs.** `Config.Providers`, `Settings` and `Profiles` are + `*bool`, nil meaning synced, so a `sync.json` from before the choice + syncs every part as it did. `Agents`, `Library`, `Memory`, `Usage` and + `SignIns` were switches already. A part left out (`Config.syncs` false) + is neither read from nor written to the file: this computer keeps its + own, the server keeps the others' (a first computer puts none of it up, + which a joining one reads as `unset`). The Settings form shows + Providers (with their API keys under it), Settings, Agents' models, + Library and Memory; Profiles, Usage and Sign-ins sit under a folded + Advanced, open when one of them is set away from its default. The form + sends a part's choice only when it is off or was off, so saving an old + setup leaves it nil. The setup text carries the choice, and the CLI's + `set providers=no settings=no profiles=no` sets it. The Sync row says + which parts stay on each computer (`sync-left`). +- **Turned back on.** `state.Off` is the parts the last sync left out. One + turned back on is joined like a first sync (`rejoin`, `again` in + `syncOnce`): the server's comes here, this computer's kept in the sync + folder, and an `unset` one on the server leaves this computer's + (`TestSyncPartTurnedBackOn`). +- **Preview.** `syncOnce` with a `*Plan` runs the same merge and returns + before any write, here or on the server. A part's plan says `in`, `up`, + `same` or `off`, whether it replaces a change made here (`replaces`), and + its items added, removed or changed; memory, sign-ins and plugins removed + by another computer are counted. `Plan.Token` hashes what the sync would + do; `SyncPreviewed(token)` runs only while a new plan has the same token, + else `ErrPlanChanged` and the GUI shows the new plan. A preview from the + form (`PreviewWith`) is of the unsaved setup, and its Save and sync is + the form's ordinary save, without a token. Reached by Settings → Sync → + Preview a sync, the form's Preview, `/api/davsync/preview`, + `/api/davsync/sync-previewed` and `magpie preview`. +- **Undo.** A sync that brings parts in keeps this computer's setup first + (`keepSealed`, as a join does) and records `state.Applied`. `UndoSync` + puts those parts back from that file, after keeping what is here now. + A part changed here since the sync is `*ChangedSince` (HTTP 409 with + `changed`), written over only with `force` (Undo anyway, `undo-sync + anyway`). The undo stays on this computer: `state.Local` is set to the + undone parts' hashes, so the next sync sends nothing and the server keeps + the others' (`TestUndoSync`). A change made here later is an ordinary + local change, and that whole part goes up. `/api/davsync/undo-sync`, + Settings → Sync → Undo the last sync, `magpie undo-sync`. + Restore's Undo (`davsync/undo`) is unchanged: it undoes a Restore. + ## Backups by themselves [`auto.go`](../../internal/backup/auto.go) writes the setup into a folder on diff --git a/internal/cli/webdav_cli.go b/internal/cli/webdav_cli.go index 071eb4c6f..2f0a7ddd3 100644 --- a/internal/cli/webdav_cli.go +++ b/internal/cli/webdav_cli.go @@ -25,9 +25,12 @@ const webdavUsage = `usage: the same on every computer through a WebDAV folder (a folder named magpie is made in it), and sync at once; asks for the password (with a user) and the passphrase - magpie webdav set k=v… change it: address, user, keys, agents, library, usage, sign-ins (yes|no); + magpie webdav set k=v… change it: address, user, providers, settings, profiles, keys, agents, + library, memory, usage, sign-ins (yes|no); password= and passphrase= ask for a new one magpie webdav now sync now (the gateway also syncs by itself while it runs: see auto) + magpie webdav preview what syncing now would change, here and on the server; nothing is changed + magpie webdav undo-sync [anyway] put back what the last sync brought in, on this computer only magpie webdav auto off|3|15|30|60 how often the gateway syncs by itself, in minutes; off: only when asked magpie webdav follow on|off on: this computer takes the server's setup on every sync and sends none of its own; a change made here is replaced, a copy kept in the @@ -47,6 +50,9 @@ const webdavUsage = `usage: again; user= alone for a server that asks for no sign-in. An app password where the server has them keys no: providers go without their API keys, and each computer keeps its own + providers, settings, profiles, agents, library, memory + no: that part stays as it is on each computer, never brought in nor sent up; e.g. + providers=no settings=no profiles=no agents=no syncs only the library and memory usage yes: this computer's usage goes up too, a file a day, sealed, and the Usage page counts the other computers' that share theirs, each named sign-ins yes: the subscriptions' accounts and the plugins' sign-ins go too, sealed with the @@ -74,9 +80,12 @@ const s3Usage = `usage: Cloudflare R2, Backblaze B2, MinIO, a NAS…), in /magpie/, and sync at once; asks for the secret and the passphrase magpie s3 set k=v… change it: address, bucket, prefix, endpoint, region, access-key-id, - path-style, keys, agents, library, usage, sign-ins (yes|no); secret= and + path-style, providers, settings, profiles, keys, agents, library, memory, + usage, sign-ins (yes|no); secret= and passphrase= ask for a new one magpie s3 now sync now (the gateway also syncs by itself while it runs: see auto) + magpie s3 preview what syncing now would change, here and on the server; nothing is changed + magpie s3 undo-sync [anyway] put back what the last sync brought in, on this computer only magpie s3 auto off|3|15|30|60 how often the gateway syncs by itself, in minutes; off: only when asked magpie s3 follow on|off on: this computer takes the server's setup on every sync and sends none of its own; a change made here is replaced, a copy kept in the @@ -98,6 +107,8 @@ const s3Usage = `usage: only used with the endpoint and access key it was given for: change either and it is asked for again keys no: providers go without their API keys, and each computer keeps its own + providers, settings, profiles, agents, library, memory + no: that part stays as it is on each computer, never brought in nor sent up usage yes: this computer's usage goes up too, a file a day, sealed, and the Usage page counts the other computers' that share theirs, each named sign-ins yes: the subscriptions' accounts and the plugins' sign-ins go too, sealed with the @@ -118,8 +129,11 @@ const githubUsage = `usage: magpie github whether sync is on, where to, and how the last sync went magpie github on github://owner/repo[/folder] [branch=…] [keys=no] [agents=no] [library=no] keep the encrypted setup in an existing GitHub repository; asks for a token and passphrase - magpie github set k=v… change it: address, branch, keys, agents, library, usage, sign-ins (yes|no) + magpie github set k=v… change it: address, branch, providers, settings, profiles, keys, agents, + library, memory, usage, sign-ins (yes|no) magpie github now sync now + magpie github preview what syncing now would change, here and on the server; nothing is changed + magpie github undo-sync [anyway] put back what the last sync brought in, on this computer only magpie github auto off|3|15|30|60 how often the gateway syncs by itself, in minutes magpie github follow on|off on: this computer takes the repository's setup and sends none of its own magpie github restore make this computer's setup the repository's; what is here is kept first @@ -136,6 +150,8 @@ const githubUsage = `usage: passphrase the same on every computer; GitHub only ever receives the sealed file. sign-ins yes: the subscriptions' accounts and the plugins' sign-ins go too, sealed with the passphrase. Off unless set + providers, settings, profiles, agents, library, memory + no: that part stays as it is on each computer, never brought in nor sent up ` // syncKind is magpie webdav's, magpie s3's or magpie github's server. @@ -226,6 +242,34 @@ func syncCmd(k syncKind, args []string) error { fmt.Printf("put back: %s\n", strings.Join(parts, ", ")) } return nil + case "preview": + if _, ok := davsync.Load(); !ok { + return fmt.Errorf("%s sync is off: %s", k.name, k.turnOn()) + } + p, err := davsync.Preview(context.Background()) + if err != nil { + return err + } + printPlan(p, k) + return nil + case "undo-sync": + if _, ok := davsync.Load(); !ok { + return fmt.Errorf("%s sync is off: %s", k.name, k.turnOn()) + } + force := len(args) == 2 && args[1] == "anyway" + if len(args) > 2 || len(args) == 2 && !force { + return fmt.Errorf("magpie %s undo-sync [anyway]", k.cmd) + } + parts, err := davsync.UndoSync(force) + var since *davsync.ChangedSince + if errors.As(err, &since) { + return fmt.Errorf("%s changed here since that sync: magpie %s undo-sync anyway puts back what was there before it, a copy of now kept first", partNames(since.Parts), k.cmd) + } + if err != nil { + return err + } + fmt.Printf("put back as before the last sync, on this computer only: %s\n", partNames(parts)) + return nil case "upload": if _, ok := davsync.Load(); !ok { return fmt.Errorf("%s sync is off: %s", k.name, k.turnOn()) @@ -273,7 +317,8 @@ func syncSet(k syncKind, args []string, on bool) error { if !on { return fmt.Errorf("%s sync is on, not %s: magpie %s set changes it; %s", c.Kind(), k.name, strings.ToLower(c.Kind()), k.turnOn()) } - next := davsync.Config{Passphrase: c.Passphrase, Keys: c.Keys, Agents: c.Agents, Library: c.Library, Usage: c.Usage, SignIns: c.SignIns} + next := davsync.Config{Passphrase: c.Passphrase, Keys: c.Keys, Agents: c.Agents, Library: c.Library, Memory: c.Memory, Usage: c.Usage, SignIns: c.SignIns, + Providers: c.Providers, Settings: c.Settings, Profiles: c.Profiles} if o, ok := c.Kept(k.name); ok { // its server, as it was kept when sync moved from it next.URL, next.User, next.Endpoint, next.Region, next.PathStyle, next.Branch = o.URL, o.User, o.Endpoint, o.Region, o.PathStyle, o.Branch } @@ -326,7 +371,8 @@ func syncSet(k syncKind, args []string, on bool) error { } else { askPhrase = true } - case key == "keys", key == "agents", key == "library", key == "usage", key == "sign-ins", key == "path-style" && k.cmd == "s3": + case key == "keys", key == "agents", key == "library", key == "usage", key == "sign-ins", key == "path-style" && k.cmd == "s3", + key == "providers", key == "settings", key == "profiles", key == "memory": if v != "yes" && v != "no" { return fmt.Errorf("%s=yes|no, not %q", key, v) } @@ -342,15 +388,23 @@ func syncSet(k syncKind, args []string, on bool) error { c.Usage = yes case "sign-ins": c.SignIns = yes + case "providers": + c.Providers = &yes + case "settings": + c.Settings = &yes + case "profiles": + c.Profiles = &yes + case "memory": + c.Memory = &yes default: c.Library = &yes } case k.cmd == "s3": - return fmt.Errorf("unknown field %q (address, bucket, prefix, endpoint, region, access-key-id, secret, passphrase, path-style, keys, agents, library, usage, sign-ins)", key) + return fmt.Errorf("unknown field %q (address, bucket, prefix, endpoint, region, access-key-id, secret, passphrase, path-style, providers, settings, profiles, keys, agents, library, memory, usage, sign-ins)", key) case k.cmd == "github": - return fmt.Errorf("unknown field %q (address, branch, token, passphrase, keys, agents, library, usage, sign-ins)", key) + return fmt.Errorf("unknown field %q (address, branch, token, passphrase, providers, settings, profiles, keys, agents, library, memory, usage, sign-ins)", key) default: - return fmt.Errorf("unknown field %q (address, user, password, passphrase, keys, agents, library, usage, sign-ins)", key) + return fmt.Errorf("unknown field %q (address, user, password, passphrase, providers, settings, profiles, keys, agents, library, memory, usage, sign-ins)", key) } } if bucket != nil || prefix != nil { @@ -505,17 +559,27 @@ func syncShow(k syncKind) error { fmt.Println(bold.Render("WebDAV sync"), v.URL, muted.Render(strings.Join(who, " · "))) } - what := []string{"providers without their API keys"} - if v.Keys { - what[0] = "providers with their API keys" + var what []string + if v.Providers && v.Keys { + what = append(what, "providers with their API keys") + } else if v.Providers { + what = append(what, "providers without their API keys") + } + if v.Settings { + what = append(what, "settings") + } + if v.Profiles { + what = append(what, "profiles") } - what = append(what, "settings", "profiles") if v.Agents { what = append(what, "agents' models") } if v.Library { what = append(what, "library") } + if v.Memory { + what = append(what, "memory") + } if v.Usage { what = append(what, "usage") } @@ -523,6 +587,9 @@ func syncShow(k syncKind) error { what = append(what, "sign-ins") } fmt.Println(" syncs", strings.Join(what, ", ")) + if left := leftOut(v); len(left) > 0 { + fmt.Println(muted.Render(" stays as it is on each computer: " + strings.Join(left, ", "))) + } if o := v.Other; o != nil { if o.Kind == "s3" { fmt.Println(muted.Render(" S3 " + o.URL + " is kept, not synced to: magpie s3 on moves back to it")) @@ -565,6 +632,9 @@ func syncShow(k syncKind) error { } fmt.Println(muted.Render(" The copies replaced are kept in " + tilde(dir) + " (magpie restore opens one; magpie " + cmd + " dismiss clears this)")) } + if a := v.Applied; a != nil { + fmt.Println(muted.Render(" The last sync brought in " + partNames(a.Parts) + " " + syncWhen(a.At) + " (magpie " + cmd + " undo-sync puts back what was here)")) + } if v.FollowServer { fmt.Println(" follows the server: takes its setup, sends none of its own (magpie " + cmd + " follow off syncs both ways)") } @@ -586,6 +656,59 @@ func syncWhen(t time.Time) string { return t.Format("2006-01-02 15:04") } +// leftOut is the parts v doesn't sync, as Settings names them. +func leftOut(v davsync.View) []string { + var out []string + for _, p := range []struct { + on bool + name string + }{{v.Providers, "providers"}, {v.Settings, "settings"}, {v.Profiles, "profiles"}, {v.Agents, "agents' models"}, {v.Library, "library"}, {v.Memory, "memory"}} { + if !p.on { + out = append(out, p.name) + } + } + return out +} + +// printPlan says what a sync would do now. +func printPlan(p davsync.Plan, k syncKind) { + if p.Empty { + fmt.Println("The server has no file yet: this computer's setup goes up.") + return + } + do := map[string]string{"in": "comes in from the server", "up": "goes up to the server", "same": "the same on both", "off": "not synced: stays as it is here"} + changes := 0 + for _, pp := range p.Parts { + line := " " + partNames([]string{pp.Part}) + ": " + do[pp.Do] + if pp.Replaces { + line += ", replacing a change made here (a copy is kept)" + } + fmt.Println(line) + if pp.Do == "in" || pp.Do == "up" { + changes++ + } + for _, it := range pp.Items { + fmt.Println(muted.Render(" " + it.Change + " " + it.Kind + " " + it.Name)) + } + } + if m := p.Memory; m != nil { + fmt.Printf(" memory: %d in, %d up\n", m.In, m.Up) + changes++ + } + if p.SignIns > 0 { + fmt.Printf(" sign-ins: %d change here\n", p.SignIns) + changes++ + } + if len(p.PluginsGone) > 0 { + fmt.Println(" plugins removed here, as another computer removed them:", strings.Join(p.PluginsGone, ", ")) + } + if changes == 0 { + fmt.Println(muted.Render(" nothing would change")) + } else { + fmt.Println(muted.Render(" magpie " + k.cmd + " now syncs; magpie " + k.cmd + " undo-sync puts back what it brought in")) + } +} + // partNames are davsync's parts, as Settings names them. func partNames(ps []string) string { names := map[string]string{"agents": "agents' models"} diff --git a/internal/cli/webdav_cli_test.go b/internal/cli/webdav_cli_test.go index 67c942d06..e4ac7488a 100644 --- a/internal/cli/webdav_cli_test.go +++ b/internal/cli/webdav_cli_test.go @@ -162,6 +162,19 @@ func TestWebdavCmd(t *testing.T) { if c, _ := davsync.Load(); c.Agents || c.Keys || c.Password != "pw" || c.Passphrase != "correct horse" || c.URL != first.url { t.Fatalf("set: %+v", c) } + // providers and settings can stay as they are on each computer (#6428) + if err := webdavCmd([]string{"set", "providers=no", "settings=no"}); err != nil { + t.Fatal(err) + } + if c, _ := davsync.Load(); c.Providers == nil || *c.Providers || c.Settings == nil || *c.Settings || c.Profiles != nil { + t.Fatalf("set providers=no settings=no: %+v", c) + } + if err := webdavCmd([]string{"set", "providers=yes", "settings=yes"}); err != nil { + t.Fatal(err) + } + if c, _ := davsync.Load(); c.Providers != nil && !*c.Providers { + t.Fatalf("set providers=yes: %+v", c) + } // an address with = in it, bare: the same server, so the password stays if err := webdavCmd([]string{"set", first.url + "?k=v"}); err != nil { t.Fatal(err) diff --git a/internal/davsync/davsync.go b/internal/davsync/davsync.go index 7e2038fd4..cb54e7577 100644 --- a/internal/davsync/davsync.go +++ b/internal/davsync/davsync.go @@ -87,6 +87,14 @@ type Config struct { Branch string `json:"branch,omitempty"` Keys bool `json:"keys"` // providers carry their API keys Agents bool `json:"agents"` // the agents' models go too + // Providers, Settings and Profiles are whether each of those parts + // goes; nil, as in a setup made before they could be left out, is yes. + // A part left out stays as it is on each computer (jinpwng on X, + // #6428: only the library and memory synced, each computer keeping its + // own providers, settings and models). + Providers *bool `json:"providers,omitempty"` + Settings *bool `json:"settings,omitempty"` + Profiles *bool `json:"profiles,omitempty"` // Library is whether the library goes too; nil, as in a setup made // before it could, is yes Library *bool `json:"library,omitempty"` @@ -186,6 +194,9 @@ func (c Config) library() bool { return c.Library == nil || *c.Library } func (c Config) memoryOn() bool { return c.Memory == nil || *c.Memory } +// yes is a part's choice, nil (a setup from before it could be made) yes. +func yes(b *bool) bool { return b == nil || *b } + // S3 is whether c keeps the file in an S3 bucket rather than a WebDAV folder. func (c Config) S3() bool { return strings.HasPrefix(strings.ToLower(strings.TrimSpace(c.URL)), "s3://") @@ -271,6 +282,12 @@ type state struct { // goes from the other (pluginPlan). Nil when not known (never synced // with them, or a blind write went over), when none is taken for removed. Plugins []string `json:"plugins,omitempty"` + // Off is the parts the last sync left out (Config.syncs): one synced + // again since is joined again, each side's own as on a first sync, + // rather than taken as unchanged on both sides while they differ. + Off []string `json:"off,omitempty"` + // Applied is the last sync that brought parts in here, for UndoSync. + Applied *applied `json:"applied,omitempty"` } // blind is a write the server didn't check: the file it wrote (Sum), and @@ -496,7 +513,7 @@ func Off() error { os.Remove(path("sync-state.json")) os.Remove(path(cacheName)) } else { - st.Error, st.Notice, st.Undo, st.Usage = "", nil, "", nil + st.Error, st.Notice, st.Undo, st.Usage, st.Applied = "", nil, "", nil, nil saveState(st) } usage.DropAllShared() // the others' usage came by sync: it goes with it (#542) @@ -524,6 +541,9 @@ type View struct { Branch string `json:"branch,omitempty"` Library bool `json:"library"` Memory bool `json:"memory"` + Providers bool `json:"providers"` + Settings bool `json:"settings"` + Profiles bool `json:"profiles"` Usage bool `json:"usage,omitempty"` SignIns bool `json:"signIns,omitempty"` // UsageError is why usage couldn't be shared the last time it was tried @@ -543,6 +563,9 @@ type View struct { FollowServer bool `json:"followServer,omitempty"` // Undo is whether the last Restore can be undone Undo bool `json:"undo,omitempty"` + // Applied is the last sync that brought parts in here, which + // UndoSync takes back on this computer + Applied *Applied `json:"applied,omitempty"` // File is what the server holds instead of a backup, when Error is // that it isn't one; File.Replace offers Upload File *ServerFile `json:"serverFile,omitempty"` @@ -571,16 +594,20 @@ type OtherView struct { func Status() View { c, ok := Load() if !ok { - return View{Keys: true, Agents: true, Library: true, Memory: true} + return View{Keys: true, Agents: true, Library: true, Memory: true, Providers: true, Settings: true, Profiles: true} } st := loadState() v := View{On: true, URL: c.URL, User: c.User, PasswordSet: c.Password != "", PassphraseSet: c.Passphrase != "", Keys: c.Keys, Agents: c.Agents, Library: c.library(), Memory: c.memoryOn(), Error: st.Error, Notice: st.Notice, + Providers: c.syncs("providers"), Settings: c.syncs("settings"), Profiles: c.syncs("profiles"), Kind: strings.ToLower(c.Kind()), Endpoint: c.Endpoint, Region: c.Region, PathStyle: c.PathStyle, Branch: c.Branch, Auto: int(c.auto() / time.Minute), FollowServer: c.FollowServer} if st.Key == stateKey(c) { v.Last = st.Last v.Undo = st.Undo != "" && isFile(st.Undo) + if a := st.Applied; a != nil && isFile(a.File) { + v.Applied = &Applied{At: a.At, Parts: a.Parts} + } if st.Error != "" { v.File = st.File } @@ -717,12 +744,22 @@ var mu sync.Mutex // Now syncs once; nothing when sync is off. Usage is shared at most every // usageEvery. -func Now(ctx context.Context) error { return syncNow(ctx, false) } +func Now(ctx context.Context) error { return syncNow(ctx, false, "") } // SyncNow is Now asked for: usage is shared whatever the time. -func SyncNow(ctx context.Context) error { return syncNow(ctx, true) } +func SyncNow(ctx context.Context) error { return syncNow(ctx, true, "") } -func syncNow(ctx context.Context, force bool) error { +// SyncPreviewed is SyncNow for what Preview told, its Token: when the +// sync would now do anything else, nothing is done, and it is +// ErrPlanChanged. +func SyncPreviewed(ctx context.Context, token string) error { + if token == "" { + return errors.New("no preview to sync") + } + return syncNow(ctx, true, token) +} + +func syncNow(ctx context.Context, force bool, expect string) error { if _, ok := Load(); !ok { // off: no lock taken, so none made return nil } @@ -747,9 +784,18 @@ func syncNow(ctx context.Context, force bool) error { if st.Key != stateKey(c) { // another folder or passphrase: start afresh st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own, Follow: st.Follow, Here: st.Here} } - err = syncOnce(ctx, c, &st) + if expect != "" { // what the user saw previewed, or nothing + p, err := preview(ctx, c, st) + if err != nil { + return err + } + if p.Token != expect { + return ErrPlanChanged + } + } + err = syncOnce(ctx, c, &st, nil) if errors.Is(err, errChanged) { // another computer got in between: again, over its version - err = syncOnce(ctx, c, &st) + err = syncOnce(ctx, c, &st, nil) } st.Error, st.File = "", nil var nb *notBackup @@ -888,12 +934,7 @@ func hashes(b backup.Bundle) map[string]string { settingsHash = h([]any{s, *b.GatewayKeys, *b.AccountGroups}) } } - ps := slices.Clone(b.Providers) - for i := range ps { // this computer's own: kept by Mirror, never synced - ps[i].KeepLogin, ps[i].KeepLoginAs, ps[i].SwitchOnly, ps[i].RestartApp = false, "", false, false - ps[i].KeepSelf = false - } - providers := []any{ps, b.Icons, b.Groups} + providers := []any{syncedProviders(b.Providers), b.Icons, b.Groups} if b.Searches != nil && len(*b.Searches) > 0 { // as before them, without one providers = append(providers, *b.Searches) } @@ -936,6 +977,17 @@ func hashes(b backup.Bundle) map[string]string { return out } +// syncedProviders is ps as they are compared: this computer's own fields, +// kept by Mirror and never synced, left out. +func syncedProviders(ps []provider.Provider) []provider.Provider { + ps = slices.Clone(ps) + for i := range ps { + ps[i].KeepLogin, ps[i].KeepLoginAs, ps[i].SwitchOnly, ps[i].RestartApp = false, "", false, false + ps[i].KeepSelf = false + } + return ps +} + // unset says whether b holds nothing of its own in part p: no provider // or routing group, settings as a new magpie has them, no profile, a // library with nothing in it. A computer joining a folder whose file's @@ -1233,7 +1285,10 @@ func keepUnseenGatewayKeys(remote *backup.Bundle, local backup.Bundle) { } } -func syncOnce(ctx context.Context, c Config, st *state) error { +// syncOnce syncs once. With pv, it is a preview: the server's file is +// read whole, what the sync would do is told in pv, and nothing is changed +// here or on the server. +func syncOnce(ctx context.Context, c Config, st *state, pv *Plan) error { d, err := newRemote(c) if err != nil { return err @@ -1281,8 +1336,15 @@ func syncOnce(ctx context.Context, c Config, st *state) error { moved := !slices.Equal(kept, st.Here) keep, afterW := withHere(own, kept), withHere(after, kept) L := hashesOwn(local, prev) + // parts left out at the last sync and synced now: joined again + var rejoin []string + for _, p := range st.Off { + if slices.Contains(Parts, p) && c.syncs(p) { + rejoin = append(rejoin, p) + } + } if unchanged { - if maps.Equal(L, st.Local) && !follow && !moved { + if maps.Equal(L, st.Local) && !follow && !moved && len(rejoin) == 0 { return nil // nothing changed on either side } // changed here: merged with the server's file as last seen, or, @@ -1318,8 +1380,16 @@ func syncOnce(ctx context.Context, c Config, st *state) error { if data == nil && c.FollowServer { return errNothingToFollow } + if data == nil && pv != nil { + pv.Empty = true + for _, p := range c.Synced() { + pv.Parts = append(pv.Parts, PartPlan{Part: p, Do: "up"}) + } + return nil + } if data == nil { // nothing there yet: this computer's setup is the first - if err := push(local, "", blind{}); err != nil { + // the parts not synced go as unset, never this computer's (only) + if err := push(c.only(local), "", blind{}); err != nil { return err } st.Own, st.Here = after, kept @@ -1328,10 +1398,14 @@ func syncOnce(ctx context.Context, c Config, st *state) error { if c.SignIns { st.SignIns = local.SignIns.Hashes() } - st.Plugins = pluginNames(local.Plugins) + st.Plugins = nil + if c.syncs("providers") { + st.Plugins = pluginNames(local.Plugins) + } + st.Off = c.left() return nil } - if sum(data) == st.Sum && maps.Equal(L, st.Local) && !follow && !moved { + if sum(data) == st.Sum && maps.Equal(L, st.Local) && !follow && !moved && len(rejoin) == 0 { st.Server = ver remember(data) return nil // nothing changed on either side @@ -1364,7 +1438,7 @@ func syncOnce(ctx context.Context, c Config, st *state) error { // survive the way they would on any sync. // A computer following the server never writes it, a rebuild // included: the computer it follows, or Upload, replaces the file. - if !errors.Is(err, backup.ErrCorrupt) || st.Local == nil || c.FollowServer { + if !errors.Is(err, backup.ErrCorrupt) || st.Local == nil || c.FollowServer || pv != nil { return described(c, data, err) } good := cached(st.Sum) // the version this computer last read whole @@ -1402,7 +1476,11 @@ func syncOnce(ctx context.Context, c Config, st *state) error { first := st.Local == nil // plugins removed on one side since the last sync: gone from the other // too, and not brought back by the part that carries them - goneHere, goneThere := pluginPlan(st.Plugins, local.Plugins, remote.Plugins) + // providers not synced: their plugins neither (they ride that part) + var goneHere, goneThere []string + if c.syncs("providers") { + goneHere, goneThere = pluginPlan(st.Plugins, local.Plugins, remote.Plugins) + } if len(goneHere) > 0 && remote.Plugins != nil { kept := without(*remote.Plugins, goneHere) remote.Plugins = &kept @@ -1410,7 +1488,7 @@ func syncOnce(ctx context.Context, c Config, st *state) error { merged := remote var bringIn, here, there []string for _, p := range Parts { - if L[p] == R[p] || (p == "agents" && !c.Agents) || (p == "library" && !c.library()) { + if L[p] == R[p] || !c.syncs(p) { continue } if p == "library" && remote.Library == nil { // from a magpie before the library went: this computer's goes up @@ -1419,12 +1497,22 @@ func syncOnce(ctx context.Context, c Config, st *state) error { } lc := !first && L[p] != st.Local[p] rc := first || R[p] != st.Remote[p] + again := !first && slices.Contains(rejoin, p) + if again { + // synced again after it was left out: each side's own counts + // as changed there, as on joining; a side with none of its own + // takes the other's (#5642), both with some, the newer stays + lc, rc = !unset(local, p), !unset(remote, p) + if !lc && !rc { + lc, rc = true, true + } + } if c.FollowServer { // following the server: what changed on either side is the // server's, a change here kept aside first. A part the server's // file holds nothing of on joining is left as it is here // (#5642): nothing has been set there to follow yet. - if remote.Library == nil && p == "library" || first && unset(remote, p) && !unset(local, p) { + if remote.Library == nil && p == "library" || (first || again) && unset(remote, p) && !unset(local, p) { continue } if lc || rc { @@ -1472,6 +1560,9 @@ func syncOnce(ctx context.Context, c Config, st *state) error { } } } + if pv != nil { + return previewed(pv, c, local, remote, merged, bringIn, here, there, goneThere, st.SignIns) + } var saved string if len(here)+len(there) > 0 { dir := path("sync") @@ -1487,6 +1578,15 @@ func syncOnce(ctx context.Context, c Config, st *state) error { } saved = dir } + // what is here before the server's parts come in, sealed with the + // keys, for UndoSync; a copy that can't be kept stops nothing + var before string + if len(bringIn) > 0 { + var err error + if before, err = keepSealed(c, "before-sync"); err != nil { + log.Printf("sync: keeping this computer's setup before bringing in %v: %v", bringIn, err) + } + } for _, p := range bringIn { if p == "agents" { got, err := bringAgents(remote.Agents, afterW) @@ -1597,12 +1697,16 @@ func syncOnce(ctx context.Context, c Config, st *state) error { } } st.Local = now + st.Off = c.left() + if before != "" { + st.Applied = &applied{At: time.Now(), Parts: bringIn, File: before, After: now} + } st.SignIns = nil if c.SignIns { st.SignIns = bothSides(shared, local.SignIns.Hashes()) } st.Plugins = nil - if merged.Plugins != nil { + if merged.Plugins != nil && c.syncs("providers") { // on both sides now; a removal that failed here stays known, so // the next sync tries it again both := slices.DeleteFunc(pluginNames(local.Plugins), func(n string) bool { diff --git a/internal/davsync/plan.go b/internal/davsync/plan.go new file mode 100644 index 000000000..3a7ba7d77 --- /dev/null +++ b/internal/davsync/plan.go @@ -0,0 +1,425 @@ +package davsync + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "maps" + "os" + "slices" + "strconv" + "time" + + "github.com/yetone/magpie/internal/backup" + "github.com/yetone/magpie/internal/memory" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// applied is the last sync that brought parts in from the server (#6428): +// which, the copy of this computer kept before (keepSealed), and the +// parts' hashes right after, so UndoSync can tell a change made since. +type applied struct { + At time.Time `json:"at"` + Parts []string `json:"parts"` + File string `json:"file"` + After map[string]string `json:"after,omitempty"` +} + +// Applied is what Status tells of the last sync that brought parts in, +// while its copy is there to undo it. +type Applied struct { + At time.Time `json:"at"` + Parts []string `json:"parts"` +} + +// Plan is what a sync would do now (Preview), nothing done. +type Plan struct { + // Empty: the server has no file yet, and this computer's goes up. + Empty bool `json:"empty,omitempty"` + // Follow: this computer follows the server, never writing it. + Follow bool `json:"follow,omitempty"` + Parts []PartPlan `json:"parts"` + // Memory is how many memories come in here and go up, by id. + Memory *MemoryPlan `json:"memory,omitempty"` + // SignIns is how many sign-ins change here, when they sync. + SignIns int `json:"signIns,omitempty"` + // PluginsGone are the plugins removed here because another computer + // removed them. + PluginsGone []string `json:"pluginsGone,omitempty"` + // Token tells this plan from another: SyncPreviewed syncs only while + // the sync would still do what it says. + Token string `json:"token"` +} + +// PartPlan is what a sync would do with one part. +type PartPlan struct { + Part string `json:"part"` + // Do is "in" (the server's comes in here), "up" (this computer's goes + // to the server), "same", or "off" (not synced: stays as it is here). + Do string `json:"do"` + // Replaces: a change made here too is replaced, a copy kept first. + Replaces bool `json:"replaces,omitempty"` + Items []Item `json:"items,omitempty"` +} + +// Item is one thing in a part that the sync adds, removes or changes on +// the side it writes. Only names: never a value, which may be a key. +type Item struct { + Kind string `json:"kind"` + Name string `json:"name"` + Change string `json:"change"` // added, removed, changed +} + +// MemoryPlan counts the memories a sync would change on each side. +type MemoryPlan struct { + In int `json:"in"` + Up int `json:"up"` +} + +// ErrPlanChanged is SyncPreviewed's when the sync would now do something +// other than the preview said: something changed here or on the server. +var ErrPlanChanged = errors.New("something changed since the preview: look at it again before syncing") + +// Preview is what syncing now would do, with the setup saved; nothing is +// changed here or on the server. +func Preview(ctx context.Context) (Plan, error) { + var p Plan + err := locked(func() error { + c, ok := Load() + if !ok { + return ErrOff + } + st := loadState() + if st.Key != stateKey(c) { + st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own, Follow: st.Follow, Here: st.Here} + } + var err error + p, err = preview(ctx, c, st) + return err + }) + return p, err +} + +// PreviewWith is Preview for a setup not saved yet: Settings shows what +// saving it would do first. A password or passphrase left empty is the +// saved one's, as Configure takes it. +func PreviewWith(ctx context.Context, c Config) (Plan, error) { + var p Plan + err := locked(func() error { + if old, ok := Load(); ok { + if c.Password == "" && c.URL == old.URL && c.User == old.User && c.Endpoint == old.Endpoint { + c.Password = old.Password + } + if c.Passphrase == "" { + c.Passphrase = old.Passphrase + } + } + st := loadState() + if st.Key != stateKey(c) { + st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own, Follow: st.Follow, Here: st.Here} + } + var err error + p, err = preview(ctx, c, st) + return err + }) + return p, err +} + +// preview runs syncOnce as a preview over a copy of st: the server's file +// is read whole, whatever was seen of it before. +func preview(ctx context.Context, c Config, st state) (Plan, error) { + st.Server = version{} + st.Local, st.Remote = maps.Clone(st.Local), maps.Clone(st.Remote) + st.Own, st.Brought, st.Replaced = maps.Clone(st.Own), maps.Clone(st.Brought), maps.Clone(st.Replaced) + var p Plan + if err := syncOnce(ctx, c, &st, &p); err != nil { + return Plan{}, err + } + p.Follow = c.FollowServer + p.Token = "" + j, _ := json.Marshal(p) + p.Token = sum(j)[:16] + return p, nil +} + +// previewed fills pv from what syncOnce decided. +func previewed(pv *Plan, c Config, local, remote, merged backup.Bundle, bringIn, here, there, goneThere []string, prevSignIns map[string]string) error { + M := hashes(merged) + Rh := hashes(remote) + for _, p := range Parts { + pp := PartPlan{Part: p, Do: "same"} + switch { + case !c.syncs(p): + pp.Do = "off" + case slices.Contains(bringIn, p): + pp.Do = "in" + pp.Replaces = slices.Contains(here, p) + pp.Items = diffItems(itemsOf(local, p), itemsOf(remote, p)) + case M[p] != Rh[p] && !c.FollowServer: + pp.Do = "up" + pp.Replaces = slices.Contains(there, p) + pp.Items = diffItems(itemsOf(remote, p), itemsOf(local, p)) + } + pv.Parts = append(pv.Parts, pp) + } + pv.PluginsGone = slices.Clone(goneThere) + if c.memoryOn() && (local.Memory != nil || remote.Memory != nil) { + both := memory.Combine(local.Memory, remote.Memory) + in, up := memoryDiff(local.Memory, both), memoryDiff(remote.Memory, both) + if c.FollowServer { + up = 0 + } + if in+up > 0 { + pv.Memory = &MemoryPlan{In: in, Up: up} + } + } + if c.SignIns { + _, plan, _ := provider.MergeSignIns(local.SignIns, remote.SignIns, prevSignIns) + pv.SignIns = plan.Count() + } + return nil +} + +// memoryDiff is how many memories of to aren't in from as they are there: +// new, changed, or deleted. +func memoryDiff(from, to *memory.Bundle) int { + key := func(m *memory.Memory) string { + k := *m + k.Used, k.Uses = time.Time{}, 0 + j, _ := json.Marshal(k) + return string(j) + } + have := map[string]string{} + if from != nil { + for _, m := range from.Memories { + if m != nil { + have[m.ID] = key(m) + } + } + } + n := 0 + seen := map[string]bool{} + for _, m := range to.Memories { + if m == nil { + continue + } + seen[m.ID] = true + if have[m.ID] != key(m) { + n++ + } + } + for id := range have { + if !seen[id] { + n++ + } + } + return n +} + +// itemsOf is part p of b as named items (kind\x00key → its JSON), as its +// hash sees them: what is this computer's own left out. +func itemsOf(b backup.Bundle, p string) map[string]item { + out := map[string]item{} + switch p { + case "providers": + flatten(out, "provider", syncedProviders(b.Providers)) + flatten(out, "group", b.Groups) + if b.Searches != nil { + flatten(out, "search", *b.Searches) + } + if b.Plugins != nil { + flatten(out, "plugin", *b.Plugins) + } + if b.Proxies != nil { + flatten(out, "proxy", *b.Proxies) + } + if len(b.Order) > 0 || len(b.GroupOrder) > 0 { + flatten(out, "order", map[string]any{"providers": b.Order, "groups": b.GroupOrder}) + } + case "settings": + var s settings.Settings + if b.Settings != nil { + s = *b.Settings + } + s.KeepOwn(settings.Settings{}) + flatten(out, "setting", s) + if b.GatewayKeys != nil { + flatten(out, "gatewayKey", *b.GatewayKeys) + } + if b.AccountGroups != nil { + flatten(out, "accountGroup", *b.AccountGroups) + } + case "profiles": + flatten(out, "profile", b.Profiles) + case "agents": + flatten(out, "agent", b.Agents) + case "library": + if b.Library == nil { + break + } + var top map[string]json.RawMessage + j, _ := json.Marshal(b.Library) + json.Unmarshal(j, &top) + for k, v := range top { + if k == "icons" { + continue + } + var x any + json.Unmarshal(v, &x) + if k == "instructions" { + out["instructions\x00"] = item{Kind: "instructions", Raw: string(v)} + continue + } + flatten(out, k, x) + } + } + return out +} + +type item struct { + Kind, Name, Raw string +} + +// flatten puts v's items in out: an object's by key, a list's by each +// element's id, name or spec. +func flatten(out map[string]item, kind string, v any) { + j, _ := json.Marshal(v) + var x any + json.Unmarshal(j, &x) + switch x := x.(type) { + case map[string]any: + for k, e := range x { + r, _ := json.Marshal(e) + out[kind+"\x00"+k] = item{Kind: kind, Name: k, Raw: string(r)} + } + case []any: + for i, e := range x { + r, _ := json.Marshal(e) + key, name := strconv.Itoa(i), "" + if o, ok := e.(map[string]any); ok { + for _, f := range []string{"id", "name", "spec", "key", "path"} { + if s, ok := o[f].(string); ok && s != "" { + key = s + break + } + } + for _, f := range []string{"name", "label", "id", "spec"} { + if s, ok := o[f].(string); ok && s != "" { + name = s + break + } + } + } + if name == "" { + name = key + } + out[kind+"\x00"+key] = item{Kind: kind, Name: name, Raw: string(r)} + } + } +} + +// diffItems is what going from a to b adds, removes and changes, in order. +func diffItems(a, b map[string]item) []Item { + var out []Item + for _, k := range slices.Sorted(maps.Keys(b)) { + was, ok := a[k] + switch { + case !ok: + out = append(out, Item{Kind: b[k].Kind, Name: b[k].Name, Change: "added"}) + case was.Raw != b[k].Raw: + out = append(out, Item{Kind: b[k].Kind, Name: b[k].Name, Change: "changed"}) + } + } + for _, k := range slices.Sorted(maps.Keys(a)) { + if _, ok := b[k]; !ok { + out = append(out, Item{Kind: a[k].Kind, Name: a[k].Name, Change: "removed"}) + } + } + return out +} + +// UndoSync puts back the parts the last sync brought in, as they were +// before it (#6428). It stays on this computer: the next sync doesn't take +// it to the server, and the server's copy comes in again only when it +// changes there. A part changed here since that sync is not written over +// unless force, and the error says which. +func UndoSync(force bool) ([]string, error) { + var back []string + err := locked(func() error { + c, ok := Load() + if !ok { + return ErrOff + } + st := loadState() + a := st.Applied + if st.Key != stateKey(c) || a == nil || !isFile(a.File) { + return errors.New("there is no sync to undo") + } + data, err := os.ReadFile(a.File) + if err != nil { + return fmt.Errorf("the copy kept before the sync is gone: %w", err) + } + kept, err := backup.Open(data, c.Passphrase) + if err != nil { + return err + } + local, err := collect(c) + if err != nil { + return err + } + ownNow := withHere(st.Own, st.Here) + H := hashesOwn(local, ownNow) + if !force { + var since []string + for _, p := range a.Parts { + if a.After != nil && H[p] != a.After[p] { + since = append(since, p) + } + } + if len(since) > 0 { + return &ChangedSince{Parts: since} + } + } + if _, err := keepSealed(c, "before-undo"); err != nil { + return fmt.Errorf("keeping a copy before undoing: %w", err) + } + for _, p := range a.Parts { + if !c.syncs(p) || p == "library" && kept.Library == nil { + continue + } + if p == "agents" { + if _, err := bringAgents(kept.Agents, ownNow); err != nil { + return fmt.Errorf("bringing back the %s: %w", p, err) + } + } else if err := bring(kept, p); err != nil { + return fmt.Errorf("bringing back the %s: %w", p, err) + } + back = append(back, p) + } + // as the last sync left them: what is here now is not a change + // to take up, so the undo stays on this computer + if local, err = collect(c); err != nil { + return err + } + H = hashesOwn(local, ownNow) + if st.Local == nil { + st.Local = map[string]string{} + } + for _, p := range back { + st.Local[p] = H[p] + } + st.Applied = nil + saveState(st) + return nil + }) + return back, err +} + +// ChangedSince is UndoSync's when parts changed here after the sync. +type ChangedSince struct{ Parts []string } + +func (e *ChangedSince) Error() string { + return fmt.Sprintf("changed here since the sync: %v", e.Parts) +} diff --git a/internal/davsync/restore.go b/internal/davsync/restore.go index cf31c70bf..410927770 100644 --- a/internal/davsync/restore.go +++ b/internal/davsync/restore.go @@ -13,6 +13,7 @@ import ( "github.com/yetone/magpie/internal/backup" "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" ) // ErrOff is a Restore, Undo or SetAuto asked for with sync off. @@ -210,7 +211,17 @@ func Upload(ctx context.Context) error { if err != nil { return err } - b := local + // a part not synced goes as the server last had it, when this + // computer read it whole before, else unset: never this computer's, + // and never an empty one over what the others have when it can be helped + b := c.only(local) + if st := loadState(); st.Key == stateKey(c) && len(c.left()) > 0 { + if prev, err := backup.Open(cached(st.Sum), c.Passphrase); err == nil { + for _, p := range c.left() { + take(&b, prev, p) + } + } + } b.Created, b.App = time.Now().UTC(), "magpie" sealed, err := backup.Seal(b, c.Passphrase) if err != nil { @@ -281,16 +292,77 @@ func Undo() ([]string, error) { return back, err } -// syncs is whether part goes to the server with c. +// syncs is whether part goes to the server with c. A part that doesn't +// stays as it is on each computer: never brought in, never taken up. func (c Config) syncs(part string) bool { - return (part != "agents" || c.Agents) && (part != "library" || c.library()) + switch part { + case "providers": + return yes(c.Providers) + case "settings": + return yes(c.Settings) + case "profiles": + return yes(c.Profiles) + case "agents": + return c.Agents + case "library": + return c.library() + case "memory": + return c.memoryOn() + } + return true +} + +// Synced is the parts c syncs, in Parts' order, memory last. +func (c Config) Synced() []string { + var out []string + for _, p := range append(slices.Clone(Parts), "memory") { + if c.syncs(p) { + out = append(out, p) + } + } + return out +} + +// left is the parts of Parts c doesn't sync. +func (c Config) left() []string { + var out []string + for _, p := range Parts { + if !c.syncs(p) { + out = append(out, p) + } + } + return out +} + +// only is b with the parts c doesn't sync as a new magpie has them +// (unset): what goes up to a server with none of its own. Another +// computer that syncs such a part then puts its own there on joining, as +// with any unset part (#5642), and none is brought down from this one. +// Agents, library and memory are left out by collect already. +func (c Config) only(b backup.Bundle) backup.Bundle { + if !c.syncs("providers") { + b.Providers, b.Groups, b.Icons, b.Order, b.GroupOrder = nil, nil, nil, nil, nil + b.Searches, b.Plugins, b.Proxies = nil, nil, nil + } + if !c.syncs("settings") { + s := settings.Defaults() + b.Settings, b.GatewayKeys, b.AccountGroups = &s, nil, nil + } + if !c.syncs("profiles") { + b.Profiles = nil + } + return b } func withKeys(c Config) Config { c.Keys = true; return c } // keepHere seals this computer's setup, keys and all, into the sync // folder before a restore replaces it; the path. The newest few are kept. -func keepHere(c Config) (string, error) { +func keepHere(c Config) (string, error) { return keepSealed(c, "before-restore") } + +// keepSealed seals this computer's setup, keys and all, into the sync +// folder as