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).
This commit is contained in:
yetone
2026-10-13 16:55:27 +08:00
parent 9b52fb504a
commit 7d6358ff6b
14 changed files with 621 additions and 4 deletions
File diff suppressed because one or more lines are too long
+201
View File
@@ -0,0 +1,201 @@
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)
}
}
+27 -2
View File
@@ -872,8 +872,25 @@ func (s *Server) models(w http.ResponseWriter, r *http.Request) {
// shows its Fast switch on a model whose tiers hold priority
// (#1914). A model with none says nothing
tiers := codexTiers(shown)
for i, e := range shown {
// each model by its bare id as well, after the provider/model ids,
// when the user asked for it (settings.BareModelIDs): a client
// moved from another proxy asks for gpt-5.6-sol (love1sbug on X).
// Never for another magpie, whose provider would list each twice.
// Each row is the entry the bare id reaches, its label that one's.
rows, ids := slices.Clip(shown), map[int]string{}
if !magpie && provider.BareModelIDs() {
labels = slices.Clip(labels)
for _, b := range provider.BareEntries(shown) {
ids[len(rows)] = b.ID
rows = append(rows, shown[b.Of])
labels = append(labels, labels[b.Of])
}
}
for i, e := range rows {
m := modelObject(e)
if id, ok := ids[i]; ok {
m["id"] = id
}
if magpie {
if how := webSearchOf(e, searches); how != "" {
m["web_search"] = how
@@ -939,12 +956,20 @@ func (s *Server) models(w http.ResponseWriter, r *http.Request) {
func (s *Server) model(w http.ResponseWriter, r *http.Request) {
id := unprefixed(r.PathValue("id"))
for _, e := range keyAllowed(r, provider.Catalog()) {
shown := keyAllowed(r, provider.Catalog())
for _, e := range shown {
if e.ID == id {
writeJSON(w, 200, modelObject(e))
return
}
}
// by its bare id, as the list gives it with that setting on
if provider.BareModelIDs() {
if e, ok := provider.BareEntry(shown, id); ok {
writeJSON(w, 200, modelObject(e))
return
}
}
writeError(w, provider.Chat, 404, "unknown model "+id)
}
+15
View File
@@ -1179,6 +1179,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
in.UsageAgentsHidden = cur.UsageAgentsHidden
// how agents' lists name models, set on its own for the agents to be told
in.PlainNames, in.PlainOwnNames = cur.PlainNames, cur.PlainOwnNames
in.BareModelIDs = cur.BareModelIDs // set on its own (bare-ids below)
in.CodexAgentsV1 = cur.CodexAgentsV1
in.FullContext = cur.FullContext // set on its own (full-context below)
in.CompactAt = cur.CompactAt // and so is the threshold
@@ -1365,6 +1366,20 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
}
writeJSON(rw, settingsState())
})
// whether the gateway's /v1/models lists each model by its id without
// the provider as well (settings.BareModelIDs, love1sbug on X)
mux.HandleFunc("POST /api/settings/bare-ids", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ On bool }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
if err := provider.SetBareModelIDs(in.On); err != nil {
fail(rw, err)
return
}
writeJSON(rw, settingsState())
})
// whether Codex's OpenAI models say multi-agent V1 (#141): Codex's lists
// are written again and asked for again
mux.HandleFunc("POST /api/settings/codex-agents-v1", func(rw http.ResponseWriter, r *http.Request) {
+11
View File
@@ -21236,6 +21236,7 @@ function renderSettings() {
renderDiscovery(s);
renderOTel(s, keep);
renderPort(s);
renderBareIds(s);
renderLAN(s);
renderAllow(s);
renderCORS(s);
@@ -23309,6 +23310,16 @@ function renderPort(s) {
box.replaceChildren(r); // swapped whole: the list is never laid out empty
}
// renderBareIds: Model ids without the provider (settings.bareModelIDs,
// love1sbug on X, moving from CLIProxyAPI): the gateway's /v1/models
// lists each model by its own id as well, gpt-5.6-sol beside
// codex/gpt-5.6-sol. Posted on its own; off by default.
function renderBareIds(s) {
$("#bareIdsSegs").replaceChildren(segs([[false, t("Off")], [true, t("On")]], !!s.bareModelIDs, (on) =>
writingPrefs(api("settings/bare-ids", { on })).then((ns) => { prefs = state.settings = ns; renderSettings(); })
.catch((e) => { status(t(e.message), "err"); renderSettings(); })));
}
// renderCORS: the web pages whose scripts may call the gateway from a
// browser (#1051), by origin — a row to add one, and one row each to take
// it away. A page listed calls with a gateway key; none listed, no page
+8
View File
@@ -2977,6 +2977,8 @@ const I18N = {
// the Settings page's parts, a tab each
"General": "常规",
"Network and sharing": "网络与共享",
"Model ids without the provider": "不带供应商的模型 ID",
"The gateway’s model list also names each model by its own id, as gpt-5.6-sol beside codex/gpt-5.6-sol, for apps moved from another proxy. One that several providers serve goes to them in the Providers order": "网关的模型列表还会以模型自己的 ID 列出每个模型,如 codex/gpt-5.6-sol 旁的 gpt-5.6-sol,供从其他代理迁来的应用使用。多个供应商都提供的模型,按“供应商”中的顺序发往它们",
"Session terminal": "会话终端",
"The terminal a session opens in": "打开会话时使用的终端",
"System default ({name})": "系统默认({name})",
@@ -7641,6 +7643,8 @@ const I18N = {
"Preferences": "偏好",
"General": "常規",
"Network and sharing": "網路與共享",
"Model ids without the provider": "不帶供應商的模型 ID",
"The gateway’s model list also names each model by its own id, as gpt-5.6-sol beside codex/gpt-5.6-sol, for apps moved from another proxy. One that several providers serve goes to them in the Providers order": "閘道的模型列表還會以模型自己的 ID 列出每個模型,如 codex/gpt-5.6-sol 旁的 gpt-5.6-sol,供從其他代理遷來的應用使用。多個供應商都提供的模型,按「供應商」中的順序發往它們",
"Session terminal": "會話終端機",
"The terminal a session opens in": "開啟會話時使用的終端機",
"System default ({name})": "系統預設({name})",
@@ -12314,6 +12318,8 @@ const I18N = {
"Preferences": "環境設定",
"General": "一般",
"Network and sharing": "ネットワークと共有",
"Model ids without the provider": "プロバイダなしのモデル ID",
"The gateway’s model list also names each model by its own id, as gpt-5.6-sol beside codex/gpt-5.6-sol, for apps moved from another proxy. One that several providers serve goes to them in the Providers order": "ゲートウェイのモデル一覧に、各モデルを自身の ID でも載せます(codex/gpt-5.6-sol の隣に gpt-5.6-sol)。ほかのプロキシから移ってきたアプリ向けです。複数のプロバイダが提供するモデルは「プロバイダ」の順に送られます",
"Session terminal": "セッション用ターミナル",
"The terminal a session opens in": "セッションを開くターミナル",
"System default ({name})": "システムのデフォルト({name})",
@@ -16987,6 +16993,8 @@ const I18N = {
"Preferences": "Einstellungen",
"General": "Allgemein",
"Network and sharing": "Netzwerk und Freigabe",
"Model ids without the provider": "Modell-IDs ohne Anbieter",
"The gateway’s model list also names each model by its own id, as gpt-5.6-sol beside codex/gpt-5.6-sol, for apps moved from another proxy. One that several providers serve goes to them in the Providers order": "Die Modellliste des Gateways nennt jedes Modell auch bei seiner eigenen ID, etwa gpt-5.6-sol neben codex/gpt-5.6-sol, für Apps, die von einem anderen Proxy kommen. Ein Modell, das mehrere Anbieter bereitstellen, geht an sie in der Reihenfolge unter Anbieter",
"Session terminal": "Sitzungs-Terminal",
"The terminal a session opens in": "Das Terminal, in dem eine Sitzung öffnet",
"System default ({name})": "Systemstandard ({name})",
+6
View File
@@ -492,6 +492,12 @@
<div class="list prefs" id="githubList"></div>
<div class="row-head"><span class="label" data-t>Gateway</span></div>
<div class="list prefs" id="portList"></div>
<div class="list prefs">
<div class="row pref" id="bareIdsRow">
<div class="who"><div class="name" data-t>Model ids without the provider</div><div class="sub" data-t>The gateway’s model list also names each model by its own id, as gpt-5.6-sol beside codex/gpt-5.6-sol, for apps moved from another proxy. One that several providers serve goes to them in the Providers order</div></div>
<div id="bareIdsSegs"></div>
</div>
</div>
<div class="row-head"><span class="label" data-t>Local network</span></div>
<div class="list prefs" id="lanList"></div>
<div class="list prefs" id="allowList"></div>
+42
View File
@@ -0,0 +1,42 @@
package gui
import (
"encoding/json"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/settings"
)
// Settings › Network and sharing › Model ids without the provider posts
// settings/bare-ids on its own (love1sbug on X): it is saved, the page is
// answered the settings with it, and off saves it off again.
func TestBareModelIDsSetting(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
for _, on := range []bool{true, false} {
rec := httptest.NewRecorder()
body := `{"on":false}`
if on {
body = `{"on":true}`
}
Handler(nil, nil).ServeHTTP(rec, httptest.NewRequest("POST", "/api/settings/bare-ids", strings.NewReader(body)))
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
var got struct {
BareModelIDs bool `json:"bareModelIDs"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if got.BareModelIDs != on || settings.Load().BareModelIDs != on {
t.Fatalf("on %v: answered %v, saved %v", on, got.BareModelIDs, settings.Load().BareModelIDs)
}
}
}
+1
View File
@@ -148,6 +148,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
UsageAgentsHidden: []string{"curl"},
PlainNames: true,
PlainOwnNames: true,
BareModelIDs: true,
CodexAgentsV1: true,
CodexTitles: "off",
CodexDescriptions: "fake/m1",
+7
View File
@@ -560,6 +560,13 @@ then it post `settings/plain-names` with `mode: "on"` and `mode: "own"`,
neither click scrolls the page, the hint isn't cut short and the three fit
the row at 900px and 560px. English and Chinese, Chromium and WebKit.
`bare-ids.test.cjs` checks Settings › Network and sharing › "Model ids
without the provider" (love1sbug on X): off by default, On posts
`settings/bare-ids` with `on: true` on its own and lights On, Off posts it
back, neither click scrolls the page, the row is drawn in gateway mode, and
nothing runs out of the row or the page sideways at 420px and 900px. Every
language, Chromium and WebKit.
`routing-steady.test.cjs` scrolls the Routing page down to its routing groups,
opens one in its editor and types into its name, then streams six requests in
from the trace (new agents and accounts on the stage, failures and retries in
+140
View File
@@ -0,0 +1,140 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Settings › Network and sharing › Model ids without the provider (love1sbug
// on X: apps moved from CLIProxyAPI ask for gpt-5.6-sol, and magpie's
// /v1/models only gave codex/gpt-5.6-sol): off by default; On posts
// settings/bare-ids on its own and lights On, Off posts it back, and neither
// click scrolls the Settings page. The row is drawn in gateway mode too,
// which is where such apps are. Every language, Chromium and WebKit, at a
// narrow and a wide window; no backend, the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { watchSettingsReads, settingsDrawn } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
function settingsPayload(over) {
return {
theme: "light", lang: "en", tray: "panel", quotaLeft: false, currency: "usd",
dock: false, dockWindow: false, proxy: "", redact: false, redactPersonal: false, redactWords: [],
codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "", workbuddyCheckin: false, noStats: false,
trayUsage: "", trayUsageEvery: 3, vision: "", imageGen: "",
version: "0.1.1220", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425",
proxyNow: "none", proxySource: "none", login: false,
visionModels: [], imageGenModels: [], workbuddyCheckins: [], lan: false, lanURLs: [],
fx: { rate: 7.2, at: new Date().toISOString(), stale: false },
...over,
};
}
// gateway: magpie as a gateway alone (magpie web with no agents here), as
// gateway-mode.test.cjs fakes it
function server(lang, gateway, posted) {
let cur = settingsPayload({ lang, ...(gateway ? { web: true, gatewayMode: "on", gatewayOn: true } : {}) });
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${gateway}${gateway ? ",gateway:true" : ""}};` });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/window/fit") return route.fulfill({ status: 204 });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, fx: cur.fx });
if (url.pathname === "/api/settings/bare-ids") {
const body = req.postDataJSON();
posted.push(["bare-ids", body]);
cur = { ...cur, bareModelIDs: body.on };
return json(cur);
}
if (url.pathname === "/api/settings") {
if (req.method() === "POST") posted.push(["settings", req.postDataJSON()]);
return json(cur);
}
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const want = {
en: { name: "Model ids without the provider", off: "Off", on: "On", sub: "gpt-5.6-sol beside codex/gpt-5.6-sol" },
zh: { name: "不带供应商的模型 ID", off: "关闭", on: "开启", sub: "codex/gpt-5.6-sol 旁的 gpt-5.6-sol" },
"zh-TW": { name: "不帶供應商的模型 ID", off: "關閉", on: "開啟", sub: "codex/gpt-5.6-sol 旁的 gpt-5.6-sol" },
ja: { name: "プロバイダなしのモデル ID", off: "オフ", on: "オン", sub: "codex/gpt-5.6-sol の隣に gpt-5.6-sol" },
de: { name: "Modell-IDs ohne Anbieter", off: "Aus", on: "An", sub: "gpt-5.6-sol neben codex/gpt-5.6-sol" },
};
const view = (page) => page.locator("#view-settings").evaluate((v) => v.scrollTop);
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const width of [420, 900]) {
for (const lang of Object.keys(want)) {
test(`${engine} ${width} ${lang}: the gateway lists bare model ids, or not`, async (t) => {
const w = want[lang];
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const context = await browser.newContext({ viewport: { width, height: 420 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(5000);
const errors = [], posted = [];
page.on("pageerror", (e) => errors.push(e.message));
// gateway mode on the narrow one: the row is the gateway's, not an
// agent file's, so it stays where agent-file rows are hidden
const gateway = width === 420;
await page.route("**/*", server(lang, gateway, posted));
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${width}-${lang}-bare-ids.png`) });
}
await browser.close();
});
await watchSettingsReads(page);
await page.goto("http://magpie.test/?view=settings&tab=network");
await settingsDrawn(page);
const segs = page.locator("#bareIdsSegs .opt");
await segs.first().waitFor();
const row = page.locator("#bareIdsRow");
assert.equal(await page.locator("#codexTitlesRow").evaluate((r) => r.hidden), gateway, "gateway mode as faked");
assert(await row.isVisible(), "the row is drawn");
assert.equal((await row.locator(".name").textContent()).trim(), w.name);
assert((await row.locator(".sub").textContent()).includes(w.sub), "the sub says what it does");
assert.deepEqual((await segs.allTextContents()).map((s) => s.trim()), [w.off, w.on]);
assert.equal(await segs.nth(0).evaluate((b) => b.classList.contains("on")), true, "off by default");
assert.equal(await page.locator("#bareIdsRow select").count(), 0, "no native select");
const border = await row.evaluate((r) => getComputedStyle(r).borderLeftWidth);
assert(border === "0px" || border === "", "no left border accent: " + border);
// nothing wider than the window at the narrow width
assert(await page.locator("#view-settings").evaluate((v) => v.scrollWidth <= v.clientWidth + 1), "the settings scroll sideways");
const rb = await row.boundingBox(), sb = await page.locator("#bareIdsSegs").boundingBox();
assert(sb.x + sb.width <= rb.x + rb.width + 1, "the switch runs out of its row");
// scrolled by a wheel till the row is mid-view, On moves nothing and
// is posted on its own
const box = await page.locator("#view-settings").boundingBox();
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
const top = () => page.locator("#bareIdsSegs").evaluate((e) => e.getBoundingClientRect().top);
for (let i = 0; i < 40 && (await top()) > 200; i++) { await page.mouse.wheel(0, 100); await page.waitForTimeout(30); }
await page.waitForTimeout(300);
const before = await view(page);
assert(before > 0, "the settings list must scroll to the row");
await segs.nth(1).click();
await page.locator("#bareIdsSegs .opt.on", { hasText: w.on }).waitFor();
await page.waitForTimeout(400);
assert.equal(await view(page), before, "the click scrolled the page");
assert.deepEqual(posted, [["bare-ids", { on: true }]]);
// back off
await segs.nth(0).click();
await page.locator("#bareIdsSegs .opt.on", { hasText: w.off }).waitFor();
assert.deepEqual(posted.at(-1), ["bare-ids", { on: false }]);
assert.equal(posted.length, 2);
assert.equal(await view(page), before, "the click scrolled the page");
assert.deepEqual(errors, []);
});
}
}
}
+110
View File
@@ -0,0 +1,110 @@
package provider
import (
"strings"
"github.com/yetone/magpie/internal/settings"
)
// Model ids without the provider (settings.BareModelIDs; love1sbug on X):
// a client moved from another proxy (CLIProxyAPI) asks for gpt-5.6-sol,
// not codex/gpt-5.6-sol, and picks its model from /v1/models. The gateway
// has always taken a bare id (GroupFor, then Resolve); with the setting on,
// /v1/models lists each model by its bare id as well, after the
// provider/model ids, which stay as they were. Off by default: a list
// nobody asked to grow keeps its ids.
//
// A bare id is listed only where a request for it goes, as the gateway
// routes it: two providers' gpt-5.6-sol is one row, the routing group magpie
// found for it (its members in the Providers order, failed over between),
// or with found groups off the first provider in the Providers order. A
// bare id that is a catalog id already, or that the gateway would take to
// a model the list doesn't show (a gateway key held to other models, an
// id like anthropic/claude-x that names a provider of the user's), isn't
// listed by it.
// BareModelIDs says whether /v1/models lists models by their bare ids too.
func BareModelIDs() bool { return settings.Load().BareModelIDs }
// SetBareModelIDs turns settings.BareModelIDs on or off. The list is built
// for each request, so the next one has the bare ids, or goes without
// them; no agent's file names a model by one, so none is written again.
func SetBareModelIDs(on bool) error {
s := settings.Load()
if s.BareModelIDs == on {
return nil
}
s.BareModelIDs = on
return settings.Save(s)
}
// Bare is a row a list adds for a bare id: ID, and Of, the index in the
// list of the entry a request for it reaches.
type Bare struct {
ID string
Of int
}
// BareEntries are the rows a list of shown adds for the bare ids, in the
// order the models first appear in shown, each once.
func BareEntries(shown []Entry) []Bare {
defer Hold()()
ids := make(map[string]bool, len(shown))
for _, e := range shown {
ids[e.ID] = true
}
entries := providerEntries()
all := groupsIn(entries)
var out []Bare
seen := map[string]bool{}
for _, e := range shown {
m := e.Model
if e.Group != "" || m == "" || seen[m] || ids[m] {
continue
}
seen[m] = true
if i := bareTarget(shown, all, entries, m); i >= 0 {
out = append(out, Bare{ID: m, Of: i})
}
}
return out
}
// bareTarget is the index in shown of the entry a request for the bare id
// reaches: the routing group GroupFor gives it, else the provider's model
// Resolve does; -1 when shown has neither.
func bareTarget(shown []Entry, all []Group, entries []Entry, id string) int {
if !strings.Contains(id, "/") {
if gid, ok := groupForIn(all, id); ok {
for i, e := range shown {
if e.ID == gid {
return i
}
}
return -1
}
}
p, model, ok := resolveIn(entries, id)
if !ok {
return -1
}
for i, e := range shown {
if e.Group == "" && e.Provider.ID == p.ID && e.Model == model {
return i
}
}
return -1
}
// BareEntry is the entry of shown a client asking for a model by its bare
// id is told of (GET /v1/models/{id}), its ID the bare id.
func BareEntry(shown []Entry, id string) (Entry, bool) {
for _, b := range BareEntries(shown) {
if b.ID == id {
e := shown[b.Of]
e.ID = id
return e, true
}
}
return Entry{}, false
}
+5 -1
View File
@@ -611,7 +611,11 @@ func GroupFor(id string) (string, bool) {
if id == "" || strings.Contains(id, "/") {
return "", false
}
all := Groups()
return groupForIn(Groups(), id)
}
// groupForIn is GroupFor over the groups all, read once for many ids.
func groupForIn(all []Group, id string) (string, bool) {
k := Slug(sameModel(id))
for _, gid := range []string{strings.ToLower(id), k, "auto-" + k} {
if g, ok := groupOf(all, gid); ok {
+5
View File
@@ -352,6 +352,11 @@ type Settings struct {
// it (#92: "Opus 5.5", not "Opus 5.5 · Claude Code"), the vendor's names
// keeping their provider's after them (see provider.Labels).
PlainOwnNames bool `json:"plainOwnNames,omitempty"`
// BareModelIDs has the gateway's /v1/models list each model by its id
// without the provider as well ("gpt-5.6-sol" beside
// "codex/gpt-5.6-sol"), for clients moved from another proxy that ask
// for bare ids (love1sbug on X; provider.BareEntries). Off by default.
BareModelIDs bool `json:"bareModelIDs,omitempty"`
// CodexAgentsV1 has the OpenAI models magpie hands Codex — the ChatGPT
// account's own, their codex/ ids and the groups one is in — say
// multi_agent_version "v1" (#141): their subagents are then handed