Files
magpie/internal/gateway/bare_ids_test.go
T
yetone 7d6358ff6b gateway: /v1/models can list each model by its bare id too, for apps moved from another proxy (love1sbug on X)
love1sbug moved from CLIProxyAPI: their clients ask for gpt-5.6-sol, and
magpie's /v1/models gave only codex/gpt-5.6-sol. "Provider in model names"
(36ca5432d, 6fa3109ea, 250bdd5c4) changes labels in agents' lists, never
ids, so no setting changed what the list returned. A bare request already
routed (serve: GroupFor, then Resolve); only the list didn't offer it.

What changed
- settings.BareModelIDs, off by default; Settings › Network and sharing ›
  "Model ids without the provider" (en, zh, zh-TW, ja, de), posted on its
  own to POST /api/settings/bare-ids (the general settings save keeps it).
  Drawn in gateway mode too, where such apps are.
- On, /v1/models (and ?format=text) lists every row it listed before,
  unchanged and first, then one row per bare model id
  (provider.BareEntries): the row of the entry that id reaches, its label
  that one's. GET /v1/models/{id} answers a bare id the same way.
- Which entry is decided by the gateway's own resolution (groupForIn, the
  GroupFor loop now shared; then resolveIn), so the list never offers what
  a request wouldn't reach: a model several providers serve is listed once
  and goes to its found group (found groups on) or the first provider in
  the Providers order (off), exactly as a bare request did before. An id
  already a catalog id isn't listed twice.
- The target must be in the shown list, so a gateway key held to some
  models sees only bare ids that reach them. Never listed for another
  magpie (DrawersHeader), whose remote provider would list each twice, nor
  in Claude Desktop's list.
- No agent file changes: magpie still writes provider/model ids, so the
  switch rewrites nothing and nobody who hasn't turned it on sees a change.
- docs/subsystems/gateway-routing.md: a section and verification lines.

What was run
- go test -tags nogui ./internal/gateway -run TestBareModelIDs: the
  reporter's case (a Codex provider with gpt-5.6-sol listed as
  gpt-5.6-sol, then asked for it on chat, responses and messages against a
  fake ChatGPT backend that saw gpt-5.6-sol; off, the list is byte-equal
  to before) and several providers with found groups on and off, a held
  key, another magpie. Both go red with the listing disabled by hand.
- go test -tags nogui ./internal/gui -run 'TestBareModelIDsSetting|TestSettingsSave'.
- node --test internal/gui/tests/bare-ids.test.cjs (playwright 1.62.0):
  Chromium and WebKit, 420px (gateway mode) and 900px, all five languages,
  20/20; i18n-keys.test.cjs passes.
- gofmt -l clean; go vet ./... (darwin), go vet -tags nogui ./... on
  darwin, GOOS=linux, GOOS=windows clean.
- go test -tags nogui ./internal/provider ./internal/gateway ./internal/gui
  ./internal/settings ./internal/cli ./internal/agent -timeout 40m,
  rebased on origin/main 06ff45fed: all six ok (gateway 533s, agent 460s,
  the machine at load ~130; the default 10m ran out on wall time in an
  earlier run, the test then running 1s in, nothing failed). Before the
  rebase agent's TestFolderVarsAreListed was red on REASONIX_STATE_HOME,
  fixed upstream by 24146c031.
