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 {