diff --git a/docs/reference.md b/docs/reference.md index b2d8e9618..b054b3683 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -2552,7 +2552,8 @@ the copy made before a write. What you set: - `settings.json` — Settings -- `providers.json` — your providers, keys included (0600) +- `providers.json` — your providers, keys included (0600); `pluginLeft` in it + keeps a removed plugin's model picks until it is added again - `profiles.json` — saved profiles - `library.json`, `library/` — the library: its instructions, skills, MCP servers and hooks, and the agents each goes to diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index e52cb787c..f28ac016c 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -129,6 +129,16 @@ Installing the plugin independently can also hand over ownership through `provid `MoveBack` restores built-in ownership and records `back`. Compatible accounts added through the plugin can return too; incompatible accounts can remain with the plugin under its separate id. Removing or disabling a plugin first moves affected built-ins back and stops if that fails. A package installed by the user remains after moving back; a migration-installed package is removed only when no remaining signed-in or moved provider needs it. +Removing a plugin also sets aside the model picks its providers left in `providers.json` (#2057, `plugin_left.go`). Before, nothing listed those records and `magpie provider rm` couldn't find them, so sync and backup asked for a sign-in to them on every run (`NotSignedIn`). + +- `RemovePlugin` reads which ids the plugin's providers have (`pluginRecordIDs`: `PluginID` of each provider `plugin.Listed` last gave for its spec, an off plugin's included) while it is still installed. It leaves out: + - a built-in's id; + - any id another installed plugin also serves. +- After `plugin.Remove`, only records under those ids that hold picks alone (`OnlyPicks`) move into `providers.json`'s `pluginLeft`, under the package's name. A record with an endpoint or a key is the user's own provider and stays. +- With no listing known (no cache and no readable `plugin-providers.json`), nothing is set aside. +- `provider.AddPlugin` is what the GUI, the CLI and `AddPlugins` (backup and sync) add through. It puts the package's records back, each one whose id has no record now. One the user gave to a provider since stays aside. +- Switching a plugin off sets nothing aside, since off is undone by switching it back on. Records left behind by removals before this change stay as they are; they can't be told from picks a sync brought for a plugin not installed here yet. + New users do not see an unused deprecated built-in in the Add sheet. `unusedSub` leaves it out when it has no account. Until an installed replacement takes ownership, `replacedSub` makes the Add sheet show the plugin tile. The Plugins page is the installation entry point. `keepMovedCurrent` maintains the required plugin version for moved subscriptions. Raising the owning mover's `min` after publishing a plugin fix triggers this update path. Update failures are logged; disabled packages and local-folder installations are not automatically replaced. diff --git a/internal/cli/plugins_cli.go b/internal/cli/plugins_cli.go index c3228d064..d6bacc525 100644 --- a/internal/cli/plugins_cli.go +++ b/internal/cli/plugins_cli.go @@ -53,7 +53,7 @@ func pluginCmd(args []string) error { if !plugin.IsPath(rest[0]) && !plugin.HasBun() { fmt.Println(muted.Render("Downloading Bun " + plugin.BunInUse() + ", which plugins run on…")) } - e, err := plugin.Add(ctx, rest[0]) + e, err := provider.AddPlugin(ctx, rest[0]) if err != nil { return err } diff --git a/internal/gui/plugins.go b/internal/gui/plugins.go index 6c5911977..63fc48e24 100644 --- a/internal/gui/plugins.go +++ b/internal/gui/plugins.go @@ -370,7 +370,7 @@ func pluginMarketState(ctx context.Context, w Windows) pluginMarketJSON { // addPlugin, removePlugin, updatePlugins and upgradePlugin are what // /api/plugins/{op} runs, for tests to stand in for. var ( - addPlugin = plugin.Add + addPlugin = provider.AddPlugin removePlugin = provider.RemovePlugin updatePlugins = plugin.Update upgradePlugin = plugin.Upgrade diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go index 0694d2ee2..021fb511a 100644 --- a/internal/plugin/providers.go +++ b/internal/plugin/providers.go @@ -451,6 +451,24 @@ func UseCached(ps []Provider) { listSeen.Unlock() } +// Listed is every provider the plugins last listed, an off plugin's among +// them, as Cached keeps them, with no sign-in read: false when no listing +// is known (none kept, plugin-providers.json missing or unreadable), which +// is never "no providers". +func Listed() ([]Provider, bool) { + provMu.Lock() + ps := provCache + provMu.Unlock() + if ps != nil { + return slices.Clone(ps), true + } + b, err := steady.ReadFile(providersPath()) + if err != nil || json.Unmarshal(b, &ps) != nil { + return nil, false + } + return ps, true +} + // refreshing is Cached's refreshes in the background. var refreshing sync.WaitGroup diff --git a/internal/provider/backup.go b/internal/provider/backup.go index 4d7f4babf..baf6066dc 100644 --- a/internal/provider/backup.go +++ b/internal/provider/backup.go @@ -182,7 +182,7 @@ func AddPlugins(ctx context.Context, es []plugin.Entry) (added []string, failed continue } here[plugin.Name(e.Spec)] = true - got, err := addPlugin(ctx, e.Spec) + got, err := AddPlugin(ctx, e.Spec) if err == nil && e.Off { err = plugin.SetOff(got.Spec, true) } diff --git a/internal/provider/migrate.go b/internal/provider/migrate.go index 9eee7322b..e3ccfc61b 100644 --- a/internal/provider/migrate.go +++ b/internal/provider/migrate.go @@ -1305,12 +1305,26 @@ func releasePlugin(ctx context.Context, name string) error { } // RemovePlugin removes the plugin named, the built-ins moved onto it moved -// back to themselves first. +// back to themselves first, and sets aside the model picks of its +// providers it leaves in providers.json (plugin_left.go). func RemovePlugin(ctx context.Context, name string) error { if err := releasePlugin(ctx, name); err != nil { return err } - return plugin.Remove(ctx, name) + // what it served is read while it is still on the list + spec := installedSpec(name) + ids, known := pluginRecordIDs(spec) + pkg := plugin.PackageName(spec) + if err := plugin.Remove(ctx, name); err != nil { + return err + } + if spec == "" || !known { + return nil + } + if err := setAside(pkg, ids); err != nil { + return fmt.Errorf("%s is removed; its model picks were left in providers.json: %w", name, err) + } + return nil } // SetPluginOff turns the plugin named off, the built-ins moved onto it diff --git a/internal/provider/plugin_left.go b/internal/provider/plugin_left.go new file mode 100644 index 000000000..db760050e --- /dev/null +++ b/internal/provider/plugin_left.go @@ -0,0 +1,142 @@ +package provider + +import ( + "context" + "fmt" + "slices" + + "github.com/yetone/magpie/internal/plugin" +) + +// A plugin's provider leaves a record in providers.json once the user picks +// its models or changes a setting on it: its id, and no endpoint or key of +// its own (OnlyPicks). Removing the plugin left that record behind, where +// nothing listed it and `magpie provider rm` couldn't find it, and a sync +// or a backup then asked for a sign-in to it on every run (#2057, dawn1095). +// So removing a plugin sets its records aside, and adding it again puts +// them back. + +// LeftRecord is a record set aside when the plugin it was one of was +// removed: Package is the plugin's package name, as plugin.PackageName +// gives it. +type LeftRecord struct { + Package string `json:"package"` + Provider Provider `json:"provider"` +} + +// pluginRecordIDs are the ids the records in providers.json that the +// plugin spec made have: its providers' ids as magpie lists them, apart +// from a built-in's (whose picks are the built-in's own) and one another +// installed plugin serves too. false when the plugins' listing isn't +// known, which sets nothing aside. +func pluginRecordIDs(spec string) ([]string, bool) { + listed, ok := plugin.Listed() + if !ok { + return nil, false + } + installed := map[string]bool{} + for _, e := range plugin.Load().Plugins { + installed[e.Spec] = true + } + others := map[string]bool{} + for _, pp := range listed { + if pp.Spec != spec && installed[pp.Spec] { + others[PluginID(pp.ID)] = true + } + } + var ids []string + for _, pp := range listed { + id := PluginID(pp.ID) + if pp.Spec != spec || id == "" || id == "magpie" || slices.Contains(accountIDs, id) || others[id] || slices.Contains(ids, id) { + continue + } + ids = append(ids, id) + } + return ids, true +} + +// installedSpec is the spec of the installed plugin named (by its spec or +// its name, as plugin.Remove takes it), "" for none. +func installedSpec(name string) string { + es := plugin.Load().Plugins + if i := slices.IndexFunc(es, func(e plugin.Entry) bool { return e.Spec == name }); i >= 0 { + return es[i].Spec + } + if i := slices.IndexFunc(es, func(e plugin.Entry) bool { return plugin.Name(e.Spec) == name }); i >= 0 { + return es[i].Spec + } + return "" +} + +// setAside moves the records with the ids given that hold only picks out +// of providers.json's providers into its pluginLeft, under pkg. A record +// with an endpoint or a key is the user's own provider, never the +// plugin's, and stays where it is. +func setAside(pkg string, ids []string) error { + if len(ids) == 0 { + return nil + } + f, err := read() + if err != nil { + return err + } + keep := make([]Provider, 0, len(f.Providers)) + moved := false + for _, p := range f.Providers { + if slices.Contains(ids, p.ID) && OnlyPicks(p) { + // one set aside before under the same id gives way to this + f.PluginLeft = slices.DeleteFunc(f.PluginLeft, func(l LeftRecord) bool { return l.Provider.ID == p.ID }) + f.PluginLeft = append(f.PluginLeft, LeftRecord{Package: pkg, Provider: p}) + moved = true + continue + } + keep = append(keep, p) + } + if !moved { + return nil + } + f.Providers = keep + return store(f) +} + +// takeBackLeft puts the records set aside for the plugin spec back among the +// providers, each one whose id has no record now; one that has (the user +// gave the id to a provider since) stays aside. +func takeBackLeft(spec string) error { + pkg := plugin.PackageName(spec) + f, err := read() + if err != nil { + return err + } + if !slices.ContainsFunc(f.PluginLeft, func(l LeftRecord) bool { return l.Package == pkg }) { + return nil + } + left := f.PluginLeft[:0] + changed := false + for _, l := range f.PluginLeft { + if l.Package == pkg && !slices.ContainsFunc(f.Providers, func(p Provider) bool { return p.ID == l.Provider.ID }) { + f.Providers = append(f.Providers, l.Provider) + changed = true + continue + } + left = append(left, l) + } + if !changed { + return nil + } + f.PluginLeft = left + return store(f) +} + +// AddPlugin installs the plugin spec, as plugin.Add does, and puts back +// what was set aside of it when it was last removed. +func AddPlugin(ctx context.Context, spec string) (plugin.Entry, error) { + e, err := addPlugin(ctx, spec) + if err != nil { + return e, err + } + if err := takeBackLeft(e.Spec); err != nil { + return e, fmt.Errorf("%s is added; its model picks from before weren't put back: %w", e.Spec, err) + } + return e, nil +} diff --git a/internal/provider/plugin_left_test.go b/internal/provider/plugin_left_test.go new file mode 100644 index 000000000..daa533444 --- /dev/null +++ b/internal/provider/plugin_left_test.go @@ -0,0 +1,213 @@ +package provider + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/yetone/magpie/internal/plugin" +) + +// leftPlugins installs two plugins from folders (so removing one runs no +// Bun) and lists their providers as the host last told them: foo's +// plugin serves foo, zap and shared; bar's serves bar and shared. +func leftPlugins(t *testing.T) (foo, bar string) { + t.Helper() + dir := t.TempDir() + foo, bar = filepath.Join(dir, "foo"), filepath.Join(dir, "bar") + for spec, name := range map[string]string{foo: "@x/opencode-foo-auth", bar: "@x/opencode-bar-auth"} { + if err := os.MkdirAll(spec, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(spec, "package.json"), []byte(`{"name":"`+name+`","version":"1.0.0"}`), 0o600); err != nil { + t.Fatal(err) + } + } + list := filepath.Join(filepath.Dir(plugin.Dir()), "plugins.json") + if err := os.MkdirAll(filepath.Dir(list), 0o700); err != nil { + t.Fatal(err) + } + b, _ := json.Marshal(map[string]any{"plugins": []map[string]string{{"spec": foo}, {"spec": bar}}}) + if err := os.WriteFile(list, b, 0o600); err != nil { + t.Fatal(err) + } + plugin.UseCached([]plugin.Provider{ + {ID: "foo", Spec: foo}, {ID: "zap", Spec: foo}, {ID: "shared", Spec: foo}, + {ID: "bar", Spec: bar}, {ID: "shared", Spec: bar}, + }) + t.Cleanup(func() { plugin.UseCached(nil) }) + return foo, bar +} + +// writeProviders puts ps in providers.json as the user's file has them. +func writeProviders(t *testing.T, ps []Provider) { + t.Helper() + if err := store(file{Providers: ps}); err != nil { + t.Fatal(err) + } +} + +func storedIDs(t *testing.T) []string { + t.Helper() + ps, err := Stored() + if err != nil { + t.Fatal(err) + } + var ids []string + for _, p := range ps { + ids = append(ids, p.ID) + } + slices.Sort(ids) + return ids +} + +// Removing a plugin takes its providers' model picks out of providers.json +// with it, where nothing listed them and a sync asked for a sign-in to +// them on every run (#2057); every record the user made by hand, and every +// one another plugin or a built-in serves, stays as it was. +func TestRemovePluginSetsItsPicksAside(t *testing.T) { + claudeHome(t) + foo, _ := leftPlugins(t) + writeProviders(t, []Provider{ + // the user's own provider named zap: the plugin's zap is + // zap-plugin beside it + {ID: "zap", Name: "My zap", Chat: "https://zap.example/v1", Key: "sk-mine", Models: []string{"z-1"}}, + // the plugin's: model picks alone + {ID: "foo", Models: []string{"foo-1", "foo-2"}}, + {ID: "zap-plugin", Models: []string{"zap-big"}}, + // served by the other plugin too + {ID: "shared", Models: []string{"s-1"}}, + // the other plugin's alone + {ID: "bar", Models: []string{"bar-1"}}, + // a built-in's picks + {ID: "claude", Models: []string{"claude-sonnet-4-5"}}, + // the user's own provider, an id no plugin has + {ID: "mine", Chat: "https://mine.example/v1", Key: "sk-2"}, + }) + if got := NotSignedIn(mustStored(t)); !slices.Contains(got, "foo") { + t.Fatalf("before: foo isn't among those asked to sign in: %v", got) + } + + if err := RemovePlugin(context.Background(), foo); err != nil { + t.Fatal(err) + } + if got, want := storedIDs(t), []string{"bar", "claude", "mine", "shared", "zap"}; !slices.Equal(got, want) { + t.Fatalf("providers.json after foo's plugin went: %v, want %v", got, want) + } + ps := mustStored(t) + for _, p := range ps { + if p.ID == "zap" && (p.Chat != "https://zap.example/v1" || p.Key != "sk-mine" || p.Name != "My zap") { + t.Fatalf("the user's own zap was changed: %+v", p) + } + } + if got := NotSignedIn(ps); slices.Contains(got, "foo") || slices.Contains(got, "zap-plugin") { + t.Fatalf("a sync still asks for a sign-in to the removed plugin's providers: %v", got) + } + f, err := read() + if err != nil { + t.Fatal(err) + } + var left []string + for _, l := range f.PluginLeft { + if l.Package != "@x/opencode-foo-auth" { + t.Fatalf("set aside under %q, not the plugin's package", l.Package) + } + left = append(left, l.Provider.ID) + } + slices.Sort(left) + if !slices.Equal(left, []string{"foo", "zap-plugin"}) { + t.Fatalf("set aside: %v", left) + } + + // added again, its picks are as they were; the user's zap untouched + oldAdd := addPlugin + t.Cleanup(func() { addPlugin = oldAdd }) + addPlugin = func(_ context.Context, spec string) (plugin.Entry, error) { return plugin.Entry{Spec: spec}, nil } + if _, err := AddPlugin(context.Background(), foo); err != nil { + t.Fatal(err) + } + if got, want := storedIDs(t), []string{"bar", "claude", "foo", "mine", "shared", "zap", "zap-plugin"}; !slices.Equal(got, want) { + t.Fatalf("providers.json after foo's plugin came back: %v, want %v", got, want) + } + for _, p := range mustStored(t) { + if p.ID == "foo" && !slices.Equal(p.Models, []string{"foo-1", "foo-2"}) { + t.Fatalf("foo's picks came back as %v", p.Models) + } + } + if f, _ := read(); len(f.PluginLeft) != 0 { + t.Fatalf("still set aside: %+v", f.PluginLeft) + } +} + +// What the plugins serve not known (no listing kept, plugin-providers.json +// missing), removing one leaves providers.json as it was: unknown is never +// "none of them is the user's". +func TestRemovePluginUnknownListingKeepsRecords(t *testing.T) { + claudeHome(t) + foo, _ := leftPlugins(t) + plugin.UseCached(nil) + writeProviders(t, []Provider{{ID: "foo", Models: []string{"foo-1"}}, {ID: "bar", Models: []string{"bar-1"}}}) + if err := RemovePlugin(context.Background(), foo); err != nil { + t.Fatal(err) + } + if got := storedIDs(t); !slices.Equal(got, []string{"bar", "foo"}) { + t.Fatalf("records went with no listing known: %v", got) + } +} + +// A record set aside whose id the user has given to a provider since +// stays aside when the plugin is added again, and theirs stays theirs. +func TestAddPluginLeavesTheUsersRecord(t *testing.T) { + claudeHome(t) + foo, _ := leftPlugins(t) + writeProviders(t, []Provider{{ID: "foo", Models: []string{"foo-1"}}}) + if err := RemovePlugin(context.Background(), foo); err != nil { + t.Fatal(err) + } + mine := Provider{ID: "foo", Name: "Mine", Chat: "https://foo.example/v1", Key: "sk-3"} + f, _ := read() + f.Providers = append(f.Providers, mine) + if err := store(f); err != nil { + t.Fatal(err) + } + oldAdd := addPlugin + t.Cleanup(func() { addPlugin = oldAdd }) + addPlugin = func(_ context.Context, spec string) (plugin.Entry, error) { return plugin.Entry{Spec: spec}, nil } + if _, err := AddPlugin(context.Background(), foo); err != nil { + t.Fatal(err) + } + ps := mustStored(t) + if len(ps) != 1 || ps[0].Chat != mine.Chat || ps[0].Key != mine.Key { + t.Fatalf("the user's foo: %+v", ps) + } +} + +func mustStored(t *testing.T) []Provider { + t.Helper() + ps, err := Stored() + if err != nil { + t.Fatal(err) + } + return ps +} + +// A record with an endpoint or a key is the user's own provider whatever +// its id, even one a removed plugin's provider would be listed under. +func TestRemovePluginKeepsTheUsersEndpoints(t *testing.T) { + claudeHome(t) + foo, _ := leftPlugins(t) + writeProviders(t, []Provider{ + {ID: "zap", Chat: "https://zap.example/v1", Key: "sk-1"}, + {ID: "zap-plugin", Anthropic: "https://zap2.example", Key: "sk-2"}, + {ID: "foo", Models: []string{"foo-1"}}, + }) + if err := RemovePlugin(context.Background(), foo); err != nil { + t.Fatal(err) + } + if got := storedIDs(t); !slices.Equal(got, []string{"zap", "zap-plugin"}) { + t.Fatalf("providers.json: %v", got) + } +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index ca4d4bb9c..ed015948d 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -393,6 +393,10 @@ type file struct { // Routing page (#779), by id, found ones among them; one not in it // follows those that are (see SetGroupOrder). GroupOrder []string `json:"groupOrder,omitempty"` + // PluginLeft are the picks of a removed plugin's providers, set aside + // when it was removed and put back when it is added again (#2057; see + // plugin_left.go). + PluginLeft []LeftRecord `json:"pluginLeft,omitempty"` } // Path is the file the user's providers live in.