keys: a custom provider's key can be made for its Gemini API (corddis_114)

corddis_114 on Discord has a relay that gives out a key per protocol,
one of them for Gemini ("gemini sk-d…SarG"), and the key row's protocol
menu offered Any, Anthropic, Chat Completions and Responses only. A
custom provider already serves Gemini upstream (its Gemini URL, the
"Gemini compatible" tab, x-goog-api-key, the model list through
FetchGemini, probes), so only the per-key layer lacked it:

- keyProtocolOK takes "gemini"; WithKey leaves a Gemini key the Gemini
  URL only and takes the Gemini URL from a key made for another
  protocol (it had kept it, so an Anthropic key could be sent to
  generateContent).
- keyFit: a gemini* model (modelFamily Gemini) goes to the key made for
  Gemini first, the other keys in their order behind it; a GPT model is
  never put on the Gemini key (it ranked 0 there before). Claude's rule
  is unchanged.
- app.js: Gemini in PROTO_OPTS ("Gemini API (generateContent) · Gemini
  CLI, Gemini models"), offered when the provider has a Gemini URL;
  keyLacksURL says "No Gemini URL" for a Gemini key without one. The
  note in zh, zh-TW, ja and de. The provider-level tabs and Routing's
  "keys for Gemini" already had it.

Run on mote (go1.26.8):
- go test -timeout 45m ./internal/provider ./internal/gateway: both ok (provider 229s, gateway 938s).
- TestKeyMadeForGemini, TestKeyProtocolGemini, TestKeysMadeForOneProtocol,
  TestKeyForAProtocolWithNoURLIsSaid, TestKeyPoolsByProtocol,
  TestCustomGeminiUpstream ok; internal/gui's budget tests ok.
- GUI (node --test, Chromium and WebKit, en/zh/zh-TW/ja/de, 420 and
  1000px): key-gemini (new, 40/40), key-nourl, proto-menu-overflow,
  key-row-chips-fit, key-plan, key-import, key-weight-fit,
  provider-many-keys, provider-gemini, provider-add-gemini,
  provider-url-each-api, model-api-gemini, provider-base-api,
  routing-keys-fold and i18n-keys ok; the only red in the 360 was
  tencent-cloud's region-strip test (#4321, open).
- gofmt -l clean; go vet, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet on provider, gateway, gui ok.

Broken by hand: the old fallback.go turns TestKeyMadeForGemini red
(Gemini models went to the Chat or Anthropic key, GPT to the Gemini
one); the old keys.go turns TestKeyProtocolGemini red (unknown
protocol "gemini"), and WithKey keeping p.Gemini turns it red too (the
Anthropic key speaks [anthropic gemini]); the old app.js turns
key-gemini red in all 40.

Not tried: the reporter's relay or any real Gemini-compatible relay;
the real app's editor.
This commit is contained in:
yetone
2026-11-04 21:21:32 +08:00
parent 4062cda781
commit b61c71448c
8 changed files with 267 additions and 7 deletions
+1 -1
View File
@@ -34,7 +34,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| 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). Requests that miss a build together (a write drops what is held) wait for the first one's build and take it, unless a write came while it was built; a wait is bounded (`heldWait`), so a caller never waits for good. Before, each built again behind `logins.json`'s lock, and requests sat past the 30s unrouted deadline (#5104: `TestLoginsMissedTogetherListedOnce`, `TestHeldWaiterBuildsAgainAfterAWrite`, `TestHeldWaiterNeverStuck`). `OwnPaused` is held the same way, once a request. | [`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 <id> 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). Codex's own list at `/backend-api/codex/models` drops the ChatGPT account's visible models too, as spawn_agent's list of them does, and the list's ETag changes so a running Codex asks again (`CodexNativePicked` in [`codex_models.go`](../../internal/provider/codex_models.go), #2530); the hidden ones Codex runs jobs of its own on (codex-auto-review, gpt-reserve) and other providers' models stay. The editor's serves control names it Usage only, beside Vendor's list and Picked only, and the card says "usage only" (#2068); Picked only from there picks the models the vendor's list serves, to unpick from. A file without `noModels` reads as before, and a pick clears it. With nothing picked and Select none off, Best in family (`BestInFamily`, `magpie provider models <id> best`, the editor's fourth option, Steven on Discord) serves only the newest model of each family the vendor lists, up to 24: the family is the id with its version numbers taken out, a dated snapshot counts as its alias, and sizes and suffixes (-mini, -pro, -8b) stay in the name (`FamilyOf`, `BestInFamily` in [`family.go`](../../internal/catalog/family.go)). A newer one the vendor lists later takes the old one's place with nothing saved. Codex's own list narrows the same way (`CodexNativePicked`). An older one named by its `provider/model` id is still served, as an unpicked one is under Picked only. A pick or Select none clears it, and a file without `bestInFamily` reads as before. `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. While some picks are set aside (the list is known to be short), a save with new picks keeps the models the earlier `PickedFrom` had beside those listed now, so a model the user saw and left unpicked isn't new when that list has it again; a list short of no pick is taken as it is. A pick a list fetched again stops listing (`Refetch`, `KeepListsFresh`, and a plugin's hourly `KeepPluginsListed`) leaves `Models` for `Delisted` (`dropGonePicks`), not served, and goes back among the picks when a later list has it (`relistPicks`): Our Free Model's plugin lists its account channels' models only once its service has read them after a restart, and its free pools only while they answer, so each magpie update had its user pick every model again (多喝热水 on Discord). Every save keeps `Delisted` but for what it picks again (`delistedWith`); Select none clears it. A provider whose every pick is in `Delisted` serves none of its models for `pickWait` (an hour) from when the last one left (`DelistedAt`, `waitsForPicks`), not the vendor's list; after that, or for picks set aside before `DelistedAt` was kept, the picks are taken as gone for good and the list is served as if none were picked, while they still come back with a list that has them. WorkBuddy AI took its Free plan's deepseek-v4.1-flash off its list for hy3, and an account whose one pick it was got no model in the agents' picker, its row reading "1 image model" (maxleebeta on Discord). `KeepPluginsListed` asks again after `relistSoon` (5 minutes) when a list left a pick out. `TestPluginPicksComeBackWithTheirList`, `TestEveryPickDelistedServesNone`, `TestPicksGoneForGoodServeTheList` and `TestRelayPicksComeBackWithTheirList` cover it. | [`models.go`](../../internal/provider/models.go), [`provider.go`](../../internal/provider/provider.go) |
| List schedule and rules | A provider of the user's own (not an account, a plugin's or a decision-only one) can set `RefreshEvery` (`magpie provider refresh-every <id> 6h`, or 1d, or off, at least 10m) and `AutoInclude` (`magpie provider auto-include <id> 'gpt-*' 're:claude-.*'`, or none; a glob with `*`, or `re:` matching the whole id, both in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter); a plain id is refused) (#2135). The gateway (`magpie serve` or the app) looks each minute and fetches a list once `Fetched` is that old, through the same `Refetch` as Fetch models (`KeepListsFresh`); a failed fetch waits `min(every, 15m)`. `RefetchTaking` adds to the picks a model the fetch newly lists that a rule matches (`takeMatching`), starting from what is served now (`Exposed`), so nothing served is taken away and a model the user unticks stays out (it is not new to the next fetch). Setting the rules takes the current list's matches. Every save that doesn't set them keeps them, the window's editor among them; the editor has no fields for them yet. A Remote magpie with no `RefreshEvery` is fetched every 10m (`RemoteMagpieEvery`, `RefreshSchedule`), so a model the other magpie lists later (ZCode's GLM-5.3-Trial once its plugin read the gift, 6igsteven on Discord) is served without Fetch models; `off` set on it is kept as `"off"` and asks it only when told (`TestRemoteMagpieListFollowsTheOtherMagpie`). | [`autolist.go`](../../internal/provider/autolist.go), [`models.go`](../../internal/provider/models.go), [`providers_cli.go`](../../internal/cli/providers_cli.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`). A key's value can be replaced in place (`ReplaceKey`, #1869: a key rotated at the vendor): it keeps its name, place, protocol, weight and on or off, and what was set for it by its fingerprint (`AccountModels`, `AccountProxies`, `AccountConcurrency`) and the gateway keys held to it (`access.ReplaceAccount`) move to the new one; the GUI's `keys/replace` also lifts its rests (`UnrestAll`). Its past requests stay under the old fingerprint, by the same name. A provider may hold thousands of keys (@NetRozee on X: a thousand froze magpie). Nothing goes over its keys once for each key: `KeysOn` drops a repeat by a set, a row's rest keys come from `RestKeys` (whether several are on, found once), and whether each key serves a model from `Serving`, which reads the lists once and keeps each model's keys as a set until the lists are read anew (`keyLists`). `KeysListed` and `ListsRead` count them for the tests (`TestProviderInfoListsKeysOnce`, `TestPerKeyReadsListsOnce`). A provider's keys have their balances, plans and remote limits read `keyReadsAtOnce` (8) at a time (`keySlots`); other providers' beside them. The editor's per-key proxy lines fold as its Accounts list does (`proxyLines`, `provider-many-keys-proxy.test.cjs`). Asking a key's models (`fetchPerKey`) still goes one key after another. | [`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`): Anthropic, Chat, Responses or a custom provider's Gemini API (corddis_114 on Discord). `WithKey` leaves it that protocol's URL only, and the gateway puts the key that suits the model first (`keyFit`: Claude to the Anthropic key, GPT to a Chat or Responses one, Gemini to the Gemini one; `TestKeyMadeForGemini`, `TestKeyProtocolGemini`, `key-gemini.test.cjs`). 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`). A key's value can be replaced in place (`ReplaceKey`, #1869: a key rotated at the vendor): it keeps its name, place, protocol, weight and on or off, and what was set for it by its fingerprint (`AccountModels`, `AccountProxies`, `AccountConcurrency`) and the gateway keys held to it (`access.ReplaceAccount`) move to the new one; the GUI's `keys/replace` also lifts its rests (`UnrestAll`). Its past requests stay under the old fingerprint, by the same name. A provider may hold thousands of keys (@NetRozee on X: a thousand froze magpie). Nothing goes over its keys once for each key: `KeysOn` drops a repeat by a set, a row's rest keys come from `RestKeys` (whether several are on, found once), and whether each key serves a model from `Serving`, which reads the lists once and keeps each model's keys as a set until the lists are read anew (`keyLists`). `KeysListed` and `ListsRead` count them for the tests (`TestProviderInfoListsKeysOnce`, `TestPerKeyReadsListsOnce`). A provider's keys have their balances, plans and remote limits read `keyReadsAtOnce` (8) at a time (`keySlots`); other providers' beside them. The editor's per-key proxy lines fold as its Accounts list does (`proxyLines`, `provider-many-keys-proxy.test.cjs`). Asking a key's models (`fetchPerKey`) still goes one key after another. | [`keys.go`](../../internal/provider/keys.go) |
| Accounts at once | `MaxAccounts *int` is the user's own count of keys or accounts taking requests at the same time: nil takes the plugin's (`PluginAtOnce`: `maxAccounts` on the plugin's auth hook or package.json `magpie`, host.js `atOnceOf`), 0 is no limit, saved clamped to 0..`MaxLimit`; a subscription's is kept with its picks (`withPicks`). `AtOnce()` answers the one in force, `SetAtOnce` sets it (`magpie provider at-once`, the editor's Accounts at once; GUI save leaves it as it was when the body has none). The gateway's use is in [gateway routing](gateway-routing.md) (`TestAtOnce`, `TestAtOnceSave`, `TestAtOnceCmd`). | [`concurrency.go`](../../internal/provider/concurrency.go) |
| A provider with no key | A provider of the user's own saves, imports and is `Ready` with no key when it is a preset with `NoKey` or its host is on this computer or the user's own network (`keyOptional`, `ownNetwork`): localhost, a loopback, private, link-local or carrier-grade NAT (Tailscale's 100.64/10) address, or a `.local` name, read from the URL alone with no lookup. A company's keyless relay at a LAN address is taken as a local server is (iSnow_999 on X: a Codex relay at http://<LAN IP>:8080 was left out of a CC Switch import as "it has no API key"); a keyless address on the internet still needs its key. With no key it is asked as one on 127.0.0.1 is: a Responses request carries no `Authorization`. | [`provider.go`](../../internal/provider/provider.go), [`importapps.go`](../../internal/provider/importapps.go), [`import_lan_test.go`](../../internal/provider/import_lan_test.go) |
| A key a provider | One vendor's keys saved a provider each — an app that keeps an entry a key, as CC Switch does, imported (yuluo_yx on X: "NVIDIA #001" to "#600" at one address, "Mistral #0001"…) — are folded into one provider with those keys (`FoldCopies` at start-up, `foldAdded` after `ImportFromApps`): hundreds of copies listed every model hundreds of times in every agent's picker and found group, and 3,000 made `/api/state` 86 MB. At start-up only copies by name are folded: a base name and that name with a number after it (`copyBase`: " #12", or `freeName`'s " 2"), one at least numbered; an import folds what it added whatever their names. Either way they must be alike in all but their key (`foldShape`: the provider with its id, name, keys and on/off left out), what the settings say of their models (`modelPrefs`) and where they are named (`foldRefs`: Visible, the agents' picked, hidden and ordered models, the groups, the providers falling back to them), so one key shown to one agent and another to another stays apart. Not folded: a subscription's, a hidden one, one without a key, Vertex, one with a StepFun sign-in of its own. The first on, in the providers' order, takes the rest in; its name becomes the base and its key is named its old name. Each other is a key in order, named its name, off if it was off (all off: the provider is off, its keys on); its id goes in `Was`, so its calls count with the provider by their key (`ProviderKeyID` is the key's fingerprint, unchanged) and a model picked by the old id still reaches it. Group members, rules, weights and fallbacks naming them name the provider once; their per-model settings and fetched lists go; balance and window history kept by their id moves to their key's name (`foldHistories`). A providers.json that doesn't parse is left alone. It runs at every start and writes nothing when there is nothing to fold. `TestFoldCopies`, `TestFoldCopiesIntoOneOn`, `TestFoldCopiesUnreadable`, `TestImportFoldsAKeyAnEntry`. | [`fold.go`](../../internal/provider/fold.go), [`importapps.go`](../../internal/provider/importapps.go), [`main.go`](../../internal/cli/main.go) |
+15 -2
View File
@@ -498,10 +498,20 @@ func keyFit(q provider.Provider, model string, from provider.Protocol) int {
}
return 2
case provider.Chat:
if q.KeyProtocol != provider.Anthropic {
if q.KeyProtocol != provider.Anthropic && q.KeyProtocol != provider.Gemini {
return 0
}
return 2
case provider.Gemini:
// a key made for the Gemini API before any other (corddis_114
// on Discord); the others keep their order behind it
if q.KeyProtocol == provider.Gemini {
return 0
}
if q.Base(from) != "" {
return 1
}
return 2
}
if q.Base(from) != "" {
return 0
@@ -510,7 +520,8 @@ func keyFit(q provider.Provider, model string, from provider.Protocol) int {
}
// modelFamily is the protocol a model is at home in, when its name says:
// Anthropic for Claude, Chat (standing for OpenAI's) for GPT and the o-series.
// Anthropic for Claude, Chat (standing for OpenAI's) for GPT and the o-series,
// Gemini for Gemini.
func modelFamily(model string) provider.Protocol {
m := strings.ToLower(model)
if i := strings.LastIndex(m, "/"); i >= 0 {
@@ -521,6 +532,8 @@ func modelFamily(model string) provider.Protocol {
return provider.Anthropic
case strings.HasPrefix(m, "gpt-"), strings.Contains(m, "codex"), len(m) > 1 && m[0] == 'o' && m[1] >= '1' && m[1] <= '9':
return provider.Chat
case strings.HasPrefix(m, "gemini"):
return provider.Gemini
}
return ""
}
+89
View File
@@ -0,0 +1,89 @@
package gateway
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// A relay that gives out a key per protocol, Gemini's among them
// (corddis_114 on Discord): a Gemini model goes to the key made for the
// Gemini API, on generateContent, whatever the agent spoke, and Claude
// and GPT models never go there, though the Gemini key is the first.
func TestKeyMadeForGemini(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
restingUntil.Lock()
restingUntil.m = map[string]time.Time{}
restingUntil.Unlock()
var seen []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
key := r.Header.Get("x-api-key")
if key == "" {
key = r.Header.Get("x-goog-api-key")
}
if key == "" {
key = strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
}
seen = append(seen, r.URL.Path+" "+key)
gem := strings.HasPrefix(r.URL.Path, "/v1beta/models/")
want := map[string]string{"/v1/messages": "k-ant", "/v1/chat/completions": "k-oai"}[r.URL.Path]
if gem {
want = "k-gem"
}
if key != want {
w.WriteHeader(401)
io.WriteString(w, `{"error":{"message":"this key is for another protocol"}}`)
return
}
switch {
case gem:
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(`data: {"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":1,"totalTokenCount":2}}`))
case r.URL.Path == "/v1/messages":
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"m1","type":"message","role":"assistant","model":"x","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`)
case bytes.Contains(b, []byte(`"stream":true`)):
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]`))
default:
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"c1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)
}
}))
defer srv.Close()
p := provider.Provider{ID: "relay", Name: "Relay", Chat: srv.URL + "/v1", Anthropic: srv.URL, Gemini: srv.URL + "/v1beta",
Key: "k-gem", KeyProtocol: provider.Gemini, Models: []string{"claude-opus-4-8", "gpt-5.5", "gemini-3-pro"},
Keys: []provider.KeyAccount{{Key: "k-ant", Protocol: provider.Anthropic}, {Key: "k-oai", Protocol: provider.Chat}}}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
for _, x := range []struct{ path, body, want string }{
// Claude Code and an OpenAI agent asking for Gemini: the Gemini key
{"/v1/messages", `{"model":"relay/gemini-3-pro","max_tokens":9,"messages":[{"role":"user","content":"hi"}]}`, "/v1beta/models/gemini-3-pro:streamGenerateContent k-gem"},
{"/v1/chat/completions", `{"model":"relay/gemini-3-pro","messages":[{"role":"user","content":"hi"}]}`, "/v1beta/models/gemini-3-pro:streamGenerateContent k-gem"},
// Claude and GPT never go to the Gemini key, the first though it is
{"/v1/messages", `{"model":"relay/claude-opus-4-8","max_tokens":9,"messages":[{"role":"user","content":"hi"}]}`, "/v1/messages k-ant"},
{"/v1/messages", `{"model":"relay/gpt-5.5","max_tokens":9,"messages":[{"role":"user","content":"hi"}]}`, "/v1/chat/completions k-oai"},
{"/v1/chat/completions", `{"model":"relay/gpt-5.5","messages":[{"role":"user","content":"hi"}]}`, "/v1/chat/completions k-oai"},
} {
seen = nil
code, body := post(t, x.path, x.body)
if code != 200 || len(seen) != 1 || seen[0] != x.want {
t.Errorf("%s %s: %d %s, upstream saw %v", x.path, x.body, code, body, seen)
}
}
if got := modelFamily("google/gemini-2.5-flash"); got != provider.Gemini {
t.Errorf("gemini: %q", got)
}
}
+3 -2
View File
@@ -14872,12 +14872,13 @@ const PROTO_OPTS = [
{ v: "anthropic", pill: "Anthropic", name: "Anthropic", note: "Messages API · Claude Code, Claude" },
{ v: "chat", pill: "Chat", name: "Chat Completions", note: "OpenAI API · GPT models, most agents" },
{ v: "responses", pill: "Responses", name: "Responses", note: "OpenAI Responses API · Codex" },
{ v: "gemini", pill: "Gemini", name: "Gemini", note: "Gemini API (generateContent) · Gemini CLI, Gemini models" },
];
// 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 "";
if (!["anthropic", "chat", "responses", "gemini"].includes(k.protocol) || p[k.protocol]) return "";
return t(PROTO_OPTS.find((o) => o.v === k.protocol).pill);
}
@@ -14885,7 +14886,7 @@ function keyLacksURL(p, k) {
// that says what each choice is for.
function protoPicker(p, value, onChange) {
value = value || "";
const have = ["anthropic", "chat", "responses"].filter((x) => p[x]);
const have = ["anthropic", "chat", "responses", "gemini"].filter((x) => p[x]);
if (have.length < 2 && !value) return null;
return pickPill(PROTO_OPTS.filter((o) => !o.v || have.includes(o.v) || o.v === value), value, "", "Some relays give out a key per protocol. Set it here and the gateway sends each request to the key that fits: Claude models to the Anthropic key, GPT models to the OpenAI one.", undefined, onChange);
}
+4
View File
@@ -1932,6 +1932,7 @@ const I18N = {
"Messages API · Claude Code, Claude": "Messages API · Claude Code、Claude 模型",
"OpenAI API · GPT models, most agents": "OpenAI API · GPT 模型、大多数 agent",
"OpenAI Responses API · Codex": "OpenAI Responses API · Codex",
"Gemini API (generateContent) · Gemini CLI, Gemini models": "Gemini API(generateContent)· Gemini CLI、Gemini 模型",
"Some relays give out a key per protocol. Set it here and the gateway sends each request to the key that fits: Claude models to the Anthropic key, GPT models to the OpenAI one.": "有的中转站按协议发放不同密钥。在此标明后,网关按请求选用对应密钥:Claude 模型走 Anthropic 密钥,GPT 模型走 OpenAI 密钥。",
"Use this key too": "同时启用这个密钥",
"First": "首选",
@@ -6517,6 +6518,7 @@ const I18N = {
"Messages API · Claude Code, Claude": "Messages API · Claude Code、Claude 模型",
"OpenAI API · GPT models, most agents": "OpenAI API · GPT 模型、大多數 agent",
"OpenAI Responses API · Codex": "OpenAI Responses API · Codex",
"Gemini API (generateContent) · Gemini CLI, Gemini models": "Gemini API(generateContent)· Gemini CLI、Gemini 模型",
"Some relays give out a key per protocol. Set it here and the gateway sends each request to the key that fits: Claude models to the Anthropic key, GPT models to the OpenAI one.": "有的中轉站按協議發放不同金鑰。在此標明後,閘道按請求選用對應金鑰:Claude 模型走 Anthropic 金鑰,GPT 模型走 OpenAI 金鑰。",
"Use this key too": "同時啟用這個金鑰",
"First": "首選",
@@ -11078,6 +11080,7 @@ const I18N = {
"Messages API · Claude Code, Claude": "Messages API · Claude Code、Claude",
"OpenAI API · GPT models, most agents": "OpenAI API · GPT モデル、ほとんどのエージェント",
"OpenAI Responses API · Codex": "OpenAI Responses API · Codex",
"Gemini API (generateContent) · Gemini CLI, Gemini models": "Gemini API(generateContent)· Gemini CLI、Gemini モデル",
"Some relays give out a key per protocol. Set it here and the gateway sends each request to the key that fits: Claude models to the Anthropic key, GPT models to the OpenAI one.": "中継サービスによってはプロトコルごとにキーを発行します。ここで設定すると、ゲートウェイは各リクエストを適切なキーに送ります。Claude モデルは Anthropic のキーへ、GPT モデルは OpenAI のキーへ。",
"Use this key too": "このキーも使用",
"First": "最初",
@@ -15670,6 +15673,7 @@ const I18N = {
"Messages API · Claude Code, Claude": "Messages API · Claude Code, Claude",
"OpenAI API · GPT models, most agents": "OpenAI API · GPT-Modelle, die meisten Agenten",
"OpenAI Responses API · Codex": "OpenAI Responses API · Codex",
"Gemini API (generateContent) · Gemini CLI, Gemini models": "Gemini-API (generateContent) · Gemini CLI, Gemini-Modelle",
"Some relays give out a key per protocol. Set it here and the gateway sends each request to the key that fits: Claude models to the Anthropic key, GPT models to the OpenAI one.": "Manche Relays vergeben einen Schlüssel pro Protokoll. Legen Sie ihn hier fest, schickt der Zugangspunkt jede Anfrage an den passenden Schlüssel: Claude-Modelle an den Anthropic-Schlüssel, GPT-Modelle an den OpenAI-Schlüssel.",
"Use this key too": "Diesen Schlüssel ebenfalls verwenden",
"First": "Erstes",
+106
View File
@@ -0,0 +1,106 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A relay's key made for its Gemini API (corddis_114 on Discord): the key
// row's protocol menu offers Gemini beside Anthropic, Chat Completions and
// Responses when the provider has a Gemini URL, with what it is for, and
// picking it saves "gemini" for that key. A key set to Gemini on a
// provider with no Gemini URL says "No Gemini URL". 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 relay = (id, name, gemini) => ({
id, name, icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "https://relay.example.com", gemini, catalog: "",
models: [{ id: "gemini-3-pro", name: "", on: true }], agents: [], fallback: [], headers: {}, routing: "",
key: { set: true, masked: "sk-…one" }, balanceToken: { takes: false, set: false }, proxy: "",
keyList: [
{ id: id + "-a", name: "claude", masked: "sk-…one", on: true, active: true, protocol: "anthropic" },
{ id: id + "-g", name: "gemini", masked: "sk-…SarG", on: true, protocol: gemini ? "" : "gemini" },
],
});
function serve(lang, saved) {
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: [], profiles: [], settings: { lang, theme: "light" } });
const list = () => ({ providers: [relay("relay", "Relay", "https://relay.example.com/v1beta"), relay("nogem", "No Gem", "")], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/keys/protocol") {
saved.push(JSON.parse(request.request().postData() || "{}"));
return json(list());
}
if (url.pathname === "/api/providers") return json(list());
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, 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);
page.setDefaultNavigationTimeout(60000);
const errors = [], saved = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, saved));
await page.goto("http://magpie.test/?view=providers");
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, saved, 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 can be set to Gemini`, async (t) => {
const { page, errors, saved, say } = await open(t, engine, lang, width);
await page.locator(".row.provider", { hasText: "Relay" }).first().click();
const row = page.locator('.editor .accts.keys .acc[data-account-id="relay-g"]');
await row.waitFor();
await row.hover(); // an unset pill shows on the row's hover
await row.locator("button.proto").click();
const items = page.locator(".proto-menu .pm-item");
await items.first().waitFor();
const names = (await items.locator(".pm-name").allTextContents()).map((s) => s.trim());
const want = [];
for (const n of ["Any protocol", "Anthropic", "Chat Completions", "Gemini"]) want.push(await say(n));
assert.deepEqual(names, want);
const gem = items.filter({ has: page.locator(".pm-name", { hasText: /^Gemini$/ }) });
assert.equal((await gem.locator(".pm-note").textContent()).trim(), await say("Gemini API (generateContent) · Gemini CLI, Gemini models"));
const box = await page.locator(".proto-menu").boundingBox();
assert.ok(box && box.x >= 0 && box.x + box.width <= width, `the menu runs off the window: ${JSON.stringify(box)}`);
await gem.click();
await page.waitForFunction(() => !document.querySelector(".proto-menu"));
assert.deepEqual(saved, [{ id: "relay", ref: "relay-g", protocol: "gemini" }]);
assert.equal(await sideways(page), false, "the page scrolls sideways");
assert.deepEqual(errors, []);
});
test(`${engine} ${lang} ${width}px: a Gemini key with no Gemini URL says so`, async (t) => {
const { page, errors, say } = await open(t, engine, lang, width);
await page.locator(".row.provider", { hasText: "No Gem" }).first().click();
const row = page.locator('.editor .accts.keys .acc[data-account-id="nogem-g"]');
await row.waitFor();
const api = await say("Gemini");
assert.equal((await row.locator(".key-nourl").textContent()).trim(), await say("No {api} URL", { api }));
assert.equal((await row.locator("button.proto").textContent()).trim(), api);
assert.equal(await sideways(page), false, "the page scrolls sideways");
assert.deepEqual(errors, []);
});
}
}
}
+6 -1
View File
@@ -336,7 +336,7 @@ func (p *Provider) setFirst(k KeyAccount) {
func keyProtocolOK(proto Protocol) error {
switch proto {
case "", Chat, Responses, Anthropic:
case "", Chat, Responses, Anthropic, Gemini:
return nil
}
return fmt.Errorf("unknown protocol %q", proto)
@@ -450,6 +450,11 @@ func (p Provider) WithKey(k KeyAccount) Provider {
}
}
}
// a custom provider's Gemini API, kept for a key made for it only
// (a relay's key per protocol, corddis_114 on Discord)
if k.Protocol != Gemini {
p.Gemini = ""
}
}
return p
}
+43 -1
View File
@@ -1,6 +1,9 @@
package provider
import "testing"
import (
"slices"
"testing"
)
func TestSeveralKeys(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
@@ -94,3 +97,42 @@ func TestKeyProtocol(t *testing.T) {
t.Fatalf("a key for any protocol: %+v", q)
}
}
// A relay's key made for its Gemini API (corddis_114 on Discord): it can
// be set so, and is then used on the Gemini API only, while a key made for
// another protocol is never sent to the Gemini API.
func TestKeyProtocolGemini(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
if err := Save(Provider{ID: "relay", Name: "Relay", Chat: "https://relay.test/v1", Anthropic: "https://relay.test", Gemini: "https://relay.test/v1beta", Key: "sk-ant-1111", KeyProtocol: Anthropic}); err != nil {
t.Fatal(err)
}
if err := AddKey("relay", "gemini", "sk-gem-2222", Gemini); err != nil {
t.Fatal(err)
}
if err := AddKey("relay", "", "sk-oai-3333", ""); err != nil {
t.Fatal(err)
}
if err := SetKeyProtocol("relay", keyID("sk-oai-3333"), Gemini); err != nil {
t.Fatal(err)
}
if err := SetKeyProtocol("relay", keyID("sk-oai-3333"), Chat); err != nil {
t.Fatal(err)
}
p, _ := Find("relay")
ks := p.KeyList()
if ks[1].Protocol != Gemini || ks[2].Protocol != Chat {
t.Fatalf("keys %+v", ks)
}
if q := p.WithKey(p.Keys[0]); !slices.Equal(q.Speaks(), []Protocol{Gemini}) || q.Base(Gemini) != "https://relay.test/v1beta" {
t.Fatalf("the Gemini key speaks %v", q.Speaks())
}
for _, k := range []KeyAccount{p.first(), p.Keys[1]} {
if q := p.WithKey(k); q.Base(Gemini) != "" || len(q.Speaks()) == 0 {
t.Fatalf("the %s key speaks %v", k.Protocol, q.Speaks())
}
}
if q := p.WithKey(KeyAccount{Key: "k"}); q.Base(Gemini) == "" || len(q.Speaks()) != 3 {
t.Fatalf("a key for any protocol speaks %v", q.Speaks())
}
}