From 1a67ca614ed6a8180eaf6ea0442dd1272e43d603 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 4 Nov 2026 19:29:39 +0800 Subject: [PATCH] provider: Fetch models refreshes each key's own models, keeping what the user un-ticked (young02036) young02036 on Discord: a provider holds several keys, each at a group of a relay's that serves different models. Each key's own list was read only when the key was added (PrefillNewKeys); Fetch models merged every key's list into the provider's (fetchPerKey marks each model with the keys that list it) but never changed a key's own models, so a model a group took on later was never sent to its key and one it gave up still was. Fix: refetch, which every Fetch goes through (the editor's button, the CLI, the TUI, the automatic re-list), takes each key's marks before and after the fetch and carries the difference into that key's AccountModels (key_models_refresh.go): a model the key's list has now and didn't before is ticked for it, one it had and has no more is taken out. A model the user un-ticked that the list had before and still has stays un-ticked; one the user ticked that the list never had stays ticked. Only keys with a list of their own are touched (a key serving every model still does), a key with no marks before or now (one key on, just added, a list that failed) is unknown and left alone, nothing is ever narrowed to an empty list, and a key whose models the user changed while the lists were asked keeps the user's. The provider's own picks (what agents get) are not touched. No GUI change: the editor's Fetch already redraws the key rows from the saved provider. Test: TestFetchRefreshesEachKeysModels, against an httptest relay whose per-key lists change between fetches: add a key (prefill), un-tick by hand, groups change, fetch; un-tick again and tick a model the list lacks, fetch twice; a key's list failing; the provider's picks unset. Red on the old code (the refreshKeyModels call removed): "sk-a after a fetch: [gpt-5.5 deepseek-v4], want [gpt-5.5 kimi-k3]", "sk-c after a fetch: [deepseek-v4 qwen3-max], want glm-5 ticked", and the gateway's AccountServes check. Broken by hand: ticking every listed model instead of only those new to the key turns the un-tick, hand-tick and failed-list cases red (4 errors). Run on mote at this tree (on 78128b510): gofmt clean; go vet ./internal/provider ./internal/gui, GOOS=linux -tags nogui and GOOS=windows go vet: ok. go test -count=1 -timeout 45m ./internal/provider ./internal/cli ./internal/tui: ok. ./internal/gui: TestCoreScriptBudget (#5139) and TestMainWindowCorners/macOS_26_SDK (#3949) red, the same as for 78128b510; no gui file changed here. GUI files, chromium and webkit, every language they run: account-models and account-refresh 26/26 ok. provider-fetch-again, provider-picks-stay and gateway-key-models (en) are red, and red the same way at a clean 78128b510 checkout with no change of this commit: #5232 and #5233. Not tried: a real relay with per-group keys, and the full suite before the push. --- internal/provider/key_models_refresh.go | 128 +++++++++++++++++ internal/provider/key_models_refresh_test.go | 144 +++++++++++++++++++ internal/provider/models.go | 6 + 3 files changed, 278 insertions(+) create mode 100644 internal/provider/key_models_refresh.go create mode 100644 internal/provider/key_models_refresh_test.go diff --git a/internal/provider/key_models_refresh.go b/internal/provider/key_models_refresh.go new file mode 100644 index 000000000..b33d5ce62 --- /dev/null +++ b/internal/provider/key_models_refresh.go @@ -0,0 +1,128 @@ +package provider + +// Each key's own models, again on every fetch (young02036 on Discord): a +// provider of several keys, each at a group of a relay's that serves some +// of its models, had each key's list read only when it was added +// (PrefillNewKeys). Fetch models merged every key's list into the +// provider's, marking each model with the keys that list it, but a key's +// own models stayed what its list had when it was added: a model its +// group took on later was never sent to it, one its group gave up still +// was. +// +// A fetch now carries what each key's list gained and lost since the +// fetch before into that key's models: a model its list has now and +// didn't before is ticked for it, one it had and has no more is taken +// out. A model the user un-ticked for a key that its list had before and +// still has stays un-ticked, and one the user ticked that its list never +// had stays ticked: magpie's default never overrides what the user set. +// Only a key the user, or its add, narrowed has a list to carry it into; +// a key that serves every model still does. A key with no marks before or +// now (one key on, a key just added, one switched off) is unknown, and +// its models stay as they are. + +import ( + "slices" + + "github.com/yetone/magpie/internal/catalog" +) + +// keyMarks are, by key fingerprint, the provider's own ids of the models +// its fetched list marks each key as seeing (catalog.Model.Keys). +func keyMarks(id string) map[string]map[string]bool { + ms, _, _ := catalog.Live(id) + ms = append(ms, catalog.LiveDrawers(id)...) + ms = append(ms, catalog.LiveVideomakers(id)...) + out := map[string]map[string]bool{} + for _, m := range ms { + for _, k := range m.Keys { + if out[k] == nil { + out[k] = map[string]bool{} + } + out[k][m.ID] = true + } + } + return out +} + +// refreshKeyModels carries what each of the provider id's keys' lists +// gained and lost between before and now into the models it serves +// (AccountModels), and answers how many keys' models changed. +func refreshKeyModels(id string, before, now map[string]map[string]bool) int { + if len(before) == 0 || len(now) == 0 { + return 0 + } + p, err := Find(id) + if err != nil || len(p.AccountModels) == 0 { + return 0 + } + var am map[string][]string + n := 0 + for _, k := range p.KeysOn() { + kid := keyID(k.Key) + was := p.AccountModels[accountKey(kid)] + o, w := before[kid], now[kid] + if was == nil || len(o) == 0 || len(w) == 0 { + continue + } + var list []string + for _, m := range was { + own := p.OwnModelID(m) + if o[own] && !w[own] { + continue // its list had it and has no more + } + list = append(list, m) + } + var gained []string + for m := range w { + if !o[m] { + gained = append(gained, m) + } + } + slices.Sort(gained) + for _, m := range gained { + if !slices.ContainsFunc(list, func(x string) bool { return x == m || p.OwnModelID(x) == m }) { + list = append(list, p.ListedModelID(m)) + } + } + if len(list) == 0 || slices.Equal(list, was) { + continue // nothing left would read as every model: keep it + } + if am == nil { + am = make(map[string][]string, len(p.AccountModels)) + for k, v := range p.AccountModels { + am[k] = v + } + } + am[accountKey(kid)] = list + n++ + } + if n == 0 { + return 0 + } + // read again: the user may have set a key's models while the lists + // were asked for, and what they set stands + q, err := Find(id) + if err != nil { + return 0 + } + merged := make(map[string][]string, len(q.AccountModels)) + for k, v := range q.AccountModels { + merged[k] = v + } + n = 0 + for k, v := range am { + if slices.Equal(v, p.AccountModels[k]) || !slices.Equal(q.AccountModels[k], p.AccountModels[k]) { + continue + } + merged[k] = v + n++ + } + if n == 0 { + return 0 + } + q.AccountModels = merged + if Save(*q) != nil { + return 0 + } + return n +} diff --git a/internal/provider/key_models_refresh_test.go b/internal/provider/key_models_refresh_test.go new file mode 100644 index 000000000..6cb64778c --- /dev/null +++ b/internal/provider/key_models_refresh_test.go @@ -0,0 +1,144 @@ +package provider + +import ( + "context" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" +) + +// lists is a relay's models for each key, changed between fetches. +type relayLists struct { + mu sync.Mutex + by map[string][]string +} + +func (l *relayLists) set(key string, ids ...string) { + l.mu.Lock() + defer l.mu.Unlock() + l.by[key] = ids +} + +func (l *relayLists) serve(t *testing.T) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + l.mu.Lock() + ids, ok := l.by[key] + l.mu.Unlock() + if !ok { + http.Error(rw, `{"error":{"message":"invalid key"}}`, http.StatusUnauthorized) + return + } + var b strings.Builder + b.WriteString(`{"data":[`) + for i, id := range ids { + if i > 0 { + b.WriteString(",") + } + b.WriteString(`{"id":"` + id + `"}`) + } + b.WriteString(`]}`) + _, _ = rw.Write([]byte(b.String())) + })) + t.Cleanup(srv.Close) + return srv +} + +// young02036 on Discord: a provider's keys each serve the models of their +// own group, and each key's list was read only when it was added. Fetch +// models now carries what each key's list gained and lost into that key's +// models, and leaves what the user un-ticked, or ticked, as they set it. +func TestFetchRefreshesEachKeysModels(t *testing.T) { + prefillHome(t) + l := &relayLists{by: map[string][]string{ + "sk-a": {"gpt-5.5", "deepseek-v4", "glm-5"}, + "sk-b": {"kimi-k3"}, + }} + srv := l.serve(t) + if err := Save(Provider{ID: "relay", Name: "Relay", Chat: srv.URL + "/v1", Key: "sk-a", + Keys: []KeyAccount{{Key: "sk-b"}}}); err != nil { + t.Fatal(err) + } + fetch := func() { + t.Helper() + p, _ := Find("relay") + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + } + models := func(key string) []string { + p, _ := Find("relay") + return p.AccountModels[keyID(key)] + } + fetch() + + // a key added takes its own list, as the GUI's add does it + l.set("sk-c", "deepseek-v4", "qwen3-max") + had := KeysHeld("relay") + if err := AddKey("relay", "C group", "sk-c", ""); err != nil { + t.Fatal(err) + } + PrefillNewKeys(context.Background(), had, "relay") + fetch() + if got := models("sk-c"); !slices.Equal(got, []string{"deepseek-v4", "qwen3-max"}) { + t.Fatalf("the added key's models %v", got) + } + // the user narrows sk-a by hand: glm-5 un-ticked + if err := SetAccountModels("relay", keyID("sk-a"), []string{"gpt-5.5", "deepseek-v4"}); err != nil { + t.Fatal(err) + } + + // the groups change: sk-a's gives up deepseek-v4 and takes kimi-k3, + // sk-c's takes glm-5 + l.set("sk-a", "gpt-5.5", "glm-5", "kimi-k3") + l.set("sk-c", "deepseek-v4", "qwen3-max", "glm-5") + fetch() + if got := models("sk-a"); !slices.Equal(got, []string{"gpt-5.5", "kimi-k3"}) { + t.Errorf("sk-a after a fetch: %v, want [gpt-5.5 kimi-k3] (deepseek-v4 gone, glm-5 still un-ticked)", got) + } + if got := models("sk-c"); !slices.Equal(got, []string{"deepseek-v4", "qwen3-max", "glm-5"}) { + t.Errorf("sk-c after a fetch: %v, want glm-5 ticked", got) + } + if got := models("sk-b"); got != nil { + t.Errorf("sk-b serves every model and was given %v", got) + } + // the gateway sends sk-c the model its group took on + if p, _ := Find("relay"); !p.AccountServes(keyID("sk-c"), "glm-5") || p.AccountServes(keyID("sk-a"), "deepseek-v4") { + t.Error("the keys' models don't hold the gateway's requests") + } + + // the user un-ticks glm-5 for sk-c and ticks deepseek-v4 for sk-a, + // which its list hasn't; fetched again, both stay as they set them + if err := SetAccountModels("relay", keyID("sk-c"), []string{"deepseek-v4", "qwen3-max"}); err != nil { + t.Fatal(err) + } + if err := SetAccountModels("relay", keyID("sk-a"), []string{"gpt-5.5", "kimi-k3", "deepseek-v4"}); err != nil { + t.Fatal(err) + } + fetch() + fetch() + if got := models("sk-c"); !slices.Equal(got, []string{"deepseek-v4", "qwen3-max"}) { + t.Errorf("sk-c's un-tick undone by a fetch: %v", got) + } + if got := models("sk-a"); !slices.Equal(got, []string{"gpt-5.5", "kimi-k3", "deepseek-v4"}) { + t.Errorf("sk-a's tick undone by a fetch: %v", got) + } + + // a key whose list can't be read now keeps its models + l.mu.Lock() + delete(l.by, "sk-c") + l.mu.Unlock() + l.set("sk-a", "gpt-5.5") + fetch() + if got := models("sk-c"); !slices.Equal(got, []string{"deepseek-v4", "qwen3-max"}) { + t.Errorf("sk-c's models changed while its list failed: %v", got) + } + // the provider's own picks, what agents get, stay the user's + if p, _ := Find("relay"); len(p.Models) != 0 { + t.Errorf("the provider's picks were set: %v", p.Models) + } +} diff --git a/internal/provider/models.go b/internal/provider/models.go index a78faea1d..42e4b7771 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -304,7 +304,13 @@ func (p Provider) refetch(ctx context.Context) ([]catalog.Model, []string, map[s return ms, nil, nil, err } before := liveIDs(p.ID) + marks := keyMarks(p.ID) ms, err := p.fetch(ctx) + if err == nil { + // each key's own models follow what its list gained and lost + // (key_models_refresh.go) + refreshKeyModels(p.ID, marks, keyMarks(p.ID)) + } if err == nil && p.listsDecisions() { // OpenRouter's decision models, listed apart from its chat ones if _, derr := p.fetchDecide(p.Via(ctx)); derr != nil {