diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 1f4d7189e..c3c7e91b8 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -23,7 +23,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | providers.json | `Path` is `providers.json` in magpie's config folder. A read that fails returns `ErrUnreadable` and is never treated as empty. `store` writes atomically through a rename and drops the cached catalog (`catalog.Touched`). | [`provider.go`](../../internal/provider/provider.go) | | The list | `All` merges stored providers with `Accounts()`. An entry with no URL stores the user's picks for an account. The order is `file.Order`. Reads within one request share one build (`Hold`, #746). | [`provider.go`](../../internal/provider/provider.go) | | Model picks | `Models` are the models the user picked for agents; none means the vendor's list, up to 24 (`Exposed`), unless the user chose Select none (`NoModels`, `magpie provider models none`): then none of its models is served, not to agents, not to any routing group (auto groups included), not by a `provider/model` id, not as a classifier, while its balance and usage are still read (`ServesNone`, #1818). A file without `noModels` reads as before, and a pick clears it. `Save` keeps beside new picks the models listed then (`PickedFrom`, `listedWith`), and the same picks saved again keep it. When the picks held every model listed then, one the vendor lists since is served first beside them (`withNewlyListed`, `Picks`); one listed then and left unpicked stays out. Picks saved before `PickedFrom` was kept are taken to hold every model when they hold every one released up to the newest of them (models.dev's `release_date`), so a Claude account whose user picked them all is served Haiku 5.5 (wakaka). The editor and the TUI start from `Picks`, so a later Save keeps the new model. | [`models.go`](../../internal/provider/models.go), [`provider.go`](../../internal/provider/provider.go) | -| Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. `Key` stays the first, so other code reads it as before. A key can be made for one protocol (`KeyProtocol`). | [`keys.go`](../../internal/provider/keys.go) | +| Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. `Key` stays the first, so other code reads it as before. A key can be made for one protocol (`KeyProtocol`). A key made for a protocol its provider has no URL for is skipped (`perKeyBarred`); when every key is, the provider is still tried whole on the URLs it has, and the candidate carries `noURL` so it isn't quiet: Routing's row (`Weighed.NoURL`) says "key set to {api} only, no {api} URL · sent on the others", and the editor's key row shows a "No {api} URL" chip (`keyLacksURL`; #1702, `TestKeyForAProtocolWithNoURLIsSaid`, `key-nourl.test.cjs`). | [`keys.go`](../../internal/provider/keys.go) | | Google Vertex AI | `google-vertex` (`VertexPreset`, `IsVertex`) is a provider of the user's own with no key. `Provider.Vertex` holds `project`, `location` (`global`, `us`, `eu` or a region; `global` when empty), `credentials` (a file; empty for Application Default Credentials) and `impersonate` (a service account's email). Save refuses a key given it, then normalizes them (`Normal`) and checks each (`check`); `normalize` clears the four URLs and any key put in `providers.json` by hand, which stands in for neither a token nor a project and leaves the provider as found savable, so the provider's one address is `vertexBase`, `https:///v1/projects//locations/`, its host following the location (`vertexHost`). It speaks Gemini alone (`Speaks`, `Base`). It is `Ready` once that address can be made, never from a key or an account; until then the app, `magpie providers` and the TUI say it needs a project, and `magpie provider ` says how to give it one. `hasEndpoint` counts it as a provider of the user's own, not a subscription's picks. An import link naming it is refused (`ParseImport`): its project and credentials are the user's own, which no link hands over. `Sign` refuses any other address and sets the bearer token before the user's `Headers`; `AuthHeaders` gives it no key header. Its models are its location's (`vertexModels`, in `planModels`): the preset has `NoList`, because Vertex AI has no list that says what a location serves. The lists are in the [reference](../reference.md#google-vertex-ai). | [`vertex.go`](../../internal/provider/vertex.go), [`provider.go`](../../internal/provider/provider.go), [`account.go`](../../internal/provider/account.go), [`rename.go`](../../internal/provider/rename.go), [`models.go`](../../internal/provider/models.go), [`importurl.go`](../../internal/provider/importurl.go) | | Vertex AI tokens | `vertexCredentialsFile` finds the credentials as Google's libraries find Application Default Credentials: the provider's `credentials`, else the file `GOOGLE_APPLICATION_CREDENTIALS` names, else `application_default_credentials.json` in gcloud's folder (`CLOUDSDK_CONFIG`, else `~/.config/gcloud`, `%APPDATA%\gcloud` on Windows); a `~/` that starts any of them is the home. `mint` reads three kinds: `authorized_user` (a refresh-token grant), `service_account` (an RS256 JWT, RFC 7523: `signed`) and gcloud's `impersonated_service_account`, whose `source_credentials` are minted and traded at IAM Credentials, along its `delegates`, for the account its `service_account_impersonation_url` names (`impersonationURL`: the token never goes to that URL's host). With `impersonate` set, the token those give is traded at IAM Credentials' `generateAccessToken` for a `cloud-platform` token of that account's, as gcloud's `--impersonate-service-account` does (`impersonateFor`); the credentials' account needs `roles/iam.serviceAccountTokenCreator` on it, which the 403 names. `vertexTokens` keeps one token per file and impersonated account, in memory only; requests made together mint it once, and those that waited through a mint that failed are given its error rather than each minting in turn (`mints`, `failed`). A mint cut short because its own request was given up on fails none of them: the next one mints. It is minted again within `vertexRefreshLead` (5 minutes) of expiry, or when the file's size or modification time has changed (gcloud signed in again). One mint, every exchange included, gets `vertexMintWait` (30 seconds). The file is only read. | [`vertex.go`](../../internal/provider/vertex.go), [`signin.go`](../../internal/provider/signin.go) | | Subscription accounts | `Accounts` reads the credentials each agent keeps on disk or in the macOS Keychain; nothing is stored twice. With account discovery off (#1535, below) none of them is read. A built-in that has moved to its plugin is dropped (`Moved`), and plugin accounts are placed in its slot (`placeMoved`). `Sign` adds the account's own auth, then the user's `Headers`. | [`account.go`](../../internal/provider/account.go) | diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 6e42ed66f..f043ce3be 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -49,6 +49,10 @@ type candidate struct { rank int // capped is set on an account left out as held at its usage cap capped *capHold + // noURL is the protocol its provider's keys are all set to that the + // provider has no URL for (#1702): the provider is tried whole, on the + // URLs it has, and the routing trace says why + noURL provider.Protocol } // capHold is how an account is held at its usage cap: the cap of the @@ -220,9 +224,13 @@ func perKeyBarred(p provider.Provider, model string, from provider.Protocol) (ou } keys := p.KeysOn() var unlisted []candidate + var noURL provider.Protocol for i, k := range keys { q := p.WithKey(k) if len(q.Speaks()) == 0 && !q.DecidesModel(model) { + if noURL == "" { + noURL = k.Protocol + } continue // made for a protocol this provider has no endpoint for } rest := p.ID @@ -247,7 +255,10 @@ func perKeyBarred(p provider.Provider, model string, from provider.Protocol) (ou return nil, nil, nil, barred } if len(out) == 0 { - return []candidate{{p: p, model: model, rest: p.ID}}, nil, nil, nil + // every key is set to a protocol the provider has no URL for (or + // it has none on): the provider as it is, on the URLs it has, + // marked so Routing says so rather than sending it there quietly + return []candidate{{p: p, model: model, rest: p.ID, noURL: noURL}}, nil, nil, nil } sort.SliceStable(out, func(i, j int) bool { return keyFit(out[i].p, model, from) < keyFit(out[j].p, model, from) }) pool := out[:0:0] diff --git a/internal/gateway/key_nourl_test.go b/internal/gateway/key_nourl_test.go new file mode 100644 index 000000000..84457b24f --- /dev/null +++ b/internal/gateway/key_nourl_test.go @@ -0,0 +1,72 @@ +package gateway + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" +) + +// A key set to Responses on a provider with only a Chat URL (#1702, +// edussss: one key, Responses picked, the address typed in the +// OpenAI-compatible field only) has no endpoint of its own. The request +// still goes out on the Chat URL the provider has, as before, but the +// routing trace marks the provider with the protocol it lacks, so Routing +// says why it went to /v1/chat/completions. A key set to Any beside it is +// used as ever and nothing is marked. +func TestKeyForAProtocolWithNoURLIsSaid(t *testing.T) { + testenv.SetHome(t, t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + var mu sync.Mutex + var seen []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + seen = append(seen, r.URL.Path+" "+strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")) + mu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"}}]}`, + `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`, + `data: [DONE]`)) + })) + defer srv.Close() + body := `{"model":"relay/gpt-5.5","stream":false,"input":"hi"}` + for _, c := range []struct { + name string + keys []provider.KeyAccount // after the first, k-resp set to Responses + noURL provider.Protocol + want string + }{ + {"the reporter's: one key, Responses", nil, provider.Responses, "/v1/chat/completions k-resp"}, + {"a key for Any beside it", []provider.KeyAccount{{Key: "k-any"}}, "", "/v1/chat/completions k-any"}, + } { + p := provider.Provider{ID: "relay", Name: "Relay", Chat: srv.URL + "/v1", Models: []string{"gpt-5.5"}, + Key: "k-resp", KeyProtocol: provider.Responses, Keys: c.keys} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + s := New() + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body))) + mu.Lock() + got := seen + seen = nil + mu.Unlock() + if rec.Code != 200 || len(got) != 1 || got[0] != c.want { + t.Fatalf("%s: %d %s, upstream saw %v", c.name, rec.Code, rec.Body.String(), got) + } + routes := s.Trace(context.Background(), 0, 0).Routes + if len(routes) != 1 || len(routes[0].Order) != 1 { + t.Fatalf("%s: routes %+v", c.name, routes) + } + if w := routes[0].Order[0]; w.NoURL != c.noURL { + t.Fatalf("%s: noURL = %q, want %q (%+v)", c.name, w.NoURL, c.noURL, w) + } + } +} diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index 9a4ff5acb..29f65cd78 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -238,6 +238,9 @@ type Weighed struct { // Aside: a key made for another protocol than the keys routed over, // tried only after them Aside bool `json:"aside,omitempty"` + // NoURL: its keys are all set to this protocol, which its provider has + // no URL for, so it was tried on the URLs it has (#1702) + NoURL provider.Protocol `json:"noURL,omitempty"` // Via: the groups in the group it is of, outermost first, when it is // of a group in the group asked for Via []string `json:"via,omitempty"` @@ -326,7 +329,7 @@ type planned struct { func weighed(c candidate, p provider.Provider, wg weighing, fallback bool, from provider.Protocol) Weighed { w := Weighed{ID: c.rest, Provider: p.ID, Name: p.Name, Icon: p.Icon, Preset: p.Preset, Model: c.model, Fixed: c.effort, Fast: c.fast, - Routing: p.Routing, Fallback: fallback, Shared: c.rest != p.ID, Rank: c.rank} + Routing: p.Routing, Fallback: fallback, Shared: c.rest != p.ID, Rank: c.rank, NoURL: c.noURL} switch { case c.p.Account != nil: w.Kind, w.Who, w.Agent, w.Plan = "account", c.p.Account.User, c.p.Account.Agent, c.p.Account.Plan diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 2dc264ad2..72681a0c4 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2322,6 +2322,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .accts.weighted .acc .key-weight { display: inline-block; } .acc .key-weight-in { width: 64px; flex: none; font-size: 12px; padding: 1px 6px; } .acc .key-rest { flex: none; font-size: 11px; padding: 1px 6px; border-radius: 5px; color: var(--amber); background: var(--amber-soft); white-space: nowrap; } +.acc .key-nourl { flex: none; font-size: 11px; padding: 1px 6px; border-radius: 5px; color: var(--amber); background: var(--amber-soft); white-space: nowrap; } .acc .proto { flex: none; display: inline-flex; align-items: center; gap: 3px; height: 20px; padding: 0 5px 0 7px; font: inherit; font-size: 11px; color: var(--muted); border: 0; border-radius: 5px; background: var(--pill); white-space: nowrap; cursor: default; transition: opacity .15s, background .12s, color .12s; } .acc .proto svg { opacity: .7; transition: transform .15s var(--ease); } .acc .proto.open svg { transform: rotate(180deg); } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 3fb98cb3e..3f01430c1 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -13569,6 +13569,15 @@ function renderKeyAccounts(p) { if (k.on && several) row.append(keyWeight(p, k, weightOf(k), weights)); const proto = protoPicker(p, k.protocol, (v) => accountAction("keys/protocol", { id: p.id, ref: k.id, protocol: v })); if (proto) row.append(proto); + // set to a protocol the provider has no URL for (#1702): the gateway + // can't send it there, so the row says so rather than the request + // quietly going out on another URL + const lacks = keyLacksURL(p, k); + if (lacks) { + const n = el("span", "key-nourl", t("No {api} URL", { api: lacks })); + n.title = t("This key is set to {api} only, but {name} has no {api} URL, so no request reaches {api} with it. Fill in the {api} URL, or set the key to Any protocol.", { api: lacks, name: p.name }); + row.append(n); + } // its own models (#474), when there is another key to send the rest to const [amPill, amBox] = p.keyList.length > 1 || accountModelsOf(p, k.id).length ? accountModels(p, k.id, true, k.name || k.masked) : []; if (amPill) row.append(amPill); @@ -13817,6 +13826,13 @@ const PROTO_OPTS = [ { v: "responses", pill: "Responses", name: "Responses", note: "OpenAI Responses API · Codex" }, ]; +// keyLacksURL is the protocol a key is set to when its provider has no URL +// for it (the pill's own name), else "". +function keyLacksURL(p, k) { + if (!["anthropic", "chat", "responses"].includes(k.protocol) || p[k.protocol]) return ""; + return t(PROTO_OPTS.find((o) => o.v === k.protocol).pill); +} + // protoPicker is the key row's protocol badge; clicking it drops a small menu // that says what each choice is for. function protoPicker(p, value, onChange) { diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index e9b188eb9..bd3cef317 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3038,6 +3038,9 @@ const I18N = { "{pattern} is not a regular expression magpie can read": "{pattern} 不是 magpie 能识别的正则表达式", "Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "模式匹配的模型均入组(含供应商日后新增的),排在上方模型之后:* 匹配 provider/model 中任意字符,re: 开头表示正则表达式。", "{api} only · after the others": "仅 {api} · 排在其他之后", + "No {api} URL": "没有 {api} 地址", + "This key is set to {api} only, but {name} has no {api} URL, so no request reaches {api} with it. Fill in the {api} URL, or set the key to Any protocol.": "这个 key 只用于 {api},但 {name} 没有填 {api} 地址,所以用这个 key 的请求到不了 {api}。请填上 {api} 地址,或者把 key 改回「任意协议」。", + "key set to {api} only, no {api} URL · sent on the others": "key 只用 {api},没有 {api} 地址 · 改走其他地址", "any API": "任意 API", "{who} is made for {api}, not {other} as the keys routed over are, so it isn't one of them: it's tried after them.": "{who} 用于 {api},与参与路由的 {other} 密钥不同,不算其中一员,排在它们之后尝试。", "{n} keys for {api}": "{n} 个 {api} 密钥", @@ -7555,6 +7558,9 @@ const I18N = { "{pattern} is not a regular expression magpie can read": "{pattern} 不是 magpie 能識別的正規表示式", "Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "模式匹配的模型均入組(含供應商日後新增的),排在上方模型之後:* 匹配 provider/model 中任意字元,re: 開頭表示正規表示式。", "{api} only · after the others": "僅 {api} · 排在其他之後", + "No {api} URL": "沒有 {api} 位址", + "This key is set to {api} only, but {name} has no {api} URL, so no request reaches {api} with it. Fill in the {api} URL, or set the key to Any protocol.": "這個 key 只用於 {api},但 {name} 沒有填 {api} 位址,所以用這個 key 的請求到不了 {api}。請填上 {api} 位址,或把 key 改回「任意協議」。", + "key set to {api} only, no {api} URL · sent on the others": "key 只用 {api},沒有 {api} 位址 · 改走其他位址", "any API": "任意 API", "{who} is made for {api}, not {other} as the keys routed over are, so it isn't one of them: it's tried after them.": "{who} 用於 {api},與參與路由的 {other} 金鑰不同,不算其中一員,排在它們之後嘗試。", "{n} keys for {api}": "{n} 個 {api} 金鑰", @@ -12084,6 +12090,9 @@ const I18N = { "{pattern} is not a regular expression magpie can read": "{pattern} は magpie が読める正規表現ではありません", "Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "パターンに一致するモデルは、プロバイダが今後追加するものも含めてすべて、上のモデルの後にグループに入ります。* は provider/model の任意の文字列、re: で始めると正規表現です。", "{api} only · after the others": "{api} のみ · 他の後", + "No {api} URL": "{api} の URL がありません", + "This key is set to {api} only, but {name} has no {api} URL, so no request reaches {api} with it. Fill in the {api} URL, or set the key to Any protocol.": "このキーは {api} 専用ですが、{name} には {api} の URL がないため、このキーでのリクエストは {api} に届きません。{api} の URL を入力するか、キーを「任意のプロトコル」に戻してください。", + "key set to {api} only, no {api} URL · sent on the others": "キーは {api} 専用、{api} の URL なし · 他の URL で送信", "any API": "任意の API", "{who} is made for {api}, not {other} as the keys routed over are, so it isn't one of them: it's tried after them.": "{who} は {api} 用で、ルーティング対象のキーのような {other} 用ではないため、その一員にはなりません。それらの後に試されます。", "{n} keys for {api}": "{api} 用のキー {n} 個", @@ -16612,6 +16621,9 @@ const I18N = { "{pattern} is not a regular expression magpie can read": "{pattern} ist kein regulärer Ausdruck, den magpie lesen kann", "Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "Jedes Modell, auf das ein Muster passt, ist in der Gruppe, jetzt und sobald Anbieter neue auflisten, nach den Modellen oben: * steht für beliebige Zeichen in provider/model, re: leitet einen regulären Ausdruck ein.", "{api} only · after the others": "nur {api} · nach den anderen", + "No {api} URL": "Keine {api}-URL", + "This key is set to {api} only, but {name} has no {api} URL, so no request reaches {api} with it. Fill in the {api} URL, or set the key to Any protocol.": "Dieser Schlüssel ist nur für {api} eingestellt, aber {name} hat keine {api}-URL, daher erreicht keine Anfrage mit ihm {api}. Trag die {api}-URL ein oder stell den Schlüssel auf Beliebiges Protokoll.", + "key set to {api} only, no {api} URL · sent on the others": "Schlüssel nur für {api}, keine {api}-URL · über die anderen gesendet", "any API": "beliebige API", "{who} is made for {api}, not {other} as the keys routed over are, so it isn't one of them: it's tried after them.": "{who} ist für {api} gedacht, nicht für {other} wie die Schlüssel der Weiterleitung, und gehört daher nicht zu ihnen: Es wird nach ihnen versucht.", "{n} keys for {api}": "{n} Schlüssel für {api}", diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index 5d22a90b1..5986ff9f8 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -409,6 +409,9 @@ // or the user set the account or key to serve other models only (#474) // or it is held at the usage cap the user set on the account const unlistedWord = (w) => w.held ? t("not an account the gateway key may use") : w.noCredits ? t("held: its allowance used up, set not to spend credits") : w.capped ? t("held at its {cap}% usage cap", { cap: w.capped }) : w.barred ? t("set to serve other models, not {model}", { model: w.model }) : w.kind === "key" ? t("{name}'s list for this key has no {model}", { name: w.name, model: w.model }) : t("its plan doesn't list {model}", { model: w.model }); + // noURLWord: its keys are all set to a protocol its provider has no URL + // for, so it went out on the URLs it has (#1702) + const noURLWord = (w) => t("key set to {api} only, no {api} URL · sent on the others", { api: API[w.noURL] || w.noURL }); const group = (w) => w.used >= 98 ? "spent" : w.used >= 90 ? "low" : "fine"; const renews = (w) => (w.renews || []).map((s) => known0(s) ? at(s) : 0); // usedRenews is when the window w.used is the share of renews: a row @@ -1504,6 +1507,7 @@ else if (trying.has(id)) s = r.id !== cur.id && agents.size <= 1 ? t("answering another request…") : t("answering…"); else if (answered.has(id)) s = agents.size > 1 ? t("answered {agent}", { agent: agentName(r.agent) }) : t("answered this request"); else if (gave.has(id)) s = t("{status} · {fail} · passed to {agent}", { status: gave.get(id).status, fail: failWord(gave.get(id).fail), agent: agentName(r.agent) }); + else if (w.noURL) s = noURLWord(w); else if (w.sunk) s = t("rate limited at {time} · at the back", { time: clock(w.sunk) }); else if (w.known) { const soon = usedRenews(w); @@ -2436,6 +2440,7 @@ const resting = a.rest && at(a.rest.until) > n; if (resting) { st = `${failWord(a.rest.why)} · ${restWhen(a.rest)}`; cls = "rest"; } else if (w.unlisted) { st = unlistedWord(w); cls = "left"; } + else if (w.noURL) st = noURLWord(w); else if (w.known) { const soon = usedRenews(w); st = soon && soon <= n ? quota(w, "{n} used at {time}; it has renewed since", "{n} left at {time}; it has renewed since", { time: clock(a.at) }) diff --git a/internal/gui/tests/key-nourl.test.cjs b/internal/gui/tests/key-nourl.test.cjs new file mode 100644 index 000000000..afb538773 --- /dev/null +++ b/internal/gui/tests/key-nourl.test.cjs @@ -0,0 +1,114 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A key set to a protocol its provider has no URL for (#1702, edussss: one +// key set to Responses, the address in the OpenAI-compatible field only) +// says so. In the editor its row has "No Responses URL", whose tooltip +// says what to do; a key set to Any, or to a protocol the provider has a +// URL for, has nothing. On the Routing page the provider tried whole on +// the URLs it has says its key is set to that protocol only. A click on +// the row's chip scrolls nothing, and nothing runs off a 420px window. In +// every language, Chromium and WebKit. +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 assets = path.resolve(__dirname, "../assets"); +const now = new Date(); +const relay = () => ({ + id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "https://relay.example.com", catalog: "", + models: [{ id: "gpt-5.5", name: "", on: true }], agents: [], fallback: [], headers: {}, routing: "", + key: { set: true, masked: "sk-…one" }, balanceToken: { takes: false, set: false }, proxy: "", + keyList: [ + { id: "aaaaaaaaaa", name: "resp", masked: "sk-…one", on: true, active: true, protocol: "responses" }, + { id: "bbbbbbbbbb", name: "any", masked: "sk-…two", on: true }, + { id: "cccccccccc", name: "chat", masked: "sk-…three", on: true, protocol: "chat" }, + ], +}); +const route = { + id: 1, seq: 1, time: new Date(now.getTime() - 60e3).toISOString(), agent: "codex", model: "relay/gpt-5.5", provider: "relay", done: true, status: 200, ms: 900, tokens: 1200, + order: [{ id: "relay", provider: "relay", name: "Relay", kind: "provider", model: "gpt-5.5", noURL: "responses" }], + tries: [{ id: "relay", model: "gpt-5.5", start: new Date(now.getTime() - 60e3).toISOString(), done: true, status: 200, ms: 900 }], +}; + +function serve(lang) { + return async (request) => { + const url = new URL(request.request().url()); + const json = (data) => request.fulfill({ json: data }); + if (url.pathname === "/boot.js") return request.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return request.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json({ providers: [relay()], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes + return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 1 }, routes: [route] }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + 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 request.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType }); + }; +} + +async function open(t, engine, lang, view, width) { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.goto(`http://magpie.test/?view=${view}`); + // what a string says in lang, its {names} filled in + const say = (key, vars = {}) => page.evaluate(([lang, key, vars]) => { + const s = (lang !== "en" && I18N[lang]?.[key]) || key; + return s.replace(/\{(\w+)\}/g, (_, k) => vars[k] ?? `{${k}}`); + }, [lang, key, vars]); + return { page, errors, say }; +} + +const sideways = (page) => page.evaluate(() => document.documentElement.scrollWidth > innerWidth); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [420, 1000]) { + test(`${engine} ${lang} ${width}px: a key set to a protocol with no URL says so in the editor`, async (t) => { + const { page, errors, say } = await open(t, engine, lang, "providers", width); + await page.locator(".row.provider", { hasText: "Relay" }).first().click(); + const row = (id) => page.locator(`.editor .accts.keys .acc[data-account-id="${id}"]`); + await row("aaaaaaaaaa").waitFor(); + const api = await say("Responses"); + const chip = row("aaaaaaaaaa").locator(".key-nourl"); + assert.equal((await chip.textContent()).trim(), await say("No {api} URL", { api })); + assert.equal(await chip.getAttribute("title"), await say("This key is set to {api} only, but {name} has no {api} URL, so no request reaches {api} with it. Fill in the {api} URL, or set the key to Any protocol.", { api, name: "Relay" })); + // Any, and Chat (which it has a URL for), have nothing + assert.equal(await row("bbbbbbbbbb").locator(".key-nourl").count(), 0); + assert.equal(await row("cccccccccc").locator(".key-nourl").count(), 0); + await chip.scrollIntoViewIfNeeded(); + const box = await chip.boundingBox(); + assert.ok(box && box.x >= 0 && box.x + box.width <= width, `the chip runs off the window: ${JSON.stringify(box)}`); + const scrolled = () => page.evaluate(() => [window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop > 0).map((e) => `${e.className}:${e.scrollTop}`)].join(" ")); + const sc = await scrolled(); + await chip.click(); + assert.equal(await scrolled(), sc, "a click scrolled"); + assert.equal(await sideways(page), false, "the page scrolls sideways"); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang} ${width}px: Routing says the provider went out on its other URLs`, async (t) => { + const { page, errors, say } = await open(t, engine, lang, "routing", width); + const req = page.locator(".rt-req").first(); + await req.waitFor(); + if (await req.getAttribute("aria-pressed") !== "true") await req.click(); + await page.locator(".rt-steps li.why").first().waitFor(); + const want = await say("key set to {api} only, no {api} URL · sent on the others", { api: "OpenAI Responses" }); + await page.waitForFunction((w) => [...document.querySelectorAll(".rt-act .st")].some((e) => e.textContent.trim() === w), want); + assert.equal(await sideways(page), false, "the page scrolls sideways"); + assert.deepEqual(errors, []); + }); + } + } +}