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 <webdav|s3|github> 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 <kind> 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 <kind> 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 base48e394146): - 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/main52c9880cb(#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/main7eecbcc56(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.
This commit is contained in:
@@ -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 <webdav|s3|github> 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 <kind> 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
|
||||
|
||||
+135
-12
@@ -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 <prefix>/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"}
|
||||
|
||||
@@ -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)
|
||||
|
||||
+127
-23
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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 <time>-<tag>; the path. The newest 5 so tagged are kept.
|
||||
func keepSealed(c Config, tag string) (string, error) {
|
||||
b, err := collect(withKeys(c))
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -303,12 +375,12 @@ func keepHere(c Config) (string, error) {
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return "", err
|
||||
}
|
||||
name := filepath.Join(dir, time.Now().Format("2006-01-02-150405")+"-before-restore"+backup.Ext)
|
||||
name := filepath.Join(dir, time.Now().Format("2006-01-02-150405.000")+"-"+tag+backup.Ext)
|
||||
if err := edit.WriteAtomic(name, sealed); err != nil {
|
||||
return "", err
|
||||
}
|
||||
os.Chmod(name, 0o600)
|
||||
old, _ := filepath.Glob(filepath.Join(dir, "*-before-restore"+backup.Ext))
|
||||
old, _ := filepath.Glob(filepath.Join(dir, "*-"+tag+backup.Ext))
|
||||
slices.Sort(old)
|
||||
for len(old) > 5 {
|
||||
os.Remove(old[0])
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
package davsync
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/backup"
|
||||
"github.com/yetone/magpie/internal/library"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
const serverFile = "/dav/magpie/magpie.magpie-backup"
|
||||
|
||||
func scopeServer(t *testing.T) (*fakeDAV, Config) {
|
||||
fake := &fakeDAV{files: map[string][]byte{}, etags: map[string]string{}, dirs: map[string]bool{"/dav": true}}
|
||||
srv := httptest.NewServer(fake)
|
||||
t.Cleanup(srv.Close)
|
||||
return fake, Config{URL: srv.URL + "/dav/", User: "me", Password: "pw", Passphrase: "correct horse", Keys: true, Agents: true}
|
||||
}
|
||||
|
||||
func syncOK(t *testing.T) View {
|
||||
t.Helper()
|
||||
if err := Now(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v := Status()
|
||||
if v.Error != "" {
|
||||
t.Fatalf("sync: %s", v.Error)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func serverBundle(t *testing.T, fake *fakeDAV) backup.Bundle {
|
||||
t.Helper()
|
||||
b, err := backup.Open(onServer(fake, serverFile), "correct horse")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func sharedText() string {
|
||||
iv, _ := library.ReadInstructions()
|
||||
return iv.Shared
|
||||
}
|
||||
|
||||
func saySharedText(t *testing.T, text string) {
|
||||
t.Helper()
|
||||
if _, err := library.SaveInstructions(library.InstructionsChange{Shared: &text, Agents: []string{"claude"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func serverIDs(b backup.Bundle) []string {
|
||||
var out []string
|
||||
for _, p := range b.Providers {
|
||||
out = append(out, p.ID)
|
||||
}
|
||||
slices.Sort(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// #6428 (jinpwng): a computer that syncs only the library and memory
|
||||
// keeps its own providers and settings, and never sends them up: the
|
||||
// library comes in, the server keeps the other computer's providers and
|
||||
// settings, and a change to either here stays here.
|
||||
func TestSyncOnlyLibraryKeepsEachComputersOwn(t *testing.T) {
|
||||
fake, cfg := scopeServer(t)
|
||||
|
||||
a := newComputer(t)
|
||||
a.use(t)
|
||||
provider.Save(provider.Provider{ID: "pa", Name: "A", Chat: "https://a/v1", Key: "ka"})
|
||||
settings.Save(settings.Settings{Theme: "dark"})
|
||||
os.MkdirAll(filepath.Join(string(a), ".claude"), 0o755)
|
||||
saySharedText(t, "Be brief.")
|
||||
Configure(cfg)
|
||||
syncOK(t)
|
||||
|
||||
b := newComputer(t)
|
||||
b.use(t)
|
||||
os.MkdirAll(filepath.Join(string(b), ".claude"), 0o755)
|
||||
provider.Save(provider.Provider{ID: "pb", Name: "B", Chat: "https://b/v1", Key: "kb"})
|
||||
settings.Save(settings.Settings{Theme: "light"})
|
||||
no := false
|
||||
only := cfg
|
||||
only.Providers, only.Settings, only.Profiles, only.Agents = &no, &no, &no, false
|
||||
if err := Configure(only); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v := syncOK(t)
|
||||
if v.Providers || v.Settings || v.Profiles || !v.Library || !v.Memory {
|
||||
t.Fatalf("status: %+v", v)
|
||||
}
|
||||
if got := ids(); !slices.Equal(got, []string{"pb=kb"}) {
|
||||
t.Fatalf("b's providers: %v", got)
|
||||
}
|
||||
if s := settings.Load(); s.Theme != "light" {
|
||||
t.Fatalf("b's theme: %q", s.Theme)
|
||||
}
|
||||
if got := sharedText(); got != "Be brief." {
|
||||
t.Fatalf("b's library: %q", got)
|
||||
}
|
||||
// b changes its own: the server never gets them
|
||||
provider.Save(provider.Provider{ID: "pc", Name: "C", Chat: "https://c/v1", Key: "kc"})
|
||||
settings.Save(settings.Settings{Theme: "system"})
|
||||
syncOK(t)
|
||||
srv := serverBundle(t, fake)
|
||||
if got := serverIDs(srv); !slices.Equal(got, []string{"pa"}) {
|
||||
t.Fatalf("server's providers: %v", got)
|
||||
}
|
||||
if srv.Settings == nil || srv.Settings.Theme != "dark" {
|
||||
t.Fatalf("server's settings: %+v", srv.Settings)
|
||||
}
|
||||
|
||||
// a changes its own: b keeps b's
|
||||
a.use(t)
|
||||
provider.Save(provider.Provider{ID: "pz", Name: "Z", Chat: "https://z/v1", Key: "kz"})
|
||||
syncOK(t)
|
||||
b.use(t)
|
||||
syncOK(t)
|
||||
if got := ids(); !slices.Equal(got, []string{"pb=kb", "pc=kc"}) {
|
||||
t.Fatalf("b's providers after a's change: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A computer whose folder is empty, syncing only the library, puts none
|
||||
// of its providers or settings on the server: the next computer to join
|
||||
// keeps its own (#5642's unset rule) rather than taking them.
|
||||
func TestSyncOnlyLibraryFirstSendsNoProviders(t *testing.T) {
|
||||
fake, cfg := scopeServer(t)
|
||||
b := newComputer(t)
|
||||
b.use(t)
|
||||
provider.Save(provider.Provider{ID: "pb", Name: "B", Chat: "https://b/v1", Key: "kb"})
|
||||
settings.Save(settings.Settings{Theme: "light"})
|
||||
no := false
|
||||
only := cfg
|
||||
only.Providers, only.Settings, only.Profiles = &no, &no, &no
|
||||
Configure(only)
|
||||
syncOK(t)
|
||||
srv := serverBundle(t, fake)
|
||||
if len(srv.Providers) != 0 || !unset(srv, "settings") {
|
||||
t.Fatalf("server got b's: providers %v, settings %+v", serverIDs(srv), srv.Settings)
|
||||
}
|
||||
}
|
||||
|
||||
// A part turned back on is joined as on a first sync: this computer,
|
||||
// which had none, takes the server's.
|
||||
func TestSyncPartTurnedBackOn(t *testing.T) {
|
||||
_, cfg := scopeServer(t)
|
||||
a := newComputer(t)
|
||||
a.use(t)
|
||||
provider.Save(provider.Provider{ID: "pa", Name: "A", Chat: "https://a/v1", Key: "ka"})
|
||||
Configure(cfg)
|
||||
syncOK(t)
|
||||
|
||||
b := newComputer(t)
|
||||
b.use(t)
|
||||
no := false
|
||||
off := cfg
|
||||
off.Providers = &no
|
||||
Configure(off)
|
||||
syncOK(t)
|
||||
if got := ids(); len(got) != 0 {
|
||||
t.Fatalf("b's providers with them off: %v", got)
|
||||
}
|
||||
Configure(cfg)
|
||||
syncOK(t)
|
||||
if got := ids(); !slices.Equal(got, []string{"pa=ka"}) {
|
||||
t.Fatalf("b's providers turned back on: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Preview says what the sync then does, changing nothing itself; a sync
|
||||
// asked for by its token runs only while it would still do that.
|
||||
func TestPreviewThenSync(t *testing.T) {
|
||||
fake, cfg := scopeServer(t)
|
||||
a := newComputer(t)
|
||||
a.use(t)
|
||||
provider.Save(provider.Provider{ID: "pa", Name: "A", Chat: "https://a/v1", Key: "ka"})
|
||||
Configure(cfg)
|
||||
syncOK(t)
|
||||
|
||||
b := newComputer(t)
|
||||
b.use(t)
|
||||
provider.Save(provider.Provider{ID: "pb", Name: "B", Chat: "https://b/v1", Key: "kb"})
|
||||
Configure(cfg)
|
||||
puts := fake.puts
|
||||
p, err := Preview(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fake.puts != puts || !slices.Equal(ids(), []string{"pb=kb"}) {
|
||||
t.Fatalf("the preview changed something: %d puts, providers %v", fake.puts-puts, ids())
|
||||
}
|
||||
var prov PartPlan
|
||||
for _, pp := range p.Parts {
|
||||
if pp.Part == "providers" {
|
||||
prov = pp
|
||||
}
|
||||
}
|
||||
want := []Item{{Kind: "provider", Name: "A", Change: "added"}, {Kind: "provider", Name: "B", Change: "removed"}}
|
||||
if prov.Do != "in" || !prov.Replaces || !slices.Equal(prov.Items, want) {
|
||||
t.Fatalf("providers' plan: %+v", prov)
|
||||
}
|
||||
if p.Token == "" {
|
||||
t.Fatal("no token")
|
||||
}
|
||||
|
||||
// a changes the server meanwhile: the preview is stale, nothing runs
|
||||
a.use(t)
|
||||
provider.Save(provider.Provider{ID: "pz", Name: "Z", Chat: "https://z/v1", Key: "kz"})
|
||||
syncOK(t)
|
||||
b.use(t)
|
||||
if err := SyncPreviewed(context.Background(), p.Token); !errors.Is(err, ErrPlanChanged) {
|
||||
t.Fatalf("a stale preview: %v", err)
|
||||
}
|
||||
if got := ids(); !slices.Equal(got, []string{"pb=kb"}) {
|
||||
t.Fatalf("a stale preview synced: %v", got)
|
||||
}
|
||||
p, err = Preview(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SyncPreviewed(context.Background(), p.Token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := ids(); !slices.Equal(got, []string{"pa=ka", "pz=kz"}) {
|
||||
t.Fatalf("after the previewed sync: %v", got)
|
||||
}
|
||||
// nothing left to do: every part the same
|
||||
p, err = Preview(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, pp := range p.Parts {
|
||||
if pp.Do != "same" {
|
||||
t.Fatalf("after syncing, %s: %+v", pp.Part, pp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// UndoSync puts back what the last sync brought in, on this computer
|
||||
// only; a part changed here since is written over only when asked.
|
||||
func TestUndoSync(t *testing.T) {
|
||||
fake, cfg := scopeServer(t)
|
||||
a := newComputer(t)
|
||||
a.use(t)
|
||||
provider.Save(provider.Provider{ID: "pa", Name: "A", Chat: "https://a/v1", Key: "ka"})
|
||||
Configure(cfg)
|
||||
syncOK(t)
|
||||
b := newComputer(t)
|
||||
b.use(t)
|
||||
Configure(cfg)
|
||||
syncOK(t)
|
||||
|
||||
a.use(t)
|
||||
provider.Save(provider.Provider{ID: "pz", Name: "Z", Chat: "https://z/v1", Key: "kz"})
|
||||
syncOK(t)
|
||||
b.use(t)
|
||||
v := syncOK(t)
|
||||
if v.Applied == nil || !slices.Equal(v.Applied.Parts, []string{"providers"}) {
|
||||
t.Fatalf("applied: %+v", v.Applied)
|
||||
}
|
||||
if got := ids(); !slices.Equal(got, []string{"pa=ka", "pz=kz"}) {
|
||||
t.Fatalf("b brought in: %v", got)
|
||||
}
|
||||
back, err := UndoSync(false)
|
||||
if err != nil || !slices.Equal(back, []string{"providers"}) {
|
||||
t.Fatalf("undo: %v %v", back, err)
|
||||
}
|
||||
if got := ids(); !slices.Equal(got, []string{"pa=ka"}) {
|
||||
t.Fatalf("b after undo: %v", got)
|
||||
}
|
||||
if Status().Applied != nil {
|
||||
t.Fatal("still undoable")
|
||||
}
|
||||
// it stays here: the next sync sends nothing, and the server keeps pz
|
||||
puts := fake.puts
|
||||
syncOK(t)
|
||||
if fake.puts != puts {
|
||||
t.Fatalf("the undo went up (%d puts)", fake.puts-puts)
|
||||
}
|
||||
if got := ids(); !slices.Equal(got, []string{"pa=ka"}) {
|
||||
t.Fatalf("b after the next sync: %v", got)
|
||||
}
|
||||
if got := serverIDs(serverBundle(t, fake)); !slices.Equal(got, []string{"pa", "pz"}) {
|
||||
t.Fatalf("server after b's undo: %v", got)
|
||||
}
|
||||
|
||||
// changed here since: asked first
|
||||
a.use(t)
|
||||
provider.Save(provider.Provider{ID: "py", Name: "Y", Chat: "https://y/v1", Key: "ky"})
|
||||
syncOK(t)
|
||||
b.use(t)
|
||||
syncOK(t)
|
||||
provider.Save(provider.Provider{ID: "pb", Name: "B", Chat: "https://b/v1", Key: "kb"})
|
||||
var since *ChangedSince
|
||||
if _, err := UndoSync(false); !errors.As(err, &since) || !slices.Equal(since.Parts, []string{"providers"}) {
|
||||
t.Fatalf("undo over a change: %v", err)
|
||||
}
|
||||
if _, err := UndoSync(true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := ids(); !slices.Equal(got, []string{"pa=ka"}) {
|
||||
t.Fatalf("b after undo anyway: %v", got)
|
||||
}
|
||||
}
|
||||
@@ -26,12 +26,17 @@ type Setup struct {
|
||||
Region string `json:"region,omitempty"`
|
||||
PathStyle bool `json:"pathStyle,omitempty"`
|
||||
Branch string `json:"branch,omitempty"`
|
||||
Keys bool `json:"keys"`
|
||||
Agents bool `json:"agents"`
|
||||
Library bool `json:"library"`
|
||||
Memory bool `json:"memory"`
|
||||
Usage bool `json:"usage,omitempty"`
|
||||
SignIns bool `json:"signIns,omitempty"`
|
||||
// Providers, Settings and Profiles are false when left out of sync;
|
||||
// nil, as from a magpie before they could be, is synced.
|
||||
Providers *bool `json:"providers,omitempty"`
|
||||
Settings *bool `json:"settings,omitempty"`
|
||||
Profiles *bool `json:"profiles,omitempty"`
|
||||
Keys bool `json:"keys"`
|
||||
Agents bool `json:"agents"`
|
||||
Library bool `json:"library"`
|
||||
Memory bool `json:"memory"`
|
||||
Usage bool `json:"usage,omitempty"`
|
||||
SignIns bool `json:"signIns,omitempty"`
|
||||
}
|
||||
|
||||
// ErrSetupOff is SetupText with sync off: there is nothing to copy.
|
||||
@@ -56,7 +61,7 @@ func SetupText() (string, error) {
|
||||
}
|
||||
b, err := json.Marshal(Setup{URL: c.URL, User: c.User, Password: c.Password, Endpoint: c.Endpoint, Region: c.Region,
|
||||
PathStyle: c.PathStyle, Branch: c.Branch, Keys: c.Keys, Agents: c.Agents, Library: c.library(), Memory: c.memoryOn(),
|
||||
Usage: c.Usage, SignIns: c.SignIns})
|
||||
Usage: c.Usage, SignIns: c.SignIns, Providers: offOnly(c.Providers), Settings: offOnly(c.Settings), Profiles: offOnly(c.Profiles)})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -67,6 +72,15 @@ func SetupText() (string, error) {
|
||||
return SetupPrefix + base64.RawURLEncoding.EncodeToString(sealed), nil
|
||||
}
|
||||
|
||||
// offOnly is b as a setup carries it: false, or nil for synced.
|
||||
func offOnly(b *bool) *bool {
|
||||
if yes(b) {
|
||||
return nil
|
||||
}
|
||||
f := false
|
||||
return &f
|
||||
}
|
||||
|
||||
// setupBody is the setup's text after its prefix, to the first character
|
||||
// that can't be in it: line breaks and spaces a chat or a mail wrapped it
|
||||
// with are in it, and taken out after.
|
||||
|
||||
@@ -82,3 +82,23 @@ func writeSetup(t *testing.T, c Config) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// A setup that leaves providers and settings out of sync (#6428) opens on
|
||||
// the next computer with them left out too; one that syncs them says
|
||||
// nothing, so a setup from before the choice opens the same.
|
||||
func TestSetupTextCarriesWhatStaysHere(t *testing.T) {
|
||||
newComputer(t).use(t)
|
||||
no := false
|
||||
writeSetup(t, Config{URL: "https://dav.example.com/dav/", User: "me", Password: "pw", Passphrase: "correct horse", Providers: &no, Settings: &no})
|
||||
text, err := SetupText()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := OpenSetupText(text, "correct horse")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.Providers == nil || *s.Providers || s.Settings == nil || *s.Settings || s.Profiles != nil {
|
||||
t.Fatalf("opened providers %v, settings %v, profiles %v", s.Providers, s.Settings, s.Profiles)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4757,7 +4757,8 @@ body.panel .modal { padding: 16px 12px; }
|
||||
.editor label.tick input { margin: 0; }
|
||||
.editor .fname { flex: 1; min-width: 0; font-size: 12.5px; color: var(--fg-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.editor.sync-form .done { grid-column: 1 / -1; font-size: 12.5px; color: var(--fg-2); user-select: text; -webkit-user-select: text; }
|
||||
.editor.sync-form .bar { grid-column: 1 / -1; }
|
||||
/* Preview beside Save (#6428): a narrow window puts the buttons on a second line, at the end */
|
||||
.editor.sync-form .bar { grid-column: 1 / -1; flex-wrap: wrap; justify-content: flex-end; row-gap: 6px; }
|
||||
/* Back up by itself (autobackup.js): a control too wide for the row goes
|
||||
under its name, at the right, as Agents' rows do */
|
||||
.prefs .row.pref.auto-backup { flex-wrap: wrap; row-gap: 8px; }
|
||||
@@ -5403,3 +5404,9 @@ body .row.agent .ag-prefs .row.pref .who { display: block; }
|
||||
body.linux .modal, body.linux .pop, body.linux.panel .profiles.open,
|
||||
body.linux:not(.side-nav) #view-settings .set-head::before,
|
||||
body.linux .action-confirm::backdrop { -webkit-backdrop-filter: none; backdrop-filter: none; }
|
||||
/* what syncs (#6428): the keys' tick under Providers; a preview's items */
|
||||
.editor.sync-form .sync-sub-tick { padding-left: 22px; }
|
||||
.sync-preview .sync-items { display: grid; gap: 2px; margin: -2px 0 8px; padding: 6px 10px; border-radius: 8px; background: var(--pill); font-size: 12.5px; max-height: 180px; overflow-y: auto; }
|
||||
.sync-preview .sync-item { display: flex; justify-content: space-between; gap: 12px; min-width: 0; }
|
||||
.sync-preview .sync-item span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.sync-preview .sync-item .sub, .sync-preview .sync-items > .sub, .sync-preview .lib-confirm.sub { color: var(--muted); }
|
||||
|
||||
@@ -176,6 +176,7 @@ async function api(path, body, heads, signal) {
|
||||
setTimeout(() => configBlockedAsk(data.blocked), 0);
|
||||
}
|
||||
if (data?.why) err.why = data.why; // a failed move's reason, said in the reader's language
|
||||
if (data?.changed) err.changed = data.changed; // an undo's parts changed since (davsync/undo-sync)
|
||||
if (data?.said) err.message = t(data.said, data); // an i18n.js key (api.go)
|
||||
// an account the agent is signed in to, refused removal while it has
|
||||
// another: said in the reader's language
|
||||
@@ -20352,17 +20353,14 @@ async function renderSync(v) {
|
||||
};
|
||||
const btn = (label, fn, cls = "text") => { const b = el("button", cls, label); b.onclick = fn; return b; };
|
||||
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", memory: "memory", usage: "usage", signins: "sign-ins" }[p])).join(t(", "));
|
||||
const parts = window.syncParts = (ps) => ps.map((p) => t({ providers: "providers", settings: "settings", profiles: "profiles", agents: "agents' models", library: "library", memory: "memory", usage: "usage", signins: "sign-ins" }[p])).join(t(", "));
|
||||
|
||||
// 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");
|
||||
if (v.memory !== false) goes.push("memory");
|
||||
const goes = ["settings", "profiles", "agents", "library", "memory"].filter((p) => v[p] !== false);
|
||||
if (v.usage) goes.push("usage");
|
||||
if (v.signIns) goes.push("signins");
|
||||
let line = t("Keeps {parts} the same on every computer", {
|
||||
parts: t(v.keys === false ? "providers without their API keys" : "providers with their API keys") + t(", ") + parts(goes) });
|
||||
const provs = v.providers === false ? [] : [t(v.keys === false ? "providers without their API keys" : "providers with their API keys")];
|
||||
let line = t("Keeps {parts} the same on every computer", { parts: [...provs, parts(goes)].filter(Boolean).join(t(", ")) });
|
||||
const s3 = v.on && v.kind === "s3";
|
||||
const github = v.on && v.kind === "github";
|
||||
if (v.on) {
|
||||
@@ -20424,6 +20422,9 @@ async function renderSync(v) {
|
||||
}
|
||||
if (syncOpen === "dav") box.append(syncFile("davForm", v));
|
||||
if (v.on) {
|
||||
// the parts left out of sync, Preview a sync and Undo the last sync
|
||||
// (#6428), in syncfiles.js
|
||||
syncFile("askPreviewRows", box.appendChild(el("div")), v, sub);
|
||||
// how often it syncs by itself, or never: a free 坚果云 account is
|
||||
// allowed only so many requests (#847)
|
||||
const every = v.auto ?? 3;
|
||||
|
||||
+136
-7
@@ -3258,6 +3258,40 @@ const I18N = {
|
||||
"MinIO and most NAS servers need it.": "MinIO 和大多数 NAS 需要勾选。",
|
||||
"Name the bucket": "请填写存储桶名称",
|
||||
"Keeps {parts} the same on every computer": "让每台电脑上的{parts}保持一致",
|
||||
"With their API keys": "连同它们的 API Key",
|
||||
"What syncs": "同步内容",
|
||||
"What isn't ticked stays as it is on each computer.": "未勾选的项目在每台电脑上各自保留。",
|
||||
"Preview": "预览",
|
||||
"Preview…": "预览…",
|
||||
"Save and sync": "保存并同步",
|
||||
"Preview of the sync": "同步预览",
|
||||
"and {n} more": "还有 {n} 项",
|
||||
"added": "新增",
|
||||
"removed": "移除",
|
||||
"changed": "更改",
|
||||
"The server has no backup yet: this computer's setup goes up.": "服务器上还没有备份:将上传这台电脑的配置。",
|
||||
"Comes here from the server: {part}": "从服务器同步到这台电脑:{part}",
|
||||
"It was changed here too: the server's newer one replaces it, and what is here is kept in the sync folder first.": "这台电脑上也改过:服务器上较新的版本会替换它,替换前这里的版本会先保存在同步文件夹中。",
|
||||
"Goes to the server from here: {part}": "从这台电脑上传到服务器:{part}",
|
||||
"Memory: {n} come here": "记忆:{n} 条同步到这台电脑",
|
||||
"Memory: {n} go to the server": "记忆:{n} 条上传到服务器",
|
||||
"Sign-ins: {n} change here": "登录:这台电脑上有 {n} 项变化",
|
||||
"Plugins removed here, as another computer removed them: {names}": "另一台电脑移除了这些插件,这里也会移除:{names}",
|
||||
"Nothing to sync: this computer and the server are the same.": "无需同步:这台电脑与服务器一致。",
|
||||
"Already the same: {parts}": "已经一致:{parts}",
|
||||
"Stays as it is on each computer: {parts}": "每台电脑各自保留:{parts}",
|
||||
"Undo the last sync?": "撤销上次同步?",
|
||||
"This computer's {parts} go back to how they were before the sync {when}. The server and your other computers keep theirs.": "这台电脑的{parts}会恢复到{when}同步之前的样子。服务器和你的其他电脑保持不变。",
|
||||
"What is here now is kept in the sync folder first.": "当前这里的内容会先保存在同步文件夹中。",
|
||||
"Undo sync": "撤销同步",
|
||||
"{parts} changed here since the sync. Undoing replaces those changes too.": "同步之后这台电脑上的{parts}又改过。撤销会把这些改动一并替换。",
|
||||
"Undo anyway": "仍然撤销",
|
||||
"Undo…": "撤销…",
|
||||
"Preview a sync": "预览同步",
|
||||
"What syncing now would change, here and on the server. Nothing changes until you sync.": "查看现在同步会在这台电脑和服务器上改变什么。同步之前不会有任何改动。",
|
||||
"Undo the last sync": "撤销上次同步",
|
||||
"It brought {parts} here {when}. Undo puts back what was here before, on this computer only.": "它在{when}把{parts}同步到了这台电脑。撤销会恢复之前的内容,只影响这台电脑。",
|
||||
"something changed since the preview: look at it again before syncing": "预览之后有内容发生了变化:请在同步前再看一遍",
|
||||
"providers with their API keys": "供应商(含 API Key)",
|
||||
"providers without their API keys": "供应商(不含 API Key)",
|
||||
"Couldn't sync: {error}": "同步失败:{error}",
|
||||
@@ -3355,7 +3389,6 @@ const I18N = {
|
||||
"saved · type a new one to replace it": "已保存 · 输入新的即可替换",
|
||||
"password, or an app password": "密码或应用密码",
|
||||
"the same on every computer": "每台电脑上都一样",
|
||||
"Providers' API keys": "供应商的 API Key",
|
||||
"Agents' models": "各 agent 选的模型",
|
||||
"Library: instructions, MCP servers, skills, hooks and subagents": "资源库:指令、MCP 服务器、技能、Hooks 和子代理",
|
||||
"Usage: this computer's calls, for the Usage page on the others": "用量:本机的请求,在其他电脑的用量页里显示",
|
||||
@@ -8440,6 +8473,40 @@ const I18N = {
|
||||
"MinIO and most NAS servers need it.": "MinIO 和大多數 NAS 需要勾選。",
|
||||
"Name the bucket": "請填寫儲存桶名稱",
|
||||
"Keeps {parts} the same on every computer": "讓每臺電腦上的{parts}保持一致",
|
||||
"With their API keys": "連同它們的 API Key",
|
||||
"What syncs": "同步內容",
|
||||
"What isn't ticked stays as it is on each computer.": "未勾選的項目在每臺電腦上各自保留。",
|
||||
"Preview": "預覽",
|
||||
"Preview…": "預覽…",
|
||||
"Save and sync": "儲存並同步",
|
||||
"Preview of the sync": "同步預覽",
|
||||
"and {n} more": "還有 {n} 項",
|
||||
"added": "新增",
|
||||
"removed": "移除",
|
||||
"changed": "變更",
|
||||
"The server has no backup yet: this computer's setup goes up.": "伺服器上還沒有備份:將上傳這臺電腦的設定。",
|
||||
"Comes here from the server: {part}": "從伺服器同步到這臺電腦:{part}",
|
||||
"It was changed here too: the server's newer one replaces it, and what is here is kept in the sync folder first.": "這臺電腦上也改過:伺服器上較新的版本會取代它,取代前這裡的版本會先保存在同步資料夾中。",
|
||||
"Goes to the server from here: {part}": "從這臺電腦上傳到伺服器:{part}",
|
||||
"Memory: {n} come here": "記憶:{n} 條同步到這臺電腦",
|
||||
"Memory: {n} go to the server": "記憶:{n} 條上傳到伺服器",
|
||||
"Sign-ins: {n} change here": "登入:這臺電腦上有 {n} 項變化",
|
||||
"Plugins removed here, as another computer removed them: {names}": "另一臺電腦移除了這些外掛,這裡也會移除:{names}",
|
||||
"Nothing to sync: this computer and the server are the same.": "無需同步:這臺電腦與伺服器一致。",
|
||||
"Already the same: {parts}": "已經一致:{parts}",
|
||||
"Stays as it is on each computer: {parts}": "每臺電腦各自保留:{parts}",
|
||||
"Undo the last sync?": "復原上次同步?",
|
||||
"This computer's {parts} go back to how they were before the sync {when}. The server and your other computers keep theirs.": "這臺電腦的{parts}會恢復到{when}同步之前的樣子。伺服器和你的其他電腦保持不變。",
|
||||
"What is here now is kept in the sync folder first.": "目前這裡的內容會先保存在同步資料夾中。",
|
||||
"Undo sync": "復原同步",
|
||||
"{parts} changed here since the sync. Undoing replaces those changes too.": "同步之後這臺電腦上的{parts}又改過。復原會把這些改動一併取代。",
|
||||
"Undo anyway": "仍然復原",
|
||||
"Undo…": "復原…",
|
||||
"Preview a sync": "預覽同步",
|
||||
"What syncing now would change, here and on the server. Nothing changes until you sync.": "查看現在同步會在這臺電腦和伺服器上改變什麼。同步之前不會有任何改動。",
|
||||
"Undo the last sync": "復原上次同步",
|
||||
"It brought {parts} here {when}. Undo puts back what was here before, on this computer only.": "它在{when}把{parts}同步到了這臺電腦。復原會還原之前的內容,只影響這臺電腦。",
|
||||
"something changed since the preview: look at it again before syncing": "預覽之後有內容發生了變化:請在同步前再看一遍",
|
||||
"providers with their API keys": "供應商(含 API Key)",
|
||||
"providers without their API keys": "供應商(不含 API Key)",
|
||||
"Couldn't sync: {error}": "同步失敗:{error}",
|
||||
@@ -8543,7 +8610,6 @@ const I18N = {
|
||||
"saved · type a new one to replace it": "已儲存 · 輸入新的即可替換",
|
||||
"password, or an app password": "密碼或應用密碼",
|
||||
"the same on every computer": "每臺電腦上都一樣",
|
||||
"Providers' API keys": "供應商的 API Key",
|
||||
"Agents' models": "各 agent 選的模型",
|
||||
"Library: instructions, MCP servers, skills, hooks and subagents": "資源庫:指令、MCP 伺服器、技能、Hooks 和子代理",
|
||||
"Usage: this computer's calls, for the Usage page on the others": "用量:本機的請求,在其他電腦的用量頁裡顯示",
|
||||
@@ -8578,7 +8644,6 @@ const I18N = {
|
||||
"User": "使用者",
|
||||
"Password": "密碼",
|
||||
"Passphrase": "口令",
|
||||
"Also sync": "同時同步",
|
||||
"A folder named magpie is made in it.": "會在其中建一個名為 magpie 的資料夾。",
|
||||
"The file is sealed with it on this computer; the server only ever sees it sealed. Keep it: without it the file can't be opened.": "檔案在本機用它加密,伺服器只能看到加密後的內容。請記住它:沒有口令無法開啟檔案。",
|
||||
"Turn on": "開啟",
|
||||
@@ -13641,6 +13706,40 @@ const I18N = {
|
||||
"MinIO and most NAS servers need it.": "MinIO やほとんどの NAS サーバーで必要です。",
|
||||
"Name the bucket": "バケット名を入力してください",
|
||||
"Keeps {parts} the same on every computer": "{parts}をすべてのコンピューターで同じに保ちます",
|
||||
"With their API keys": "APIキーも含める",
|
||||
"What syncs": "同期するもの",
|
||||
"What isn't ticked stays as it is on each computer.": "チェックしていないものは、各コンピューターでそのまま保たれます。",
|
||||
"Preview": "プレビュー",
|
||||
"Preview…": "プレビュー…",
|
||||
"Save and sync": "保存して同期",
|
||||
"Preview of the sync": "同期のプレビュー",
|
||||
"and {n} more": "ほか {n} 件",
|
||||
"added": "追加",
|
||||
"removed": "削除",
|
||||
"changed": "変更",
|
||||
"The server has no backup yet: this computer's setup goes up.": "サーバーにはまだバックアップがありません。このコンピューターの構成がアップロードされます。",
|
||||
"Comes here from the server: {part}": "サーバーからこのコンピューターへ:{part}",
|
||||
"It was changed here too: the server's newer one replaces it, and what is here is kept in the sync folder first.": "このコンピューターでも変更されています。サーバーの新しいほうで置き換えられ、ここにあるものは先に同期フォルダーに保存されます。",
|
||||
"Goes to the server from here: {part}": "このコンピューターからサーバーへ:{part}",
|
||||
"Memory: {n} come here": "メモリー:{n} 件がこのコンピューターへ",
|
||||
"Memory: {n} go to the server": "メモリー:{n} 件がサーバーへ",
|
||||
"Sign-ins: {n} change here": "サインイン:このコンピューターで {n} 件変わります",
|
||||
"Plugins removed here, as another computer removed them: {names}": "別のコンピューターで削除されたため、ここでも削除されるプラグイン:{names}",
|
||||
"Nothing to sync: this computer and the server are the same.": "同期するものはありません。このコンピューターとサーバーは同じです。",
|
||||
"Already the same: {parts}": "すでに同じ:{parts}",
|
||||
"Stays as it is on each computer: {parts}": "各コンピューターでそのまま:{parts}",
|
||||
"Undo the last sync?": "前回の同期を取り消しますか?",
|
||||
"This computer's {parts} go back to how they were before the sync {when}. The server and your other computers keep theirs.": "このコンピューターの{parts}が、{when}の同期の前の状態に戻ります。サーバーとほかのコンピューターはそのままです。",
|
||||
"What is here now is kept in the sync folder first.": "いまここにあるものは、先に同期フォルダーに保存されます。",
|
||||
"Undo sync": "同期を取り消す",
|
||||
"{parts} changed here since the sync. Undoing replaces those changes too.": "同期のあと、ここで{parts}が変更されています。取り消すとその変更も置き換えられます。",
|
||||
"Undo anyway": "それでも取り消す",
|
||||
"Undo…": "取り消す…",
|
||||
"Preview a sync": "同期をプレビュー",
|
||||
"What syncing now would change, here and on the server. Nothing changes until you sync.": "いま同期すると、ここやサーバーで何が変わるかを表示します。同期するまで何も変わりません。",
|
||||
"Undo the last sync": "前回の同期を取り消す",
|
||||
"It brought {parts} here {when}. Undo puts back what was here before, on this computer only.": "{when}に{parts}をこのコンピューターに取り込みました。取り消すと、このコンピューターだけ前の状態に戻ります。",
|
||||
"something changed since the preview: look at it again before syncing": "プレビューのあとで変更がありました。同期する前にもう一度確認してください",
|
||||
"providers with their API keys": "プロバイダ(APIキーを含む)",
|
||||
"providers without their API keys": "プロバイダ(APIキーを除く)",
|
||||
"Couldn't sync: {error}": "同期できませんでした:{error}",
|
||||
@@ -13744,7 +13843,6 @@ const I18N = {
|
||||
"saved · type a new one to replace it": "保存済み · 置き換えるには新しく入力",
|
||||
"password, or an app password": "パスワードまたはアプリパスワード",
|
||||
"the same on every computer": "すべてのコンピューターで共通",
|
||||
"Providers' API keys": "プロバイダの APIキー",
|
||||
"Agents' models": "エージェントのモデル",
|
||||
"Library: instructions, MCP servers, skills, hooks and subagents": "ライブラリ:指示、MCP サーバー、スキル、フック、サブエージェント",
|
||||
"Usage: this computer's calls, for the Usage page on the others": "使用量:このコンピューターの呼び出し(他のコンピューターの「使用量」ページ用)",
|
||||
@@ -13779,7 +13877,6 @@ const I18N = {
|
||||
"User": "ユーザー",
|
||||
"Password": "パスワード",
|
||||
"Passphrase": "パスフレーズ",
|
||||
"Also sync": "あわせて同期",
|
||||
"A folder named magpie is made in it.": "その中に magpie という名前のフォルダーが作られます。",
|
||||
"The file is sealed with it on this computer; the server only ever sees it sealed. Keep it: without it the file can't be opened.": "ファイルはこのコンピューター上でこれを使って暗号化され、サーバーには暗号化された状態でしか見えません。忘れないでください:これがないとファイルを開けません。",
|
||||
"Turn on": "オンにする",
|
||||
@@ -18851,6 +18948,40 @@ const I18N = {
|
||||
"MinIO and most NAS servers need it.": "MinIO und die meisten NAS-Server benötigen das.",
|
||||
"Name the bucket": "Bucket angeben",
|
||||
"Keeps {parts} the same on every computer": "Hält {parts} auf jedem Computer gleich",
|
||||
"With their API keys": "Mit ihren API-Schlüsseln",
|
||||
"What syncs": "Was synchronisiert wird",
|
||||
"What isn't ticked stays as it is on each computer.": "Was nicht angehakt ist, bleibt auf jedem Computer, wie es ist.",
|
||||
"Preview": "Vorschau",
|
||||
"Preview…": "Vorschau…",
|
||||
"Save and sync": "Speichern und synchronisieren",
|
||||
"Preview of the sync": "Vorschau der Synchronisierung",
|
||||
"and {n} more": "und {n} weitere",
|
||||
"added": "hinzugefügt",
|
||||
"removed": "entfernt",
|
||||
"changed": "geändert",
|
||||
"The server has no backup yet: this computer's setup goes up.": "Auf dem Server ist noch kein Backup: Die Einrichtung dieses Computers wird hochgeladen.",
|
||||
"Comes here from the server: {part}": "Kommt vom Server hierher: {part}",
|
||||
"It was changed here too: the server's newer one replaces it, and what is here is kept in the sync folder first.": "Es wurde auch hier geändert: Die neuere Fassung vom Server ersetzt es, und was hier ist, wird zuerst im Sync-Ordner aufbewahrt.",
|
||||
"Goes to the server from here: {part}": "Geht von hier zum Server: {part}",
|
||||
"Memory: {n} come here": "Gedächtnis: {n} kommen hierher",
|
||||
"Memory: {n} go to the server": "Gedächtnis: {n} gehen zum Server",
|
||||
"Sign-ins: {n} change here": "Anmeldungen: {n} ändern sich hier",
|
||||
"Plugins removed here, as another computer removed them: {names}": "Hier entfernte Plugins, weil ein anderer Computer sie entfernt hat: {names}",
|
||||
"Nothing to sync: this computer and the server are the same.": "Nichts zu synchronisieren: Dieser Computer und der Server sind gleich.",
|
||||
"Already the same: {parts}": "Schon gleich: {parts}",
|
||||
"Stays as it is on each computer: {parts}": "Bleibt auf jedem Computer, wie es ist: {parts}",
|
||||
"Undo the last sync?": "Letzte Synchronisierung rückgängig machen?",
|
||||
"This computer's {parts} go back to how they were before the sync {when}. The server and your other computers keep theirs.": "Die {parts} dieses Computers werden wieder so, wie sie vor der Synchronisierung {when} waren. Der Server und deine anderen Computer behalten ihre.",
|
||||
"What is here now is kept in the sync folder first.": "Was jetzt hier ist, wird zuerst im Sync-Ordner aufbewahrt.",
|
||||
"Undo sync": "Synchronisierung rückgängig machen",
|
||||
"{parts} changed here since the sync. Undoing replaces those changes too.": "{parts} wurden seit der Synchronisierung hier geändert. Rückgängig machen ersetzt auch diese Änderungen.",
|
||||
"Undo anyway": "Trotzdem rückgängig machen",
|
||||
"Undo…": "Rückgängig…",
|
||||
"Preview a sync": "Synchronisierung vorab ansehen",
|
||||
"What syncing now would change, here and on the server. Nothing changes until you sync.": "Was eine Synchronisierung jetzt hier und auf dem Server ändern würde. Nichts ändert sich, bevor du synchronisierst.",
|
||||
"Undo the last sync": "Letzte Synchronisierung rückgängig machen",
|
||||
"It brought {parts} here {when}. Undo puts back what was here before, on this computer only.": "Sie hat {when} {parts} hierher gebracht. Rückgängig stellt wieder her, was vorher hier war, nur auf diesem Computer.",
|
||||
"something changed since the preview: look at it again before syncing": "Seit der Vorschau hat sich etwas geändert: Sieh sie dir vor dem Synchronisieren noch einmal an",
|
||||
"providers with their API keys": "Anbieter mit ihren API-Schlüsseln",
|
||||
"providers without their API keys": "Anbieter ohne ihre API-Schlüssel",
|
||||
"Couldn't sync: {error}": "Synchronisierung fehlgeschlagen: {error}",
|
||||
@@ -18954,7 +19085,6 @@ const I18N = {
|
||||
"saved · type a new one to replace it": "gespeichert · zum Ersetzen neu eingeben",
|
||||
"password, or an app password": "Passwort oder App-Passwort",
|
||||
"the same on every computer": "auf jedem Computer gleich",
|
||||
"Providers' API keys": "API-Schlüssel der Anbieter",
|
||||
"Agents' models": "Modelle der Agenten",
|
||||
"Library: instructions, MCP servers, skills, hooks and subagents": "Bibliothek: Anweisungen, MCP-Server, Skills, Hooks und Subagenten",
|
||||
"Usage: this computer's calls, for the Usage page on the others": "Nutzung: Aufrufe dieses Computers, für die Seite „Nutzung“ auf den anderen",
|
||||
@@ -18989,7 +19119,6 @@ const I18N = {
|
||||
"User": "Benutzer",
|
||||
"Password": "Passwort",
|
||||
"Passphrase": "Passphrase",
|
||||
"Also sync": "Auch synchronisieren",
|
||||
"A folder named magpie is made in it.": "Darin wird ein Ordner namens magpie angelegt.",
|
||||
"The file is sealed with it on this computer; the server only ever sees it sealed. Keep it: without it the file can't be opened.": "Die Datei wird damit auf diesem Computer verschlüsselt; der Server sieht sie nur verschlüsselt. Bewahren Sie die Passphrase auf: Ohne sie lässt sich die Datei nicht öffnen.",
|
||||
"Turn on": "Einschalten",
|
||||
|
||||
@@ -32,10 +32,20 @@ window.davForm = function (v) {
|
||||
const ghPrefix = input(ghParts?.[2] || "", t("optional"));
|
||||
const token = input("", gh.passwordSet ? saved : t("GitHub token"), "password");
|
||||
const phrase = input("", v.passphraseSet ? saved : t("the same on every computer"), "password");
|
||||
const [keysL, keys] = tick(t("Providers' API keys"), v.keys !== false);
|
||||
// what syncs (#6428, jinpwng on X): a part not ticked stays as it is on
|
||||
// each computer, and the server keeps the others' copy of it
|
||||
const [provL, prov] = tick(t("Providers"), v.providers !== false);
|
||||
const [keysL, keys] = tick(t("With their API keys"), v.keys !== false);
|
||||
keysL.classList.add("sync-sub-tick");
|
||||
const [setL, sets] = tick(t("Settings"), v.settings !== false);
|
||||
const [agentsL, agents] = tick(t("Agents' models"), v.agents !== false);
|
||||
const [libL, lib] = tick(t("Library: instructions, MCP servers, skills, hooks and subagents"), v.library !== false);
|
||||
const [memL, mem] = tick(t("Memory: what the agents know, merged memory by memory"), v.memory !== false);
|
||||
const keysShow = () => { keysL.hidden = !prov.checked; };
|
||||
keysShow();
|
||||
prov.onchange = keysShow;
|
||||
// rarely changed: under Advanced, open when one is set away from its default
|
||||
const [profL, prof] = tick(t("Profiles"), v.profiles !== false);
|
||||
// usage: off unless picked, each computer its own (#542)
|
||||
const [useL, use] = tick(t("Usage: this computer's calls, for the Usage page on the others"), !!v.usage);
|
||||
// sign-ins: off unless picked, sealed with the passphrase like the rest
|
||||
@@ -45,7 +55,12 @@ window.davForm = function (v) {
|
||||
siSay.hidden = !si.checked;
|
||||
si.onchange = () => { siSay.hidden = !si.checked; };
|
||||
const what = el("div", "stack");
|
||||
what.append(keysL, agentsL, libL, memL, useL, siL, siSay);
|
||||
what.append(provL, keysL, setL, agentsL, libL, memL);
|
||||
const adv = el("details", "more advanced sync-advanced");
|
||||
adv.open = v.profiles === false || !!v.usage || !!v.signIns;
|
||||
const advIn = el("div", "stack");
|
||||
advIn.append(profL, useL, siL, siSay, el("div", "hint", t("Usage goes as a file a day: times, tokens, models and costs, never what was said. Turn it on on each computer that shares its own.")));
|
||||
adv.append(el("summary", "", t("Advanced")), advIn);
|
||||
const davFields = [...field(t("Address"), url, t("A folder named magpie is made in it.")),
|
||||
...field(t("User"), user),
|
||||
...field(t("Password"), pass)];
|
||||
@@ -78,14 +93,17 @@ window.davForm = function (v) {
|
||||
ed.append(...to,
|
||||
...davFields, ...s3Fields, ...ghFields,
|
||||
...field(t("Passphrase"), phrase, t("The file is sealed with it on this computer; the server only ever sees it sealed. Keep it: without it the file can't be opened.")),
|
||||
...field(t("Also sync"), what, t("Usage goes as a file a day: times, tokens, models and costs, never what was said. Turn it on on each computer that shares its own.")));
|
||||
...field(t("What syncs"), what, t("What isn't ticked stays as it is on each computer.")),
|
||||
...field("", adv));
|
||||
show();
|
||||
const off = v.on ? el("button", "text danger", t("Turn off")) : el("span");
|
||||
const cancel = el("button", "text", t("Cancel"));
|
||||
// this setup as text, for another computer (WJaunita45604 on X): sealed
|
||||
// with the passphrase, which the text never holds
|
||||
const copySetup = v.on ? el("button", "text sync-copy", t("Copy setup")) : el("span");
|
||||
const said = syncBar(ed, "", off, copySetup, el("span", "grow"), cancel, save);
|
||||
// what saving would sync, before it does (#6428)
|
||||
const peek = el("button", "text sync-peek", t("Preview"));
|
||||
const said = syncBar(ed, "", off, copySetup, el("span", "grow"), cancel, peek, save);
|
||||
const say = (msg, note) => { said(msg); ed.querySelector(".editor-error").classList.toggle("note", !!note); };
|
||||
copySetup.onclick = async () => {
|
||||
try {
|
||||
@@ -107,6 +125,10 @@ window.davForm = function (v) {
|
||||
repo.value = m?.[1] || ""; ghPrefix.value = m?.[2] || ""; branch.value = s.branch || ""; token.value = s.password || "";
|
||||
} else { url.value = s.url; user.value = s.user || ""; pass.value = s.password || ""; }
|
||||
keys.checked = !!s.keys; agents.checked = !!s.agents; lib.checked = !!s.library; mem.checked = !!s.memory; use.checked = !!s.usage; si.checked = !!s.signIns;
|
||||
// left out only when the setup says so: one from before the choice syncs them
|
||||
prov.checked = s.providers !== false; sets.checked = s.settings !== false; prof.checked = s.profiles !== false;
|
||||
keysShow();
|
||||
if (!prof.checked || use.checked || si.checked) adv.open = true;
|
||||
siSay.hidden = !si.checked;
|
||||
// the kind picked as a click on it would, its thumb moved too
|
||||
to[1].querySelector(`.segs [data-seg="${kind}"]`)?.click();
|
||||
@@ -137,23 +159,41 @@ window.davForm = function (v) {
|
||||
phrase.addEventListener("change", () => { if (pasted) openPasted(); });
|
||||
cancel.onclick = () => { syncOpen = ""; renderSync(); };
|
||||
off.onclick = async () => { syncOpen = ""; renderSync(await api("davsync/off", {}).catch(() => null) || undefined); };
|
||||
save.onclick = async () => {
|
||||
if (!(await openPasted())) return;
|
||||
// form: the setup as typed, or a reason it can't be saved yet
|
||||
const form = () => {
|
||||
const b = bucket.value.trim(), p = prefix.value.trim().replace(/^\/+|\/+$/g, "");
|
||||
if (kind === "s3" && !b) return say(t("Name the bucket"));
|
||||
if (kind === "s3" && !b) return t("Name the bucket");
|
||||
const repository = repo.value.trim().replace(/^https:\/\/github\.com\//i, "").replace(/\/+$/, "").replace(/\.git$/i, "");
|
||||
const ghFolder = ghPrefix.value.trim().replace(/^\/+|\/+$/g, "");
|
||||
if (kind === "github" && !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository)) return say(t("Name the GitHub repository as owner/repo"));
|
||||
if (kind === "github" && !gh.passwordSet && !token.value.trim()) return say(t("Enter a GitHub token with Contents read and write permission"));
|
||||
if (!v.passphraseSet && !phrase.value) return say(t("Pick a passphrase: the file is sealed with it"));
|
||||
save.classList.add("busy");
|
||||
if (kind === "github" && !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository)) return t("Name the GitHub repository as owner/repo");
|
||||
if (kind === "github" && !gh.passwordSet && !token.value.trim()) return t("Enter a GitHub token with Contents read and write permission");
|
||||
if (!v.passphraseSet && !phrase.value) return t("Pick a passphrase: the file is sealed with it");
|
||||
const where = kind === "github"
|
||||
? { url: "github://" + repository + (ghFolder ? "/" + ghFolder : ""), branch: branch.value.trim(), password: token.value.trim() }
|
||||
: kind === "s3"
|
||||
? { url: "s3://" + b + (p ? "/" + p : ""), user: keyID.value.trim(), password: secret.value, endpoint: endpoint.value.trim(), region: region.value.trim(), pathStyle: pathStyle.checked }
|
||||
: { url: url.value.trim(), user: user.value.trim(), password: pass.value };
|
||||
// a part left out is said; one synced only when it was left out before,
|
||||
// so a setup from before the choice is saved as it was
|
||||
const outs = {};
|
||||
for (const [k, c] of [["providers", prov], ["settings", sets], ["profiles", prof]]) if (!c.checked || v[k] === false) outs[k] = c.checked;
|
||||
return { ...where, passphrase: phrase.value, keys: keys.checked, agents: agents.checked, library: lib.checked, memory: mem.checked, ...outs, ...(use.checked || v.usage ? { usage: use.checked } : {}), ...(si.checked || v.signIns ? { signIns: si.checked } : {}) };
|
||||
};
|
||||
peek.onclick = async () => {
|
||||
if (!(await openPasted())) return;
|
||||
const f = form();
|
||||
if (typeof f === "string") return say(f);
|
||||
peek.classList.add("busy");
|
||||
try { askSyncPreview(await api("davsync/preview", { form: f }), () => save.click()); } catch (e) { say(t(e.message)); }
|
||||
peek.classList.remove("busy");
|
||||
};
|
||||
save.onclick = async () => {
|
||||
if (!(await openPasted())) return;
|
||||
const f = form();
|
||||
if (typeof f === "string") return say(f);
|
||||
save.classList.add("busy");
|
||||
try {
|
||||
const r = await api("davsync/save", { ...where, passphrase: phrase.value, keys: keys.checked, agents: agents.checked, library: lib.checked, memory: mem.checked, ...(use.checked || v.usage ? { usage: use.checked } : {}), ...(si.checked || v.signIns ? { signIns: si.checked } : {}) });
|
||||
const r = await api("davsync/save", f);
|
||||
if (!r.error) syncOpen = "";
|
||||
renderSync(r);
|
||||
if (r.error) return;
|
||||
@@ -279,9 +319,7 @@ window.askRestore = function (v, parts) {
|
||||
const head = el("div", "ehead");
|
||||
head.append(el("b", "", t("Restore from the server?")));
|
||||
ed.append(head);
|
||||
const goes = ["providers", "settings", "profiles"];
|
||||
if (v.agents !== false) goes.push("agents");
|
||||
if (v.library !== false) goes.push("library");
|
||||
const goes = ["providers", "settings", "profiles", "agents", "library"].filter((p) => v[p] !== false);
|
||||
ed.append(el("p", "lib-confirm", t("This computer's {parts} become the ones on the server, as your other computers last synced them. Whatever was changed here since is replaced.", { parts: parts(goes) })));
|
||||
ed.append(el("p", "lib-confirm", t("What is here now is sealed into the sync folder first, and Undo puts it back.")));
|
||||
const err = el("p", "editor-error", "");
|
||||
@@ -352,3 +390,158 @@ window.askUpload = function (f) {
|
||||
$("#modal").classList.add("lib");
|
||||
cancel.focus(NO_SCROLL);
|
||||
};
|
||||
|
||||
// askSyncPreview shows what syncing now would do (#6428, jinpwng on X),
|
||||
// nothing done yet: what comes here, what goes to the server, and what
|
||||
// stays as it is. go is the form's save, when the preview is of a setup
|
||||
// not saved yet; otherwise the sync shown is the one run, or none.
|
||||
window.askSyncPreview = function (plan, go) {
|
||||
const ed = el("div", "editor restore-ask sync-preview");
|
||||
const draw = (plan, note) => {
|
||||
ed.replaceChildren();
|
||||
const head = el("div", "ehead");
|
||||
head.append(el("b", "", t("Preview of the sync")));
|
||||
ed.append(head);
|
||||
const by = (d) => plan.parts.filter((p) => p.do === d);
|
||||
const items = (p) => {
|
||||
const list = el("div", "sync-items");
|
||||
const shown = (p.items || []).slice(0, 8);
|
||||
for (const it of shown) {
|
||||
const r = el("div", "sync-item");
|
||||
r.append(el("span", "", it.name || t(it.kind)), el("span", "sub", t({ added: "added", removed: "removed", changed: "changed" }[it.change] || it.change)));
|
||||
list.append(r);
|
||||
}
|
||||
if ((p.items || []).length > shown.length) list.append(el("div", "sub", t("and {n} more", { n: p.items.length - shown.length })));
|
||||
return list;
|
||||
};
|
||||
const ins = by("in"), ups = by("up");
|
||||
const mem = plan.memory || { in: 0, up: 0 };
|
||||
if (plan.empty) ed.append(el("p", "lib-confirm", t("The server has no backup yet: this computer's setup goes up.")));
|
||||
for (const p of ins) {
|
||||
ed.append(el("p", "lib-confirm", t("Comes here from the server: {part}", { part: syncParts([p.part]) })));
|
||||
if (p.replaces) ed.append(el("p", "lib-confirm sub", t("It was changed here too: the server's newer one replaces it, and what is here is kept in the sync folder first.")));
|
||||
if (p.items?.length) ed.append(items(p));
|
||||
}
|
||||
for (const p of ups) {
|
||||
ed.append(el("p", "lib-confirm", t("Goes to the server from here: {part}", { part: syncParts([p.part]) })));
|
||||
if (!plan.empty && p.items?.length) ed.append(items(p));
|
||||
}
|
||||
if (mem.in) ed.append(el("p", "lib-confirm", t("Memory: {n} come here", { n: mem.in })));
|
||||
if (mem.up) ed.append(el("p", "lib-confirm", t("Memory: {n} go to the server", { n: mem.up })));
|
||||
if (plan.signIns) ed.append(el("p", "lib-confirm", t("Sign-ins: {n} change here", { n: plan.signIns })));
|
||||
if (plan.pluginsGone?.length) ed.append(el("p", "lib-confirm", t("Plugins removed here, as another computer removed them: {names}", { names: plan.pluginsGone.join(", ") })));
|
||||
const nothing = !ins.length && !ups.length && !mem.in && !mem.up && !plan.signIns && !plan.pluginsGone?.length;
|
||||
if (nothing) ed.append(el("p", "lib-confirm", t("Nothing to sync: this computer and the server are the same.")));
|
||||
const same = by("same").map((p) => p.part), off = by("off").map((p) => p.part);
|
||||
if (same.length && !nothing) ed.append(el("p", "lib-confirm sub", t("Already the same: {parts}", { parts: syncParts(same) })));
|
||||
if (off.length) ed.append(el("p", "lib-confirm sub", t("Stays as it is on each computer: {parts}", { parts: syncParts(off) })));
|
||||
const err = el("p", "editor-error", note || "");
|
||||
err.setAttribute("role", "alert");
|
||||
ed.append(err);
|
||||
const bar = el("div", "bar");
|
||||
const cancel = el("button", "text", t(nothing && !go ? "Close" : "Cancel"));
|
||||
cancel.onclick = cancelAsk;
|
||||
bar.append(el("span", "grow"), cancel);
|
||||
if (go || !nothing) {
|
||||
const ok = el("button", "text primary", t(go ? "Save and sync" : "Sync now"));
|
||||
ok.onclick = async (e) => {
|
||||
e.stopPropagation();
|
||||
if (go) { closeConfirmAsk(); go(); return; }
|
||||
ok.disabled = true;
|
||||
ok.classList.add("busy");
|
||||
try {
|
||||
const r = await api("davsync/sync-previewed", { token: plan.token });
|
||||
closeConfirmAsk();
|
||||
renderSync(r);
|
||||
if (!r.error) refreshAfterSync();
|
||||
} catch (x) {
|
||||
// the server or this computer changed since: shown again, as it is now
|
||||
try { draw(await api("davsync/preview", {}), t(x.message)); } catch (y) { ok.disabled = false; ok.classList.remove("busy"); err.textContent = t(y.message); }
|
||||
}
|
||||
};
|
||||
bar.append(ok);
|
||||
}
|
||||
ed.append(bar);
|
||||
cancel.focus(NO_SCROLL);
|
||||
};
|
||||
draw(plan);
|
||||
confirmAsk = ed;
|
||||
openModal(ed);
|
||||
$("#modal").classList.add("lib");
|
||||
ed.querySelector(".bar .text")?.focus(NO_SCROLL);
|
||||
};
|
||||
|
||||
// askUndoSync asks before the parts the last sync brought in go back to
|
||||
// how they were on this computer (#6428). A part changed here since is
|
||||
// named, and written over only when asked again.
|
||||
window.askUndoSync = function (v) {
|
||||
const ed = el("div", "editor restore-ask sync-undo-ask");
|
||||
const head = el("div", "ehead");
|
||||
head.append(el("b", "", t("Undo the last sync?")));
|
||||
ed.append(head);
|
||||
const a = v.applied;
|
||||
ed.append(el("p", "lib-confirm", t("This computer's {parts} go back to how they were before the sync {when}. The server and your other computers keep theirs.", { parts: syncParts(a.parts), when: syncWhen(a.at) })));
|
||||
ed.append(el("p", "lib-confirm", t("What is here now is kept in the sync folder first.")));
|
||||
const err = el("p", "editor-error", "");
|
||||
err.setAttribute("role", "alert");
|
||||
ed.append(err);
|
||||
const bar = el("div", "bar");
|
||||
const go = el("button", "text primary danger-fill", t("Undo sync"));
|
||||
let force = false;
|
||||
go.onclick = async (e) => {
|
||||
e.stopPropagation();
|
||||
go.disabled = true;
|
||||
go.classList.add("busy");
|
||||
try {
|
||||
const r = await api("davsync/undo-sync", { force });
|
||||
closeConfirmAsk();
|
||||
renderSync(r);
|
||||
refreshAfterSync();
|
||||
} catch (x) {
|
||||
go.disabled = false;
|
||||
go.classList.remove("busy");
|
||||
if (x.changed?.length) {
|
||||
force = true;
|
||||
err.classList.add("note");
|
||||
err.textContent = t("{parts} changed here since the sync. Undoing replaces those changes too.", { parts: syncParts(x.changed) });
|
||||
go.textContent = t("Undo anyway");
|
||||
} else err.textContent = t(x.message);
|
||||
}
|
||||
};
|
||||
const cancel = el("button", "text", t("Cancel"));
|
||||
cancel.onclick = cancelAsk;
|
||||
bar.append(el("span", "grow"), cancel, go);
|
||||
ed.append(bar);
|
||||
confirmAsk = ed;
|
||||
openModal(ed);
|
||||
$("#modal").classList.add("lib");
|
||||
cancel.focus(NO_SCROLL);
|
||||
};
|
||||
|
||||
// askPreviewRows draws Settings › Sync's Preview a sync, and Undo the last
|
||||
// sync while there is one to undo (#6428), into at: renderSync's place for
|
||||
// them, kept here so the core weighs nothing more. Under sub, the sync's
|
||||
// line, it says which parts each computer keeps as it is.
|
||||
window.askPreviewRows = function (at, v, sub) {
|
||||
const left = ["providers", "settings", "profiles", "agents", "library", "memory"].filter((p) => v[p] === false);
|
||||
if (left.length) sub.after(el("div", "sub wraps sync-left", t("Stays as it is on each computer: {parts}", { parts: syncParts(left) })));
|
||||
const row = (name, sub, b, cls) => {
|
||||
const r = el("div", "row pref wraps " + cls), who = el("div", "who"), val = el("div", "val");
|
||||
who.append(el("div", "name", name), el("div", "sub", sub));
|
||||
val.append(b);
|
||||
r.append(who, val);
|
||||
at.append(r);
|
||||
};
|
||||
const peek = el("button", "text", t("Preview…"));
|
||||
peek.onclick = async () => {
|
||||
peek.classList.add("busy");
|
||||
try { askSyncPreview(await api("davsync/preview", {})); } catch (x) { status(t(x.message), "err"); }
|
||||
peek.classList.remove("busy");
|
||||
};
|
||||
row(t("Preview a sync"), t("What syncing now would change, here and on the server. Nothing changes until you sync."), peek, "sync-preview-row");
|
||||
if (v.applied?.parts?.length) {
|
||||
const undo = el("button", "text", t("Undo…"));
|
||||
undo.onclick = () => askUndoSync(v);
|
||||
row(t("Undo the last sync"), t("It brought {parts} here {when}. Undo puts back what was here before, on this computer only.", { parts: syncParts(v.applied.parts), when: syncWhen(v.applied.at) }), undo, "sync-undo-row");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -215,6 +215,43 @@ func backupRoutes(mux *http.ServeMux, w Windows) {
|
||||
err = busy(davsync.SyncNow(ctx)) // how it went is in the status
|
||||
case "now":
|
||||
err = busy(davsync.SyncNow(ctx))
|
||||
case "preview": // what syncing would do (#6428): the setup saved, or the form's when one is sent
|
||||
var in struct{ Form *davsync.Config }
|
||||
var p davsync.Plan
|
||||
if err = json.NewDecoder(r.Body).Decode(&in); err != nil && !errors.Is(err, io.EOF) {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
if in.Form != nil {
|
||||
p, err = davsync.PreviewWith(ctx, *in.Form)
|
||||
} else {
|
||||
p, err = davsync.Preview(ctx)
|
||||
}
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, p)
|
||||
return
|
||||
case "sync-previewed": // the sync a preview showed, nothing else
|
||||
var in struct{ Token string }
|
||||
if err = json.NewDecoder(r.Body).Decode(&in); err == nil {
|
||||
if err = davsync.SyncPreviewed(ctx, in.Token); !errors.Is(err, davsync.ErrPlanChanged) {
|
||||
err = busy(err) // how it went is in the status
|
||||
}
|
||||
}
|
||||
case "undo-sync": // the parts the last sync brought in, as they were before it
|
||||
var in struct{ Force bool }
|
||||
if err = json.NewDecoder(r.Body).Decode(&in); err == nil {
|
||||
_, err = davsync.UndoSync(in.Force)
|
||||
}
|
||||
var since *davsync.ChangedSince
|
||||
if errors.As(err, &since) { // the page asks before writing over them
|
||||
rw.Header().Set("Content-Type", "application/json")
|
||||
rw.WriteHeader(http.StatusConflict)
|
||||
json.NewEncoder(rw).Encode(map[string]any{"error": err.Error(), "changed": since.Parts})
|
||||
return
|
||||
}
|
||||
case "off":
|
||||
err = davsync.Off()
|
||||
case "dismiss":
|
||||
|
||||
@@ -87,7 +87,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const form = list.locator(".sync-form");
|
||||
await form.locator(".segs .opt", { hasText: "GitHub" }).click();
|
||||
const labels = (await form.locator(":scope > label:visible").allTextContents()).filter(Boolean);
|
||||
assert.deepEqual(labels, ["Sync to", "Repository", "Branch", "Folder", "GitHub token", "Passphrase", "Also sync"].map(tr));
|
||||
assert.deepEqual(labels, ["Sync to", "Repository", "Branch", "Folder", "GitHub token", "Passphrase", "What syncs"].map(tr));
|
||||
assert.ok((await form.textContent()).includes(tr("Empty uses the repository's default branch. Empty repositories are initialized by the first sync; other branches must already exist.")));
|
||||
const box = (label) => form.locator(":scope > label:visible", { hasText: new RegExp("^" + label + "$") }).locator("xpath=following-sibling::div[1]").locator("input");
|
||||
const L = { repo: tr("Repository"), folder: tr("Folder"), token: tr("GitHub token"), phrase: tr("Passphrase") };
|
||||
|
||||
@@ -85,7 +85,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await form.waitFor({ state: "visible" });
|
||||
const labels = async () => (await form.locator(":scope > label:visible").allTextContents()).filter(Boolean);
|
||||
// WebDAV is the one picked at first, S3's fields not shown
|
||||
assert.deepEqual(await labels(), zh ? ["同步到", "地址", "用户", "密码", "口令", "同时同步"] : ["Sync to", "Address", "User", "Password", "Passphrase", "Also sync"]);
|
||||
assert.deepEqual(await labels(), zh ? ["同步到", "地址", "用户", "密码", "口令", "同步内容"] : ["Sync to", "Address", "User", "Password", "Passphrase", "What syncs"]);
|
||||
await form.locator(":scope > div").nth(1).locator("input").fill("https://dav.example.com/dav/");
|
||||
|
||||
// picking S3 moves nothing on the page
|
||||
@@ -101,8 +101,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.waitForTimeout(250);
|
||||
assert.equal(await top(), before, "picking S3 must not scroll the page");
|
||||
assert.deepEqual(await labels(), zh
|
||||
? ["同步到", "接口地址", "存储桶", "前缀", "区域", "Access Key", "Secret", "口令", "同时同步"]
|
||||
: ["Sync to", "Endpoint", "Bucket", "Prefix", "Region", "Access key", "Secret", "Passphrase", "Also sync"]);
|
||||
? ["同步到", "接口地址", "存储桶", "前缀", "区域", "Access Key", "Secret", "口令", "同步内容"]
|
||||
: ["Sync to", "Endpoint", "Bucket", "Prefix", "Region", "Access key", "Secret", "Passphrase", "What syncs"]);
|
||||
// every label fits its column
|
||||
for (const l of await form.locator(":scope > label:visible").all()) {
|
||||
assert.equal(await l.evaluate((e) => e.scrollWidth <= e.clientWidth + 1), true, await l.textContent());
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// What syncs, a preview of a sync, and undoing the last one (#6428,
|
||||
// jinpwng on X: sync only the library and memory, leave each computer's
|
||||
// providers, settings and models alone, see what an apply changes first,
|
||||
// and roll it back):
|
||||
// - The form's What syncs: Providers, With their API keys under it,
|
||||
// Settings, Agents' models, Library and Memory up front; Profiles, Usage
|
||||
// and Sign-ins under Advanced, folded. Providers unticked hides the keys
|
||||
// tick. Save posts providers and settings false, and nothing for a part
|
||||
// left as it was (an old setup is saved as it was).
|
||||
// - Saved, the line under the sync says what stays on each computer.
|
||||
// - Preview… shows what comes here and what goes up, by item, and Sync now
|
||||
// sends the preview's token; a stale one is shown again, as it is now.
|
||||
// - Undo the last sync asks first; a part changed here since is named, and
|
||||
// Undo anyway sends force.
|
||||
// In all five languages, at 1100 and 420px, Chromium and WebKit, nothing
|
||||
// wider than the window. 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 { reach, openPart } = require("./reader.cjs");
|
||||
const { strings } = require("./strings.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const { I18N } = strings();
|
||||
const tr = (lang, k, vars = {}) => {
|
||||
const s = lang === "en" ? k : I18N[lang][k];
|
||||
assert.equal(typeof s, "string", `${lang} has ${JSON.stringify(k)}`);
|
||||
return s.replace(/\{(\w+)\}/g, (_, v) => vars[v]);
|
||||
};
|
||||
|
||||
const minAgo = new Date(Date.now() - 60000).toISOString();
|
||||
const base = { on: true, kind: "webdav", url: "https://dav.example.invalid/dav/", user: "me", passwordSet: true, passphraseSet: true, keys: true, agents: true, library: true, memory: true, last: minAgo, applied: { at: minAgo, parts: ["library"] } };
|
||||
const plan = (token) => ({
|
||||
token,
|
||||
parts: [
|
||||
{ part: "providers", do: "off" },
|
||||
{ part: "settings", do: "off" },
|
||||
{ part: "profiles", do: "same" },
|
||||
{ part: "agents", do: "same" },
|
||||
{ part: "library", do: "in", replaces: true, items: [
|
||||
{ kind: "skills", name: "review", change: "added" },
|
||||
{ kind: "servers", name: "github", change: "changed" },
|
||||
...Array.from({ length: 9 }, (_, i) => ({ kind: "skills", name: "old-" + i, change: "removed" })),
|
||||
] },
|
||||
],
|
||||
memory: { in: 2, up: 1 },
|
||||
});
|
||||
|
||||
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 = { ...base };
|
||||
let tokens = 0, previewed = 0, undos = 0;
|
||||
return async (route) => {
|
||||
const request = route.request();
|
||||
const pathname = new URL(request.url()).pathname;
|
||||
const json = (data, status = 200) => route.fulfill({ status, json: data });
|
||||
const post = () => { const body = request.postDataJSON(); posts.push({ path: pathname, body }); return body; };
|
||||
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 === "/api/davsync/save") {
|
||||
const b = post();
|
||||
sync = { ...sync };
|
||||
for (const k of ["providers", "settings", "profiles"]) if (k in b) sync[k] = b[k];
|
||||
return json(sync);
|
||||
}
|
||||
if (pathname === "/api/davsync/preview") { post(); return json(plan("t" + ++tokens)); }
|
||||
if (pathname === "/api/davsync/sync-previewed") {
|
||||
post();
|
||||
// the first is stale: the server changed since the preview
|
||||
if (++previewed === 1) return json({ error: "something changed since the preview: look at it again before syncing" }, 409);
|
||||
sync = { ...sync, last: new Date().toISOString() };
|
||||
return json(sync);
|
||||
}
|
||||
if (pathname === "/api/davsync/undo-sync") {
|
||||
post();
|
||||
if (++undos === 1) return json({ error: "changed here since the sync", changed: ["library"] }, 409);
|
||||
sync = { ...sync, applied: 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 });
|
||||
};
|
||||
}
|
||||
|
||||
async function noneWider(page, sel) {
|
||||
const wide = await page.evaluate((sel) => {
|
||||
const out = [];
|
||||
if (document.scrollingElement.scrollWidth > innerWidth) out.push("page " + document.scrollingElement.scrollWidth);
|
||||
for (const r of document.querySelectorAll(sel)) {
|
||||
const b = r.getBoundingClientRect();
|
||||
if (b.right > innerWidth + 0.5) out.push((r.querySelector(".name")?.textContent || r.className) + " " + b.right);
|
||||
}
|
||||
return out;
|
||||
}, sel);
|
||||
assert.deepEqual(wide, [], "wider than the window");
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const width of [1100, 420]) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
const w = (k, vars) => tr(lang, k, vars);
|
||||
test(`${engine} ${width}px ${lang}: pick what syncs, preview a sync, undo the last`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
|
||||
const errors = [], posts = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, posts));
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${width}-${lang}-sync-scope.png`), fullPage: true });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const all = (p) => posts.filter((x) => x.path === p);
|
||||
const waitPosts = async (p, n) => {
|
||||
for (let i = 0; i < 250 && all(p).length < n; i++) await page.waitForTimeout(20);
|
||||
assert.equal(all(p).length, n, `${p} posted ${n} times`);
|
||||
return all(p).at(-1).body;
|
||||
};
|
||||
const click = async (loc) => { await reach(page, loc); await loc.click(); };
|
||||
const exact = (s) => new RegExp("^" + s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "$");
|
||||
const parts = (ps) => ps.map((p) => w({ providers: "providers", settings: "settings", library: "library" }[p])).join(w(", "));
|
||||
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.locator("#prefs").click();
|
||||
await openPart(page, "sync");
|
||||
const list = page.locator("#syncList");
|
||||
const first = list.locator(".row.pref").first();
|
||||
await first.waitFor({ state: "visible" });
|
||||
assert.equal(await list.locator(".sync-left").count(), 0, "a left-out line with every part synced");
|
||||
|
||||
// the form: what syncs up front, the rare ones folded
|
||||
await click(first.locator("button", { hasText: exact(w("Edit")) }));
|
||||
const form = list.locator(".sync-form");
|
||||
const tickOf = (k) => form.locator("label.tick").filter({ hasText: exact(w(k)) });
|
||||
const prov = tickOf("Providers"), keys = tickOf("With their API keys"), sets = tickOf("Settings");
|
||||
for (const k of ["Providers", "With their API keys", "Settings", "Agents' models"]) {
|
||||
assert.equal(await tickOf(k).isVisible(), true, `${k} up front`);
|
||||
assert.equal(await tickOf(k).locator("input").isChecked(), true, `${k} on for a setup from before the choice`);
|
||||
}
|
||||
const adv = form.locator("details.sync-advanced");
|
||||
assert.equal(await adv.evaluate((d) => d.open), false, "Advanced open with nothing in it set");
|
||||
assert.equal(await tickOf("Profiles").isVisible(), false, "Profiles up front");
|
||||
await click(prov.locator("input"));
|
||||
assert.equal(await keys.isVisible(), false, "the keys tick with providers off");
|
||||
await click(prov.locator("input"));
|
||||
assert.equal(await keys.isVisible(), true, "the keys tick gone with providers on");
|
||||
await click(prov.locator("input"));
|
||||
await click(sets.locator("input"));
|
||||
await noneWider(page, "#syncList .row.pref, #syncList .sync-form, #syncList .sync-form .bar > button");
|
||||
await click(form.locator("button", { hasText: exact(w("Save")) }));
|
||||
const saved = await waitPosts("/api/davsync/save", 1);
|
||||
assert.equal(saved.providers, false);
|
||||
assert.equal(saved.settings, false);
|
||||
assert.equal("profiles" in saved, false, "profiles said with it left as it was");
|
||||
await form.waitFor({ state: "detached" });
|
||||
const left = list.locator(".sync-left");
|
||||
assert.equal(await left.textContent(), w("Stays as it is on each computer: {parts}", { parts: parts(["providers", "settings"]) }));
|
||||
|
||||
// the preview: by part and by item, then Sync now with its token
|
||||
const peekRow = list.locator(".sync-preview-row");
|
||||
assert.equal(await peekRow.locator(".name").textContent(), w("Preview a sync"));
|
||||
await click(peekRow.locator("button", { hasText: exact(w("Preview…")) }));
|
||||
const modal = page.locator("#modal .sync-preview");
|
||||
await modal.waitFor({ state: "visible" });
|
||||
const text = await modal.textContent();
|
||||
for (const s of [
|
||||
w("Comes here from the server: {part}", { part: parts(["library"]) }),
|
||||
"review", "github", w("and {n} more", { n: 3 }),
|
||||
w("Memory: {n} come here", { n: 2 }), w("Memory: {n} go to the server", { n: 1 }),
|
||||
w("Stays as it is on each computer: {parts}", { parts: parts(["providers", "settings"]) }),
|
||||
]) assert.ok(text.includes(s), `the preview says ${JSON.stringify(s)}: ${text}`);
|
||||
assert.equal(await modal.locator(".sync-item").count(), 8, "items past 8 counted, not listed");
|
||||
await noneWider(page, "#modal .sync-preview");
|
||||
await click(modal.locator("button", { hasText: exact(w("Sync now")) }));
|
||||
assert.equal((await waitPosts("/api/davsync/sync-previewed", 1)).token, "t1");
|
||||
// stale: shown again as it is now, with why
|
||||
await waitPosts("/api/davsync/preview", 2);
|
||||
await modal.locator(".editor-error", { hasText: w("something changed since the preview: look at it again before syncing") }).waitFor();
|
||||
await click(modal.locator("button", { hasText: exact(w("Sync now")) }));
|
||||
assert.equal((await waitPosts("/api/davsync/sync-previewed", 2)).token, "t2");
|
||||
await modal.waitFor({ state: "detached" });
|
||||
|
||||
// undo: asked first, then again over a change made here since
|
||||
const undoRow = list.locator(".sync-undo-row");
|
||||
assert.equal(await undoRow.locator(".name").textContent(), w("Undo the last sync"));
|
||||
await click(undoRow.locator("button", { hasText: exact(w("Undo…")) }));
|
||||
const ask = page.locator("#modal .sync-undo-ask");
|
||||
await ask.waitFor({ state: "visible" });
|
||||
assert.ok((await ask.textContent()).includes(w("What is here now is kept in the sync folder first.")));
|
||||
await click(ask.locator("button", { hasText: exact(w("Undo sync")) }));
|
||||
assert.equal((await waitPosts("/api/davsync/undo-sync", 1)).force, false);
|
||||
await ask.locator(".editor-error", { hasText: w("{parts} changed here since the sync. Undoing replaces those changes too.", { parts: parts(["library"]) }) }).waitFor();
|
||||
await noneWider(page, "#modal .sync-undo-ask");
|
||||
await click(ask.locator("button", { hasText: exact(w("Undo anyway")) }));
|
||||
assert.equal((await waitPosts("/api/davsync/undo-sync", 2)).force, true);
|
||||
await ask.waitFor({ state: "detached" });
|
||||
await undoRow.waitFor({ state: "detached" });
|
||||
assert.equal(await list.locator(".sync-preview-row").count(), 1, "Preview a sync gone after the undo");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -132,6 +132,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
let form = list.locator(".sync-form");
|
||||
const siTick = form.locator("label.tick", { hasText: w("Sign-ins: subscription accounts and plugin sign-ins") }).locator("input");
|
||||
assert.equal(await siTick.isChecked(), false, "sync's sign-ins on before picked");
|
||||
// under the form's Advanced, folded while nothing in it is set
|
||||
assert.equal(await form.locator("details.sync-advanced").evaluate((d) => d.open), false, "Advanced open with nothing in it set");
|
||||
await click(form.locator("details.sync-advanced summary"));
|
||||
const say = form.locator(".sync-signins-say");
|
||||
assert.equal(await say.isVisible(), false, "the line shows before the tick");
|
||||
await click(siTick);
|
||||
|
||||
@@ -194,13 +194,20 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const box = (label) => form.locator(":scope > label:visible", { hasText: new RegExp("^" + label + "$") }).locator("xpath=following-sibling::div[1]").locator("input");
|
||||
await box(lang === "zh" ? "口令" : "Passphrase").fill("correct horse");
|
||||
await toEnd();
|
||||
// Usage is under the form's Advanced, folded while nothing in it is set
|
||||
const adv = form.locator("details.sync-advanced");
|
||||
assert.equal(await adv.evaluate((d) => d.open), false, "Advanced open with nothing in it set");
|
||||
await adv.locator("summary").evaluate((e) => e.scrollIntoView({ block: "center" }));
|
||||
await adv.locator("summary").click();
|
||||
const tick = form.locator("label.tick", { hasText: w.tick });
|
||||
// Back up by itself's rows under the form put the tick, at the
|
||||
// page's end, under Settings' held tabs: bring it into the open
|
||||
await tick.evaluate((e) => e.scrollIntoView({ block: "center" }));
|
||||
assert.equal(await tick.locator("input").isChecked(), false, "off unless picked");
|
||||
const top = () => p.locator("#view-settings").evaluate((v) => v.scrollTop);
|
||||
const at = await top();
|
||||
// the fold just opened: measure once the page has stopped moving
|
||||
let at = await top();
|
||||
for (let i = 0; i < 50; i++) { await p.waitForTimeout(60); const now = await top(); if (now === at) break; at = now; }
|
||||
await tick.click();
|
||||
await p.waitForTimeout(200);
|
||||
assert.equal(await top(), at, "the tick moved the page");
|
||||
|
||||
@@ -117,8 +117,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
sync.value = { on: true, kind: "webdav", url: "https://dav.example.com/dav/", user: "me", passwordSet: true, passphraseSet: true,
|
||||
keys: true, agents: false, library: false };
|
||||
await focus();
|
||||
assert.equal(await settle(async () => (await first.locator(".sub").textContent()) === (zh ? "尚未同步 · dav.example.com" : "Not synced yet · dav.example.com")), true,
|
||||
assert.equal(await settle(async () => (await first.locator(".sub.say").textContent()) === (zh ? "尚未同步 · dav.example.com" : "Not synced yet · dav.example.com")), true,
|
||||
"the row must say what the CLI left, not what the page first read");
|
||||
// and the parts it left out, under it (#6428)
|
||||
assert.equal(await first.locator(".sync-left").textContent(), zh ? "每台电脑各自保留:agent 的模型、资源库" : "Stays as it is on each computer: agents' models, library");
|
||||
assert.equal(await first.locator(".name").textContent(), zh ? "WebDAV 同步" : "WebDAV sync");
|
||||
|
||||
// the form's ticks come from that fresh view
|
||||
@@ -135,7 +137,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
sync.value = { on: true, kind: "s3", url: "s3://bucket/prefix", endpoint: "https://s3.example.com", region: "auto",
|
||||
user: "key-id", passwordSet: true, passphraseSet: true, keys: true, agents: true, library: true };
|
||||
await page.evaluate(() => document.dispatchEvent(new Event("visibilitychange")));
|
||||
assert.equal(await settle(async () => (await first.locator(".sub").textContent()) === (zh ? "尚未同步 · s3://bucket/prefix · s3.example.com" : "Not synced yet · s3://bucket/prefix · s3.example.com")), true,
|
||||
assert.equal(await settle(async () => (await first.locator(".sub.say").textContent()) === (zh ? "尚未同步 · s3://bucket/prefix · s3.example.com" : "Not synced yet · s3://bucket/prefix · s3.example.com")), true,
|
||||
"an S3 setup changed behind the window must reach the page too");
|
||||
assert.equal(await first.locator(".name").textContent(), zh ? "S3 同步" : "S3 sync");
|
||||
|
||||
|
||||
@@ -647,3 +647,12 @@ func signCodexIn(l savedLogin) (bool, error) {
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Count is how many sign-ins the plan puts in or removes.
|
||||
func (p SignInPlan) Count() int {
|
||||
n := len(p.put) + len(p.remove)
|
||||
if p.codex != nil {
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
@@ -173,6 +173,7 @@
|
||||
<a href="#setup">同期をオンにする</a>
|
||||
<a href="#services">3 種類のストレージ</a>
|
||||
<a href="#keep">1 台だけ自分の値を保つ</a>
|
||||
<a href="#pick">同期するものを選ぶ・プレビュー・取り消し</a>
|
||||
<a href="#backup">一度きりのバックアップと復元</a>
|
||||
</aside>
|
||||
|
||||
@@ -201,6 +202,11 @@ magpie github # where it syncs to and how the last sync went</
|
||||
<p>3 種類を切り替えても、ほかの設定と認証情報は戻すときのために残ります。同期するのは一度に 1 つです。</p>
|
||||
<h2 id="keep"><a class="anchor" href="#keep">1 台だけ自分の値を保つ</a></h2>
|
||||
<p>あるコンピュータでエージェントのモデルを変えると、ほかのコンピュータにも届きます。同期で変わった値をそのコンピュータで元に戻すと、そのコンピュータは自分の値を保ちます。ほかの選択でもう変わらず、その選択もそこだけに残り、ほかのものは同期を続けます。<span class="ui">このコンピュータだけで保持</span> にそのフィールドが並び、<span class="ui">ほかのコンピュータに合わせる</span> で同期の値に戻ります。</p>
|
||||
<h2 id="pick"><a class="anchor" href="#pick">同期するものを選ぶ・プレビュー・取り消し</a></h2>
|
||||
<p>同期フォームの <span class="ui">同期するもの</span> で、コンピュータごとに自分の値を保ちたいもののチェックを外します:プロバイダー、設定、エージェントのモデル、ライブラリ、メモリ(プロファイル・使用量・サインインは <span class="ui">詳細設定</span> にあります)。チェックのないものは送りも受け取りもしません。このコンピュータは自分の値を、サーバーはほかのコンピュータの値を保ちます。あとでチェックし直すと初回の同期のように加わり、このコンピュータの値は先に同期フォルダに保存されます。<span class="ui">同期をプレビュー</span> は、何も変えずに、こちらに来るものとサーバーへ行くものを項目ごとに示します。そこでの <span class="ui">今すぐ同期</span> は、その間に何も変わっていないときだけ同期します。<span class="ui">前回の同期を取り消す</span> は、前回の同期で入ってきたものをこのコンピュータでだけ元に戻します。</p>
|
||||
<div class="code"><span class="lang">ターミナル</span><button class="copy" data-copy="sy-pick">コピー</button><pre id="sy-pick">magpie webdav set providers=no settings=no agents=no # ライブラリとメモリだけ同期
|
||||
magpie webdav preview # いま同期すると何が変わるか
|
||||
magpie webdav undo-sync # 前回の同期で入ったものを戻す</pre></div>
|
||||
<h2 id="backup"><a class="anchor" href="#backup">一度きりのバックアップと復元</a></h2>
|
||||
<p>同期せず新しいコンピュータに移るだけなら、暗号化バックアップファイルを使います。</p>
|
||||
<div class="code"><span class="lang">ターミナル</span><button class="copy" data-copy="sy-backup">コピー</button><pre id="sy-backup">magpie backup # writes magpie.magpie-backup, asks for a passphrase twice
|
||||
|
||||
@@ -173,6 +173,7 @@
|
||||
<a href="#setup">Turn it on</a>
|
||||
<a href="#services">Three kinds of storage</a>
|
||||
<a href="#keep">A computer keeping its own</a>
|
||||
<a href="#pick">Pick what syncs, preview, undo</a>
|
||||
<a href="#backup">A one-off backup and restore</a>
|
||||
</aside>
|
||||
|
||||
@@ -201,6 +202,11 @@ magpie github # where it syncs to and how the last sync went</
|
||||
<p>Switching between the three keeps the others' settings and credentials for switching back; one syncs at a time.</p>
|
||||
<h2 id="keep"><a class="anchor" href="#keep">A computer keeping its own</a></h2>
|
||||
<p>A change to an agent's model on one computer reaches the others. When sync changes one on a computer and you set it back there, that computer keeps its own: the others' picks no longer change it, and its picks stay there, while everything else keeps syncing. <span class="ui">Kept on this computer</span> lists those fields, and <span class="ui">Follow the others</span> takes the synced value again.</p>
|
||||
<h2 id="pick"><a class="anchor" href="#pick">Pick what syncs, preview, undo</a></h2>
|
||||
<p>Under <span class="ui">What syncs</span> in the sync's form, untick what each computer should keep as its own: providers, settings, agents' models, the library or memory (profiles, usage and sign-ins are under <span class="ui">Advanced</span>). A part not ticked is neither sent nor taken: this computer keeps its own, and the server keeps the others'. Ticked again later, it is joined like a first sync, with this computer's copy kept in the sync folder first. <span class="ui">Preview a sync</span> lists what would come here and what would go to the server, item by item, before anything changes; <span class="ui">Sync now</span> there runs that sync only if nothing changed since. <span class="ui">Undo the last sync</span> puts back what the last sync brought in, on this computer only.</p>
|
||||
<div class="code"><span class="lang">Terminal</span><button class="copy" data-copy="sy-pick">Copy</button><pre id="sy-pick">magpie webdav set providers=no settings=no agents=no # only the library and memory sync
|
||||
magpie webdav preview # what syncing now would change
|
||||
magpie webdav undo-sync # put back what the last sync brought in</pre></div>
|
||||
<h2 id="backup"><a class="anchor" href="#backup">A one-off backup and restore</a></h2>
|
||||
<p>For a move to a new computer without sync, use an encrypted backup file:</p>
|
||||
<div class="code"><span class="lang">Terminal</span><button class="copy" data-copy="sy-backup">Copy</button><pre id="sy-backup">magpie backup # writes magpie.magpie-backup, asks for a passphrase twice
|
||||
|
||||
@@ -173,6 +173,7 @@
|
||||
<a href="#setup">开启同步</a>
|
||||
<a href="#services">三种存储</a>
|
||||
<a href="#keep">某台电脑保留自己的设置</a>
|
||||
<a href="#pick">选择同步内容、预览、撤销</a>
|
||||
<a href="#backup">一次性备份和恢复</a>
|
||||
</aside>
|
||||
|
||||
@@ -201,6 +202,11 @@ magpie github # where it syncs to and how the last sync went</
|
||||
<p>在三种之间切换时,另外两种的设置和凭据会保留,方便切回来;同一时间只用一种。</p>
|
||||
<h2 id="keep"><a class="anchor" href="#keep">某台电脑保留自己的设置</a></h2>
|
||||
<p>在一台电脑上改了 Agent 的模型,其他电脑会跟着改。如果同步改了某台电脑上的值,你又在那台电脑上改了回去,那台电脑就保留自己的:别的电脑的选择不再改它,它的选择也只留在它自己这里,其他内容照常同步。<span class="ui">仅本机保留</span> 列出这些字段,点 <span class="ui">跟随其他电脑</span> 就重新用同步的值。</p>
|
||||
<h2 id="pick"><a class="anchor" href="#pick">选择同步内容、预览、撤销</a></h2>
|
||||
<p>在同步表单的 <span class="ui">同步内容</span> 里,取消勾选每台电脑要各自保留的部分:供应商、设置、Agent 的模型、资源库或记忆(配置档、用量和登录在 <span class="ui">高级</span> 里)。没勾选的部分既不上传也不下载:这台电脑保留自己的,服务器上保留其他电脑的。之后再勾上,就像第一次同步那样加入,这台电脑原来的会先存进同步文件夹。<span class="ui">预览同步</span> 会逐项列出哪些会同步到这台电脑、哪些会传到服务器,什么都不改;在那里点 <span class="ui">立即同步</span>,只有这期间没有变化时才会执行。<span class="ui">撤销上次同步</span> 会把上次同步带来的内容恢复成之前的样子,只在这台电脑上。</p>
|
||||
<div class="code"><span class="lang">终端</span><button class="copy" data-copy="sy-pick">复制</button><pre id="sy-pick">magpie webdav set providers=no settings=no agents=no # 只同步资源库和记忆
|
||||
magpie webdav preview # 现在同步会改什么
|
||||
magpie webdav undo-sync # 撤销上次同步带来的内容</pre></div>
|
||||
<h2 id="backup"><a class="anchor" href="#backup">一次性备份和恢复</a></h2>
|
||||
<p>不想开同步,只是搬到新电脑,就用加密备份文件:</p>
|
||||
<div class="code"><span class="lang">终端</span><button class="copy" data-copy="sy-backup">复制</button><pre id="sy-backup">magpie backup # writes magpie.magpie-backup, asks for a passphrase twice
|
||||
|
||||
Reference in New Issue
Block a user