catalog: a provider's model list names each model once (#6582)

elis_pina (LoveEcho1145) on X: some APIs list a model more than once in
their /models, and each copy was a row of its own. A provider asked at its
base already merged copies by id (Provider.fetchOne's add), but one asked at
the URL its list is at (ModelsURL), the add form's List, and every list
fetched another way (accounts, Azure, Kilo, Cline, decision lists) kept
them, in the pickers, /v1/models and the agents' lists.

catalog.Unique keeps each id once: the first copy in its place, with what
it leaves unsaid (a name other than the id, window, output, levels, price,
APIs, tiers, magpie_via, keys) taken from the copies after it, as the
lookups by id (LiveByID's callers) already took the first copy that said
it. It runs at the parse of every upstream /models (catalog.fetchOne, all
pages), at every save (saveLive: the list and each base's part, whoever
fetched it), and at every read (readLive), so a list saved before reads
each id once without waiting for a fetch. A list with no copies comes back
as it is. Plugins' lists are keyed by id in host.js already. Keyed by id
alone, as Provider.fetchOne and fetchPerKey merge already.

Tests: TestFetchedListNamesEachModelOnce, TestSavedListNamesEachModelOnce
(saved, sides, LiveByID, and a file written before with copies),
TestUniqueLeavesAListWithoutCopies, TestProviderListsEachModelOnce (at
base and at ModelsURL: Fetch, List, Available). Broken by hand: with
Unique returning its input, the first two and the ModelsURL case of the
last are red (Fetch/List/Available listed [gpt-5.6 glm-5.3 gpt-5.6
glm-5.3]); with readLive's Unique alone taken out, the saved-before case
is red.

Run on mica: gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags
nogui ./... ok; go test -timeout 45m ./... at b552edb12 (base 6af327e2b):
100 packages ok, internal/plugin red on TestCancelledSignInSavesNothing,
#5532 (filed, same tok-late output, passes -count=10 alone at this head).
Rebased on 87a0af212 (changes only gateway test files and LESSONS
since); at the pushed head internal/catalog and
internal/provider ok, linux/windows vet of both ok. No GUI file changed
and no API shape changed, so no GUI suite was run. Not tried: a real
vendor that lists copies (the reporter named none).
This commit is contained in:
yetone
2026-11-15 09:02:39 +08:00
parent 87a0af2126
commit 97e6ac36c9
4 changed files with 258 additions and 5 deletions
+12 -1
View File
@@ -206,7 +206,18 @@ A signed-in account's model list exists only at its vendor (the ChatGPT backend'
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.
A provider's fetched model list keeps the upstream ids and order. Display
A provider's fetched model list keeps the upstream ids and order, each id
once: a list that names a model more than once (#6582) keeps the first
copy, in its place, with what it leaves unsaid (a name other than the id,
window, output, levels, price, APIs, tiers, `magpie_via`, keys) taken from
the copies after it (`catalog.Unique`). It runs where every list passes:
the parse of an upstream `/models` (`fetchOne`, so the add form's `List`
too), every save (`saveLive`, the list and each base's part, whoever
fetched it), and every read, so a list saved before reads each id once
without a fetch (`readLive`). The pickers, `/v1/models` and the agents'
lists are built from those (`TestFetchedListNamesEachModelOnce`,
`TestSavedListNamesEachModelOnce`, `TestProviderListsEachModelOnce`). A
plugin's list is its plugin's, keyed by id there. 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
+89 -4
View File
@@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"math"
"net/http"
"net/url"
@@ -71,9 +72,13 @@ func readLive(provider string) (liveFile, error) {
return f, err
}
f.key = liveKey(b, f.Since != nil)
// a list saved before Unique was: each model once from its first
// read, not from its next fetch
f.Models = Unique(f.Models)
mendKinds(f.Models, f.Base)
for _, side := range f.Sides {
mendKinds(side, f.Base)
for b, side := range f.Sides {
f.Sides[b] = Unique(side)
mendKinds(f.Sides[b], f.Base)
}
f.byID = map[string][]Model{}
for _, m := range Chat(f.Models) {
@@ -154,7 +159,7 @@ func liveKey(b []byte, dropFetched bool) string {
}
// LiveByID are the models of Live with this id, in the list's order
// (a list may name one twice): what a look through Live finds, without
// (one since Unique; a slice for the callers that read it so): what a look through Live finds, without
// the list copied for each model asked about.
func LiveByID(provider, model string) []Model {
f, err := readLive(provider)
@@ -290,6 +295,76 @@ func Chat(ms []Model) []Model {
return out
}
// Unique is ms with each model id once (#6582: some APIs list a model
// more than once, and every copy was a row of its own in the pickers, the
// gateway's /v1/models and the agents' lists). The first keeps its place,
// and what it leaves unsaid is taken from the copies after it, as the
// lookups by id (LiveByID's callers) already took the first copy that
// said it: a name other than the id, a window, an output cap, levels, a
// price, the APIs, tiers, the magpies on its way and the keys that list
// it. ms comes back as it is when no id is in it twice.
func Unique(ms []Model) []Model {
if len(ms) < 2 {
return ms
}
at := make(map[string]int, len(ms))
dup := false
for _, m := range ms {
if _, ok := at[m.ID]; ok {
dup = true
break
}
at[m.ID] = 0
}
if !dup {
return ms
}
clear(at)
out := make([]Model, 0, len(ms))
for _, m := range ms {
i, ok := at[m.ID]
if !ok {
at[m.ID] = len(out)
out = append(out, m)
continue
}
k := &out[i]
if (k.Name == "" || k.Name == k.ID) && m.Name != "" {
k.Name = m.Name
}
if k.Context == 0 {
k.Context = m.Context
}
if k.Output == 0 {
k.Output = m.Output
}
if len(k.Efforts) == 0 {
k.Efforts = m.Efforts
}
if k.Price == nil {
k.Price = m.Price
}
if len(k.APIs) == 0 {
k.APIs = m.APIs
}
if len(k.Tiers) == 0 {
k.Tiers = m.Tiers
}
if len(k.Via) == 0 {
k.Via = m.Via
}
if k.ImageInput == nil && m.ImageInput != nil {
k.ImageInput, k.Images = m.ImageInput, m.Images
}
for _, key := range m.Keys {
if !slices.Contains(k.Keys, key) {
k.Keys = append(slices.Clip(k.Keys), key)
}
}
}
return out
}
// SaveLive stores a fetched list; an empty list forgets it.
func SaveLive(provider, base string, models []Model) error {
return saveLive(provider, base, "", models, nil)
@@ -370,6 +445,15 @@ func saveLive(provider, base, asked string, models []Model, sides map[string][]M
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
// each model once, in the list and in each endpoint's part (Unique),
// whichever way the list was fetched
models = Unique(models)
if sides != nil {
sides = maps.Clone(sides)
for b, ms := range sides {
sides[b] = Unique(ms)
}
}
now := time.Now()
f := liveFile{Fetched: now, Base: base, Models: models, Sides: sides, Kinded: true,
Since: liveSince(provider, models, now), Asked: asked}
@@ -703,7 +787,8 @@ func fetchOne(ctx context.Context, url, key string, anthropic bool, headers map[
if err != nil {
return nil, err
}
return out, nil
// a model the list (or its pages) names more than once is one model
return Unique(out), nil
}
// Paged asks a model list that pages for every page of itself: page asks
+99
View File
@@ -0,0 +1,99 @@
package catalog
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
)
func uniqueHome(t *testing.T) {
t.Helper()
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
}
func idsOf(ms []Model) []string {
out := make([]string, len(ms))
for i, m := range ms {
out[i] = m.ID
}
return out
}
// #6582: an API whose /models names a model twice gave it two rows. The
// list read is each id once, in the order first listed, and what the first
// copy leaves unsaid comes from the copy after it.
func TestFetchedListNamesEachModelOnce(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"object":"list","data":[{"id":"gpt-5.6"},{"id":"glm-5.3"},{"id":"gpt-5.6","context_length":400000},{"id":"glm-5.3"}]}`)
}))
t.Cleanup(srv.Close)
ms, err := FetchURL(context.Background(), srv.URL+"/v1/models", "k", false, nil)
if err != nil {
t.Fatal(err)
}
if got := idsOf(ms); len(got) != 2 || got[0] != "gpt-5.6" || got[1] != "glm-5.3" {
t.Fatalf("ids = %v, want [gpt-5.6 glm-5.3]", got)
}
if ms[0].Context != 400000 {
t.Errorf("gpt-5.6's window = %d, want the second copy's 400000", ms[0].Context)
}
}
// Every list saved, whoever fetched it (an account's, Azure's, Kilo's),
// and every list saved before the fix, is read with each id once.
func TestSavedListNamesEachModelOnce(t *testing.T) {
uniqueHome(t)
dup := []Model{{ID: "a", Name: "a"}, {ID: "b", Name: "B"}, {ID: "a", Name: "Model A", Keys: []string{"k2"}}}
if err := SaveLiveSides("saved", "https://x/v1", dup, map[string][]Model{"https://x/v1": dup}); err != nil {
t.Fatal(err)
}
ms, _, ok := Live("saved")
if !ok || len(ms) != 2 || ms[0].ID != "a" || ms[1].ID != "b" {
t.Fatalf("saved list = %v", idsOf(ms))
}
if ms[0].Name != "Model A" || len(ms[0].Keys) != 1 {
t.Errorf("a = %+v, want the second copy's name and key", ms[0])
}
sides, _, _ := LiveSplit("saved")
if got := idsOf(sides["https://x/v1"]); len(got) != 2 {
t.Errorf("side = %v, want each id once", got)
}
if n := len(LiveByID("saved", "a")); n != 1 {
t.Errorf("LiveByID(a) = %d models, want 1", n)
}
// a file written before Unique, with the copies in it
b, _ := json.Marshal(liveFile{Fetched: time.Now(), Base: "https://y/v1", Models: dup, Kinded: true})
p := LivePath("old")
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, b, 0o644); err != nil {
t.Fatal(err)
}
ms, _, ok = Live("old")
if !ok || len(ms) != 2 {
t.Fatalf("old list = %v, want each id once", idsOf(ms))
}
if all, _ := LiveAll("old"); len(all) != 2 {
t.Errorf("LiveAll = %v, want each id once", idsOf(all))
}
}
// A list with no id twice comes back as it is, not copied.
func TestUniqueLeavesAListWithoutCopies(t *testing.T) {
ms := []Model{{ID: "a"}, {ID: "b"}}
if got := Unique(ms); &got[0] != &ms[0] || len(got) != 2 {
t.Errorf("Unique copied a list with no copies: %v", idsOf(got))
}
}
+58
View File
@@ -0,0 +1,58 @@
package provider
import (
"context"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/yetone/magpie/internal/catalog"
)
// #6582: an API whose model list names a model twice. A provider asked at
// the URL its list is at (ModelsURL), as one asked at its base, lists each
// model once: in Fetch's answer, the add form's List and Available, which
// the pickers, /v1/models and the agents' lists are made from.
func TestProviderListsEachModelOnce(t *testing.T) {
isolateFetchHome(t)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"object":"list","data":[{"id":"gpt-5.6"},{"id":"glm-5.3"},{"id":"gpt-5.6"},{"id":"glm-5.3"}]}`)
}))
t.Cleanup(srv.Close)
for _, p := range []Provider{
{ID: "at-base", Name: "At base", Chat: srv.URL + "/v1", Key: "k"},
{ID: "at-url", Name: "At URL", Chat: srv.URL + "/v1", ModelsURL: srv.URL + "/v1/models", Key: "k"},
} {
if err := Save(p); err != nil {
t.Fatal(err)
}
q, err := Find(p.ID)
if err != nil {
t.Fatal(err)
}
once := func(what string, ms []catalog.Model) {
t.Helper()
if len(ms) != 2 || ms[0].ID != "gpt-5.6" || ms[1].ID != "glm-5.3" {
ids := []string{}
for _, m := range ms {
ids = append(ids, m.ID)
}
t.Errorf("%s %s = %v, want [gpt-5.6 glm-5.3]", p.ID, what, ids)
}
}
ms, err := q.Fetch(context.Background())
if err != nil {
t.Fatal(err)
}
once("Fetch", ms)
ls, err := q.List(context.Background())
if err != nil {
t.Fatal(err)
}
once("List", ls)
q, _ = Find(p.ID)
once("Available", q.Available())
}
}