From 7d6358ff6bc3f06237dbfc0b6b3412e63d2963a7 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 13 Oct 2026 16:40:01 +0800 Subject: [PATCH] gateway: /v1/models can list each model by its bare id too, for apps moved from another proxy (love1sbug on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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). --- docs/subsystems/gateway-routing.md | 44 +++++- internal/gateway/bare_ids_test.go | 201 +++++++++++++++++++++++++++ internal/gateway/gateway.go | 29 +++- internal/gui/api.go | 15 ++ internal/gui/assets/app.js | 11 ++ internal/gui/assets/i18n.js | 8 ++ internal/gui/assets/index.html | 6 + internal/gui/bare_ids_test.go | 42 ++++++ internal/gui/settings_keep_test.go | 1 + internal/gui/tests/README.md | 7 + internal/gui/tests/bare-ids.test.cjs | 140 +++++++++++++++++++ internal/provider/bare.go | 110 +++++++++++++++ internal/provider/group.go | 6 +- internal/settings/settings.go | 5 + 14 files changed, 621 insertions(+), 4 deletions(-) create mode 100644 internal/gateway/bare_ids_test.go create mode 100644 internal/gui/bare_ids_test.go create mode 100644 internal/gui/tests/bare-ids.test.cjs create mode 100644 internal/provider/bare.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 52d34afae..3ae87670b 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -17,7 +17,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). | --- | --- | --- | | Address and caller | `DefaultAddr`. The local token `magpie` and the per-agent `magpie-` (`TokenFor`). `agentOf` tells which agent asked, first by token, then by User-Agent. | [`gateway.go`](../../internal/gateway/gateway.go) | | HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. `null` and other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost`, `*.localhost`, a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`; the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | -| Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) | +| Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) | | Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576). So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) | | Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace` or `weight` (`weightedFirst`). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `wrrMove`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/provider/routing.go`](../../internal/provider/routing.go) | | Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`), counting each for a second more (`rpmSlack`), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks, and every account of it keeps them, those on beside the first as well (`withPicks`, called by `All` and `AlsoOn`; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | @@ -456,6 +456,46 @@ Nothing is disabled by default. `TestModelDisableCmd`, `TestDisabledModelsSetting`, and `internal/gui/tests/disabled-models.test.cjs`. +## Model ids without the provider + +A client moved from another proxy (love1sbug on X, from CLIProxyAPI) keeps +asking for `gpt-5.6-sol`, and picks from `/v1/models`, where magpie lists +only `codex/gpt-5.6-sol`. A bare request already routes (Model resolution, +above); the list didn't offer it. "Provider in model names" (`PlainNames`) +changes labels only, never ids. + +Settings › Network and sharing › Model ids without the provider, +`POST /api/settings/bare-ids` (`settings.BareModelIDs`, +`provider.SetBareModelIDs`), off by default. On, `models` lists every row +it listed before, unchanged and first, then one row per bare model id +(`provider.BareEntries`, [`internal/provider/bare.go`](../../internal/provider/bare.go)): +the row of the entry that id reaches, with its label, under the bare id. +`GET /v1/models/{id}` answers a bare id the same way (`provider.BareEntry`). + +- Which entry: the gateway's own resolution, so the list never offers what + a request would not reach. A found or user group the id names (`groupForIn`, + as `GroupFor`) gives the group's row; else `resolveIn` (as `Resolve`) + gives the first provider in the Providers order that serves it. So a model + several providers serve is listed once, and answered by its group with + found groups on, else by the first provider, as before. +- An id already in the catalog as is (a group's or a provider's own id) is + not listed twice. Group rows themselves add nothing. +- The target must be in the list shown: a gateway key held to some models + sees only the bare ids that reach one of its models, so a key held to + `b/*` doesn't see `glm-5.3` that would go to `a`. +- Never for another magpie (`DrawersHeader`), whose remote provider would + list each model twice, nor for Claude Desktop's list, which has its own + shape. +- No agent file changes: magpie still writes `provider/model` ids + (`magpieModels`), so turning it on or off rewrites nothing. +- Tests: `TestBareModelIDsReporterCase` (Codex `gpt-5.6-sol` listed bare and + answered on Chat, Responses and Messages, the list unchanged when off), + `TestBareModelIDsShared` (several providers, found groups on and off, a + held key, another magpie) in + [`bare_ids_test.go`](../../internal/gateway/bare_ids_test.go), + `TestBareModelIDsSetting` in `internal/gui`, and + `internal/gui/tests/bare-ids.test.cjs`. + ## Verification ```sh @@ -463,6 +503,8 @@ go test -tags nogui ./internal/gateway -run 'TestGroupAsksOneRestingMemberNotEac go test -tags nogui ./internal/gateway -run 'TestVertex' go test -tags nogui ./internal/gateway ./internal/provider ./internal/cli ./internal/gui -run 'TestDisabled|TestModelDisableCmd' node --test internal/gui/tests/disabled-models.test.cjs +go test -tags nogui ./internal/gateway ./internal/gui -run 'TestBareModelIDs' +node --test internal/gui/tests/bare-ids.test.cjs go test -tags nogui ./internal/gateway -run 'TestTextWritten|TestGLMTextCall|TestPluginTextWrittenCall|TestQuietWholeReplyStreamed' go test -tags nogui ./internal/gateway -run 'TestAutoMode|TestClaudeBridgeSafeguard' go test -tags nogui ./internal/gateway -run 'TestCreditsExhaustedIsOutOfCredit|TestOutOfCreditLeavesFreeModels' diff --git a/internal/gateway/bare_ids_test.go b/internal/gateway/bare_ids_test.go new file mode 100644 index 000000000..d0e92c39f --- /dev/null +++ b/internal/gateway/bare_ids_test.go @@ -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) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 9f7e7d9c0..70440c465 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -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) } diff --git a/internal/gui/api.go b/internal/gui/api.go index 4e61f0721..34c3f2cdd 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -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) { diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 87751a792..9b4121568 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -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 diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 0b09e1621..c29e64e68 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -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})", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 3317671a5..1003c35cb 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -492,6 +492,12 @@
Gateway
+
+
+
Model ids without the provider
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
+
+
+
Local network
diff --git a/internal/gui/bare_ids_test.go b/internal/gui/bare_ids_test.go new file mode 100644 index 000000000..11752afb8 --- /dev/null +++ b/internal/gui/bare_ids_test.go @@ -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) + } + } +} diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go index d0349dca9..50389ad87 100644 --- a/internal/gui/settings_keep_test.go +++ b/internal/gui/settings_keep_test.go @@ -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", diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 7a327856e..fd8cdd022 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -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 diff --git a/internal/gui/tests/bare-ids.test.cjs b/internal/gui/tests/bare-ids.test.cjs new file mode 100644 index 000000000..93ff26ca6 --- /dev/null +++ b/internal/gui/tests/bare-ids.test.cjs @@ -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, []); + }); + } + } +} diff --git a/internal/provider/bare.go b/internal/provider/bare.go new file mode 100644 index 000000000..b68236e38 --- /dev/null +++ b/internal/provider/bare.go @@ -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 +} diff --git a/internal/provider/group.go b/internal/provider/group.go index 8bef6d110..81509b774 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -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 { diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 383ac70a5..4fe1ede60 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -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