diff --git a/docs/subsystems/sync-backup.md b/docs/subsystems/sync-backup.md index a7ab84557..11836d89f 100644 --- a/docs/subsystems/sync-backup.md +++ b/docs/subsystems/sync-backup.md @@ -223,6 +223,13 @@ clock. `auto-backup.test.cjs`). - **Sign-ins:** off unless picked (`SignIns`, with `Passphrase`); see [Sign-ins, when picked](#sign-ins-when-picked). +- **Plugins:** ride the providers part. `AddPlugins` only adds, so a removal is + `syncOnce`'s: it keeps the names both sides had after the last sync + (`state.Plugins`), and a name one side has since lost is removed on the other + (`pluginPlan`, `removePlugin`), however the providers part came out. One that + can't be removed (its agent is on magpie) is tried again next sync. A plugin + added on one side stays (dolacmeo on X; `TestSyncPluginRemovalSpreads`). Not + yet: an older sync with no record (`state.Plugins` empty) removes nothing. - **Memory:** on unless turned off (`Memory`), merged memory by memory in `syncOnce` after the sign-ins, never replaced as a part; see [Memory's backups and sync](memory.md#backups-and-sync). diff --git a/internal/backup/backup.go b/internal/backup/backup.go index 527aa888a..30098294d 100644 --- a/internal/backup/backup.go +++ b/internal/backup/backup.go @@ -239,6 +239,9 @@ func Collect(keys bool, app string) (Bundle, error) { } } plugins := provider.Carried(keys) + if plugins == nil { + plugins = []plugin.Entry{} // none, as against a file that carries no list + } b.Plugins = &plugins searches := []provider.SearchAPI{} for _, a := range provider.StoredSearchAPIs() { diff --git a/internal/davsync/davsync.go b/internal/davsync/davsync.go index 8a1f156b9..4046f9899 100644 --- a/internal/davsync/davsync.go +++ b/internal/davsync/davsync.go @@ -53,6 +53,14 @@ import ( // addPlugins is backup.AddPlugins: a var so a test installs nothing. var addPlugins = backup.AddPlugins +// removePlugin is provider.RemovePlugin, as Settings → Plugins removes one: +// a var so a test removes nothing. +var removePlugin = func(name string) error { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + return provider.RemovePlugin(ctx, name) +} + // Every is how often the gateway's magpie syncs. const Every = 3 * time.Minute @@ -258,6 +266,11 @@ type state struct { // when not known (never synced with them, or a blind write went // over), when none is taken for removed. SignIns map[string]string `json:"signIns"` + // Plugins is the plugins (by name) the last sync left both on the + // server and here: one gone from a side since was removed there, and + // 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"` } // blind is a write the server didn't check: the file it wrote (Sum), and @@ -1236,6 +1249,7 @@ func syncOnce(ctx context.Context, c Config, st *state) error { if !unchanged && sum(data) != b.Sum { st.Remote, st.Local = b.Remote, b.Local st.SignIns = nil // what went up may be gone: nothing is taken for removed + st.Plugins = nil } st.Blind = nil } @@ -1312,6 +1326,7 @@ func syncOnce(ctx context.Context, c Config, st *state) error { if c.SignIns { st.SignIns = local.SignIns.Hashes() } + st.Plugins = pluginNames(local.Plugins) return nil } if sum(data) == st.Sum && maps.Equal(L, st.Local) && !follow && !moved { @@ -1383,6 +1398,13 @@ func syncOnce(ctx context.Context, c Config, st *state) error { // below changes remote (a join's unseen gateway keys) R, Rafter := hashesOwn(remote, prev), hashesOwn(remote, afterW) 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) + if len(goneHere) > 0 && remote.Plugins != nil { + kept := without(*remote.Plugins, goneHere) + remote.Plugins = &kept + } merged := remote var bringIn, here, there []string for _, p := range Parts { @@ -1492,9 +1514,23 @@ func syncOnce(ctx context.Context, c Config, st *state) error { } } st.Own, st.Here, R = after, kept, Rafter + // the plugins the other computers removed, removed here as Settings + // removes one; one that can't be (its agent is on magpie) is tried + // again at the next sync, and isn't sent up meanwhile + var stuck []string + for _, name := range goneThere { + if err := removePlugin(name); err != nil { + log.Printf("sync: removing plugin %s, which another computer removed: %v", name, err) + stuck = append(stuck, name) + } + } + if gone := slices.Concat(goneHere, goneThere); len(gone) > 0 && merged.Plugins != nil { + kept := without(*merged.Plugins, gone) + merged.Plugins = &kept + } // the server's file is in; what is pushed next counts as changed here // until the push is done - if len(bringIn) > 0 || follow { + if len(bringIn) > 0 || follow || len(goneThere) > 0 { if local, err = collect(c); err != nil { return err } @@ -1563,9 +1599,63 @@ func syncOnce(ctx context.Context, c Config, st *state) error { if c.SignIns { st.SignIns = bothSides(shared, local.SignIns.Hashes()) } + st.Plugins = nil + if merged.Plugins != nil { + // 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 { + return !slices.Contains(pluginNames(merged.Plugins), n) + }) + st.Plugins = append(both, stuck...) + } return nil } +// pluginNames is the names of the plugins in es, nil for none. +func pluginNames(es *[]plugin.Entry) []string { + if es == nil { + return nil + } + var out []string + for _, e := range *es { + out = append(out, plugin.Name(e.Spec)) + } + return out +} + +// without is es less the plugins named. +func without(es []plugin.Entry, names []string) []plugin.Entry { + out := []plugin.Entry{} + for _, e := range es { + if !slices.Contains(names, plugin.Name(e.Spec)) { + out = append(out, e) + } + } + return out +} + +// pluginPlan tells which plugins one side removed since the last sync (base, +// the names both had then), as sign-ins are told: a plugin base had that +// here lacks was removed here (goneHere), and one the server lacks was +// removed there (goneThere, still here). A plugin on one side that base +// never had is a new one, and stays. Nothing is told when base is unknown +// or the server's file carries no plugin list (an older magpie). +func pluginPlan(base []string, local, remote *[]plugin.Entry) (goneHere, goneThere []string) { + if len(base) == 0 || remote == nil { + return nil, nil + } + here, there := pluginNames(local), pluginNames(remote) + for _, n := range base { + switch inHere, inThere := slices.Contains(here, n), slices.Contains(there, n); { + case !inHere && inThere: + goneHere = append(goneHere, n) + case inHere && !inThere: + goneThere = append(goneThere, n) + } + } + return goneHere, goneThere +} + // bothSides is the sign-ins on the server (shared) that are here too, as // the server has them: one the server has that wasn't put in here (more // than one account here could be it, the agent's own here) isn't taken diff --git a/internal/davsync/davsync_test.go b/internal/davsync/davsync_test.go index 72570b506..266b1118e 100644 --- a/internal/davsync/davsync_test.go +++ b/internal/davsync/davsync_test.go @@ -660,7 +660,7 @@ func TestConfigurePassword(t *testing.T) { // them, and its status names the subscriptions it brought the settings of // with no account there (yapechan on Discord: after a WebDAV sync no // providers showed, and nothing said why). A plugin taken off one computer -// stays on the others. +// goes from the others too (TestSyncPluginRemovalSpreads). func TestSyncPluginsAndSignIn(t *testing.T) { fake := &fakeDAV{files: map[string][]byte{}, etags: map[string]string{}, dirs: map[string]bool{"/dav": true}} srv := httptest.NewServer(fake) @@ -712,7 +712,7 @@ func TestSyncPluginsAndSignIn(t *testing.T) { t.Fatalf("b's status names %v to sign in to, want claude", got) } - // a takes the plugin away: b keeps its own + // a takes the plugin away: b asks for nothing more a.use(t) if err := os.WriteFile(pluginsJSON, []byte(`{"plugins":[]}`), 0o600); err != nil { t.Fatal(err) diff --git a/internal/davsync/plugin_removal_test.go b/internal/davsync/plugin_removal_test.go new file mode 100644 index 000000000..289d40675 --- /dev/null +++ b/internal/davsync/plugin_removal_test.go @@ -0,0 +1,127 @@ +package davsync + +import ( + "context" + "encoding/json" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// pluginsHere is the specs in this computer's plugins.json. +func pluginsHere() []string { + var out []string + for _, e := range plugin.Load().Plugins { + out = append(out, e.Spec) + } + return out +} + +func setPlugins(t *testing.T, specs ...string) { + t.Helper() + var l plugin.List + l.Plugins = []plugin.Entry{} + for _, s := range specs { + l.Plugins = append(l.Plugins, plugin.Entry{Spec: s}) + } + b, _ := json.Marshal(l) + if err := os.MkdirAll(settings.Dir(), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), b, 0o600); err != nil { + t.Fatal(err) + } +} + +// dolacmeo on X shares one WebDAV config across computers: a plugin removed +// on one came back from another, which still held it and sent it up again. +// A removal is now one too: a plugin both computers had at the last sync and +// one side no longer has is removed on the other, however the part that +// carries it came out; a plugin added meanwhile stays. +func TestSyncPluginRemovalSpreads(t *testing.T) { + fake := &fakeDAV{files: map[string][]byte{}, etags: map[string]string{}, dirs: map[string]bool{"/dav": true}} + srv := httptest.NewServer(fake) + defer srv.Close() + cfg := Config{URL: srv.URL + "/dav/", User: "me", Password: "pw", Passphrase: "correct horse"} + now := func(t *testing.T) { + t.Helper() + if err := Now(context.Background()); err != nil { + t.Fatal(err) + } + } + oldAdd, oldRemove := addPlugins, removePlugin + t.Cleanup(func() { addPlugins, removePlugin = oldAdd, oldRemove }) + var removed []string + addPlugins = func(es []plugin.Entry) ([]string, map[string]string) { + here := pluginsHere() + for _, e := range es { + if !slices.Contains(here, e.Spec) { + here = append(here, e.Spec) + } + } + setPlugins(t, here...) + return nil, nil + } + removePlugin = func(name string) error { + removed = append(removed, name) + setPlugins(t, slices.DeleteFunc(pluginsHere(), func(s string) bool { return plugin.Name(s) == name })...) + return nil + } + const x, y, z = "@magpie-community/opencode-x-auth", "@magpie-community/opencode-y-auth", "@magpie-community/opencode-z-auth" + a, b := newComputer(t), newComputer(t) + + a.use(t) + setPlugins(t, x, y) + Configure(cfg) + now(t) + b.use(t) + Configure(cfg) + now(t) + if got := pluginsHere(); !slices.Equal(got, []string{x, y}) { + t.Fatalf("b has %v after joining, want both", got) + } + a.use(t) + now(t) // a sees b's join: both hold both + + // a removes x and syncs; b follows it, and doesn't send x back + setPlugins(t, y) + now(t) + b.use(t) + now(t) + if got := pluginsHere(); !slices.Equal(got, []string{y}) || !slices.Equal(removed, []string{plugin.Name(x)}) { + t.Fatalf("b has %v, removed %v after a removed x; want only y, x removed", got, removed) + } + now(t) + a.use(t) + now(t) + if got := pluginsHere(); !slices.Equal(got, []string{y}) { + t.Fatalf("a has %v after b's sync, want x not back", got) + } + + // both change: b adds z (and edits providers) while a removes y; the + // removal still reaches b, whichever side's providers part wins + b.use(t) + setPlugins(t, y, z) + if err := os.WriteFile(provider.Path(), []byte(`{"providers":[{"id":"acme","name":"Acme","chat":"https://acme.example.invalid/v1","key":"sk-acme"}]}`), 0o600); err != nil { + t.Fatal(err) + } + a.use(t) + setPlugins(t) + now(t) + b.use(t) + now(t) + if got := pluginsHere(); !slices.Equal(got, []string{z}) { + t.Fatalf("b has %v, want y gone and its own z kept", got) + } + a.use(t) + now(t) + if got := pluginsHere(); slices.Contains(got, y) { + t.Fatalf("a has %v, want y not back", got) + } +} diff --git a/internal/provider/backup.go b/internal/provider/backup.go index 9ed64aef4..21fb71ba8 100644 --- a/internal/provider/backup.go +++ b/internal/provider/backup.go @@ -183,8 +183,8 @@ func withoutSecretOptions(opts map[string]any) map[string]any { // AddPlugins installs the plugins another computer has (Carried) that // aren't here, the way Settings → Plugins adds one, and hands each a // deprecated built-in it serves (HandOver). It never takes a plugin away -// or changes one already here: a plugin removed on one computer stays on -// the others. It returns the specs added and why the others couldn't be. +// or changes one already here; a removal is davsync's, which tracks the +// plugins both sides had at the last sync. It returns the specs added and why the others couldn't be. func AddPlugins(ctx context.Context, es []plugin.Entry) (added []string, failed map[string]error) { here := map[string]bool{} for _, e := range plugin.Load().Plugins {