Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
access: a key with accounts and no model may use only its accounts' providers' models
yetone05a6087e1f7e
diff --git a/docs/reference.md b/docs/reference.mdindex 8ee973bee..f272086c0 100644--- a/docs/reference.md+++ b/docs/reference.md@@ -704,7 +704,11 @@ fingerprint — or with`magpie gateway-key accounts <id> codex/[email protected] openai/<key id>`(`all` takes the restriction off). The list holds a key to some accounts**of the providers it names**: a provider it names no account of, the key-uses as it always did. The list keeps an account by its stable id, kept+uses as its models allow. A key that lists accounts and **no model** may use+only the models of those accounts' providers (`access.HeldModels`, each+`<provider>/*`): ticking only an account narrows the key to it, where it+used to leave the key every model of every other provider (Linka on+Discord). The list keeps an account by its stable id, keptthrough renames, shown by who is signed in; one gone later — a keyrotated, an account signed out, an account of an agent that keeps nologins renamed — is kept as it is, matching nothing, so the key is helddiff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.mdindex abf2172b0..d88811aa5 100644--- a/docs/subsystems/providers-accounts.md+++ b/docs/subsystems/providers-accounts.md@@ -272,7 +272,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.- An Antigravity subscription offers the union of its On accounts' models (`antigravityPoolModels` in [`antigravity_pool.go`](../../internal/provider/antigravity_pool.go)), each account's own list kept beside it (`accountModels`, read by `Account.Lists` for routing). The lists are fetched at the first listing, a probe, a sync or a Refetch, and also at each account's quota reading, which asks `fetchAvailableModels` anyway: a reading whose models differ from the account's saved list saves it and merges the pooled list again from every On account's own (`noteAntigravityList`), so a model Google gives one account of several later (01huadalang on Discord: Gemini 4) is offered, routed to and given its bar without that account made preferred or probed. A switched-off account's reading changes nothing. `TestAntigravityQuotaReadingListsNewModels`. Each `fetchAvailableModels` names the account's paid and current tier first (`entitlement.userTier`, `askTiers`), then none; a tier Google answers 400 (a Google AI Pro account's g1-pro-tier, #1553) is left out of that account's lists and quota readings for `tierRefusedFor` (a day), and the refused request is no row of the request log.- A provider removed or switched off takes its models out of the catalog. [Agent wiring](agent-wiring.md)'s `Reseat` moves agents off them.- A preset marked `NoList` uses its preset model list instead of requesting `/models`, and ignores previously fetched lists, including their protocol and key restrictions, unless the user sets `ModelsURL` or chooses a region marked `Lists`. Each region can carry a different list. Volcengine Ark's Coding Plan and Agent Plan use separate preset lists. Both plans include their embedding model separately from agents' chat-model lists; Agent Plan additionally exposes its image- and video-generation models to Settings → Images; Ark itself refuses video generation on Small and Medium Agent Plans, which include it only in the Large and Max tiers. Models magpie does not yet serve (Agent Plan's speech models) are not advertised. Ark's pay-as-you-go region still fetches its own list. Coding's `/api/coding/v3/models` returns a general Ark catalog instead of the plan's model ids, while Agent's `/api/plan/v3/models` returns 404. [`presets.go`](../../internal/provider/presets.go) defines these choices; `List`, `fetch`, `live`, `planModels`, `PlanEmbeddings`, `PlanDrawers` and `PlanVideos` in [`models.go`](../../internal/provider/models.go) apply them when adding, refreshing and reading cached models. `TestVolcengineModelLists` checks that the plans make no list requests, ignore old cached lists and return their own preset models; pay-as-you-go and an explicit list URL still make requests.-- A gateway key held to some accounts (#905) is held to those of the providers its list names: a provider it names no account of, the key uses as it always did. The key's menu says so on each account of such a provider ("Used: no … account is picked"), and its badge's tooltip that a key is kept off a provider by its models (#2077: unticking every Codex account left Codex's models served). The list keeps an account by its stable id — `logins.json`'s `id`, set once written and kept through renames; the agents that keep no logins (and plugins) are known by a hash of the account's name, so an account renamed there drops out of a key's list, holding it closer, never wider. Storing an id for every agent is a larger change, not this one's.+- A gateway key held to some accounts (#905) is held to those of the providers its list names: a provider it names no account of, the key uses as its models allow. A key that lists accounts and no model may use only those accounts' providers' models (`access.HeldModels`, applied where `access.Authenticate` makes the request's `Identity`, so every route's model check holds it; Linka on Discord: ticking only an account let the key list and use every other provider's models; `TestGatewayKeyAccountsOnlyHoldTheModels`). The key's menu says so on each account of such a provider ("Used: no … account is picked" when its models reach the provider, "Not used: no … model or account is picked" when they don't), and its badge's tooltip that a key is kept off a provider by its models (#2077: unticking every Codex account left Codex's models served), or, with no model picked, that only the picked accounts' providers' models are the key's. The list keeps an account by its stable id — `logins.json`'s `id`, set once written and kept through renames; the agents that keep no logins (and plugins) are known by a hash of the account's name, so an account renamed there drops out of a key's list, holding it closer, never wider. Storing an id for every agent is a larger change, not this one's.- A sub2api key's windows are fixed: each starts at the key's first request after it was empty, aligned to the relay's day, and a window not started yet says `used 0` with no `reset_at`, so it is taken to renew a span from now. They count this key's spend only, not the relay's accounts behind it. `ForgetBalances` (a key or Balance URL changed) has every key's windows read again at its next ask, a read begun before dropped; until then the last reading stands, fresher than the card's, which routing's reads never write. A key changed is another key (`keyID`), with windows of its own.- A Volcengine Ark provider's access key (`TakesVolcAccessKey`: any of its bases on `ark.<region>.volces.com`) is kept with its keys and never sent to the GUI: `/api/providers` tells the editor its ID and whether a Secret is saved (`accessKey`). A save that leaves the Secret blank keeps it, one that leaves the ID out or sends it blank keeps both (an editor opened before the key was given sends `""`, #1821), and `clearAccessKey` drops both. The ID and Secret go together everywhere the keys go: a copy takes them, also when its form sends the source's ID without the Secret (`AddCopy`), a backup or sync without keys has neither (`withoutKeys`), and a restore, mirror or sync keeps this machine's (`KeepSecrets` in `Restore`, `Mirror`, davsync's `take`) when it came without keys, or with the same key and no access key at all, as a magpie before v0.1.1142 or one the access key was never given on sends it (#1821); another key is another account and brings its own. A copy without keys keeps this machine's secret headers (`SecretHeader`) the same way. A plan endpoint with no provider on it holding the access key is a card that says which to give (`accessKeyCard`, `needsAccessKey`), with a button to the provider's settings, not a card left out. A `providers.json` saved with a UTF-8 BOM is read through it, not taken for a broken file whose `.bak` stands in. The plan read is the endpoint's: `/api/coding` asks `GetCodingPlanUsage`, `/api/plan` asks `GetAFPUsage`, pay-as-you-go (`/api/v3`) has no card; the region is the host's. One card is read for each access key and plan. `GetCodingPlanUsage`'s reply (`QuotaUsage[]` with `Level`, `Percent`, `ResetTimestamp` in seconds) is the one three tools built on it read; `GetAFPUsage`'s buckets are read in each form those tools read (`Used` of `Quota` or `Total`, or `Percent`; `ResetTime` or `ResetTimestamp`), none of them seen from a real account here. A reply none of that reads says so on the card with the reply's head. Changing the access key drops the cached cards (`ForgetPlanQuotas`).- A Tencent Cloud provider's SecretId and SecretKey are kept, listed and saved the same way, in the same fields (`AccessKeyVendor` tells the editor whose: `accessKey.vendor`, the preset's `accessKeyVendor`). Only the Token Plan 企业版's endpoints are read with them (`TakesTencentAccessKey`: `/plan` on `tokenhub.tencentmaas.com`, region `ap-guangzhou`, or `tokenhub-intl.tencentmaas.com`, `ap-singapore`); the personal plan (`api.lkeap.cloud.tencent.com`) has no usage API and TokenHub's pay as you go no plan, so neither has a card. The preset lists its regions that take one (`accessKeyRegions`, `presetAccessKey`), and the editor shows SecretId and SecretKey at those alone. `DescribeTokenPlanList` gives the account's team plans (a sub-user sees the ones it made); each is asked `DescribeTokenPlan` for its `PackageInfo` and `TokenSummary`, the list's kept for what the reply leaves out. The card's one window is `TotalUsed` of `CycleQuota` (else `TotalQuota`), resetting at `TokenSummary.CycleEndTime`, else counted in months from `StartTime` and never past `ExpireTime`. A plan not `enable` says its status beside the plan's name. Errors come back as 200 with `Response.Error`; an `AuthFailure…` or `UnauthorizedOperation` one says to check the key. Built from the API docs (api/1823/132270 and siblings) and the signing doc's worked example; never seen from a real account here.diff --git a/internal/access/access.go b/internal/access/access.goindex 7921241c7..beff2878b 100644--- a/internal/access/access.go+++ b/internal/access/access.go@@ -122,7 +122,8 @@ type Key struct {// key has them only beside a Limit, which an older magpie still reads.More []Limit `json:"moreLimits,omitempty"`// Models are the models the key may use (#882): "<provider>/<model>",- // "<provider>/*" or a group's "group/<name>"; none for every model.+ // "<provider>/*" or a group's "group/<name>"; none for every model,+ // unless it lists accounts: then its accounts' providers' (HeldModels).Models []string `json:"models,omitempty"`// Accounts are the accounts and keys the key may use (#905), as// "<provider>/<account>": a signed-in account by its stable id, a@@ -501,7 +502,7 @@ func Authenticate(secret string) (Identity, bool) {if k.Off {return Identity{}, false}- return Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: k.Models, Accounts: k.Accounts, Quotas: k.Quotas}, true+ return Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Accounts: k.Accounts, Quotas: k.Quotas}, true}}s := settings.Load()diff --git a/internal/access/held_models_test.go b/internal/access/held_models_test.gonew file mode 100644index 000000000..db96b7863--- /dev/null+++ b/internal/access/held_models_test.go@@ -0,0 +1,27 @@+package access++import (+ "slices"+ "testing"+)++// A key that names accounts and no model may use only its accounts'+// providers' models (Linka on Discord); one that lists models keeps+// them, and one that lists neither uses every model.+func TestHeldModels(t *testing.T) {+ for _, c := range []struct {+ models, accounts, want []string+ }{+ {nil, nil, nil},+ {[]string{"openai/gpt-5"}, []string{"codex/acct-1"}, []string{"openai/gpt-5"}},+ {nil, []string{"codex/acct-1", "CODEX/acct-2", "relay/abc"}, []string{"codex/*", "relay/*"}},+ } {+ if got := HeldModels(c.models, c.accounts); !slices.Equal(got, c.want) {+ t.Errorf("HeldModels(%v, %v) = %v, want %v", c.models, c.accounts, got, c.want)+ }+ }+ who := Identity{Models: HeldModels(nil, []string{"codex/acct-1"}), Accounts: []string{"codex/acct-1"}}+ if !who.Allows("codex/gpt-5.5") || who.Allows("anthropic/claude-opus-4-8") || who.Allows("group/any") {+ t.Fatal("an account-only key's models", who.Models)+ }+}diff --git a/internal/access/models.go b/internal/access/models.goindex 96dd291c2..8c74bf6e6 100644--- a/internal/access/models.go+++ b/internal/access/models.go@@ -33,12 +33,43 @@ func CleanModels(in []string) ([]string, error) {return out, nil}+// HeldModels is the models a key that lists models and accounts may+// use. A key that names some accounts and no model may use only the+// models of those accounts' providers, "<provider>/*" each (Linka on+// Discord): in the Gateway page's "Models this key may use", ticking an+// account and no model narrows the key to that account, and never leaves+// it every model of every other provider, as it did when the accounts+// held only the providers they name (#905). A key that lists models is+// held to those, its accounts holding the providers they name, as before.+func HeldModels(models, accounts []string) []string {+ if len(models) > 0 || len(accounts) == 0 {+ return models+ }+ var out []string+ for _, a := range accounts {+ pid, _, ok := strings.Cut(strings.TrimSpace(a), "/")+ if !ok || pid == "" {+ continue+ }+ m := pid + "/*"+ if !slices.ContainsFunc(out, func(o string) bool { return strings.EqualFold(o, m) }) {+ out = append(out, m)+ }+ }+ if len(out) == 0 {+ // no account entry names a provider: held to nothing rather+ // than let off to every model+ return []string{"/"}+ }+ return out+}+// Restricted says the key may use only the models or accounts it lists.func (who Identity) Restricted() bool { return len(who.Models) > 0 || len(who.Accounts) > 0 }// Allows says one of ids is among the key's models; any, for a key that-// lists none. The accounts a key may be held to say nothing of its-// models: they hold the candidates of a plan, not its models.+// lists none. An Identity's models are already HeldModels: a key that+// names accounts and no model may use its accounts' providers' models.func (who Identity) Allows(ids ...string) bool {if len(who.Models) == 0 {return truediff --git a/internal/cli/gateway_keys_cli.go b/internal/cli/gateway_keys_cli.goindex 93227f723..682d42209 100644--- a/internal/cli/gateway_keys_cli.go+++ b/internal/cli/gateway_keys_cli.go@@ -82,9 +82,11 @@ func gatewayKeysTo(out io.Writer, args []string) error {if k.Off {state = "disabled"}+ // a key that names accounts and no model may use only its+ // accounts' providers' models (access.HeldModels)models := "all"- if len(k.Models) > 0 {- models = strings.Join(k.Models, ",")+ if ms := access.HeldModels(k.Models, k.Accounts); len(ms) > 0 {+ models = strings.Join(ms, ",")}accounts := "all"if len(k.Accounts) > 0 {@@ -385,6 +387,10 @@ func gatewayKeyModels(out io.Writer, args []string) error {return fmt.Errorf("Key not found")}k := keys[i]+ if len(k.Models) == 0 && len(k.Accounts) > 0 {+ _, err = fmt.Fprintf(out, "%s: only its accounts' providers' models, %s\n", k.Name, strings.Join(access.HeldModels(nil, k.Accounts), ", "))+ return err+ }if len(k.Models) == 0 {_, err = fmt.Fprintf(out, "%s: every model\n", k.Name)return errdiff --git a/internal/gateway/key_accounts_only_test.go b/internal/gateway/key_accounts_only_test.gonew file mode 100644index 000000000..44132e05b--- /dev/null+++ b/internal/gateway/key_accounts_only_test.go@@ -0,0 +1,154 @@+package gateway++import (+ "encoding/base64"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "slices"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/access"+ "github.com/yetone/magpie/internal/provider"+)++// A gateway key that names an account and no model (Linka on Discord:+// "Models this key may use" with only an account ticked) may use only+// that account's provider's models, on every route a model reaches it+// by: the model lists, a chat on each API, counting tokens, embeddings,+// pictures, Codex's backend, System One, a group with another+// provider's model in it and a fallback to one. Before, the account held+// only its own provider, and the key could list and use every model of+// every other provider.+func TestGatewayKeyAccountsOnlyHoldTheModels(t *testing.T) {+ fresh(t)+ plan := &fake{t: t, ctype: "application/json", reply: `{"id":"from-plan","choices":[]}`}+ spare := &fake{t: t, ctype: "application/json", reply: `{"id":"from-spare","choices":[]}`}+ twoProviders(t, plan, spare)+ var decided int+ jev := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ decided+++ w.Header().Set("Content-Type", "application/json")+ io.WriteString(w, `{"answers":{"intent":{"choice":"bug"}},"usage":{"input_tokens":10,"output_tokens":2}}`)+ }))+ t.Cleanup(jev.Close)+ if err := provider.Save(provider.Provider{ID: "jev", Name: "Jev", Key: "k", Decide: jev.URL + "/v1"}); err != nil {+ t.Fatal(err)+ }+ var drew int+ art := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ drew+++ w.Header().Set("Content-Type", "application/json")+ io.WriteString(w, `{"created":1,"data":[{"b64_json":"`+base64.StdEncoding.EncodeToString(pngBytes)+`"}]}`)+ }))+ t.Cleanup(art.Close)+ if err := provider.Save(provider.Provider{ID: "art", Name: "Art", Chat: art.URL + "/v1", Key: "kA", Models: []string{"gpt-image-1"}}); err != nil {+ t.Fatal(err)+ }+ for _, g := range []provider.Group{+ {Name: "Both", Members: []string{"plan/m1", "spare/m2"}, Routing: provider.Ordered},+ {Name: "Solo", Members: []string{"plan/m1"}, Routing: provider.Ordered},+ } {+ if err := provider.SaveGroup(g); err != nil {+ t.Fatal(err)+ }+ }+ keys, secrets := newCaller(t, "Held", "Free")+ if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"plan/" + provider.KeyID("k")}}); err != nil {+ t.Fatal(err)+ }+ if ks, _ := access.List(); len(ks[len(ks)-2].Models) != 0 {+ t.Fatalf("the key's own models were written: %+v", ks[len(ks)-2])+ }+ h := New().Handler()+ do := func(secret, method, path, body string) *httptest.ResponseRecorder {+ r := httptest.NewRequest(method, path, strings.NewReader(body))+ r.Header.Set("Authorization", "Bearer "+secret)+ w := httptest.NewRecorder()+ h.ServeHTTP(w, r)+ return w+ }+ refused := func(what string, w *httptest.ResponseRecorder) {+ t.Helper()+ if w.Code != 403 || !strings.Contains(w.Body.String(), "Held") {+ t.Errorf("%s: %d %s", what, w.Code, w.Body.String())+ }+ }++ // the lists: the account's provider's models and a group of them only+ var l struct{ Data []struct{ ID string } }+ if w := do(secrets[0], "GET", "/v1/models", ""); json.Unmarshal(w.Body.Bytes(), &l) != nil {+ t.Fatal(w.Body.String())+ }+ var ids []string+ for _, m := range l.Data {+ ids = append(ids, m.ID)+ }+ if !slices.Contains(ids, "plan/m1") || !slices.Contains(ids, "group/solo") || slices.Contains(ids, "spare/m2") || slices.Contains(ids, "group/both") || slices.Contains(ids, "jev/jev-latest") {+ t.Errorf("/v1/models lists %v", ids)+ }+ if w := do(secrets[0], "GET", "/v1beta/models", ""); w.Code != 200 || !strings.Contains(w.Body.String(), "m1") || strings.Contains(w.Body.String(), "m2") {+ t.Errorf("gemini list %d %s", w.Code, w.Body.String())+ }+ if w := do(secrets[0], "GET", "/v1/models/spare/m2", ""); w.Code == 200 {+ t.Error("a model of another provider was found", w.Body.String())+ }++ // a request for another provider's model, on every API+ for _, model := range []string{"spare/m2", "m2", "group/both"} {+ refused("chat "+model, do(secrets[0], "POST", "/v1/chat/completions", `{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`))+ }+ refused("responses", do(secrets[0], "POST", "/v1/responses", `{"model":"spare/m2","input":"hi"}`))+ refused("messages", do(secrets[0], "POST", "/v1/messages", `{"model":"spare/m2","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`))+ refused("gemini", do(secrets[0], "POST", "/v1beta/models/spare/m2:generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`))+ refused("count_tokens", do(secrets[0], "POST", "/v1/messages/count_tokens", `{"model":"spare/m2","messages":[{"role":"user","content":"hi"}]}`))+ refused("countTokens", do(secrets[0], "POST", "/v1beta/models/spare/m2:countTokens", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`))+ refused("embeddings", do(secrets[0], "POST", "/v1/embeddings", `{"model":"spare/m2","input":"hi"}`))+ refused("codex backend", do(secrets[0], "POST", CodexPath+"/responses", `{"model":"spare/m2","input":"hi","stream":true}`))+ refused("system one", do(secrets[0], "POST", "/v1/systemone", `{"model":"jev/jev-latest","state":{"message":"hi"},"questions":{"intent":{"type":"choice"}}}`))+ refused("images", do(secrets[0], "POST", "/v1/images/generations", `{"model":"art/gpt-image-1","prompt":"a magpie"}`))+ if spare.calls != 0 || decided != 0 || drew != 0 {+ t.Fatal("a held request reached another provider", spare.calls, decided, drew)+ }+ if w := do(secrets[1], "POST", "/v1/images/generations", `{"model":"art/gpt-image-1","prompt":"a magpie"}`); w.Code != 200 || drew != 1 {+ t.Errorf("a free key's drawing: %d %s", w.Code, w.Body.String())+ }++ // its own provider's models are served, a group of them too+ for _, model := range []string{"plan/m1", "m1", "group/solo"} {+ if w := do(secrets[0], "POST", "/v1/chat/completions", `{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`); w.Code != 200 || !strings.Contains(w.Body.String(), "from-plan") {+ t.Errorf("%s: %d %s", model, w.Code, w.Body.String())+ }+ }+ // a fallback to another provider's model is not the key's+ plan.code, plan.reply = 429, `{"error":{"message":"slow down"}}`+ if w := do(secrets[0], "POST", "/v1/chat/completions", chatReq); w.Code == 200 || spare.calls != 0 {+ t.Errorf("a held key fell back to another provider: %d %s", w.Code, w.Body.String())+ }+ // a free key is served everywhere, the fallback too+ if w := do(secrets[1], "POST", "/v1/chat/completions", chatReq); w.Code != 200 || !strings.Contains(w.Body.String(), "from-spare") {+ t.Errorf("a free key's fallback: %d %s", w.Code, w.Body.String())+ }+ plan.code, plan.reply = 0, `{"id":"from-plan","choices":[]}`++ // a key that lists models keeps them: its account holds only the+ // provider it names, as before (#905)+ if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"spare/*"}}); err != nil {+ t.Fatal(err)+ }+ if w := do(secrets[0], "POST", "/v1/chat/completions", `{"model":"spare/m2","messages":[{"role":"user","content":"hi"}]}`); w.Code != 200 || !strings.Contains(w.Body.String(), "from-spare") {+ t.Errorf("a listed model: %d %s", w.Code, w.Body.String())+ }+ // and one let off its accounts uses every model again+ if _, err := access.Update("models-key", access.Change{Key: keys[0].ID}); err != nil {+ t.Fatal(err)+ }+ if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID}); err != nil {+ t.Fatal(err)+ }+ if w := do(secrets[0], "POST", "/v1/chat/completions", `{"model":"spare/m2","messages":[{"role":"user","content":"hi"}]}`); w.Code != 200 {+ t.Errorf("a key let off: %d %s", w.Code, w.Body.String())+ }+}diff --git a/internal/gateway/key_accounts_test.go b/internal/gateway/key_accounts_test.goindex 38d6f9ab6..3d7e40472 100644--- a/internal/gateway/key_accounts_test.go+++ b/internal/gateway/key_accounts_test.go@@ -193,14 +193,21 @@ func TestGatewayKeyAccountsListModels(t *testing.T) {t.Fatalf("the key's models: %s", got)}// a provider with no account and no key (a local ollama) is one the- // key names no account of: its models stay listed, as its requests- // pass (#905)+ // key names no account of: not its while it lists no model (Linka on+ // Discord); among the models it lists, its models stay listed, as its+ // requests pass (#905)if err := provider.Save(provider.Provider{ID: "local", Name: "Local", Chat: "http://127.0.0.1:11434/v1", Models: []string{"tiny"}}); err != nil {t.Fatal(err)}if err := catalog.SaveLive("local", "http://127.0.0.1:11434/v1", []catalog.Model{{ID: "tiny"}}); err != nil {t.Fatal(err)}+ if got := list(secrets[0]); strings.Contains(got, `"local/tiny"`) {+ t.Fatalf("an account-only key lists another provider: %s", got)+ }+ if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"codex/*", "local/*", "relay/*"}}); err != nil {+ t.Fatal(err)+ }if got := list(secrets[0]); !strings.Contains(got, `"local/tiny"`) {t.Fatalf("a provider with no account or key: %s", got)}@@ -442,13 +449,25 @@ func TestGatewayKeyAccountsSystemOne(t *testing.T) {if w := ask(secrets[0]); w.Code != 200 || decided != 1 {t.Fatalf("the key's account: %d %s, decided %d", w.Code, w.Body.String(), decided)}- // a provider the key names no account of: asked as it always did+ // a provider the key names no account of, among its models: asked as+ // it always didif _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"relay/" + provider.KeyID("sk-1")}}); err != nil {t.Fatal(err)}+ if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"jev/*", "relay/*"}}); err != nil {+ t.Fatal(err)+ }if w := ask(secrets[0]); w.Code != 200 || decided != 2 {t.Fatalf("an unnamed provider: %d %s, decided %d", w.Code, w.Body.String(), decided)}+ // with no model listed, the key may use its accounts' providers' only+ // (Linka on Discord): the decider is not its+ if _, err := access.Update("models-key", access.Change{Key: keys[0].ID}); err != nil {+ t.Fatal(err)+ }+ if w := ask(secrets[0]); w.Code != http.StatusForbidden || decided != 2 {+ t.Fatalf("an account-only key's decider: %d %s, decided %d", w.Code, w.Body.String(), decided)+ }// the provider named, its account set not to serve the decision modelif _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"jev/" + provider.KeyID("kj")}}); err != nil {t.Fatal(err)@@ -564,9 +583,11 @@ func TestGatewayKeyAccountsDrawOnAnAllowedKey(t *testing.T) {}}-// A key held to some accounts of one provider uses another's as it always-// did (#905): the list holds it to some accounts of the providers it-// names, not to the providers themselves.+// A key that lists models and some accounts of one provider uses another+// provider's models it lists on every account (#905): the accounts hold+// it to some accounts of the providers they name, not to those+// providers. (One that lists accounts and no model may use only their+// providers' models: TestGatewayKeyAccountsOnlyHoldTheModels.)func TestGatewayKeyAccountsOfANamedProvider(t *testing.T) {fresh(t)plan := &fake{t: t, ctype: "application/json", reply: `{"id":"from-plan","choices":[]}`}@@ -576,6 +597,9 @@ func TestGatewayKeyAccountsOfANamedProvider(t *testing.T) {if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"plan/" + provider.KeyID("k")}}); err != nil {t.Fatal(err)}+ if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"plan/*", "spare/*"}}); err != nil {+ t.Fatal(err)+ }h := New().Handler()// plan is named: only its key may serve; spare, named nowhere, serves// as it always diddiff --git a/internal/gateway/quotas_scope_test.go b/internal/gateway/quotas_scope_test.goindex 41b1648c8..7146c5090 100644--- a/internal/gateway/quotas_scope_test.go+++ b/internal/gateway/quotas_scope_test.go@@ -95,7 +95,9 @@ func TestHeldKeyToldItsOwnQuotas(t *testing.T) {"AlphaAll": {"alpha:one", "alpha:two"},"AlphaSome": {"beta:"}, // none of alpha's: m2 spends its quota too"AlphaTwo": {"alpha:two"},- "BetaKey": every,+ // beta's key alone and no model: beta's models alone are the+ // key's (Linka on Discord), so alpha's cards are not its+ "BetaKey": {"beta:"},}for _, path := range []string{"/v1/magpie/quotas?kept=1", provider.RemoteCardsPath} {for i, s := range secrets {diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex a1a8da347..309ac9df0 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -379,6 +379,9 @@ const I18N = {"Not served now": "当前未提供","{name} may use only the models picked": "{name} 仅可使用所选模型","{name} may use every model": "{name} 可使用全部模型",+ "No model is picked, so this key may use only the picked accounts' providers' models": "没有勾选模型,此密钥只能使用所勾选账号所属供应商的模型",+ "Not used: no {provider} model or account is picked": "不会被使用:{provider} 没有勾选任何模型或账号",+ "{name} may use only the picked accounts' models": "{name} 仅可使用所选账号的模型","{used} of {limit} tokens · {left} left": "已用 {used} / {limit} Token · 剩余 {left}","{used} of {limit} estimated · {left} left": "估算费用 {used} / {limit} · 剩余 {left}","refused until {when}": "{when} 前拒绝请求",@@ -4514,6 +4517,9 @@ const I18N = {"Not served now": "目前未提供","{name} may use only the models picked": "{name} 僅可使用所選模型","{name} may use every model": "{name} 可使用全部模型",+ "No model is picked, so this key may use only the picked accounts' providers' models": "沒有勾選模型,此金鑰只能使用所勾選帳號所屬供應商的模型",+ "Not used: no {provider} model or account is picked": "不會被使用:{provider} 沒有勾選任何模型或帳號",+ "{name} may use only the picked accounts' models": "{name} 僅可使用所選帳號的模型","{used} of {limit} tokens · {left} left": "已用 {used} / {limit} Token · 剩餘 {left}","{used} of {limit} estimated · {left} left": "估算費用 {used} / {limit} · 剩餘 {left}","refused until {when}": "{when} 前拒絕請求",@@ -8611,6 +8617,9 @@ const I18N = {"Not served now": "現在は提供されていません","{name} may use only the models picked": "{name} は選んだモデルのみ使えます","{name} may use every model": "{name} はすべてのモデルを使えます",+ "No model is picked, so this key may use only the picked accounts' providers' models": "モデルが選ばれていないため、このキーは選んだアカウントのプロバイダーのモデルだけを使えます",+ "Not used: no {provider} model or account is picked": "使われません:{provider} のモデルもアカウントも選ばれていません",+ "{name} may use only the picked accounts' models": "{name} は選んだアカウントのモデルのみ使えます","{used} of {limit} tokens · {left} left": "{used} / {limit} トークン · 残り {left}","{used} of {limit} estimated · {left} left": "推定 {used} / {limit} · 残り {left}","refused until {when}": "{when} まで拒否",@@ -12725,6 +12734,9 @@ const I18N = {"Not served now": "Derzeit nicht angeboten","{name} may use only the models picked": "{name} darf nur die gewählten Modelle nutzen","{name} may use every model": "{name} darf alle Modelle nutzen",+ "No model is picked, so this key may use only the picked accounts' providers' models": "Kein Modell ist ausgewählt, daher darf dieser Schlüssel nur Modelle der Anbieter der ausgewählten Konten nutzen",+ "Not used: no {provider} model or account is picked": "Wird nicht genutzt: kein {provider}-Modell und kein Konto ist ausgewählt",+ "{name} may use only the picked accounts' models": "{name} darf nur die Modelle der gewählten Konten nutzen","{used} of {limit} tokens · {left} left": "{used} von {limit} Token · {left} übrig","{used} of {limit} estimated · {left} left": "{used} von {limit} geschätzt · {left} übrig","refused until {when}": "abgelehnt bis {when}",diff --git a/internal/gui/assets/plugins/gateway/keys.js b/internal/gui/assets/plugins/gateway/keys.jsindex 63fca1af1..e229d3b06 100644--- a/internal/gui/assets/plugins/gateway/keys.js+++ b/internal/gui/assets/plugins/gateway/keys.js@@ -307,9 +307,13 @@ function gatewayModelsBadge(k) {b.textContent = !ms.length && !as.length ? t("All models"): ms.length ? (ms.length === 1 && !as.length ? ms[0] : t("{n} models", { n: ms.length })): (as.length === 1 ? accountShown(as[0]) : t("{n} accounts", { n: as.length }));+ // an account picked and no model holds the key to the accounts'+ // providers' models (access.HeldModels, Linka on Discord): it is not+ // let off to every other provider'sb.title = (ms.length ? t("Only these models: {list}", { list: ms.join(", ") }) : t("Pick the models this key may use"))+ (as.length ? "\n" + t("Only these accounts: {list}", { list: as.map(accountShown).join(", ") })- + "\n" + t("A provider with no account picked is used on every account; to keep the key off it, pick only other providers' models") : "");+ + "\n" + (ms.length ? t("A provider with no account picked is used on every account; to keep the key off it, pick only other providers' models")+ : t("No model is picked, so this key may use only the picked accounts' providers' models")) : "");b.setAttribute("aria-label", t("Models this key may use"));b.setAttribute("aria-haspopup", "menu");b.setAttribute("aria-expanded", "false");@@ -327,10 +331,20 @@ function gatewayModelsBadge(k) {// every one, and its unticked accounts say so (#2077: unticking all of// Codex's left Codex's models served)const named = new Set(as.map((v) => v.split("/")[0].toLowerCase()));+ // a provider the key's models leave out is used on none of its+ // accounts: with no model picked, every provider no account is+ // picked of (access.HeldModels)+ const modelsReach = (pid) => ms.some((m) => {+ const head = m.split("/")[0].toLowerCase();+ return head === pid || head.includes("*");+ });for (const a of accounts || []) {accountsSet.add(a.id);- const note = as.length && !named.has(String(a.provider).toLowerCase())- ? t("Used: no {provider} account is picked", { provider: a.providerName })+ const pid = String(a.provider).toLowerCase();+ const note = as.length && !named.has(pid)+ ? (ms.length && modelsReach(pid)+ ? t("Used: no {provider} account is picked", { provider: a.providerName })+ : t("Not used: no {provider} model or account is picked", { provider: a.providerName })): a.plan ? a.providerName + " · " + a.plan : a.providerName;const o = { v: a.id, name: a.name, note, literalName: true };ofProvider.set(a.provider, [...(ofProvider.get(a.provider) || []), o]);@@ -380,7 +394,10 @@ function gatewayModelsBadge(k) {const pickedModels = picked.filter((v) => !accountsSet.has(v));const pickedAccounts = picked.filter((v) => accountsSet.has(v));const out = await gatewayKeyAction("models-key", { key: k.id, models: pickedModels });- if (out) status(t(pickedModels.length ? "{name} may use only the models picked" : "{name} may use every model", { name: k.name }), "ok");+ if (out) {+ status(t(pickedModels.length ? "{name} may use only the models picked"+ : pickedAccounts.length ? "{name} may use only the picked accounts' models" : "{name} may use every model", { name: k.name }), "ok");+ }if (pickedAccounts.length !== as.length || pickedAccounts.some((v) => !as.includes(v))) {await gatewayKeyAction("accounts-key", { key: k.id, accounts: pickedAccounts });}diff --git a/internal/gui/tests/gateway-key-accounts.test.cjs b/internal/gui/tests/gateway-key-accounts.test.cjsindex 3176b68da..033c41d70 100644--- a/internal/gui/tests/gateway-key-accounts.test.cjs+++ b/internal/gui/tests/gateway-key-accounts.test.cjs@@ -17,11 +17,11 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",page.setDefaultTimeout(6000);const events = [], errors = [];page.on("pageerror", (e) => errors.push(e.message));- await page.route("**/*", fixture(lang, "light", events, { lan: true, keyHolds: { server: { accounts: ["relay/[email protected]"] }, laptop: { models: ["relay/gone"], accounts: ["relay/[email protected]"] } } }));+ await page.route("**/*", fixture(lang, "light", events, { lan: true, keyHolds: { server: { accounts: ["relay/[email protected]"] }, laptop: { models: ["relay/gone", "openai/gpt-5"], accounts: ["relay/[email protected]"] } } }));const zh = lang === "zh";const w = zh- ? { label: "此密钥可用的模型", all: "全部模型", gone: "当前未提供", off: "当前未登录", used: "会被使用:OpenAI 没有勾选任何账号", hint: "没勾选任何账号的供应商" }- : { label: "Models this key may use", all: "All models", gone: "Not served now", off: "Not signed in now", used: "Used: no OpenAI account is picked", hint: "A provider with no account picked is used on every account" };+ ? { label: "此密钥可用的模型", all: "全部模型", gone: "当前未提供", off: "当前未登录", used: "会被使用:OpenAI 没有勾选任何账号", unused: "不会被使用:OpenAI 没有勾选任何模型或账号", hint: "没勾选任何账号的供应商", only: "此密钥只能使用所勾选账号所属供应商的模型", told: "Server 仅可使用所选账号的模型" }+ : { label: "Models this key may use", all: "All models", gone: "Not served now", off: "Not signed in now", used: "Used: no OpenAI account is picked", unused: "Not used: no OpenAI model or account is picked", hint: "A provider with no account picked is used on every account", only: "this key may use only the picked accounts' providers' models", told: "Server may use only the picked accounts' models" };await page.goto("http://magpie.test/?view=gateway");await page.locator("#gatewayKeys .acc[data-key]").last().waitFor();const row = (id) => page.locator(`#gatewayKeys .acc[data-key="${id}"]`);@@ -76,19 +76,24 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",await badge("server").click();await menu.waitFor();assert.deepEqual((await menu.locator(".pm-item.on").allTextContents()).map((s) => s.trim()), ["[email protected] · Pro"]);- // #2077: the list holds the key to the accounts of the providers it- // names only, so OpenAI's key, none of OpenAI's picked, is used, and- // says so; Relay's unpicked account is not, and says its provider+ // Linka on Discord: an account picked and no model holds the key to+ // the account's provider's models, so OpenAI's key, none of+ // OpenAI's picked, is not used, and says so (it said "Used" when+ // the key could use every other provider); Relay's unpicked account+ // is not either, and says its providerconst noteOf = async (s) => (await menu.locator(".pm-item", { hasText: s }).locator(".pm-note").textContent()).trim();- assert.equal(await noteOf("k-1a2b3c"), w.used);+ assert.equal(await noteOf("k-1a2b3c"), w.unused);assert.equal(await noteOf("[email protected]"), "Relay");- assert(String(await badge("server").getAttribute("title")).includes(w.hint), await badge("server").getAttribute("title"));+ const serverTitle = String(await badge("server").getAttribute("title"));+ assert(serverTitle.includes(w.only) && !serverTitle.includes(w.hint), serverTitle);await menu.locator(".pm-item", { hasText: "[email protected]" }).click();await menu.locator(".pm-item", { hasText: "k-1a2b3c" }).click();await page.keyboard.press("Escape");await menu.waitFor({ state: "detached" });await until(() => events.filter((e) => e.action === "accounts-key").length > 0 && events.filter((e) => e.action === "accounts-key").at(-1).body.key === "server");assert.deepEqual(events.filter((e) => e.action === "accounts-key").at(-1).body, { key: "server", accounts: ["openai/k-1a2b3c"] });+ // what it is told says the accounts hold its models, not "every model"+ await page.waitForFunction((want) => document.body.textContent.includes(want), w.told);await badge("server").click();await menu.waitFor();await menu.locator(".pm-item", { hasText: w.all }).first().click();@@ -111,7 +116,12 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",assert(dead[atDead("relay/[email protected]")] === "relay/[email protected]" + w.off, dead.join(" | "));assert(atDead("relay/gone") > atDead("k-1a2b3c"), dead.join(" | "));assert(atDead("relay/[email protected]") > atDead("relay/gone"), dead.join(" | "));- assert.deepEqual((await menu.locator(".pm-item.on").allTextContents()).map((s) => s.trim()), ["relay/gone" + w.gone, "relay/[email protected]" + w.off]);+ assert.deepEqual((await menu.locator(".pm-item.on").allTextContents()).map((s) => s.trim()), ["GPT-5openai/gpt-5", "relay/gone" + w.gone, "relay/[email protected]" + w.off]);+ // #2077: a key that lists models holds only the providers its+ // accounts name to them: OpenAI, among its models and no account of+ // it picked, is used on its key, and says so+ assert.equal(await noteOf("k-1a2b3c"), w.used);+ assert(String(await badge("laptop").getAttribute("title")).includes(w.hint), await badge("laptop").getAttribute("title"));await page.keyboard.press("Escape");await menu.waitFor({ state: "detached" });const lefts = await page.locator("#gatewayKeys .key-models, .proto-menu .pm-item").evaluateAll((els) => els.map((e) => getComputedStyle(e).borderLeftStyle));