diff --git a/internal/gui/importapps.go b/internal/gui/importapps.go index e3b4fc931..5c0c9c25a 100644 --- a/internal/gui/importapps.go +++ b/internal/gui/importapps.go @@ -73,7 +73,12 @@ func importAppsRoutes(mux *http.ServeMux) { fail(rw, err) return } + had := provider.KeysHeld() added, err := provider.ImportFromApps(in.Picks) + // a key imported beside others is given the models its own list + // has, as one added by hand is (PrefillNewKeys); those an import + // that stopped part way added too + provider.PrefillNewKeys(r.Context(), had) if err != nil { fail(rw, err) return diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 3ffe82b14..4648fa5a8 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -1965,9 +1965,22 @@ func providerRoutes(mux *http.ServeMux, w Windows) { provider.ForgetPlanQuotas() } // a new key means a new vendor list is worth a try; keep it short - if p, err := provider.Find(in.ID); err == nil && p.Ready() && (old == nil || old.Key != p.Key) { + if p, err := provider.Find(in.ID); err == nil && p.Ready() { ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) - p.Fetch(ctx) + // and each key it didn't have before is given the models + // its own list has, beside it (PrefillNewKeys) + had := map[string]map[string]bool{in.ID: {}} + if old != nil { + for _, k := range old.KeyList() { + had[in.ID][k.ID] = true + } + } + var wg sync.WaitGroup + wg.Go(func() { provider.PrefillNewKeys(ctx, had, in.ID) }) + if old == nil || old.Key != p.Key { + p.Fetch(ctx) + } + wg.Wait() cancel() } // after the list is fetched: a limit has to name a model it has @@ -2446,6 +2459,12 @@ func providerRoutes(mux *http.ServeMux, w Windows) { } var err error var moved []agent.Move + // the keys it had, so a key added is asked for its own models + // (PrefillNewKeys) + var held map[string]map[string]bool + if a := r.PathValue("action"); a == "add" || a == "import" { + held = provider.KeysHeld(in.ID) + } switch r.PathValue("action") { case "add": err = provider.AddKey(in.ID, in.Name, in.Key, in.Protocol) @@ -2489,7 +2508,14 @@ func providerRoutes(mux *http.ServeMux, w Windows) { if a := r.PathValue("action"); a == "add" || a == "import" || a == "on" || a == "plan" { if p, err := provider.Find(in.ID); err == nil && p.Ready() && (len(p.KeysOn()) > 1 || a == "plan") { ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) + // and a key added is given the models its own list has + // beside it, in the same wait (Young on Discord) + var wg sync.WaitGroup + if held != nil { + wg.Go(func() { provider.PrefillNewKeys(ctx, held, in.ID) }) + } p.Fetch(ctx) + wg.Wait() cancel() } } diff --git a/internal/provider/key_models_prefill.go b/internal/provider/key_models_prefill.go new file mode 100644 index 000000000..fce5338cf --- /dev/null +++ b/internal/provider/key_models_prefill.go @@ -0,0 +1,212 @@ +package provider + +// A key's own models when it is added (Young on Discord): a provider of +// several keys, each of a group of the relay's that serves some of its +// models, had every new key take every model (AccountModels' "all"), and +// the user narrowed each by hand. A key added now is asked for its own +// list, with that key alone, and is given what it answers as its models, +// when that leaves out a model the provider's other keys serve. +// +// Only a key that is new and has no list of its own is given one: an +// existing key's list, or one the user set, is never changed. A key whose +// list can't be read now (an error, a timeout, a base that didn't answer, +// an empty list) is unknown and keeps every model, as before; so does a +// key of a vendor with no list to ask (Preset.NoList, a plan's preset +// models), and a key whose list has every model the others have, which a +// list would only hold back from what the vendor adds later. + +import ( + "context" + "slices" + "sync" + "time" +) + +// prefillWait is the longest an add waits for the keys' lists. +const prefillWait = 8 * time.Second + +// KeysHeld is the keys, on or off, each provider of ids (every provider +// when none is named) has now, by provider id and KeyID: what +// PrefillNewKeys tells the keys added since by. +func KeysHeld(ids ...string) map[string]map[string]bool { + out := map[string]map[string]bool{} + for _, p := range All() { + if len(ids) > 0 && !slices.Contains(ids, p.ID) { + continue + } + set := map[string]bool{} + for _, k := range p.KeyList() { + set[k.ID] = true + } + out[p.ID] = set + } + return out +} + +// PrefillNewKeys gives each key on that a provider of ids (every provider +// when none is named) has and before didn't — a provider before has no +// entry for is new, all its keys with it — the models its own list +// answers, as AccountModels: only a key with no models of its own yet, of +// a provider with more than one key on, whose list leaves out a model the +// provider's others list. It answers how many keys were given a list. +func PrefillNewKeys(ctx context.Context, before map[string]map[string]bool, ids ...string) int { + ctx, cancel := context.WithTimeout(ctx, prefillWait) + defer cancel() + type job struct { + p Provider + k KeyAccount + } + var jobs []job + for _, p := range All() { + if len(ids) > 0 && !slices.Contains(ids, p.ID) { + continue + } + if p.Account != nil || p.IsPlugin() || !p.Ready() { + continue + } + keys := p.KeysOn() + if len(keys) < 2 { + continue // one key's list is the provider's + } + for _, k := range keys { + id := keyID(k.Key) + if before[p.ID][id] || p.AccountModels[accountKey(id)] != nil { + continue + } + jobs = append(jobs, job{p, k}) + } + } + if len(jobs) == 0 { + return 0 + } + // each new key's own list, a few at a time: an import of a thousand + // keys is not a thousand requests to one relay at once + lists := make([][]string, len(jobs)) + slots := make(chan struct{}, keyReadsAtOnce) + var wg sync.WaitGroup + for i, j := range jobs { + wg.Go(func() { + select { + case slots <- struct{}{}: + case <-ctx.Done(): + return + } + defer func() { <-slots }() + lists[i] = ownList(ctx, j.p.WithKey(j.k)) + }) + } + wg.Wait() + // what the provider's keys list between them: its saved list, and the + // new keys' own + all := map[string]map[string]bool{} + for i, j := range jobs { + set := all[j.p.ID] + if set == nil { + set = map[string]bool{} + if live, ok := j.p.liveAll(); ok { + for _, m := range live { + set[m.ID] = true + } + } + all[j.p.ID] = set + } + for _, m := range lists[i] { + set[m] = true + } + } + give := map[string]map[string][]string{} // provider id → key id → models + for i, j := range jobs { + ms := lists[i] + if len(ms) == 0 { + continue // unknown: every model, as before + } + has := make(map[string]bool, len(ms)) + for _, m := range ms { + has[m] = true + } + short := false + for m := range all[j.p.ID] { + if !has[m] { + short = true + break + } + } + if !short { + continue // it serves all the provider has; a list adds nothing + } + if give[j.p.ID] == nil { + give[j.p.ID] = map[string][]string{} + } + give[j.p.ID][keyID(j.k.Key)] = ms + } + n := 0 + for pid, keys := range give { + // read again: the user may have set a key's models, or removed + // it, while its list was asked for + p, err := Find(pid) + if err != nil { + continue + } + am := map[string][]string{} + for k, v := range p.AccountModels { + am[k] = v + } + changed := 0 + for kid, ms := range keys { + if am[accountKey(kid)] != nil || !p.HasKeyID(kid) { + continue + } + am[accountKey(kid)] = ms + changed++ + } + if changed == 0 { + continue + } + p.AccountModels = am + if Save(*p) == nil { + n += changed + } + } + return n +} + +// HasKeyID reports whether the key of fingerprint id is one of the +// provider's, on or off. +func (p Provider) HasKeyID(id string) bool { + return slices.ContainsFunc(p.KeyList(), func(k KeyInfo) bool { return k.ID == id }) +} + +// ownList is the ids of the models q, a provider seen with one of its +// keys, is listed by the vendor now, with that key alone; nil when it +// can't be told: a vendor with no list to ask, a list that failed or +// answered nothing, or one of its bases that didn't answer, whose part +// would be filled in from the provider's list saved before. +func ownList(ctx context.Context, q Provider) []string { + if !q.ListAsks() { + return nil + } + if _, ok := q.planOnly(); ok { + return nil + } + if q.IsCline() || q.IsKilo() { + return nil // lists of their own feeds, not a key's /models + } + l, err := q.fetchOne(ctx) + if err != nil || ctx.Err() != nil { + return nil + } + for b := range l.sides { + if !l.answered[b] { + return nil // a base kept from before, not this key's answer + } + } + var out []string + seen := map[string]bool{} + for _, m := range l.models { + if m.ID != "" && !seen[m.ID] { + seen[m.ID] = true + out = append(out, m.ID) + } + } + return out +} diff --git a/internal/provider/key_models_prefill_test.go b/internal/provider/key_models_prefill_test.go new file mode 100644 index 000000000..65e3ae455 --- /dev/null +++ b/internal/provider/key_models_prefill_test.go @@ -0,0 +1,224 @@ +package provider + +import ( + "context" + "net/http" + "net/http/httptest" + "path/filepath" + "slices" + "strings" + "testing" + "time" +) + +// keyRelay is a relay that hands out a key per group: each key lists its +// group's models only. A key not in lists is refused; one whose list is +// "slow" answers only after the test is done with it. +func keyRelay(t *testing.T, lists map[string]string) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + if key == "" { + key = r.Header.Get("x-api-key") + } + body, ok := lists[key] + switch { + case !ok: + http.Error(rw, `{"error":{"message":"invalid key"}}`, http.StatusUnauthorized) + case body == "slow": + <-r.Context().Done() + default: + _, _ = rw.Write([]byte(body)) + } + })) + t.Cleanup(srv.Close) + return srv +} + +func prefillHome(t *testing.T) { + t.Helper() + isolate(t) + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("APPDATA", filepath.Join(h, "AppData", "Roaming")) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + t.Setenv("XDG_DATA_HOME", filepath.Join(h, ".local", "share")) +} + +const groupAll = `{"data":[{"id":"gpt-5.5"},{"id":"claude-opus-4-7"},{"id":"deepseek-v4"}]}` + +// Young on Discord: a key added to a provider of several takes the models +// its own list from the vendor has, asked with that key, not every model; +// the keys it had keep their lists (none, or the user's) as they were. +func TestNewKeyTakesItsOwnModels(t *testing.T) { + prefillHome(t) + srv := keyRelay(t, map[string]string{ + "sk-all": groupAll, + "sk-mine": groupAll, + "sk-claude": `{"data":[{"id":"claude-opus-4-7"}]}`, + "sk-gpt": `{"data":[{"id":"gpt-5.5"},{"id":"deepseek-v4"}]}`, + "sk-old": `{"data":[{"id":"deepseek-v4"}]}`, + }) + // sk-old was there before, with no list of its own though its group + // lists one model: it is not new, so it keeps every model + if err := Save(Provider{ID: "relay", Name: "Relay", Chat: srv.URL + "/v1", Key: "sk-all", + Keys: []KeyAccount{{Key: "sk-mine"}, {Key: "sk-old"}}, + AccountModels: map[string][]string{keyID("sk-mine"): {"gpt-5.5"}}}); err != nil { + t.Fatal(err) + } + p, _ := Find("relay") + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + had := KeysHeld("relay") + if err := AddKey("relay", "Claude group", "sk-claude", ""); err != nil { + t.Fatal(err) + } + if n := PrefillNewKeys(context.Background(), had, "relay"); n != 1 { + t.Fatalf("%d keys given a list, want 1", n) + } + p, _ = Find("relay") + if got := p.AccountModels[keyID("sk-claude")]; !slices.Equal(got, []string{"claude-opus-4-7"}) { + t.Fatalf("the new key's models %v, want its own list", got) + } + if p.AccountModels[keyID("sk-all")] != nil || p.AccountModels[keyID("sk-old")] != nil || !slices.Equal(p.AccountModels[keyID("sk-mine")], []string{"gpt-5.5"}) { + t.Fatalf("the keys it had changed: %v", p.AccountModels) + } + // the gateway's rule: the new key is never sent a model its list lacks + if p.AccountServes(keyID("sk-claude"), "gpt-5.5") || !p.AccountServes(keyID("sk-claude"), "claude-opus-4-7") { + t.Fatal("the new key's list doesn't hold its requests") + } + + // pasted several at once (keys/import): each its own list + had = KeysHeld("relay") + if _, _, err := AddKeys("relay", []string{"sk-gpt"}, ""); err != nil { + t.Fatal(err) + } + PrefillNewKeys(context.Background(), had, "relay") + p, _ = Find("relay") + if got := p.AccountModels[keyID("sk-gpt")]; !slices.Equal(got, []string{"gpt-5.5", "deepseek-v4"}) { + t.Fatalf("the pasted key's models %v", got) + } + // asked again, nothing is new: the lists given stay, the user's too + if n := PrefillNewKeys(context.Background(), KeysHeld("relay"), "relay"); n != 0 { + t.Fatalf("asked again, %d keys changed", n) + } +} + +// A key whose list can't be told keeps every model, as before, and no +// empty list is written: a list that fails, that answers no model, that +// answers past the wait, or that has every model the others have. A key +// the user gave models while its list was asked keeps theirs, and a +// provider of one key is its list. +func TestNewKeyListUnknownKeepsAll(t *testing.T) { + prefillHome(t) + srv := keyRelay(t, map[string]string{ + "sk-all": groupAll, + "sk-same": groupAll, + "sk-empty": `{"data":[]}`, + "sk-slow": "slow", + "sk-set": `{"data":[{"id":"deepseek-v4"}]}`, + }) + if err := Save(Provider{ID: "relay", Name: "Relay", Chat: srv.URL + "/v1", Key: "sk-all"}); err != nil { + t.Fatal(err) + } + // one key: nothing to tell it from + if n := PrefillNewKeys(context.Background(), map[string]map[string]bool{}, "relay"); n != 0 { + t.Fatalf("a provider of one key: %d", n) + } + p, _ := Find("relay") + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + had := KeysHeld("relay") + if _, _, err := AddKeys("relay", []string{"sk-refused", "sk-same", "sk-empty", "sk-slow", "sk-set"}, ""); err != nil { + t.Fatal(err) + } + // the user's own pick for a new key, set before its list came back + if err := SetAccountModels("relay", keyID("sk-set"), []string{"gpt-5.5"}); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + start := time.Now() + if n := PrefillNewKeys(ctx, had, "relay"); n != 0 { + p, _ := Find("relay") + t.Fatalf("%d keys given a list: %v", n, p.AccountModels) + } + if d := time.Since(start); d > 5*time.Second { + t.Fatalf("waited %s on a slow list past the add's wait", d) + } + p, _ = Find("relay") + for _, k := range []string{"sk-all", "sk-refused", "sk-same", "sk-empty", "sk-slow"} { + if ms, ok := p.AccountModels[keyID(k)]; ok { + t.Errorf("%s given %v, want every model", k, ms) + } + } + if got := p.AccountModels[keyID("sk-set")]; !slices.Equal(got, []string{"gpt-5.5"}) { + t.Errorf("the user's pick became %v", got) + } +} + +// A key imported from another app (CC Switch keeps an entry a key, folded +// into one provider) is asked for its own list as one added by hand is. +func TestImportedKeysTakeTheirOwnModels(t *testing.T) { + home := foldHome(t) + srv := keyRelay(t, map[string]string{ + "sk-a": groupAll, + "sk-b": `{"data":[{"id":"claude-opus-4-7"}]}`, + }) + sqliteFixture(t, filepath.Join(home, ".cc-switch", "cc-switch.db"), + `CREATE TABLE providers (id TEXT, app_type TEXT, name TEXT, settings_config TEXT, website_url TEXT, category TEXT, created_at INTEGER, sort_index INTEGER, PRIMARY KEY (id, app_type))`, + `INSERT INTO providers VALUES ('a','claude','Relay #1','{"env":{"ANTHROPIC_BASE_URL":"`+srv.URL+`","ANTHROPIC_AUTH_TOKEN":"sk-a"}}','','custom',1,0)`, + `INSERT INTO providers VALUES ('b','claude','Relay #2','{"env":{"ANTHROPIC_BASE_URL":"`+srv.URL+`","ANTHROPIC_AUTH_TOKEN":"sk-b"}}','','custom',2,1)`, + ) + had := KeysHeld() + if added, err := ImportFromApps([]AppPick{{Source: "cc-switch", Ref: "claude/a"}, {Source: "cc-switch", Ref: "claude/b"}}); err != nil || len(added) != 2 { + t.Fatalf("%v %v", added, err) + } + if n := PrefillNewKeys(context.Background(), had); n != 1 { + t.Fatalf("%d keys given a list, want 1", n) + } + ps := load().Providers + if len(ps) != 1 { + t.Fatalf("%d providers", len(ps)) + } + p := ps[0] + if got := p.AccountModels[keyID("sk-b")]; !slices.Equal(got, []string{"claude-opus-4-7"}) { + t.Fatalf("the imported key's models %v (%+v)", got, p.AccountModels) + } + if _, ok := p.AccountModels[keyID("sk-a")]; ok { + t.Fatalf("the key listing every model was given a list: %v", p.AccountModels) + } +} + +// A key whose list one of the provider's bases didn't answer is unknown: +// that base's part would be the provider's list saved before, not the +// key's own answer. +func TestNewKeyHalfAnsweredKeepsAll(t *testing.T) { + prefillHome(t) + chat := keyRelay(t, map[string]string{ + "sk-all": `{"data":[{"id":"gpt-5.5"},{"id":"deepseek-v4"}]}`, + "sk-half": `{"data":[{"id":"gpt-5.5"}]}`, + }) + anthropic := keyRelay(t, map[string]string{ + "sk-all": `{"data":[{"id":"claude-opus-4-7"}]}`, + }) + if err := Save(Provider{ID: "relay", Name: "Relay", Chat: chat.URL + "/v1", Anthropic: anthropic.URL, Key: "sk-all"}); err != nil { + t.Fatal(err) + } + p, _ := Find("relay") + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + had := KeysHeld("relay") + if err := AddKey("relay", "", "sk-half", ""); err != nil { + t.Fatal(err) + } + if n := PrefillNewKeys(context.Background(), had, "relay"); n != 0 { + p, _ := Find("relay") + t.Fatalf("a half-answered key given a list: %v", p.AccountModels) + } +}