- After the rebase (a conflict with #1914's tiers for every client, kept;
  a bare row carries its source row's tiers): gofmt, vet on all three, and
  bare-ids, i18n-keys, plain-names, gateway-port .test.cjs, 31/31.
- Rebased again on 9b52fb504 (side efforts touched settings, api.go,
  app.js, i18n.js; a doc table conflict, upstream's rows kept): gofmt, go
  vet ./... and -tags nogui on linux and windows, go test ./internal/gui
  ./internal/settings, gateway -run 'TestBareModelIDs|TestModels|
  TestCodexTiers|TestSideEffort', and bare-ids, i18n-keys, side-effort
  .test.cjs 31/31.

Not tried: a real CLIProxyAPI client against a live gateway, or the
reporter's own setup; no CLI command for the switch (Settings only).
2026-10-13 16:55:27 +08:00

202 lines
7.3 KiB
Go

package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
)
// listedIDs is /v1/models' ids, in order, as the request r is answered.
func listedIDs(t *testing.T, r *http.Request) []string {
t.Helper()
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, r)
var l struct {
Data []struct {
ID string `json:"id"`
OwnedBy string `json:"owned_by"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &l); err != nil {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
var ids []string
for _, m := range l.Data {
ids = append(ids, m.ID)
}
return ids
}
// love1sbug on X, moving from CLIProxyAPI: the old clients ask for
// gpt-5.6-sol and pick from /v1/models, and magpie listed only
// codex/gpt-5.6-sol, whatever Names in agents' lists said. With Model ids
// without the provider on, the list has gpt-5.6-sol too, after the
// provider/model ids it had, and a request for it on each API reaches the
// Codex account as gpt-5.6-sol. Off, as by default, the list is as it was.
func TestBareModelIDsReporterCase(t *testing.T) {
codexSignedIn(t)
var mu sync.Mutex
var asked []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
asked = append(asked, modelOf(b))
mu.Unlock()
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.6-sol"}}`,
`data: {"type":"response.output_text.delta","delta":"pong"}`,
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`))
}))
t.Cleanup(up.Close)
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
if err := provider.Save(provider.Provider{ID: "codex", Models: []string{"gpt-5.6-sol"}}); err != nil {
t.Fatal(err)
}
list := func() []string { return listedIDs(t, httptest.NewRequest("GET", "/v1/models", nil)) }
before := list()
if !slices.Contains(before, "codex/gpt-5.6-sol") || slices.Contains(before, "gpt-5.6-sol") {
t.Fatalf("off, as by default: %v", before)
}
if err := provider.SetBareModelIDs(true); err != nil {
t.Fatal(err)
}
after := list()
if !slices.Equal(after[:len(before)], before) || !slices.Contains(after[len(before):], "gpt-5.6-sol") {
t.Fatalf("on: %v, want %v and then gpt-5.6-sol", after, before)
}
// the text list a client takes its models from has it too
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models?format=text", nil))
if !slices.Contains(strings.Split(rec.Body.String(), "\n"), "gpt-5.6-sol") {
t.Fatalf("text list %q", rec.Body.String())
}
// and one model looked up by it
rec = httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models/gpt-5.6-sol", nil))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"id":"gpt-5.6-sol"`) {
t.Fatalf("GET /v1/models/gpt-5.6-sol: %d %s", rec.Code, rec.Body.String())
}
for _, c := range []struct{ path, body string }{
{"/v1/chat/completions", `{"model":"gpt-5.6-sol","messages":[{"role":"user","content":"hi"}]}`},
{"/v1/responses", `{"model":"gpt-5.6-sol","input":"hi"}`},
{"/v1/messages", `{"model":"gpt-5.6-sol","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`},
} {
asked = nil
req := httptest.NewRequest("POST", c.path, strings.NewReader(c.body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "python-requests/2.31") // a client magpie doesn't know, as CLIProxyAPI's are
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, req)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "pong") || rec.Header().Get("X-Magpie-Provider") != "codex" {
t.Fatalf("%s: %d by %q %s", c.path, rec.Code, rec.Header().Get("X-Magpie-Provider"), rec.Body.String())
}
if !slices.Equal(asked, []string{"gpt-5.6-sol"}) {
t.Fatalf("%s asked the backend for %v", c.path, asked)
}
}
if err := provider.SetBareModelIDs(false); err != nil {
t.Fatal(err)
}
if got := list(); !slices.Equal(got, before) {
t.Fatalf("off again: %v, want %v", got, before)
}
}
// Two providers serving one bare id list it once, and a request for it
// goes where magpie sends a bare id: the group it found for it, first
// member first, or with found groups off the first provider in the
// Providers order; the listed row is where that is. A gateway key is
// listed a bare id only where its request would be served, another magpie
// none (its provider would list each model twice), and an id that names a
// provider of the user's ("vendor/m9") isn't listed bare.
func TestBareModelIDsShared(t *testing.T) {
fresh(t)
fakes := map[string]*fake{}
for _, p := range []provider.Provider{
{ID: "a", Name: "A", Key: "k", Models: []string{"glm-5.3", "only-a"}},
{ID: "b", Name: "B", Key: "k", Models: []string{"glm-5.3", "only-b", "vendor/m9"}},
{ID: "vendor", Name: "Vendor", Key: "k", Models: []string{"m1"}},
} {
f := &fake{t: t, ctype: "application/json", reply: `{"id":"from-` + p.ID + `","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}`}
fakes[p.ID] = f
up := httptest.NewServer(f)
t.Cleanup(up.Close)
p.Chat = up.URL + "/v1"
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
if err := provider.SetBareModelIDs(true); err != nil {
t.Fatal(err)
}
keys, secrets := newCaller(t, "Held")
if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"b/*"}}); err != nil {
t.Fatal(err)
}
get := func(secret string, magpie bool) []string {
r := httptest.NewRequest("GET", "/v1/models", nil)
if secret != "" {
r.Header.Set("Authorization", "Bearer "+secret)
}
if magpie {
r.Header.Set(provider.DrawersHeader, "1")
}
return listedIDs(t, r)
}
bare := func(ids []string) []string {
var out []string
for _, id := range ids {
if !strings.Contains(id, "/") || id == "vendor/m9" {
out = append(out, id)
}
}
slices.Sort(out)
return out
}
chat := func(model string) string {
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions",
strings.NewReader(`{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`)))
if rec.Code != 200 {
t.Fatalf("%s: %d %s", model, rec.Code, rec.Body.String())
}
return rec.Header().Get("X-Magpie-Provider")
}
for _, found := range []bool{true, false} {
if err := provider.SetAutoGroups(found); err != nil {
t.Fatal(err)
}
if got, want := bare(get("", false)), []string{"glm-5.3", "m1", "only-a", "only-b"}; !slices.Equal(got, want) {
t.Fatalf("found groups %v: bare ids %v, want %v", found, got, want)
}
if by := chat("glm-5.3"); by != "a" {
t.Fatalf("found groups %v: glm-5.3 answered by %q, want a, first in the Providers order", found, by)
}
if by := chat("only-b"); by != "b" {
t.Fatalf("only-b answered by %q", by)
}
}
if got := bare(get("", true)); len(got) != 0 {
t.Fatalf("another magpie was listed bare ids %v", got)
}
// held to b/*: glm-5.3 bare reaches a first, which the key may not use
if got, want := bare(get(secrets[0], false)), []string{"only-b"}; !slices.Equal(got, want) {
t.Fatalf("held key's bare ids %v, want %v", got, want)
}
}