provider: Fetch models ticks each key's own models, the first key's too (young02036)

young02036 on Discord (#feedback, v0.1.2965): "点击供应商的获取模型,给这个
供应商的所有账号默认勾选上可用模型,和新增账号之后默认勾选上可用模型这个功能
好像失效了".

Cause: no later change broke it; the two commits that built it each left
keys out. 0431793db (v0.1.2674) gives a key its own list only when it is
added beside others and its list is short, and says "the keys it had keep
their lists". 1a67ca614 (v0.1.2942) carries on each Fetch only what a key's
list gained and lost, and only for a key that already had a list of its
own ("a key serving every model still does"). So every key on All models
stayed there through every Fetch: the provider's first key, keys added
before per-key lists, and a key whose list wasn't read in the 8s when it
was added. In the reporter's setup that is the key the provider was made
with, so the feature reads as gone.

Fix (refreshKeyModels): a key on All models whose fetched list leaves out
a model the provider's other keys list is given that list. A key whose
list has every model stays on All models, so later additions still reach
it; a lone key stays too. Keys with lists of their own work as before
(un-ticks and ticks kept).

The user's choice is never overridden: a key the user set to All models
(`accountmodels` with none, the picker's All models) is now remembered in
Provider.AccountModelsAll and left alone by Fetch. The editor's save keeps
it, a key replaced in place moves it (moveKeyed), accountSettings and
clone carry it, normalize drops a mark for a key that has a list.
Not covered: a key set back to All models before this release has no mark
and is narrowed once to its own list on the next Fetch; the user can
press All models again and it stays.

Tests:
- TestFetchTicksEachKeysListOnAllModels: keys saved with no lists are
  ticked on Fetch; a key set to All models before and after stays so
  through two fetches; an un-tick survives; a key whose list failed stays
  All models and gets its list once it reads.
- TestFetchLeavesALoneKeyOnAllModels.
- internal/gui TestFetchModelsTicksEveryKeysModels through the real
  routes: provider/save, provider/models, keys/add, accountmodels, the
  editor's save, against an httptest relay with a list per key.
- TestFetchRefreshesEachKeysModels and TestNewKeyTakesItsOwnModels pinned
  the old rule (sk-b / sk-old left on All models); they now expect the
  key's own list.

Broken by hand (mote): the old `was == nil -> continue` put back: the
new provider test, the GUI test (sk-a, the first key: [] want
[m1 m2 m3 m4]) and the two updated tests go red. The AccountModelsAll
check removed: sk-c/sk-d set to All models get narrowed, red. The editor
save not keeping AccountModelsAll: the GUI test's sk-c red.

Run (mote, at this tree): gofmt -l clean; go vet of the touched packages,
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... ok;
go test -tags nogui -count=1 -timeout 45m ./internal/provider ./internal/gui
./internal/cli ./internal/gateway ./internal/tui: all ok (provider 223s,
gui 138s, cli 106s, gateway 797s, tui 26s).
GUI: account-models, account-models-available, account-refresh,
gateway-key-models, gateway-key-models-redraw (each in Chromium and
WebKit, as the files run): 94 of 94 pass.

Rebased on origin/main 8e97e26d6 (google.go, migrate_zcode.go): ./internal/provider
run again at this head, ok (157s).

Not tried: a real relay with per-group keys; Windows and Linux test runs
(nothing OS-specific changed). No app.js change.
This commit is contained in:
yetone
2026-11-05 00:11:02 +08:00
parent 8e97e26d67
commit 7661a0aa72
9 changed files with 302 additions and 36 deletions
+1 -1
View File
@@ -34,7 +34,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| The list | `All` merges stored providers with `Accounts()`. An entry with no URL stores the user's picks for an account. The order is `file.Order`. Reads within one request share one build (`Hold`, #746). Requests that miss a build together (a write drops what is held) wait for the first one's build and take it, unless a write came while it was built; a wait is bounded (`heldWait`), so a caller never waits for good. Before, each built again behind `logins.json`'s lock, and requests sat past the 30s unrouted deadline (#5104: `TestLoginsMissedTogetherListedOnce`, `TestHeldWaiterBuildsAgainAfterAWrite`, `TestHeldWaiterNeverStuck`). `OwnPaused` is held the same way, once a request. | [`provider.go`](../../internal/provider/provider.go) |
| Model picks | `Models` are the models the user picked for agents; none means the vendor's list, up to 24 (`Exposed`), unless the user chose Select none (`NoModels`, `magpie provider models <id> none`): then none of its models is served, not to agents, not to any routing group (auto groups included), not by a `provider/model` id, not as a classifier, while its balance and usage are still read (`ServesNone`, #1818). Codex's own list at `/backend-api/codex/models` drops the ChatGPT account's visible models too, as spawn_agent's list of them does, and the list's ETag changes so a running Codex asks again (`CodexNativePicked` in [`codex_models.go`](../../internal/provider/codex_models.go), #2530); the hidden ones Codex runs jobs of its own on (codex-auto-review, gpt-reserve) and other providers' models stay. The editor's serves control names it Usage only, beside Vendor's list and Picked only, and the card says "usage only" (#2068); Picked only from there picks the models the vendor's list serves, to unpick from. A file without `noModels` reads as before, and a pick clears it. With nothing picked and Select none off, Best in family (`BestInFamily`, `magpie provider models <id> best`, the editor's fourth option, Steven on Discord) serves only the newest model of each family the vendor lists, up to 24: the family is the id with its version numbers taken out, a dated snapshot counts as its alias, and sizes and suffixes (-mini, -pro, -8b) stay in the name (`FamilyOf`, `BestInFamily` in [`family.go`](../../internal/catalog/family.go)). A newer one the vendor lists later takes the old one's place with nothing saved. Codex's own list narrows the same way (`CodexNativePicked`). An older one named by its `provider/model` id is still served, as an unpicked one is under Picked only. A pick or Select none clears it, and a file without `bestInFamily` reads as before. `Save` keeps beside new picks the models listed then (`PickedFrom`, `listedWith`), and the same picks saved again keep it. When the picks held every model listed then, one the vendor lists since is served first beside them (`withNewlyListed`, `Picks`); one listed then and left unpicked stays out. Picks saved before `PickedFrom` was kept are taken to hold every model when they hold every one released up to the newest of them (models.dev's `release_date`), so a Claude account whose user picked them all is served Haiku 5.5 (wakaka). The editor and the TUI start from `Picks`, so a later Save keeps the new model. While some picks are set aside (the list is known to be short), a save with new picks keeps the models the earlier `PickedFrom` had beside those listed now, so a model the user saw and left unpicked isn't new when that list has it again; a list short of no pick is taken as it is. A pick a list fetched again stops listing (`Refetch`, `KeepListsFresh`, and a plugin's hourly `KeepPluginsListed`) leaves `Models` for `Delisted` (`dropGonePicks`), not served, and goes back among the picks when a later list has it (`relistPicks`): Our Free Model's plugin lists its account channels' models only once its service has read them after a restart, and its free pools only while they answer, so each magpie update had its user pick every model again (多喝热水 on Discord). Every save keeps `Delisted` but for what it picks again (`delistedWith`); Select none clears it. A provider whose every pick is in `Delisted` serves none of its models for `pickWait` (an hour) from when the last one left (`DelistedAt`, `waitsForPicks`), not the vendor's list; after that, or for picks set aside before `DelistedAt` was kept, the picks are taken as gone for good and the list is served as if none were picked, while they still come back with a list that has them. WorkBuddy AI took its Free plan's deepseek-v4.1-flash off its list for hy3, and an account whose one pick it was got no model in the agents' picker, its row reading "1 image model" (maxleebeta on Discord). `KeepPluginsListed` asks again after `relistSoon` (5 minutes) when a list left a pick out. `TestPluginPicksComeBackWithTheirList`, `TestEveryPickDelistedServesNone`, `TestPicksGoneForGoodServeTheList` and `TestRelayPicksComeBackWithTheirList` cover it. | [`models.go`](../../internal/provider/models.go), [`provider.go`](../../internal/provider/provider.go) |
| List schedule and rules | A provider of the user's own (not an account, a plugin's or a decision-only one) can set `RefreshEvery` (`magpie provider refresh-every <id> 6h`, or 1d, or off, at least 10m) and `AutoInclude` (`magpie provider auto-include <id> 'gpt-*' 're:claude-.*'`, or none; a glob with `*`, or `re:` matching the whole id, both in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter); a plain id is refused) (#2135). The gateway (`magpie serve` or the app) looks each minute and fetches a list once `Fetched` is that old, through the same `Refetch` as Fetch models (`KeepListsFresh`); a failed fetch waits `min(every, 15m)`. `RefetchTaking` adds to the picks a model the fetch newly lists that a rule matches (`takeMatching`), starting from what is served now (`Exposed`), so nothing served is taken away and a model the user unticks stays out (it is not new to the next fetch). Setting the rules takes the current list's matches. Every save that doesn't set them keeps them, the window's editor among them; the editor has no fields for them yet. A Remote magpie with no `RefreshEvery` is fetched every 10m (`RemoteMagpieEvery`, `RefreshSchedule`), so a model the other magpie lists later (ZCode's GLM-5.3-Trial once its plugin read the gift, 6igsteven on Discord) is served without Fetch models; `off` set on it is kept as `"off"` and asks it only when told (`TestRemoteMagpieListFollowsTheOtherMagpie`). | [`autolist.go`](../../internal/provider/autolist.go), [`models.go`](../../internal/provider/models.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) |
| Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. `Key` stays the first, so other code reads it as before. A key can be made for one protocol (`KeyProtocol`): Anthropic, Chat, Responses or a custom provider's Gemini API (corddis_114 on Discord). `WithKey` leaves it that protocol's URL only, and the gateway puts the key that suits the model first (`keyFit`: Claude to the Anthropic key, GPT to a Chat or Responses one, Gemini to the Gemini one; `TestKeyMadeForGemini`, `TestKeyProtocolGemini`, `key-gemini.test.cjs`). A key made for a protocol its provider has no URL for is skipped (`perKeyBarred`); when every key is, the provider is still tried whole on the URLs it has, and the candidate carries `noURL` so it isn't quiet: Routing's row (`Weighed.NoURL`) says "key set to {api} only, no {api} URL · sent on the others", and the editor's key row shows a "No {api} URL" chip (`keyLacksURL`; #1702, `TestKeyForAProtocolWithNoURLIsSaid`, `key-nourl.test.cjs`). A key's value can be replaced in place (`ReplaceKey`, #1869: a key rotated at the vendor): it keeps its name, place, protocol, weight and on or off, and what was set for it by its fingerprint (`AccountModels`, `AccountProxies`, `AccountConcurrency`) and the gateway keys held to it (`access.ReplaceAccount`) move to the new one; the GUI's `keys/replace` also lifts its rests (`UnrestAll`). Its past requests stay under the old fingerprint, by the same name. A provider may hold thousands of keys (@NetRozee on X: a thousand froze magpie). Nothing goes over its keys once for each key: `KeysOn` drops a repeat by a set, a row's rest keys come from `RestKeys` (whether several are on, found once), and whether each key serves a model from `Serving`, which reads the lists once and keeps each model's keys as a set until the lists are read anew (`keyLists`). `KeysListed` and `ListsRead` count them for the tests (`TestProviderInfoListsKeysOnce`, `TestPerKeyReadsListsOnce`). A provider's keys have their balances, plans and remote limits read `keyReadsAtOnce` (8) at a time (`keySlots`); other providers' beside them. The editor's per-key proxy lines fold as its Accounts list does (`proxyLines`, `provider-many-keys-proxy.test.cjs`). Asking a key's models (`fetchPerKey`) still goes one key after another. | [`keys.go`](../../internal/provider/keys.go) |
| Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. `Key` stays the first, so other code reads it as before. A key can be made for one protocol (`KeyProtocol`): Anthropic, Chat, Responses or a custom provider's Gemini API (corddis_114 on Discord). `WithKey` leaves it that protocol's URL only, and the gateway puts the key that suits the model first (`keyFit`: Claude to the Anthropic key, GPT to a Chat or Responses one, Gemini to the Gemini one; `TestKeyMadeForGemini`, `TestKeyProtocolGemini`, `key-gemini.test.cjs`). A key made for a protocol its provider has no URL for is skipped (`perKeyBarred`); when every key is, the provider is still tried whole on the URLs it has, and the candidate carries `noURL` so it isn't quiet: Routing's row (`Weighed.NoURL`) says "key set to {api} only, no {api} URL · sent on the others", and the editor's key row shows a "No {api} URL" chip (`keyLacksURL`; #1702, `TestKeyForAProtocolWithNoURLIsSaid`, `key-nourl.test.cjs`). A key's value can be replaced in place (`ReplaceKey`, #1869: a key rotated at the vendor): it keeps its name, place, protocol, weight and on or off, and what was set for it by its fingerprint (`AccountModels`, `AccountProxies`, `AccountConcurrency`) and the gateway keys held to it (`access.ReplaceAccount`) move to the new one; the GUI's `keys/replace` also lifts its rests (`UnrestAll`). Its past requests stay under the old fingerprint, by the same name. A provider may hold thousands of keys (@NetRozee on X: a thousand froze magpie). Nothing goes over its keys once for each key: `KeysOn` drops a repeat by a set, a row's rest keys come from `RestKeys` (whether several are on, found once), and whether each key serves a model from `Serving`, which reads the lists once and keeps each model's keys as a set until the lists are read anew (`keyLists`). `KeysListed` and `ListsRead` count them for the tests (`TestProviderInfoListsKeysOnce`, `TestPerKeyReadsListsOnce`). A provider's keys have their balances, plans and remote limits read `keyReadsAtOnce` (8) at a time (`keySlots`); other providers' beside them. The editor's per-key proxy lines fold as its Accounts list does (`proxyLines`, `provider-many-keys-proxy.test.cjs`). Asking a key's models (`fetchPerKey`) still goes one key after another. Each Fetch models carries each key's list into the models it serves (`refreshKeyModels` in [`key_models_refresh.go`](../../internal/provider/key_models_refresh.go)): a key with a list of its own gains what its list gained and loses what it lost, keeping what the user ticked or un-ticked; a key on All models (the provider's first, one added before per-key lists, one whose list wasn't read in time when added) is given its own list when that list leaves out a model the other keys list. A key the user set to All models (`accountmodels` with none) is marked in `AccountModelsAll` and stays so; the editor's save keeps it. A key set to All models before the mark was kept has none, and is narrowed once to its list on the next Fetch (young02036 on Discord, `TestFetchTicksEachKeysListOnAllModels`, `TestFetchModelsTicksEveryKeysModels`). | [`keys.go`](../../internal/provider/keys.go), [`key_models_refresh.go`](../../internal/provider/key_models_refresh.go) |
| Accounts at once | `MaxAccounts *int` is the user's own count of keys or accounts taking requests at the same time: nil takes the plugin's (`PluginAtOnce`: `maxAccounts` on the plugin's auth hook or package.json `magpie`, host.js `atOnceOf`), 0 is no limit, saved clamped to 0..`MaxLimit`; a subscription's is kept with its picks (`withPicks`). `AtOnce()` answers the one in force, `SetAtOnce` sets it (`magpie provider at-once`, the editor's Accounts at once; GUI save leaves it as it was when the body has none). The gateway's use is in [gateway routing](gateway-routing.md) (`TestAtOnce`, `TestAtOnceSave`, `TestAtOnceCmd`). | [`concurrency.go`](../../internal/provider/concurrency.go) |
| A provider with no key | A provider of the user's own saves, imports and is `Ready` with no key when it is a preset with `NoKey` or its host is on this computer or the user's own network (`keyOptional`, `ownNetwork`): localhost, a loopback, private, link-local or carrier-grade NAT (Tailscale's 100.64/10) address, or a `.local` name, read from the URL alone with no lookup. A company's keyless relay at a LAN address is taken as a local server is (iSnow_999 on X: a Codex relay at http://<LAN IP>:8080 was left out of a CC Switch import as "it has no API key"); a keyless address on the internet still needs its key. With no key it is asked as one on 127.0.0.1 is: a Responses request carries no `Authorization`. | [`provider.go`](../../internal/provider/provider.go), [`importapps.go`](../../internal/provider/importapps.go), [`import_lan_test.go`](../../internal/provider/import_lan_test.go) |
| A key a provider | One vendor's keys saved a provider each — an app that keeps an entry a key, as CC Switch does, imported (yuluo_yx on X: "NVIDIA #001" to "#600" at one address, "Mistral #0001"…) — are folded into one provider with those keys (`FoldCopies` at start-up, `foldAdded` after `ImportFromApps`): hundreds of copies listed every model hundreds of times in every agent's picker and found group, and 3,000 made `/api/state` 86 MB. At start-up only copies by name are folded: a base name and that name with a number after it (`copyBase`: " #12", or `freeName`'s " 2"), one at least numbered; an import folds what it added whatever their names. Either way they must be alike in all but their key (`foldShape`: the provider with its id, name, keys and on/off left out), what the settings say of their models (`modelPrefs`) and where they are named (`foldRefs`: Visible, the agents' picked, hidden and ordered models, the groups, the providers falling back to them), so one key shown to one agent and another to another stays apart. Not folded: a subscription's, a hidden one, one without a key, Vertex, one with a StepFun sign-in of its own. The first on, in the providers' order, takes the rest in; its name becomes the base and its key is named its old name. Each other is a key in order, named its name, off if it was off (all off: the provider is off, its keys on); its id goes in `Was`, so its calls count with the provider by their key (`ProviderKeyID` is the key's fingerprint, unchanged) and a model picked by the old id still reaches it. Group members, rules, weights and fallbacks naming them name the provider once; their per-model settings and fetched lists go; balance and window history kept by their id moves to their key's name (`foldHistories`). A providers.json that doesn't parse is left alone. It runs at every start and writes nothing when there is nothing to fold. `TestFoldCopies`, `TestFoldCopiesIntoOneOn`, `TestFoldCopiesUnreadable`, `TestImportFoldsAKeyAnEntry`. | [`fold.go`](../../internal/provider/fold.go), [`importapps.go`](../../internal/provider/importapps.go), [`main.go`](../../internal/cli/main.go) |
+88
View File
@@ -0,0 +1,88 @@
package gui
import (
"net/http"
"net/http/httptest"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// young02036 on Discord (v0.1.2965): the editor's Fetch models ticks each
// account's available models, and an account added gets its own ticked.
// The provider's first key stayed on All models through every Fetch, and
// so did any key added without its own list. Through the GUI's own
// routes: add keys, Fetch models, set one to All models, save the editor,
// fetch again.
func TestFetchModelsTicksEveryKeysModels(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("APPDATA", filepath.Join(h, "AppData"))
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, ".data"))
var mu sync.Mutex
lists := map[string][]string{"sk-a": {"m1", "m2", "m3", "m4"}, "sk-b": {"m1", "m2"}, "sk-c": {"m3", "m5"}}
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
mu.Lock()
ids, ok := lists[key]
mu.Unlock()
if !ok {
http.Error(rw, `{"error":{"message":"invalid key"}}`, http.StatusUnauthorized)
return
}
var b []string
for _, id := range ids {
b = append(b, `{"id":"`+id+`"}`)
}
_, _ = rw.Write([]byte(`{"data":[` + strings.Join(b, ",") + `]}`))
}))
t.Cleanup(srv.Close)
mux := http.NewServeMux()
providerRoutes(mux, nil)
post := func(path, body string) {
t.Helper()
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", path, strings.NewReader(body)))
if w.Code != 200 {
t.Fatalf("%s: %d %s", path, w.Code, w.Body)
}
}
models := func(key string) []string {
t.Helper()
p, err := provider.Find("relay")
if err != nil {
t.Fatal(err)
}
return p.AccountModels[provider.KeyID(key)]
}
post("/api/provider/save", `{"id":"relay","name":"Relay","chat":"`+srv.URL+`/v1","key":"sk-a","new":true}`)
post("/api/provider/models", `{"id":"relay","typed":true}`)
post("/api/keys/add", `{"id":"relay","key":"sk-b"}`)
post("/api/keys/add", `{"id":"relay","key":"sk-c"}`)
post("/api/provider/models", `{"id":"relay","typed":true}`)
for key, want := range map[string][]string{"sk-a": {"m1", "m2", "m3", "m4"}, "sk-b": {"m1", "m2"}, "sk-c": {"m3", "m5"}} {
if got := models(key); !slices.Equal(got, want) {
t.Errorf("%s after Fetch models: %v, want its own list %v ticked", key, got, want)
}
}
// the user sets sk-c to All models and un-ticks m2 for sk-b, then saves
// the editor; neither is undone by the save or a Fetch
post("/api/provider/accountmodels", `{"id":"relay","account":"`+provider.KeyID("sk-c")+`","allow":[]}`)
post("/api/provider/accountmodels", `{"id":"relay","account":"`+provider.KeyID("sk-b")+`","allow":["m1"]}`)
post("/api/provider/save", `{"id":"relay","from":"relay","name":"Relay","chat":"`+srv.URL+`/v1","key":""}`)
post("/api/provider/models", `{"id":"relay","typed":true}`)
if got := models("sk-c"); got != nil {
t.Errorf("sk-c set to All models, then saved and fetched: %v", got)
}
if got := models("sk-b"); !slices.Equal(got, []string{"m1"}) {
t.Errorf("sk-b's un-tick undone: %v", got)
}
}
+1 -1
View File
@@ -1913,7 +1913,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
// each account's own models are set on their own, with
// accountmodels
if old != nil {
in.AccountModels = old.AccountModels
in.AccountModels, in.AccountModelsAll = old.AccountModels, old.AccountModelsAll
}
// and their usage caps, with accountcap and windowcap, their
// limits on requests at once, with accountconcurrency, and
+32 -1
View File
@@ -11,6 +11,7 @@ package provider
import (
"cmp"
"fmt"
"maps"
"slices"
"strings"
)
@@ -205,7 +206,10 @@ func SetAccountModels(id, ref string, models []string) error {
return fmt.Errorf("%s has no account %q", p.Name, ref)
}
ms := normalModels(models)
if len(ms) == 0 && p.AccountModels[accountKey(r)] == nil {
// a key set to every model by the user is remembered as theirs, so a
// Fetch models doesn't tick its own list for it again
all := len(ms) == 0 && p.Account == nil
if len(ms) == 0 && p.AccountModels[accountKey(r)] == nil && (!all || p.AccountModelsAll[accountKey(r)]) {
return nil
}
am := map[string][]string{}
@@ -218,6 +222,16 @@ func SetAccountModels(id, ref string, models []string) error {
am[accountKey(r)] = ms
}
p.AccountModels = am
ma := maps.Clone(p.AccountModelsAll)
if all {
if ma == nil {
ma = map[string]bool{}
}
ma[accountKey(r)] = true
} else {
delete(ma, accountKey(r))
}
p.AccountModelsAll = ma
return Save(*p)
}
@@ -263,6 +277,23 @@ func normalModels(ms []string) []string {
return out
}
// normalModelsAll is the keys set back to every model as they are kept:
// in lower case, and only those with no models of their own in am.
func normalModelsAll(m map[string]bool, am map[string][]string) map[string]bool {
var out map[string]bool
for u, on := range m {
u = accountKey(u)
if !on || u == "" || am[u] != nil {
continue
}
if out == nil {
out = map[string]bool{}
}
out[u] = true
}
return out
}
// normalAccountModels is m as it is kept: keys in lower case, lists
// normalized, accounts serving all the provider's models left out; nil
// for none.
+3 -2
View File
@@ -62,7 +62,8 @@ func TestNewKeyTakesItsOwnModels(t *testing.T) {
"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
// lists one model: the Fetch below gives it its list (young02036 on
// Discord, v0.1.2965: Fetch models ticks every key's own models)
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 {
@@ -83,7 +84,7 @@ func TestNewKeyTakesItsOwnModels(t *testing.T) {
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"}) {
if p.AccountModels[keyID("sk-all")] != nil || !slices.Equal(p.AccountModels[keyID("sk-old")], []string{"deepseek-v4"}) || !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
+56 -28
View File
@@ -15,10 +15,18 @@ package provider
// 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.
//
// A key with no models of its own yet (All models: one added before its
// own list was asked for, the provider's first key, one whose list wasn't
// read in time when it was added) is given its own list, as a key added
// now is (PrefillNewKeys), when that list leaves out a model the
// provider's other keys list (young02036 on Discord: Fetch models ticks
// the models each key can serve). A key the user set back to every model
// (AccountModelsAll) stays so, and one whose list has every model the
// others list serves every model still, so the vendor's later additions
// reach it. A key with no marks now (one key on, one switched off, a
// list that failed with nothing kept) is unknown, and its models stay as
// they are.
import (
"slices"
@@ -47,52 +55,72 @@ func keyMarks(id string) map[string]map[string]bool {
// 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.
// (AccountModels), gives a key with none of its own its list now when
// that is short of the others', 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 {
if len(now) == 0 {
return 0
}
p, err := Find(id)
if err != nil || len(p.AccountModels) == 0 {
if err != nil {
return 0
}
// every model the keys' lists have between them
every := map[string]bool{}
for _, set := range now {
for m := range set {
every[m] = true
}
}
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 {
if 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
if was == nil {
// a key on every model, by magpie's default and not the
// user's, whose list leaves some of the others' out
if p.AccountModelsAll[accountKey(kid)] || len(w) >= len(every) {
continue
}
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 }) {
for m := range w {
list = append(list, p.ListedModelID(m))
}
slices.Sort(list)
} else {
if len(o) == 0 {
continue
}
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 = map[string][]string{}
}
am[accountKey(kid)] = list
n++
@@ -112,7 +140,7 @@ func refreshKeyModels(id string, before, now map[string]map[string]bool) int {
}
n = 0
for k, v := range am {
if slices.Equal(v, p.AccountModels[k]) || !slices.Equal(q.AccountModels[k], p.AccountModels[k]) {
if !slices.Equal(q.AccountModels[k], p.AccountModels[k]) || q.AccountModelsAll[k] != p.AccountModelsAll[k] {
continue
}
merged[k] = v
+112 -2
View File
@@ -103,8 +103,10 @@ func TestFetchRefreshesEachKeysModels(t *testing.T) {
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)
// sk-b was on All models and its list is short of the provider's: the
// first fetch ticked its own list, which hasn't changed since
if got := models("sk-b"); !slices.Equal(got, []string{"kimi-k3"}) {
t.Errorf("sk-b's models %v, want its own list [kimi-k3]", 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") {
@@ -181,3 +183,111 @@ func TestKeyListedIsTheKeysOwnList(t *testing.T) {
t.Errorf("no such provider: %v", got)
}
}
// young02036 on Discord (v0.1.2965): Fetch models ticked each key's
// available models only for keys that already had a list of their own, so
// a provider's first key, keys added before per-key lists and keys whose
// list was read late all stayed on All models. Fetch now ticks each key on
// All models with its own list when that list is short of the provider's;
// a key the user set to All models, or narrowed, stays as they set it.
func TestFetchTicksEachKeysListOnAllModels(t *testing.T) {
prefillHome(t)
l := &relayLists{by: map[string][]string{
"sk-a": {"m1", "m2", "m3", "m4"},
"sk-b": {"m1", "m2"},
"sk-c": {"m3", "m5"},
"sk-d": {"m4"},
}}
srv := l.serve(t)
// every key saved without a list, as keys added before per-key models
// and a key whose read failed when it was added are
if err := Save(Provider{ID: "relay", Name: "Relay", Chat: srv.URL + "/v1", Key: "sk-a",
Keys: []KeyAccount{{Key: "sk-b"}, {Key: "sk-c"}, {Key: "sk-d"}}}); 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)]
}
// the user sets sk-d to All models before any fetch
if err := SetAccountModels("relay", keyID("sk-d"), nil); err != nil {
t.Fatal(err)
}
fetch()
if got := models("sk-b"); !slices.Equal(got, []string{"m1", "m2"}) {
t.Errorf("sk-b after a fetch: %v, want its list [m1 m2] ticked", got)
}
if got := models("sk-c"); !slices.Equal(got, []string{"m3", "m5"}) {
t.Errorf("sk-c after a fetch: %v, want its list [m3 m5] ticked", got)
}
if got := models("sk-a"); !slices.Equal(got, []string{"m1", "m2", "m3", "m4"}) {
t.Errorf("sk-a after a fetch: %v, want its list [m1 m2 m3 m4] ticked", got)
}
if got := models("sk-d"); got != nil {
t.Errorf("sk-d was set to All models by the user and was given %v", got)
}
if p, _ := Find("relay"); p.AccountServes(keyID("sk-b"), "m5") || !p.AccountServes(keyID("sk-c"), "m5") || !p.AccountServes(keyID("sk-d"), "m5") {
t.Error("the gateway would send m5 to a key whose list hasn't it")
}
// the user un-ticks m2 for sk-b, and sets sk-c to All models
if err := SetAccountModels("relay", keyID("sk-b"), []string{"m1"}); err != nil {
t.Fatal(err)
}
if err := SetAccountModels("relay", keyID("sk-c"), []string{}); err != nil {
t.Fatal(err)
}
fetch()
fetch()
if got := models("sk-b"); !slices.Equal(got, []string{"m1"}) {
t.Errorf("sk-b's un-tick undone by a fetch: %v", got)
}
if got := models("sk-c"); got != nil {
t.Errorf("sk-c set to All models was narrowed by a fetch: %v", got)
}
if got := models("sk-d"); got != nil {
t.Errorf("sk-d set to All models was narrowed by a fetch: %v", got)
}
// a key whose list can't be read stays on All models until it can
if err := AddKey("relay", "E", "sk-e", ""); err != nil {
t.Fatal(err)
}
fetch()
if got := models("sk-e"); got != nil {
t.Errorf("sk-e's list failed and it was given %v", got)
}
l.set("sk-e", "m2", "m5")
fetch()
if got := models("sk-e"); !slices.Equal(got, []string{"m2", "m5"}) {
t.Errorf("sk-e once its list reads: %v, want [m2 m5]", 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)
}
}
// One key alone has nothing to be short of: it stays on All models.
func TestFetchLeavesALoneKeyOnAllModels(t *testing.T) {
prefillHome(t)
l := &relayLists{by: map[string][]string{"sk-a": {"m1", "m2"}}}
srv := l.serve(t)
if err := Save(Provider{ID: "relay", Name: "Relay", Chat: srv.URL + "/v1", Key: "sk-a"}); err != nil {
t.Fatal(err)
}
p, _ := Find("relay")
if _, err := p.Fetch(context.Background()); err != nil {
t.Fatal(err)
}
if p, _ := Find("relay"); len(p.AccountModels) != 0 {
t.Errorf("a lone key was given %v", p.AccountModels)
}
}
+1
View File
@@ -659,6 +659,7 @@ func ReplaceKey(id, keyRef, key string) (was, now string, err error) {
p.Keys[i].Key = key
}
moveKeyed(p.AccountModels, keyRef, now)
moveKeyed(p.AccountModelsAll, keyRef, now)
moveKeyed(p.AccountProxies, keyRef, now)
moveKeyed(p.AccountConcurrency, keyRef, now)
moveKeyed(p.KeySpendCaps, keyRef, now)
+8 -1
View File
@@ -421,6 +421,11 @@ type Provider struct {
// an account by its name in lower case, a key by its KeyID. One not in
// it serves every model the provider does (see account_models.go).
AccountModels map[string][]string `json:"accountModels,omitempty"`
// AccountModelsAll is the keys, by KeyID, the user set back to every
// model (All models, or `accountmodels` with none): a Fetch models
// that ticks a key's own list for it (key_models_refresh.go) leaves
// these as the user set them.
AccountModelsAll map[string]bool `json:"accountModelsAll,omitempty"`
// AccountCaps is, for a subscription, the share (1–99) of its usage
// windows each account the user capped is used to at most, by its name
// in lower case: past it, routing takes the account for used up until
@@ -824,6 +829,7 @@ func (p Provider) clone() Provider {
p.AccountConcurrency = maps.Clone(p.AccountConcurrency)
p.AccountWeights = maps.Clone(p.AccountWeights)
p.Contexts = maps.Clone(p.Contexts)
p.AccountModelsAll = maps.Clone(p.AccountModelsAll)
if p.AccountModels != nil {
m := make(map[string][]string, len(p.AccountModels))
for k, v := range p.AccountModels {
@@ -919,7 +925,7 @@ func accountSettings(a, pk Provider) Provider {
// Send requests unmasked, the user's for a subscription and a
// plugin's provider too (isee1_1 on Discord)
a.Unredacted = pk.Unredacted
a.Proxy, a.AccountProxies, a.AccountModels = pk.Proxy, pk.AccountProxies, pk.AccountModels
a.Proxy, a.AccountProxies, a.AccountModels, a.AccountModelsAll = pk.Proxy, pk.AccountProxies, pk.AccountModels, pk.AccountModelsAll
a.AccountCaps, a.AccountWindowCaps = pk.AccountCaps, pk.AccountWindowCaps
a.CapStop, a.CapCareful = pk.CapStop, pk.CapCareful
a.AccountNames = pk.AccountNames
@@ -1574,6 +1580,7 @@ func normalize(p Provider) Provider {
p.Proxy = strings.TrimSpace(p.Proxy)
p.AccountProxies = normalAccountProxies(p.AccountProxies)
p.AccountModels = normalAccountModels(p.AccountModels)
p.AccountModelsAll = normalModelsAll(p.AccountModelsAll, p.AccountModels)
p.AccountCaps = normalAccountCaps(p.AccountCaps)
p.AccountWindowCaps = normalWindowCaps(p.AccountWindowCaps)
p.AccountNames = normalAccountNames(p.AccountNames)