From 281a7e024fc1d864d27ff33cbe668735038bb23e Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 10 Nov 2026 15:31:44 +0800 Subject: [PATCH] sync: a computer can follow the server, taking its setup and sending none (Ramon317317 on X) Ramon317317 asked for a main profile: one computer the others take their setup from, so they never drift apart. Sync merged both ways only; Restore is a one-time pull and an agent's own fields cover agents only. A computer can now be set to follow the server (Settings -> Sync -> This computer: Both ways / Follows the server; /api/davsync/follow-server; `magpie webdav|s3|github follow on|off`). It is chosen per computer and kept in sync.json (Config.FollowServer, kept by Configure like AutoEvery). A following computer: - takes every changed part from the file, whichever side is newer; - never writes the file: no push, no merged sign-in, no rebuild of a damaged file; - keeps a change made on it in the sync folder, as a join does, and the notice says it was replaced because this computer follows the server (Notice.Followed; GUI and CLI); - still keeps an unset part on the server from emptying its own, and own agent fields and agents only here; - refuses to follow a server with no file yet, sending nothing. The computer followed stays two-way; nothing changes for anyone who doesn't pick it. Usage sharing is unchanged. docs/subsystems/sync-backup.md says so. app.js stays inside the core script budget (TestCoreScriptBudget) with no raise: renderSync's comments are cut down to pay for the row. Run (mote, at this head): - go build ./...; go vet ./... (darwin), GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...; gofmt -l clean. - go test ./internal/davsync ./internal/cli ./internal/gui: ok (cli with the route guard fix committed beside this one). TestFollowServer (empty server, join, own change replaced and kept, both changed, unchanged sync, Configure keeps it, back to both ways) and TestFollowServerSendsNoSignIn are new. - GUI (node --test, Chromium and WebKit): sync-follow-server (new; en and zh, 900px and 400px: name, sub, picked segment, the post, the notice, no scroll, no overflow, no select, re-pick posts nothing), plus sync-auto-restore, sync-note-show, sync-own-fields, sync-not-backup, sync-other-kind, sync-signins, sync-spin, i18n-keys, i18n-en-no-cjk, gui-zh-tw, gui-ja, gui-de: all pass. Broken by hand: - push guard removed: TestFollowServerSendsNoSignIn red ("sent its sign-in: 1 puts"). - follow branch off: TestFollowServer red ("b's own change stayed: [deepseek=k1 kimi=kb2]"). - the row's click not posting: sync-follow-server red, 8 of 8. Not tried: a real WebDAV, S3 or GitHub server (fake servers only); two real computers; Windows run of the tests (vet only). The full suite starts after the tag. --- docs/subsystems/sync-backup.md | 16 +- internal/cli/webdav_cli.go | 25 ++- internal/davsync/davsync.go | 47 ++++- internal/davsync/follow_server_test.go | 170 ++++++++++++++++++ internal/davsync/restore.go | 24 +++ internal/gui/assets/app.js | 25 +-- internal/gui/assets/i18n.js | 20 +++ internal/gui/backup.go | 7 + .../gui/tests/sync-follow-server.test.cjs | 137 ++++++++++++++ 9 files changed, 452 insertions(+), 19 deletions(-) create mode 100644 internal/davsync/follow_server_test.go create mode 100644 internal/gui/tests/sync-follow-server.test.cjs diff --git a/docs/subsystems/sync-backup.md b/docs/subsystems/sync-backup.md index d0f3a80bc..0f7beecc9 100644 --- a/docs/subsystems/sync-backup.md +++ b/docs/subsystems/sync-backup.md @@ -139,6 +139,20 @@ on both sides keeps the newer version while retaining the replaced copy. A conditional write refused because another computer committed in between is retried through this same merge. +A computer can follow the server instead (`Config.FollowServer`, set only +by `SetFollowServer`: Settings → Sync → This computer → Follows the +server, `/api/davsync/follow-server`, or `magpie +follow on|off`; Ramon317317 on X). It takes every changed part from the +file whichever side is newer, never writes the file (not a merged +sign-in, not a rebuild of a damaged file), and a change made on it is +kept in the sync folder like a join's and said in the notice +(`Notice.Followed`). The join rules still hold: an `unset` part on the +server leaves this computer's, and own agent fields and agents only here +stay. Following a server with no file yet is an error, nothing sent. +`Configure` keeps the choice, as it keeps `AutoEvery`. The computer +followed is an ordinary two-way one (`TestFollowServer`, +`TestFollowServerSendsNoSignIn`, `sync-follow-server.test.cjs`). + When a remote file is empty, damaged or another app's format, sync stops and describes it through `ServerFile`. Settings and the backend's `upload` command can replace it with this computer's setup, keeping the old file first. @@ -428,7 +442,7 @@ with none hashes as before (`TestSyncHooks`, `TestNoHooksHashAsBefore`, ```sh go test -tags nogui ./internal/davsync go test -tags nogui ./internal/cli -run 'TestGitHubCmd|TestWebdavCmd|TestS3Cmd' -node --test internal/gui/tests/github-sync.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/sync-other-kind.test.cjs +node --test internal/gui/tests/github-sync.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/sync-other-kind.test.cjs internal/gui/tests/sync-follow-server.test.cjs ``` `TestGitHubEmptyRepository` covers the first encrypted backup initializing an diff --git a/internal/cli/webdav_cli.go b/internal/cli/webdav_cli.go index b4d669159..071eb4c6f 100644 --- a/internal/cli/webdav_cli.go +++ b/internal/cli/webdav_cli.go @@ -29,6 +29,9 @@ const webdavUsage = `usage: 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 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 + sync folder. off: both ways, as before magpie webdav restore make this computer's setup the server's; what is here is kept first magpie webdav undo put back what the last restore replaced magpie webdav upload put this computer's setup over a server file that isn't a backup @@ -75,6 +78,9 @@ const s3Usage = `usage: passphrase= ask for a new one magpie s3 now sync now (the gateway also syncs by itself while it runs: see auto) 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 + sync folder. off: both ways, as before magpie s3 restore make this computer's setup the server's; what is here is kept first magpie s3 undo put back what the last restore replaced magpie s3 upload put this computer's setup over a bucket file that isn't a backup @@ -115,6 +121,7 @@ const githubUsage = `usage: magpie github set k=v… change it: address, branch, keys, agents, library, usage, sign-ins (yes|no) magpie github now sync now 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 magpie github undo put back what the last restore replaced magpie github upload put this computer's setup over a repository file that isn't a backup; the old file is kept first @@ -186,6 +193,17 @@ func syncCmd(k syncKind, args []string) error { return err } return syncShow(k) + case "follow": + if len(args) != 2 || args[1] != "on" && args[1] != "off" { + return fmt.Errorf("magpie %s follow on|off", k.cmd) + } + if err := davsync.SetFollowServer(args[1] == "on"); err != nil { + if errors.Is(err, davsync.ErrOff) { + return fmt.Errorf("%s sync is off: %s", k.name, k.turnOn()) + } + return err + } + return syncShow(k) case "restore", "undo": if _, ok := davsync.Load(); !ok { return fmt.Errorf("%s sync is off: %s", k.name, k.turnOn()) @@ -533,7 +551,9 @@ func syncShow(k syncKind) error { fmt.Println(" Restored from the server:", partNames(n.Here)) fmt.Println(muted.Render(" This computer's setup from before is kept in " + tilde(n.Saved) + " (magpie " + cmd + " undo puts it back; magpie " + cmd + " dismiss clears this)")) } else if n != nil { - if len(n.Here) > 0 { + if len(n.Here) > 0 && n.Followed { + fmt.Println(" This computer follows the server, so what was changed here is replaced by the server's:", partNames(n.Here)) + } else if len(n.Here) > 0 { fmt.Println(" Replaced here by newer ones from another computer:", partNames(n.Here)) } if len(n.There) > 0 { @@ -545,6 +565,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 v.FollowServer { + fmt.Println(" follows the server: takes its setup, sends none of its own (magpie " + cmd + " follow off syncs both ways)") + } switch { case v.Auto == 0: fmt.Println(muted.Render(" Syncs only when asked: magpie " + cmd + " now syncs once (magpie " + cmd + " auto 3 syncs by itself again)")) diff --git a/internal/davsync/davsync.go b/internal/davsync/davsync.go index bf9fd6974..392f1d373 100644 --- a/internal/davsync/davsync.go +++ b/internal/davsync/davsync.go @@ -98,6 +98,14 @@ type Config struct { // itself: 0 is Every's 3, Manual never — then only Sync now syncs // (#847). Set by SetAuto alone; Configure keeps it. AutoEvery int `json:"autoEvery,omitempty"` + // FollowServer is this computer following the setup on the server + // rather than syncing both ways (Ramon317317 on X: one computer the + // others all take theirs from). Each sync brings in every part that + // changed on either side since the last one, and nothing goes up: a + // change made here is replaced, a copy of it kept in the sync folder + // and named in a notice. The computer the others follow keeps syncing + // both ways. Set by SetFollowServer alone; Configure keeps it. + FollowServer bool `json:"followServer,omitempty"` } // Manual is AutoEvery's never: sync runs only when asked. @@ -191,6 +199,10 @@ type Notice struct { Here []string `json:"here,omitempty"` // this computer's parts, replaced by the server's There []string `json:"there,omitempty"` // the server's parts, replaced by this computer's Saved string `json:"saved,omitempty"` // the folder the replaced copies are kept in + // Followed is that the parts in Here were changed here and replaced + // because this computer follows the server (Config.FollowServer), not + // because the server's were newer + Followed bool `json:"followed,omitempty"` // Restored is a Restore's notice: Here are the parts it brought in, // what was here before kept in Saved, which Undo brings back Restored bool `json:"restored,omitempty"` @@ -336,7 +348,8 @@ func Configure(c Config) error { if old.Other != nil { c.Servers[strings.ToLower(old.Other.config().Kind())] = *old.Other } - c.AutoEvery = old.AutoEvery // SetAuto's, not the form's + c.AutoEvery = old.AutoEvery // SetAuto's, not the form's + c.FollowServer = old.FollowServer // SetFollowServer's, not the form's if old.Kind() != c.Kind() { o := old.where() c.Other = &o @@ -504,6 +517,9 @@ type View struct { // Auto is how many minutes apart it syncs by itself; 0 never: only when // asked Auto int `json:"auto"` + // FollowServer is whether this computer takes the server's setup and + // sends none of its own (Config.FollowServer) + FollowServer bool `json:"followServer,omitempty"` // Undo is whether the last Restore can be undone Undo bool `json:"undo,omitempty"` // File is what the server holds instead of a backup, when Error is @@ -540,7 +556,7 @@ func Status() View { 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(), Error: st.Error, Notice: st.Notice, Kind: strings.ToLower(c.Kind()), Endpoint: c.Endpoint, Region: c.Region, PathStyle: c.PathStyle, Branch: c.Branch, - Auto: int(c.auto() / time.Minute)} + 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) @@ -1254,6 +1270,9 @@ func syncOnce(ctx context.Context, c Config, st *state) error { remember(sealed) return nil } + if data == nil && c.FollowServer { + return errNothingToFollow + } if data == nil { // nothing there yet: this computer's setup is the first if err := push(local, "", blind{}); err != nil { return err @@ -1297,7 +1316,9 @@ func syncOnce(ctx context.Context, c Config, st *state) error { // damaged file's ETag as the version to replace, so the push is // still checked against the server and another computer's parts // survive the way they would on any sync. - if !errors.Is(err, backup.ErrCorrupt) || st.Local == nil { + // 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 { return described(c, data, err) } good := cached(st.Sum) // the version this computer last read whole @@ -1345,6 +1366,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] + 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) { + continue + } + if lc || rc { + bringIn = append(bringIn, p) + } + if lc || first { + here = append(here, p) + } + continue + } switch { case lc && !rc: take(&merged, local, p) @@ -1463,12 +1500,12 @@ func syncOnce(ctx context.Context, c Config, st *state) error { st.Local, st.Sum, st.Server, st.Remote = pending, sum(data), ver, R remember(data) if len(here)+len(there) > 0 { - st.Notice = &Notice{At: time.Now(), Here: here, There: there, Saved: saved} + st.Notice = &Notice{At: time.Now(), Here: here, There: there, Saved: saved, Followed: c.FollowServer && !first} st.Undo = "" // a restore's undo goes with its notice } // A rebuild always writes back: the server's file is the damaged one, // so even a merge that matches the cached copy must replace it. - if rebuilt || !maps.Equal(M, R) { + if !c.FollowServer && (rebuilt || !maps.Equal(M, R)) { if err := push(merged, etag, blind{Remote: R, Local: pending}); err != nil { return err } diff --git a/internal/davsync/follow_server_test.go b/internal/davsync/follow_server_test.go new file mode 100644 index 000000000..124a6ba3d --- /dev/null +++ b/internal/davsync/follow_server_test.go @@ -0,0 +1,170 @@ +package davsync + +import ( + "context" + "encoding/json" + "errors" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/yetone/magpie/internal/backup" + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// A computer set to follow the server takes its setup and sends none of +// its own (Ramon317317 on X: one computer the others all take theirs +// from, so they never drift apart). A change made on it is replaced on +// the next sync, kept in the sync folder and said; a change on both sides +// is the server's whichever is newer. The computer followed syncs both +// ways, and one set back syncs both ways again. +func TestFollowServer(t *testing.T) { + fake := &fakeDAV{files: map[string][]byte{}, etags: map[string]string{}, dirs: map[string]bool{"/dav": true}} + srv := httptest.NewServer(fake) + defer srv.Close() + ctx := context.Background() + cfg := Config{URL: srv.URL + "/dav/", User: "me", Password: "pw", Passphrase: "correct horse", Keys: true, Agents: true} + now := func(t *testing.T) View { + t.Helper() + if err := Now(ctx); err != nil { + t.Fatal(err) + } + return Status() + } + main, b := newComputer(t), newComputer(t) + + // following an empty server: an error, and nothing goes up + b.use(t) + provider.Save(provider.Provider{ID: "mine", Name: "Mine", Chat: "https://x/v1", Key: "kb"}) + if err := Configure(cfg); err != nil { + t.Fatal(err) + } + if err := SetFollowServer(true); err != nil { + t.Fatal(err) + } + if err := Now(ctx); !errors.Is(err, errNothingToFollow) || fake.puts != 0 { + t.Fatalf("following an empty server: %v, %d puts", err, fake.puts) + } + + main.use(t) + provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k1"}) + settings.Save(settings.Settings{Theme: "dark"}) + if err := Configure(cfg); err != nil { + t.Fatal(err) + } + if v := now(t); v.FollowServer || fake.puts != 1 { + t.Fatalf("main: %+v, %d puts", v, fake.puts) + } + + // b joins following: the server's setup comes in, b's kept aside + b.use(t) + if v := now(t); !v.FollowServer || v.Notice == nil || !slices.Contains(v.Notice.Here, "providers") { + t.Fatalf("b joined: %+v", v) + } + if got := ids(); !slices.Equal(got, []string{"deepseek=k1"}) || settings.Load().Theme != "dark" { + t.Fatalf("b after joining: %v %q", got, settings.Load().Theme) + } + Dismiss() + + // a change made on b: replaced, never sent, kept and said + puts := fake.puts + provider.Save(provider.Provider{ID: "kimi", Name: "Kimi", Chat: "https://api.moonshot.cn/v1", Key: "kb2"}) + v := now(t) + if fake.puts != puts { + t.Fatalf("b, following, wrote the server %d times", fake.puts-puts) + } + if got := ids(); !slices.Equal(got, []string{"deepseek=k1"}) { + t.Fatalf("b's own change stayed: %v", got) + } + if v.Notice == nil || !v.Notice.Followed || !slices.Equal(v.Notice.Here, []string{"providers"}) { + t.Fatalf("b's notice: %+v", v.Notice) + } + kept, _ := filepath.Glob(filepath.Join(settings.Dir(), "sync", "*-this-computer"+backup.Ext)) + found := false + for _, k := range kept { + if old, err := backup.Open(must(os.ReadFile(k)), "correct horse"); err == nil && slices.ContainsFunc(old.Providers, func(p provider.Provider) bool { return p.ID == "kimi" }) { + found = true + } + } + if !found { + t.Fatalf("b's change isn't kept: %v", kept) + } + Dismiss() + + // both change the settings, b's the newer: the server's still comes in + main.use(t) + settings.Save(settings.Settings{Theme: "light"}) + now(t) + b.use(t) + settings.Save(settings.Settings{Theme: "system", Lang: "zh"}) + puts = fake.puts + if v := now(t); fake.puts != puts || settings.Load().Theme != "light" || settings.Load().Lang == "zh" || v.Notice == nil || !v.Notice.Followed { + t.Fatalf("both changed: %q %q, %d puts, %+v", settings.Load().Theme, settings.Load().Lang, fake.puts-puts, v.Notice) + } + // nothing changed since: nothing brought or written + Dismiss() + if v := now(t); fake.puts != puts || v.Notice != nil { + t.Fatalf("an unchanged sync: %d puts, %+v", fake.puts-puts, v.Notice) + } + + // saving the server's form keeps the choice; set back, b syncs both ways + if err := Configure(cfg); err != nil || !Status().FollowServer { + t.Fatalf("the form dropped following: %v", err) + } + if err := SetFollowServer(false); err != nil { + t.Fatal(err) + } + provider.Save(provider.Provider{ID: "kimi", Name: "Kimi", Chat: "https://api.moonshot.cn/v1", Key: "kb2"}) + now(t) + main.use(t) + now(t) + if got := ids(); !slices.Equal(got, []string{"deepseek=k1", "kimi=kb2"}) { + t.Fatalf("main after b synced both ways again: %v", got) + } +} + +// With sign-ins synced, one made on a computer following the server is +// still not sent: the merge of sign-ins would put it in the file, and the +// file is the followed computer's to write. +func TestFollowServerSendsNoSignIn(t *testing.T) { + fake := &fakeDAV{files: map[string][]byte{}, etags: map[string]string{}, dirs: map[string]bool{"/dav": true}} + srv := httptest.NewServer(fake) + defer srv.Close() + ctx := context.Background() + cfg := Config{URL: srv.URL + "/dav/", User: "me", Password: "pw", Passphrase: "correct horse", SignIns: true} + main, b := newComputer(t), newComputer(t) + main.use(t) + if err := Configure(cfg); err != nil { + t.Fatal(err) + } + if err := Now(ctx); err != nil { + t.Fatal(err) + } + b.use(t) + if err := Configure(cfg); err != nil { + t.Fatal(err) + } + if err := SetFollowServer(true); err != nil { + t.Fatal(err) + } + if err := Now(ctx); err != nil { + t.Fatal(err) + } + if err := plugin.EditAuth(func(m map[string]json.RawMessage) (bool, error) { + m["kiro"] = json.RawMessage(`{"type":"oauth","access":"kiro-b","refresh":"kr","expires":2000,"accountId":"k@x.com"}`) + return true, nil + }); err != nil { + t.Fatal(err) + } + puts := fake.puts + if err := Now(ctx); err != nil { + t.Fatal(err) + } + if fake.puts != puts { + t.Fatalf("b, following, sent its sign-in: %d puts", fake.puts-puts) + } +} diff --git a/internal/davsync/restore.go b/internal/davsync/restore.go index 082299e29..cf31c70bf 100644 --- a/internal/davsync/restore.go +++ b/internal/davsync/restore.go @@ -18,6 +18,30 @@ import ( // ErrOff is a Restore, Undo or SetAuto asked for with sync off. var ErrOff = errors.New("sync is off") +// errNothingToFollow is a sync of a computer following the server when +// the server has no setup yet: nothing goes up from one that follows. +var errNothingToFollow = errors.New("there is no setup on the server to follow yet: sync the computer the others follow first") + +// SetFollowServer sets whether this computer follows the setup on the +// server (Config.FollowServer) or syncs both ways. +func SetFollowServer(on bool) error { + return locked(func() error { + c, ok := Load() + if !ok { + return ErrOff + } + c.FollowServer = on + b, err := json.MarshalIndent(c, "", " ") + if err != nil { + return err + } + if err := edit.WriteAtomic(path("sync.json"), b); err != nil { + return err + } + return os.Chmod(path("sync.json"), 0o600) + }) +} + // SetAuto sets how many minutes apart the gateway's magpie syncs by // itself, one of AutoChoices; Manual: never, only when asked (#847). func SetAuto(minutes int) error { diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 98228a4da..d51261fe4 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -20283,11 +20283,7 @@ async function renderSync(v) { const toggle = (id) => () => { syncOpen = syncOpen === id ? "" : id; renderSync(); }; const parts = (ps) => ps.map((p) => t({ providers: "providers", settings: "settings", profiles: "profiles", agents: "agents' models", library: "library", usage: "usage", signins: "sign-ins" }[p])).join(t(", ")); - // WebDAV, S3 or GitHub - // off: what it would keep the same, named from the view's toggles as the - // CLI names them, so the page can't promise a part the setup leaves out. - // A view that says nothing of the toggles (a read that failed) reads as - // all on, as Status' off view is. + // off: what it would keep the same, from the view's toggles (none: all on) const goes = ["settings", "profiles"]; if (v.agents !== false) goes.push("agents"); if (v.library !== false) goes.push("library"); @@ -20312,21 +20308,15 @@ async function renderSync(v) { ? [btn(t("Sync now"), async (e) => { e.target.classList.add("busy"); renderSync(await api("davsync/now", {}).catch((x) => ({ ...v, error: x.message }))); }), btn(t(syncOpen === "dav" ? "Close" : "Edit"), toggle("dav"))] : [btn(t(syncOpen === "dav" ? "Close" : "Set up"), toggle("dav"))])); - // a failure is shown whole: what the server sent and what to do don't - // fit one line if (v.error) sub.classList.add("bad", "wraps"); if (v.on) sub.classList.add("say"); - // usage that couldn't be shared is a line of its own, in red: beside - // "Synced" in the same grey it read as part of a sync that went fine - // (#1259) + // usage not shared: its own red line (#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 synced with no account here (悠悠哥 on Discord) // with sign-ins synced, it is one no other computer shared if (v.on && v.signIn?.length) sub.after(el("div", "sub wraps sync-sign-in", v.signIns ? t("Your synced settings use {names}, which isn't signed in on this computer, and no other computer synced its sign-in. To use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.", { names: subNames(v.signIn) }) : 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 if (v.on && v.error && v.serverFile?.replace) { row(t("Upload this computer's setup"), t("It replaces the file on the server. That file is kept in the sync folder first."), btn(t("Upload…"), () => syncFile("askUpload", v.serverFile))); @@ -20345,6 +20335,7 @@ async function renderSync(v) { const n = v.notice, r = el("div", "row pref sync-note"); const lines = []; if (n.restored) lines.push(t("Restored from the server: {parts}", { parts: parts(n.here || []) })); + else if (n.here?.length && n.followed) lines.push(t("Replaced by the server's, as this computer follows it: {parts}", { parts: parts(n.here) })); else if (n.here?.length) lines.push(t("Replaced here by newer ones from another computer: {parts}", { parts: parts(n.here) })); if (n.there?.length) lines.push(t("Replaced on the server by this computer's newer ones: {parts}", { parts: parts(n.there) })); const who = el("div", "who"); @@ -20368,6 +20359,16 @@ async function renderSync(v) { segs([[0, t("Off")], [3, t("3 min")], [15, t("15 min")], [30, t("30 min")], [60, t("1 hour")]], every, async (m) => { renderSync(await api("davsync/auto", { minutes: m || -1 }).catch((x) => ({ ...v, error: x.message }))); })); + // following the server (Ramon317317 on X) + const follows = !!v.followServer; + row(t("This computer"), follows + ? t("Takes the server's setup and sends none. A change made here is replaced and kept in the sync folder.") + : t("Changes go to the other computers, and theirs come here"), + segs([["both", t("Both ways")], ["follow", t("Follows the server")]], follows ? "follow" : "both", async (m) => { + if ((m === "follow") === follows) return; + renderSync(await api("davsync/follow-server", { on: m === "follow" }).catch((x) => ({ ...v, error: x.message }))); + refreshAfterSync(); + })).classList.add("wraps", "sync-follows"); row(t("Restore from the server"), t("This computer's setup becomes the one on the server. What is here now is kept first, to undo."), btn(t("Restore…"), () => syncFile("askRestore", v, parts))); } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index f4d45673d..109653fdc 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3053,6 +3053,11 @@ const I18N = { "This computer's setup from before is kept in the sync folder.": "本机恢复前的配置已备份在 sync 文件夹。", "Undo": "撤销", "Sync by itself": "自动同步", + "Both ways": "双向同步", + "Follows the server": "跟随服务器", + "Changes go to the other computers, and theirs come here": "本机的改动同步到其他电脑,其他电脑的改动也同步到本机", + "Takes the server's setup and sends none. A change made here is replaced and kept in the sync folder.": "只采用服务器上的配置,不上传本机的。本机的改动会被替换,副本保存在同步文件夹中。", + "Replaced by the server's, as this computer follows it: {parts}": "本机跟随服务器,本机改过的{parts}已被服务器上的替换", "Back up by itself": "自动备份", "Back to {page}": "返回{page}", "1 week": "1 周", @@ -7920,6 +7925,11 @@ const I18N = { "This computer's setup from before is kept in the sync folder.": "本機恢復前的設定已備份在 sync 資料夾。", "Undo": "復原", "Sync by itself": "自動同步", + "Both ways": "雙向同步", + "Follows the server": "跟隨伺服器", + "Changes go to the other computers, and theirs come here": "本機的變更同步到其他電腦,其他電腦的變更也同步到本機", + "Takes the server's setup and sends none. A change made here is replaced and kept in the sync folder.": "只採用伺服器上的設定,不上傳本機的。本機的變更會被取代,副本保存在同步資料夾中。", + "Replaced by the server's, as this computer follows it: {parts}": "本機跟隨伺服器,本機改過的{parts}已被伺服器上的取代", "Back up by itself": "自動備份", "Back to {page}": "返回{page}", "1 week": "1 週", @@ -12797,6 +12807,11 @@ const I18N = { "This computer's setup from before is kept in the sync folder.": "復元前のこのコンピューターの設定は同期フォルダーに保存されています。", "Undo": "取り消す", "Sync by itself": "自動同期", + "Both ways": "双方向", + "Follows the server": "サーバーに従う", + "Changes go to the other computers, and theirs come here": "このコンピュータの変更はほかのコンピュータへ送られ、ほかのコンピュータの変更もここに届きます", + "Takes the server's setup and sends none. A change made here is replaced and kept in the sync folder.": "サーバーの設定を取り込むだけで、このコンピュータの設定は送りません。ここでの変更は置き換えられ、そのコピーは同期フォルダに残ります。", + "Replaced by the server's, as this computer follows it: {parts}": "このコンピュータはサーバーに従うため、ここで変更した{parts}をサーバーのもので置き換えました", "Back up by itself": "自動バックアップ", "Back to {page}": "{page}に戻る", "1 week": "1 週間", @@ -17685,6 +17700,11 @@ 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", + "Both ways": "In beide Richtungen", + "Follows the server": "Folgt dem Server", + "Changes go to the other computers, and theirs come here": "Änderungen hier gehen an die anderen Computer, und deren Änderungen kommen hierher", + "Takes the server's setup and sends none. A change made here is replaced and kept in the sync folder.": "Übernimmt die Einrichtung vom Server und sendet keine eigene. Änderungen hier werden ersetzt; eine Kopie bleibt im Sync-Ordner.", + "Replaced by the server's, as this computer follows it: {parts}": "Durch die des Servers ersetzt, da dieser Computer ihm folgt: {parts}", "Back up by itself": "Selbst sichern", "Back to {page}": "Zurück zu {page}", "1 week": "1 Woche", diff --git a/internal/gui/backup.go b/internal/gui/backup.go index bdd43e293..7bfb3ae99 100644 --- a/internal/gui/backup.go +++ b/internal/gui/backup.go @@ -218,6 +218,13 @@ func backupRoutes(mux *http.ServeMux, w Windows) { if err = json.NewDecoder(r.Body).Decode(&in); err == nil { err = davsync.SetAuto(in.Minutes) } + case "follow-server": // this computer takes the server's setup and sends none (Ramon317317 on X) + var in struct{ On bool } + if err = json.NewDecoder(r.Body).Decode(&in); err == nil { + if err = davsync.SetFollowServer(in.On); err == nil { + err = busy(davsync.SyncNow(ctx)) // how it went is in the status + } + } case "restore": // the server's setup over this computer's, which is kept brought, err = davsync.Restore(ctx) case "undo": diff --git a/internal/gui/tests/sync-follow-server.test.cjs b/internal/gui/tests/sync-follow-server.test.cjs new file mode 100644 index 000000000..7cc05c407 --- /dev/null +++ b/internal/gui/tests/sync-follow-server.test.cjs @@ -0,0 +1,137 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A computer can follow the server: take its setup and send none of its +// own (Ramon317317 on X: one computer the others all take theirs from). +// With sync on, the This computer row in the sync list shows Both ways +// picked, and says changes go both ways. Picking Follows the server posts +// follow-server on, and the row then says changes made here are replaced +// and kept. A notice from a sync that replaced a change made here says it +// was because this computer follows the server. Picking Both ways again +// posts it off. No click moves the page; nothing is wider than the window +// at a phone's width. In English and Chinese, Chromium and WebKit. The API +// is faked; nothing is synced. +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 assets = path.resolve(__dirname, "../assets"); + +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 sync = { on: true, kind: "webdav", url: "https://dav.jianguoyun.com/dav/", user: "me", passwordSet: true, passphraseSet: true, + keys: true, agents: true, library: true, auto: 3, last: new Date().toISOString() }; + 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(sync); + if (pathname.startsWith("/api/davsync/")) { + const action = pathname.slice("/api/davsync/".length); + posts.push({ action, body: request.postDataJSON() }); + if (action === "follow-server") { + const on = request.postDataJSON().on; + sync = { ...sync, followServer: on || undefined, + notice: on ? { at: new Date().toISOString(), here: ["providers"], followed: true, saved: "/tmp/magpie/sync" } : undefined }; + } + return json(sync); + } + 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 }); + }; +} + +const words = { + en: { + row: "This computer", both: "Both ways", follow: "Follows the server", + bothSub: "Changes go to the other computers, and theirs come here", + followSub: "Takes the server's setup and sends none. A change made here is replaced and kept in the sync folder.", + note: "Replaced by the server's, as this computer follows it: providers", + }, + zh: { + row: "本机", both: "双向同步", follow: "跟随服务器", + bothSub: "本机的改动同步到其他电脑,其他电脑的改动也同步到本机", + followSub: "只采用服务器上的配置,不上传本机的。本机的改动会被替换,副本保存在同步文件夹中。", + note: "本机跟随服务器,本机改过的供应商已被服务器上的替换", + }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + for (const width of [900, 400]) { + const w = words[lang]; + test(`${engine} ${lang} ${width}px: this computer can follow the server, and sync both ways again`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width, height: 700 }, 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}-${lang}-${width}-sync-follow-server.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 row = list.locator(".row.pref").filter({ has: page.locator(".sync-follows") }); + await row.waitFor({ state: "visible" }); + assert.equal(await row.locator(".name").textContent(), w.row); + assert.equal(await row.locator(".sub").textContent(), w.bothSub); + assert.equal(await row.locator(".segs .opt.on").textContent(), w.both); + await row.scrollIntoViewIfNeeded(); + await page.waitForTimeout(300); + const top = () => page.evaluate(() => document.querySelector("#view-settings").scrollTop); + + // follow: posted on, said, and a sync's notice says why + let at = await top(); + await row.locator(".segs .opt", { hasText: w.follow }).click(); + await page.waitForFunction((s) => document.querySelector("#syncList .sub.sync-follows")?.textContent === s, w.followSub); + assert.deepEqual(posts.at(-1), { action: "follow-server", body: { on: true } }); + assert.equal(await row.locator(".segs .opt.on").textContent(), w.follow); + assert.equal(await list.locator(".sync-note .sub").first().textContent(), w.note); + assert.equal(await top(), at, "picking Follows the server didn't move the page"); + const wide = await page.evaluate(() => { + const r = document.querySelector("#syncList .sub.sync-follows").closest(".row").getBoundingClientRect(); + return r.right - document.documentElement.clientWidth; + }); + assert.ok(wide <= 1, `the row is ${wide}px wider than the window`); + + // picked again: nothing posted + const n = posts.length; + await row.locator(".segs .opt", { hasText: w.follow }).click(); + await page.waitForTimeout(200); + assert.equal(posts.length, n, "picking the choice already made posts nothing"); + + // both ways again + at = await top(); + await row.locator(".segs .opt", { hasText: w.both }).click(); + await page.waitForFunction((s) => document.querySelector("#syncList .sub.sync-follows")?.textContent === s, w.bothSub); + assert.deepEqual(posts.at(-1), { action: "follow-server", body: { on: false } }); + assert.equal(await top(), at, "picking Both ways didn't move the page"); + assert.equal(await list.locator("select").count(), 0, "no native select"); + assert.deepEqual(errors, []); + }); + } + } +}