Files
magpie/internal/davsync/restore.go
T
yetone a511b11d8b sync: an agent's model set back on a computer after a sync stays that computer's (hayden4608)
hayden4608 on Discord syncs two computers through GitHub, both with
Codex, and wants each one's Codex default model kept apart. Until now
the agents part carried every agent field ("codex.model", effort,
provider...) as one set: A's pick went up, B's sync brought it over B's,
B's pick went up again and A's next sync took it back. The two
computers fought, and the only way out was turning "agents' models"
off for every agent.

Now a sync that brings an agent field over this computer's value
records what it brought (Brought) and what it wrote over (Replaced,
only when that was picked here, not itself brought). If the user then
sets the field back to the value the sync replaced, the field is this
computer's own (Own): it leaves the hashes, a sync no longer brings it,
and a push keeps the server's value, so the other computer is not
changed either. Every other new pick is an ordinary pick and still goes
both ways, so a computer that changes the model for everyone (and
TestSyncAgentDefaults' reset) still reaches the rest. Nothing to set
up: the user's own act on this computer decides it, and a synced value
never overrides it again.

Settings > Sync lists the kept fields in one row ("Kept on this
computer: Codex model ...") with a "Follow the others" button
(davsync/follow), which brings the server's values on the next sync and
ends the keeping. Restore brings everything and ends it too. The row is
drawn only while sync and agents' models are on and something is kept;
plain row and button, no new layout. app.js grew 623 bytes; the budgets
are raised by that with a note.

Tests:
- internal/davsync/own_model_test.go TestOwnModelStaysOnEachComputer:
  two sandbox HOMEs (CODEX_HOME per computer) on the GitHub fixture.
  A picks a1, B joins and gets it, B picks b1 (goes up), A gets b1, A
  sets a1 back (own; the server keeps b1), B picks b2 + effort +
  provider (A gets effort and provider, keeps a1), A picks a2 and a
  Claude model (both go up, B gets them), A follows (gets b2), B's b3
  reaches A. TestNewPicksStillGoBothWays: alternating new picks always
  reach the other computer.
- internal/gui/tests/sync-own-fields.test.cjs: the row in en, zh,
  zh-TW, ja, de at 420px, no overflow, Follow posts once and the row
  goes, no scroll; no row without own fields or with agents off.

Broken by hand, each red: noticeOwn off (own_model_test:122); any pick
after a sync counts as own (TestSyncAgentDefaults and own test:106);
keepServersOwn off (:166); the bring ignoring Own (:146); withoutOwn
off in the hashes (:143, a notice); Follow off (:182).

Run at this head (rebased on 47173f593) on mote:
gofmt -l internal/davsync internal/gui clean; go vet ./..., GOOS=linux
go vet -tags nogui ./..., GOOS=windows go vet ./... ok; go test
./internal/davsync ok, ./internal/backup ok, ./internal/gui ok but
TestSettingsSaveKeepsWhatItDoesNotSend (#4514, red on main) and the
eleven real-window AppKit tests (dock, panel, tray, corners), which
time out on mote at origin/main 47173f593 too (#4125, #2645);
-run 'Budget|Sync|Backup|Settings' passes TestCoreScriptBudget.
GUI (node --test): sync-own-fields, sync-note-show, github-sync,
s3-sync, sync-other-kind, sync-not-backup, sync-auto-restore,
sync-usage-error, i18n-keys. Chromium on mote: all pass but
sync-not-backup and sync-usage-error, whose chromium.launch({channel:
"chromium"}) segfaults on mote at origin/main 47173f593 too; on the
WSL box (magpie-desktop) they pass, 25 of 25 with sync-own-fields.
WebKit on mote hangs on launch for every file, untouched ones too; on
WSL all nine files ran: 49 of 52, the reds being i18n-keys' "a
plugin's words are its own" (#4524, red on main) and the first
page.goto of sync-own-fields and sync-note-show at 5s under nine
files at once, which pass run alone (9 of 9).
Red on main and not from this change: TestSettingsSaveKeepsWhatItDoesNotSend
(#4514), i18n-keys "Unmarked" (#4524).

Not tried: a real GitHub repo and a real Codex on two computers; the
CLI has no follow command (only the GUI and Restore end the keeping);
Undo after a Restore doesn't bring Own back.
2026-10-31 18:01:04 +08:00

283 lines
8.2 KiB
Go

package davsync
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"time"
"github.com/yetone/magpie/internal/backup"
"github.com/yetone/magpie/internal/edit"
)
// ErrOff is a Restore, Undo or SetAuto asked for with sync off.
var ErrOff = errors.New("sync is off")
// SetAuto sets how many minutes apart the gateway's magpie syncs by
// itself, one of AutoChoices; Manual: never, only when asked (#847).
func SetAuto(minutes int) error {
if !slices.Contains(AutoChoices, minutes) {
return fmt.Errorf("sync by itself every 3, 15, 30 or 60 minutes, or never, not %d", minutes)
}
return locked(func() error {
c, ok := Load()
if !ok {
return ErrOff
}
c.AutoEvery = minutes
if minutes == int(Every/time.Minute) {
c.AutoEvery = 0
}
b, err := json.MarshalIndent(c, "", " ")
if err != nil {
return err
}
if err := edit.WriteAtomic(path("sync.json"), b); err != nil {
return err
}
return os.Chmod(path("sync.json"), 0o600)
})
}
// Restore makes this computer's setup the server's, whatever changed here:
// each part synced that differs is brought in, as a sync brings in a part
// changed only there. What was here first is sealed into the sync folder,
// with the API keys, and Undo brings it back. It is the parts brought in.
func Restore(ctx context.Context) ([]string, error) {
var brought []string
err := locked(func() error {
c, ok := Load()
if !ok {
return ErrOff
}
d, err := newRemote(c)
if err != nil {
return err
}
data, ver, err := d.get(ctx, version{}) // the file as it is now, never the cached copy
if err != nil {
return err
}
if data == nil {
return errors.New("there is no magpie setup on the server yet: nothing to restore")
}
remote, err := backup.Open(data, c.Passphrase)
if errors.Is(err, backup.ErrPassphrase) {
return errors.New("the passphrase doesn't open the file on the server: it was sealed with another one; use the passphrase set on your other computers")
}
if err != nil {
return described(c, data, err)
}
local, err := collect(c)
if err != nil {
return err
}
L, R := hashes(local), hashes(remote)
for _, p := range Parts {
if L[p] == R[p] || !c.syncs(p) || (p == "library" && remote.Library == nil) {
continue
}
brought = append(brought, p)
}
st := loadState()
if st.Key != stateKey(c) {
st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own}
}
if len(brought) > 0 {
kept, err := keepHere(c)
if err != nil {
return fmt.Errorf("keeping this computer's setup before restoring: %w", err)
}
for _, p := range brought {
if p == "agents" {
// the server's whole, the fields kept here too: they
// follow the others again, as Follow leaves them
got, err := bringAgents(remote.Agents, nil)
broughtIn(&st, got)
st.Own, st.Follow = nil, false
if err != nil {
return fmt.Errorf("bringing in the %s: %w", p, err)
}
continue
}
if err := bring(remote, p); err != nil {
return fmt.Errorf("bringing in the %s: %w", p, err)
}
}
if local, err = collect(c); err != nil {
return err
}
st.Undo = kept
st.Notice = &Notice{At: time.Now(), Here: brought, Saved: filepath.Dir(kept), Restored: true}
}
// as a sync that brought them in leaves it: the next one has
// nothing to push back
st.Local, st.Remote, st.Sum, st.Server = hashesOwn(local, st.Own), hashesOwn(remote, st.Own), sum(data), ver
st.Blind = nil // what is here now is what the server has
remember(data)
st.Last, st.Error = time.Now(), ""
saveState(st)
return nil
})
return brought, err
}
// Upload writes this computer's setup over the server's file when that
// file isn't a backup a sync can read — empty, cut short, another app's —
// so a sync stopped on it has a way on that the user chooses. A file that
// opens as a backup, one sealed with another passphrase, a newer magpie's,
// and a page the server answered with instead of a file are never written
// over. What the server held is kept in the sync folder first, and nothing
// is written when it can't be. The write is made over the version read, so
// a file another computer wrote meanwhile isn't.
func Upload(ctx context.Context) error {
return locked(func() error {
c, ok := Load()
if !ok {
return ErrOff
}
d, err := newRemote(c)
if err != nil {
return err
}
data, ver, err := d.get(ctx, version{})
if err != nil {
return err
}
if data != nil {
_, err := backup.Open(data, c.Passphrase)
switch {
case err == nil:
return errors.New("the file on the server is a magpie backup this computer can open: Sync now merges with it instead, and nothing was written over it")
case errors.Is(err, backup.ErrPassphrase):
return errors.New("the file on the server is a magpie backup sealed with another passphrase, so it wasn't written over: use the passphrase set on your other computers")
}
err = described(c, data, err)
var nb *notBackup
if !errors.As(err, &nb) || !nb.f.Replace {
return err
}
if len(data) > 0 {
if err := keepAside(data, "server-replaced", 5); err != nil {
return fmt.Errorf("keeping the server's file before writing over it, so nothing was written: %w", err)
}
}
}
local, err := collect(c)
if err != nil {
return err
}
b := local
b.Created, b.App = time.Now().UTC(), "magpie"
sealed, err := backup.Seal(b, c.Passphrase)
if err != nil {
return err
}
v, err := d.put(ctx, sealed, ver.ETag)
if errors.Is(err, errChanged) {
return errors.New("the file on the server changed while it was being replaced, so it wasn't: sync now to see what it is")
}
if err != nil {
return err
}
st := loadState()
if st.Key != stateKey(c) {
st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own}
}
// as the first sync to an empty server leaves it
st.Local, st.Remote, st.Sum, st.Server = hashesOwn(local, st.Own), hashesOwn(b, st.Own), sum(sealed), v
st.Blind = nil // it replaced what wasn't a backup: nothing to merge again
remember(sealed)
st.Last, st.Error, st.File = time.Now(), "", nil
saveState(st)
return nil
})
}
// Undo puts back the setup the last Restore replaced. The next sync takes
// it to the server, as any change made here.
func Undo() ([]string, error) {
var back []string
err := locked(func() error {
c, ok := Load()
if !ok {
return ErrOff
}
st := loadState()
if st.Key != stateKey(c) || st.Undo == "" {
return errors.New("there is no restore to undo")
}
data, err := os.ReadFile(st.Undo)
if err != nil {
return fmt.Errorf("the copy kept before the restore is gone: %w", err)
}
kept, err := backup.Open(data, c.Passphrase)
if err != nil {
return err
}
local, err := collect(withKeys(c))
if err != nil {
return err
}
L, K := hashes(local), hashes(kept)
for _, p := range Parts {
if L[p] == K[p] || !c.syncs(p) || (p == "library" && kept.Library == nil) {
continue
}
if err := bring(kept, p); err != nil {
return fmt.Errorf("bringing back the %s: %w", p, err)
}
back = append(back, p)
}
st.Undo, st.Notice = "", nil
saveState(st)
return nil
})
return back, err
}
// syncs is whether part goes to the server with c.
func (c Config) syncs(part string) bool {
return (part != "agents" || c.Agents) && (part != "library" || c.library())
}
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) {
b, err := collect(withKeys(c))
if err != nil {
return "", err
}
sealed, err := backup.Seal(b, c.Passphrase)
if err != nil {
return "", err
}
dir := path("sync")
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)
if err := edit.WriteAtomic(name, sealed); err != nil {
return "", err
}
os.Chmod(name, 0o600)
old, _ := filepath.Glob(filepath.Join(dir, "*-before-restore"+backup.Ext))
slices.Sort(old)
for len(old) > 5 {
os.Remove(old[0])
old = old[1:]
}
return name, nil
}
func isFile(p string) bool {
fi, err := os.Stat(p)
return err == nil && fi.Mode().IsRegular()
}