catalog: a vendor's own model name is kept ahead of the catalog's, and fallback names never collide (#1188, fixes #1119)

Command Code's Flash Fast showed the catalog's "Flash", the same name as
plain Flash, so the picker had two "Flash" rows. An unprefixed `name`
from a vendor's /models now wins over the catalog fallback
(magpie_label and display_name still come first). A `Vendor: Model`
name such as OpenRouter's falls through to the catalog as before, so
OpenRouter's names don't change.

A catalog fallback that would give two ids one name keeps the id
instead. Exposed fills names only for unlisted picks and checks every
available name and id for a collision; listed picks keep exactly what
Available returned, Antigravity's id-only names among them.
TestNameOf's case-variant expectation changes on purpose: glm-5-turbo
and GLM-5-Turbo together keep their own ids.

Kenoia's PR head f538b19e, which conflicted with main in
internal/catalog/live.go and live_test.go; the conflict was resolved
keeping both main's live-name changes and this one.

Run on this tree (origin/main 848d2ea9 + the PR): gofmt -l clean;
go vet darwin, GOOS=linux -tags nogui and GOOS=windows on
internal/catalog and internal/provider; go test -tags nogui
./internal/catalog/ ok and ./internal/provider/ ok (805s, full
package, on the same change over 5b14ebf4), and -run Name|Catalog|Live
again on 848d2ea9. With the live.go fallback reverted, the new
live_test and model_names tests go red. Not tried against Command
Code's live /models with a real account.
This commit is contained in:
Kenoia
2026-10-13 11:43:54 +08:00
committed by yetone
parent 848d2ea9b8
commit 7df0a5bf32
7 changed files with 366 additions and 17 deletions
+13
View File
@@ -111,6 +111,19 @@ A signed-in account's model list exists only at its vendor (Cursor's `cursor-age
3. **Sign.** For each try, `Sign` gives the request its auth. A token about to expire is refreshed first, and the rotated tokens go back to their one holder: the agent's store, or `logins.json` for an account standing behind it.
4. **Allowance.** Usage endpoints are rate limited, so `SubscriptionUsage` caches its results: a cached copy comes back at once and a stale one is refreshed in the background. When an account's windows start again, `OnRenewed` tells the gateway so a resting account can come back: a Codex reset spent (`renewedNow`), or a reading routing takes (`Allowances`, as the agent the account's usage is read under, `claude` or `plugin:<id>`) that finds the account full till sooner than the last did (`renewedFrom`, the rule a key's reading goes by): the whole account, or a pool of some models with the whole account's windows over it. A window used below `SpentShareOf` its routing, or whose reset passed, is full no more; one full with its reset not known is full for good. A Claude account is back as soon as a new `/usage` or the reset passing shows the window it was out of started again, not when the time Claude Code's refusal named comes; its five hours started again in a week used up tells nothing. A first reading, a failed one, one read alike, or one leaving the full window out tells nothing, and a reset spent is told once, by `renewedNow`. A key's reading that finds a window it was full in (at `SpentShareOf` its routing) full no more, or full till sooner, tells it too, as agent `""` and the key's `KeyAllowanceID`, so a key out of its limit is back once the limit is raised or its usage reset; a first reading, a failed one, or one that finds it fuller tells nothing. An account refused for its quota has its agent's allowances read again at the next ask (`StaleAllowance`). A reading already out then was asked before the refusal: what it read is kept, as not read, so the ask after it lands reads again, as `StaleKeyAllowance` does for a key. Built-in Grok's own per-account cache (`grokLoginUsage`) doesn't keep such a reading at all: it goes to its caller only, so that next ask reaches xAI.
A provider's fetched model list keeps the upstream ids and order. Display
names prefer `magpie_label`, then `display_name`, then a `name` without a
vendor-style `: ` prefix, then the id
([`live.go`](../../internal/catalog/live.go), `fetchOne`). OpenRouter's
prefixed `name` is left to the catalog. `Decorate` and
[`Named`](../../internal/catalog/catalog.go) fill missing names from the
catalog, keeping an id when a suggested name would collide with another
model in the list, including when exact ids differ only in case. Accepted
names supplied by the provider stay as supplied. Models picked by the user
that the upstream does not list are named against all listed names and ids;
listed models keep their `Available` names unchanged
([`Exposed`](../../internal/provider/models.go)).
## Constraints and failure behavior
- Each refresh token has exactly one holder. Vendors rotate tokens on refresh, so two copies of one token would sign each other out. `savedTokenMu` stops two requests refreshing one saved account at once.
+45 -6
View File
@@ -844,19 +844,58 @@ func NameOf(id string) string {
// knows it by (NameOf), so one model reads the same under every provider:
// a GLM Coding Plan's glm-5-turbo, which Zhipu's catalog doesn't list, is
// GLM-5-Turbo as ZCode's is. Its id, and where requests go, stay as they
// are.
func Named(ms []Model) []Model {
// are. A supplemented name shared by different ids falls back to the id.
// Already named models in reserved count toward collisions but stay as given.
func Named(ms []Model, reserved ...Model) []Model {
out := slices.Clone(ms)
for i, m := range out {
fallback := make([]string, len(ms))
for i, m := range ms {
if m.Name == "" || m.Name == m.ID {
if n := NameOf(m.ID); n != "" {
out[i].Name = n
}
fallback[i] = NameOf(m.ID)
}
}
fillNames(out, fallback, reserved...)
return out
}
// fillNames applies catalog names without giving different ids the same
// name. The ids are reserved too, so falling back to one cannot collide
// with another model's supplemented name. The caller owns ms.
func fillNames(ms []Model, fallback []string, reserved ...Model) {
owners := make(map[string]string)
collisions := make(map[string]bool)
claim := func(name, id string) {
if name == "" {
return
}
if owner, ok := owners[name]; ok && owner != id {
collisions[name] = true
}
owners[name] = id
}
for _, m := range reserved {
claim(m.ID, m.ID)
claim(m.Name, m.ID)
}
for i, m := range ms {
claim(m.ID, m.ID)
name := m.Name
if fallback[i] != "" {
name = fallback[i]
}
claim(name, m.ID)
}
for i, name := range fallback {
if name == "" {
continue
}
if collisions[name] {
name = ms[i].ID
}
ms[i].Name = name
}
}
// Knows reports whether models.dev lists a model of this id at all, under
// any provider, as ContextOf and EffortsOf match it.
func Knows(id string) bool {
+9 -2
View File
@@ -331,6 +331,11 @@ func fetchOne(ctx context.Context, url, key string, anthropic bool, headers map[
continue
}
name, plain := r.DisplayName, ""
// OpenRouter's "Anthropic: Claude …" is a vendor-prefixed name;
// leave it to the catalog rather than changing every display name.
if name == "" && !strings.Contains(r.Name, ": ") {
name = r.Name
}
if r.Label != "" {
name = r.Label
if r.DisplayName != "" && r.DisplayName != r.Label {
@@ -525,14 +530,15 @@ func Decorate(live []Model, known []Model) []Model {
byID[m.ID] = m
}
out := make([]Model, 0, len(live))
for _, m := range live {
fallback := make([]string, len(live))
for i, m := range live {
k, ok := byID[m.ID]
if i := strings.LastIndexByte(m.ID, '/'); !ok && i >= 0 {
k, ok = byID[m.ID[i+1:]] // a gateway's "deepseek/deepseek-chat"
}
if ok {
if m.Name == "" || m.Name == m.ID {
m.Name = k.Name
fallback[i] = k.Name
}
m.Efforts, m.Released, m.Provider = k.Efforts, k.Released, k.Provider
m.Reasoning = m.Reasoning || k.Reasoning
@@ -556,6 +562,7 @@ func Decorate(live []Model, known []Model) []Model {
}
out = append(out, m)
}
fillNames(out, fallback)
return out
}
+102
View File
@@ -167,3 +167,105 @@ func TestLiveMagpiePrice(t *testing.T) {
t.Errorf("an odd price lost a model: %d of 6", len(ms))
}
}
// Command Code supplies distinct names for its Flash and Flash Fast models.
func TestFetchCommandCodeNames(t *testing.T) {
writeCatalog(t, `{
"coralbricks":{"models":{
"deepseek-v4.1-flash":{"id":"deepseek-v4.1-flash","name":"DeepSeek V4.1 Flash"},
"deepseek-v4.1-flash-fast":{"id":"deepseek-v4.1-flash-fast","name":"DeepSeek V4.1 Flash"}}},
"vercel":{"models":{
"deepseek-v4.1-flash-fast":{"id":"deepseek-v4.1-flash-fast","name":"DeepSeek V4.1 Flash Fast"}}}
}`)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"object":"list","data":[
{"id":"deepseek/deepseek-v4.1-flash","object":"model","created":1791381046,"owned_by":"command-code","name":"DeepSeek V4.1 Flash","context_length":1000000,"supported_endpoints":["/chat/completions","/responses"]},
{"id":"deepseek/deepseek-v4.1-flash-fast","object":"model","created":1791381046,"owned_by":"command-code","name":"DeepSeek V4.1 Flash Fast","context_length":1000000,"supported_endpoints":["/chat/completions","/responses"]}]}`))
}))
defer srv.Close()
ms, err := Fetch(context.Background(), srv.URL+"/v1", "", false, nil)
if err != nil {
t.Fatal(err)
}
if len(ms) != 2 {
t.Fatalf("models: %+v", ms)
}
for i, m := range Named(Decorate(ms, Provider("coralbricks"))) {
wantID, wantName := "deepseek/deepseek-v4.1-flash", "DeepSeek V4.1 Flash"
if i == 1 {
wantID += "-fast"
wantName += " Fast"
}
if m.ID != wantID || m.Name != wantName {
t.Errorf("model %d: id %q, name %q; want %q, %q", i, m.ID, m.Name, wantID, wantName)
}
if m.Context != 1000000 || strings.Join(m.APIs, ",") != "chat,responses" {
t.Errorf("model facts lost: %+v", m)
}
}
}
func TestFetchNamePrecedence(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"models":[
{"id":"all","magpie_label":"label","display_name":"display","name":"name"},
{"id":"display","magpie_label":"","display_name":"display name","name":"name"},
{"id":"name","display_name":"","name":"provider name"},
{"id":"id","name":""},
{"id":"prefixed","name":"Vendor: Model"},
{"id":"prefixed-display","display_name":"Vendor: Display","name":"Vendor: Name"},
{"id":"prefixed-label","magpie_label":"Vendor: Label","name":"Vendor: Name"},
{"id":"variant","name":"Model:free"},
{"name":"name-only"},
{"display_name":"no identifier"},
{}]}`))
}))
defer srv.Close()
ms, err := Fetch(context.Background(), srv.URL+"/v1", "", false, nil)
if err != nil {
t.Fatal(err)
}
var got []string
for _, m := range ms {
got = append(got, m.ID+"|"+m.Name)
}
want := "all|label\ndisplay|display name\nname|provider name\nid|id\nprefixed|prefixed\nprefixed-display|Vendor: Display\nprefixed-label|Vendor: Label\nvariant|Model:free\nname-only|name-only"
if strings.Join(got, "\n") != want {
t.Fatalf("got\n%s\nwant\n%s", strings.Join(got, "\n"), want)
}
}
// OpenRouter's real /api/v1/models shape has vendor-prefixed names and no
// display_name. Those names still come from its catalog, without the prefix.
func TestFetchOpenRouterNames(t *testing.T) {
writeCatalog(t, `{"openrouter":{"models":{
"anthropic/claude-haiku-5.5":{"id":"anthropic/claude-haiku-5.5","name":"Claude Haiku 5.5"},
"google/gemini-nano-banana-2.1":{"id":"google/gemini-nano-banana-2.1","name":"Nano Banana 2.1"}
}}}`)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Fields from https://openrouter.ai/api/v1/models, 2026-10-08.
w.Write([]byte(`{"data":[
{"id":"anthropic/claude-haiku-5.5","canonical_slug":"anthropic/claude-haiku-5.5-20261007","name":"Anthropic: Claude Haiku 5.5","created":1791397883,"context_length":1000000,"architecture":{"modality":"text+image+file->text","input_modalities":["text","image","file"],"output_modalities":["text"],"tokenizer":"Claude","instruct_type":null},"top_provider":{"context_length":1000000,"max_completion_tokens":128000,"is_moderated":true}},
{"id":"google/gemini-nano-banana-2.1","canonical_slug":"google/gemini-nano-banana-2.1-20261006","name":"Google: Nano Banana 2.1","created":1791300825,"context_length":65536,"architecture":{"modality":"text+image->text+image","input_modalities":["image","text"],"output_modalities":["image","text"],"tokenizer":"Gemini","instruct_type":null},"top_provider":{"context_length":65536,"max_completion_tokens":58982,"is_moderated":false}}]}`))
}))
defer srv.Close()
ms, err := Fetch(context.Background(), srv.URL+"/api/v1", "", false, nil)
if err != nil {
t.Fatal(err)
}
if len(ms) != 2 {
t.Fatalf("models: %+v", ms)
}
for _, m := range ms {
if m.Name != m.ID {
t.Errorf("prefixed name kept for %q: %q", m.ID, m.Name)
}
}
wantNames := []string{"Claude Haiku 5.5", "Nano Banana 2.1"}
wantContexts := []int{1000000, 65536}
for i, m := range Named(Decorate(ms, Provider("openrouter"))) {
if m.ID != ms[i].ID || m.Name != wantNames[i] || m.Context != wantContexts[i] {
t.Errorf("model %d: %+v; want id %q, name %q, context %d", i, m, ms[i].ID, wantNames[i], wantContexts[i])
}
}
}
+69 -1
View File
@@ -1,6 +1,8 @@
package catalog
import (
"reflect"
"slices"
"strings"
"testing"
)
@@ -37,7 +39,9 @@ func TestNameOf(t *testing.T) {
for _, m := range Named(in) {
got = append(got, m.ID+"|"+m.Name)
}
want := "glm-5-turbo|GLM-5-Turbo\nGLM-5-Turbo|GLM-5-Turbo\nglm-5-turbo|Turbo\nplain|plain"
// These exact ids differ, so the shared name would hide that distinction.
// NameOf still matches either case; Named keeps each id in this list.
want := "glm-5-turbo|glm-5-turbo\nGLM-5-Turbo|GLM-5-Turbo\nglm-5-turbo|Turbo\nplain|plain"
if strings.Join(got, "\n") != want {
t.Fatalf("got\n%s\nwant\n%s", strings.Join(got, "\n"), want)
}
@@ -45,3 +49,67 @@ func TestNameOf(t *testing.T) {
t.Fatalf("the list given was changed: %q", in[0].Name)
}
}
func TestNamedAvoidsCollisions(t *testing.T) {
writeCatalog(t, `{"vendor":{"models":{
"flash":{"id":"flash","name":"Flash"},
"fast":{"id":"fast","name":"Flash"},
"other":{"id":"other","name":"Other"},
"alias":{"id":"alias","name":"fast"}
}}}`)
for _, c := range []struct {
name string
in, want []Model
}{
{"supplemented", []Model{{ID: "flash", Name: "flash"}, {ID: "fast"}}, []Model{{ID: "flash", Name: "flash"}, {ID: "fast", Name: "fast"}}},
{"explicit", []Model{{ID: "flash", Name: "Flash"}, {ID: "fast", Name: "fast"}, {ID: "other"}}, []Model{{ID: "flash", Name: "Flash"}, {ID: "fast", Name: "fast"}, {ID: "other", Name: "Other"}}},
{"explicit duplicates", []Model{{ID: "flash", Name: "Vendor"}, {ID: "fast", Name: "Vendor"}}, []Model{{ID: "flash", Name: "Vendor"}, {ID: "fast", Name: "Vendor"}}},
{"fallback id", []Model{{ID: "alias"}, {ID: "fast"}}, []Model{{ID: "alias", Name: "alias"}, {ID: "fast", Name: "Flash"}}},
{"same id", []Model{{ID: "flash"}, {ID: "flash", Name: "flash"}}, []Model{{ID: "flash", Name: "Flash"}, {ID: "flash", Name: "Flash"}}},
{"unknown", []Model{{ID: "unknown", Name: "unknown"}}, []Model{{ID: "unknown", Name: "unknown"}}},
} {
t.Run(c.name, func(t *testing.T) {
for _, reverse := range []bool{false, true} {
in, want := slices.Clone(c.in), slices.Clone(c.want)
if reverse {
slices.Reverse(in)
slices.Reverse(want)
}
before := slices.Clone(in)
if got := Named(in); !reflect.DeepEqual(got, want) {
t.Errorf("Named(%+v) = %+v, want %+v", in, got, want)
}
if !reflect.DeepEqual(in, before) {
t.Errorf("input changed: %+v", in)
}
}
})
}
}
func TestDecorateAvoidsNameCollisions(t *testing.T) {
known := []Model{{ID: "flash", Name: "Flash", Context: 1000000}, {ID: "fast", Name: "Flash", Context: 1000000}}
for _, explicit := range []bool{false, true} {
in := []Model{{ID: "vendor/flash", Name: "vendor/flash"}, {ID: "vendor/fast", Name: "vendor/fast"}}
want := slices.Clone(in)
if explicit {
in[0].Name, want[0].Name = "Flash", "Flash"
}
for i := range want {
want[i].Context = 1000000
}
for _, reverse := range []bool{false, true} {
if reverse {
slices.Reverse(in)
slices.Reverse(want)
}
before := slices.Clone(in)
if got := Decorate(in, known); !reflect.DeepEqual(got, want) {
t.Errorf("Decorate(%+v) = %+v, want %+v", in, got, want)
}
if !reflect.DeepEqual(in, before) {
t.Errorf("input changed: %+v", in)
}
}
}
}
+113
View File
@@ -3,6 +3,8 @@ package provider
import (
"os"
"path/filepath"
"reflect"
"slices"
"strings"
"testing"
@@ -87,3 +89,114 @@ func TestModelNamedAsElsewhere(t *testing.T) {
t.Errorf("an Azure deployment was renamed: %+v", ms)
}
}
// Unlisted picks are named together, so each fallback sees its neighbors.
func TestPickedNamesAvoidCollisions(t *testing.T) {
home := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
if err := os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(catalog.CachePath(), []byte(`{"vendor":{"models":{
"flash":{"id":"flash","name":"Flash"},
"fast":{"id":"fast","name":"Flash"},
"other":{"id":"other","name":"Other"}
}}}`), 0o644); err != nil {
t.Fatal(err)
}
catalog.Reset()
t.Cleanup(catalog.Reset)
for _, c := range []struct {
name, preset string
live []catalog.Model
want []string
}{
{"unlisted", "", nil, []string{"flash|flash", "fast|fast", "other|Other"}},
{"listed name", "", []catalog.Model{{ID: "flash", Name: "Flash"}}, []string{"flash|Flash", "fast|fast", "other|Other"}},
{"Azure", AzurePreset, nil, []string{"flash|flash", "fast|fast", "other|other"}},
} {
t.Run(c.name, func(t *testing.T) {
p := Provider{ID: "name-picks", Preset: c.preset, Models: []string{"flash", "fast", "other"}}
if err := catalog.SaveLive(p.ID, "", c.live); err != nil {
t.Fatal(err)
}
for _, reverse := range []bool{false, true} {
want := slices.Clone(c.want)
if reverse {
slices.Reverse(p.Models)
slices.Reverse(want)
}
var got []string
for _, m := range p.Exposed() {
got = append(got, m.ID+"|"+m.Name)
}
if strings.Join(got, "\n") != strings.Join(want, "\n") {
t.Errorf("got %v, want %v", got, want)
}
}
})
}
}
// Picking a subset must not refill names Available deliberately left as ids.
// Unlisted picks still reserve all listed names and ids, even if not picked.
func TestPickedNamesKeepListed(t *testing.T) {
home := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
if err := os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(catalog.CachePath(), []byte(`{"vendor":{"models":{
"flash":{"id":"flash","name":"Flash"},
"fast":{"id":"fast","name":"Flash"},
"alias":{"id":"alias","name":"listed-id"}
}}}`), 0o644); err != nil {
t.Fatal(err)
}
catalog.Reset()
t.Cleanup(catalog.Reset)
for _, c := range []struct {
name, providerID, catalog string
live []catalog.Model
picks, want []string
}{
{"collision fallback", "picked-collision", "vendor", []catalog.Model{{ID: "flash", Name: "flash"}, {ID: "fast", Name: "fast", Context: 1000000}}, []string{"fast"}, []string{"fast|fast"}},
{"Antigravity", "antigravity", "", []catalog.Model{{ID: "fast", Context: 1000000}}, []string{"fast"}, []string{"fast|fast"}},
{"listed name", "picked-name", "", []catalog.Model{{ID: "flash", Name: "Flash"}}, []string{"flash", "fast"}, []string{"flash|Flash", "fast|fast"}},
{"unpicked name", "unpicked-name", "", []catalog.Model{{ID: "flash", Name: "Flash"}}, []string{"fast"}, []string{"fast|fast"}},
{"listed id", "picked-id", "", []catalog.Model{{ID: "listed-id", Name: "Listed custom"}}, []string{"listed-id", "alias"}, []string{"listed-id|Listed custom", "alias|alias"}},
{"unpicked id", "unpicked-id", "", []catalog.Model{{ID: "listed-id", Name: "Listed custom"}}, []string{"alias"}, []string{"alias|alias"}},
} {
t.Run(c.name, func(t *testing.T) {
p := Provider{ID: c.providerID, Catalog: c.catalog, Models: slices.Clone(c.picks)}
if err := catalog.SaveLive(p.ID, "", c.live); err != nil {
t.Fatal(err)
}
before := p.Available()
for _, reverse := range []bool{false, true} {
want := slices.Clone(c.want)
if reverse {
slices.Reverse(p.Models)
slices.Reverse(want)
}
var got []string
for _, m := range p.Exposed() {
got = append(got, m.ID+"|"+m.Name)
for _, listed := range before {
if listed.ID == m.ID && !reflect.DeepEqual(m, listed) {
t.Errorf("listed model changed: %+v; Available gave %+v", m, listed)
}
}
}
if !slices.Equal(got, want) {
t.Errorf("got %v, want %v", got, want)
}
}
if after := p.Available(); !reflect.DeepEqual(after, before) {
t.Errorf("available list changed: %+v; was %+v", after, before)
}
})
}
}
+15 -8
View File
@@ -848,21 +848,28 @@ func (p Provider) Exposed() []catalog.Model {
byID[m.ID] = m
}
pick := func(ids []string) []catalog.Model {
out := make([]catalog.Model, 0, len(ids))
var unlisted []catalog.Model
for _, id := range ids {
if m, ok := byID[id]; ok {
out = append(out, m)
} else {
if _, ok := byID[id]; !ok {
// with the levels the gateway fits an effort to (Known),
// not the none effortsOf takes a vendor's word for: the
// vendor's list doesn't have it, so it gave no word (#597)
m := catalog.Model{ID: id, Name: id, Provider: p.firstCatalog(), Efforts: p.knownElsewhere(id)}
if !p.IsAzure() {
m = catalog.Named([]catalog.Model{m})[0]
}
out = append(out, m)
unlisted = append(unlisted, m)
}
}
if !p.IsAzure() {
// Available has already named the listed models. Reserve their
// names and ids without refilling ones it left as ids.
unlisted = catalog.Named(unlisted, avail...)
}
for _, m := range unlisted {
byID[m.ID] = m
}
out := make([]catalog.Model, 0, len(ids))
for _, id := range ids {
out = append(out, byID[id])
}
return out
}
picks := p.Models