provider, gui: a custom provider's model can be asked on Gemini alone, beside chat, Responses and Anthropic (Kayphoon on Discord)

Kayphoon: "供应商为自定义的时候 现在已经兼容 gemini 格式了 但是在下方 模型的详细
配比里面还是只能限定 chat 和 anthropic". A custom provider with a Gemini URL
(#1346) offered a model only the APIs among chat, responses and anthropic
it had a URL for, in the chip's "Asked on" menu and in Names & levels' API
row (modelAPIs). The server side refused it too: SetModelAPI and ModelAPI
took only provider.Protocols (chat, responses, anthropic), so Detect APIs →
Each picked model, which can stage gemini for a model that answered only
there, failed the Save with "a model's API is chat, responses or anthropic,
not "gemini"".

- provider: SetModelAPI and ModelAPI take gemini where the provider has a
  Gemini URL (modelAPI); the gateway's usable/APIs then send every client's
  request for that model to models/{model}:streamGenerateContent under the
  Gemini URL, translated from chat or Messages, a Gemini client's relayed.
  Native stays "" for such a model, so Pi/omp/droid ask on their own API
  and it is translated.
- gui: modelAPIs counts the Gemini URL, so both pickers offer Gemini.
  Responses was already offered when its URL is set; decide is never a
  model's API. The key protocol picker (per-key, not per-model) is unchanged.
- css: .mname .mapi has min-height, not a fixed 24px: on a phone the web
  GUI's 44px options hung out of the box over the reasoning levels (seen
  with three options on main too), and four wrap to a second row.
- docs/subsystems/gateway-routing.md says a model set to Gemini is
  translated to it. CLI and TUI have no per-model API setting; no new
  strings (Gemini and its hint were already translated).

Run:
- go test -tags nogui ./... under a temp HOME with pinned caches: all ok.
- TestModelAPIGemini (new, httptest upstream with chat, Anthropic and
  Gemini routes): chat stream, chat JSON, Messages and a Gemini client's
  request for the gemini-picked model each hit only
  /v1beta/models/gm:streamGenerateContent?alt=sse with x-goog-api-key and
  the prompt in contents; the other model stays on chat. With modelAPI put
  back to Protocols it FAILs "Gemini picked for a model: a model's API is
  ... not "gemini""; with Save allowed but ModelAPI still refusing it,
  FAILs with chat/messages asked and 503 "no available channel".
- TestModelAPI also checks gemini without a Gemini URL and "decide" are
  refused.
- gofmt -l: nothing. go vet, GOOS=linux and GOOS=windows go vet -tags nogui
  on internal/provider, internal/gateway, internal/gui: clean.
- GUI: model-api-gemini.test.cjs (new), Chromium and WebKit, en, zh,
  zh-TW, ja, de, at 900px and 360px: 20/20. With modelAPIs put back, 20/20
  fail; with the fixed 24px height, the ten 360px runs fail. Whole GUI
  suite, both engines, concurrency 6: 5150/5196. Every failing file rerun
  alone: model-copy-id, agent-models-redraw, library-servers-bulk,
  number-units, sessions-*, usage-* pass alone (load). mobile-web,
  old-webkit (Safari 15.0), plugin-moved-signin and routing-context-fold,
  routing-group-fold, routing-keys-fold (WebKit) fail alone on origin/main
  1b8cb53e as well, with the same counts or more; none touches the model
  API row.
- Not tried against a real Gemini relay; the upstream path is the one
  TestCustomGeminiUpstream already covers.
This commit is contained in:
yetone
2026-10-11 00:33:18 +08:00
parent 472b36cec5
commit 9e823ad4cc
7 changed files with 232 additions and 10 deletions
+1 -1
View File
@@ -23,7 +23,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
| 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`): 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. | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) |
| Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart. | [`sink.go`](../../internal/gateway/sink.go) |
| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`. Stored in `affinity.json` next to `providers.json`. | [`affinity.go`](../../internal/gateway/affinity.go) |
| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`) and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other. Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) |
| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`) and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) |
| Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. | [`trace.go`](../../internal/gateway/trace.go) |
| Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. Only names are kept, never the text. It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). | [`prompt.go`](../../internal/gateway/prompt.go) |
| Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini alone. A request goes to `<base>/publishers/google/models/<model>:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` is asked again with every call sent so (`withoutSignatures`), for that request only. A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts. Both retries are the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) |
+82
View File
@@ -9,6 +9,7 @@ import (
"sync"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
@@ -170,3 +171,84 @@ data: {"type":"response.completed","response":{"id":"r","object":"response","sta
mu.Unlock()
}
}
// A custom provider with a Gemini URL beside its chat and Anthropic ones
// (Kayphoon on Discord: 供应商为自定义的时候已经兼容 gemini 格式了,但模型的
// 详细配置里还是只能限定 chat 和 anthropic): with Gemini picked for a model,
// a chat, a Messages and a Gemini client's request for it each go to
// models/{model}:streamGenerateContent under the Gemini URL, with the key
// in x-goog-api-key, and chat completions and Messages are never tried;
// the provider's other model stays on chat.
func TestModelAPIGemini(t *testing.T) {
var mu sync.Mutex
var hits []string
var bodies [][]byte
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
model := gjson.GetBytes(b, "model").String()
mu.Lock()
hits = append(hits, r.URL.RequestURI()+" "+model+" "+r.Header.Get("x-goog-api-key"))
bodies = append(bodies, b)
mu.Unlock()
switch {
case r.URL.Path == "/v1/chat/completions" && model == "plain":
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(`data: {"id":"c","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"from chat"}}]}`,
`data: {"id":"c","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2}}`,
`data: [DONE]`))
case r.URL.Path == "/v1beta/models/gm:streamGenerateContent":
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(
`data: {"candidates":[{"content":{"role":"model","parts":[{"text":"from "}]}}],"modelVersion":"gm"}`,
`data: {"candidates":[{"content":{"role":"model","parts":[{"text":"gemini"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":7,"candidatesTokenCount":3,"totalTokenCount":10}}`,
))
default:
http.Error(w, `{"error":{"message":"no available channel for model `+model+` under group default"}}`, 503)
}
}))
defer up.Close()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k-1", Chat: up.URL + "/v1", Anthropic: up.URL, Gemini: up.URL + "/v1beta", Models: []string{"gm", "plain"}}); err != nil {
t.Fatal(err)
}
// as the editor's Save sends it
gem := "gemini"
if err := provider.SetModelPrefs("relay", map[string]provider.ModelPref{"gm": {API: &gem}}); err != nil {
t.Fatalf("Gemini picked for a model: %v", err)
}
gw := httptest.NewServer(New().Handler())
defer gw.Close()
const toGemini = "/v1beta/models/gm:streamGenerateContent?alt=sse k-1"
for _, c := range []struct{ path, body, want, hit string }{
{"/v1/chat/completions", `{"model":"relay/gm","stream":true,"messages":[{"role":"user","content":"hi there"}]}`, "gemini", toGemini},
{"/v1/chat/completions", `{"model":"relay/gm","messages":[{"role":"user","content":"hi there"}]}`, "from gemini", toGemini},
{"/v1/messages", `{"model":"relay/gm","max_tokens":64,"messages":[{"role":"user","content":"hi there"}]}`, "from gemini", toGemini},
{"/v1beta/models/relay/gm:streamGenerateContent?alt=sse", `{"contents":[{"role":"user","parts":[{"text":"hi there"}]}]}`, "gemini", toGemini},
{"/v1/chat/completions", `{"model":"relay/plain","stream":true,"messages":[{"role":"user","content":"hi"}]}`, "from chat", "/v1/chat/completions plain "},
} {
mu.Lock()
hits, bodies = nil, nil
mu.Unlock()
res, err := http.Post(gw.URL+c.path, "application/json", strings.NewReader(c.body))
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(res.Body)
res.Body.Close()
mu.Lock()
h, bs := append([]string(nil), hits...), append([][]byte(nil), bodies...)
mu.Unlock()
if res.StatusCode != 200 || !strings.Contains(string(b), c.want) {
t.Errorf("%s %s: %d %s (upstream %v)", c.path, c.body, res.StatusCode, b, h)
continue
}
if len(h) != 1 || h[0] != c.hit {
t.Errorf("%s %s: upstream asked %q, want only %q", c.path, c.body, h, c.hit)
continue
}
if c.hit == toGemini && !strings.Contains(gjson.GetBytes(bs[0], "contents").Raw, "hi there") {
t.Errorf("%s: Gemini body %s", c.path, bs[0])
}
}
}
+4 -1
View File
@@ -2603,7 +2603,10 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.mname .mwho { display: flex; align-items: center; gap: 8px; flex: 1 1 220px; min-width: 0; }
.mname .mwho input { flex: 1; min-width: 0; max-width: 220px; height: 25px; }
.mname .mwho code { font-size: 11px; color: var(--fg-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; user-select: text; -webkit-user-select: text; cursor: text; }
.mname .mapi { flex: none; height: 24px; font-size: 11px; }
/* a model's API choice: Auto and up to four APIs, which wrap to a second
row in a phone-wide editor (Kayphoon: a Gemini URL's beside the others),
the box growing with them rather than the last one hanging out of it */
.mname .mapi { flex: none; min-height: 24px; font-size: 11px; }
.mname .msame { display: flex; align-items: center; gap: 6px; flex: 0 1 230px; min-width: 0; font-size: 11.5px; color: var(--muted); }
.mname .msame span { flex: none; }
.mname .msame input { flex: 1; min-width: 0; height: 25px; font-size: 11.5px; }
+4 -2
View File
@@ -7893,9 +7893,11 @@ const decidesModel = (p, id) => !!p.decide && (decideOnly(p) || (p.deciders ? p.
// modelAPIs: the APIs one of p's models can be asked on alone, those it has
// a URL for when it has more than one — a custom provider's, a preset's or
// a subscription's alike (01huadalang on Discord: 一个 api 里有很多模型但是不同协议;
// OpenCode Go's DeepSeek answers on Responses too)
// OpenCode Go's DeepSeek answers on Responses too), its Gemini URL's
// among them (Kayphoon on Discord: 自定义供应商兼容 gemini 格式了,模型的
// 配置里还是只能选 chat 和 anthropic)
const modelAPIs = (p) => {
const urls = ["chat", "responses", "anthropic"].filter((k) => ((draft?.id === p.id ? draft[k] : undefined) ?? p[k] ?? "").trim());
const urls = ["chat", "responses", "anthropic", "gemini"].filter((k) => ((draft?.id === p.id ? draft[k] : undefined) ?? p[k] ?? "").trim());
return urls.length < 2 ? [] : PROTOS.filter(([k]) => urls.includes(k));
};
@@ -0,0 +1,124 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A custom provider with a Gemini URL beside its chat and Anthropic ones
// (Kayphoon on Discord: 供应商为自定义的时候已经兼容 gemini 格式了,但是在下方
// 模型的详细配置里还是只能限定 chat 和 anthropic): a model can be asked on
// Gemini alone, from its chip's right-click and from Names & levels' API
// row alike, and the Save sends it as modelPrefs. Responses, which it has
// no URL for, isn't offered. In every language, wide and at a phone's
// width, where the row's API choice stays inside the editor and grows to
// hold its options when they wrap.
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 base = { icon: "generic", catalog: "", agents: [], fallback: [], headers: {}, keyList: [], balanceToken: { takes: false, set: false }, proxy: "" };
const relay = {
...base, id: "relay", name: "Relay", chat: "https://relay.example.com/v1", responses: "", anthropic: "https://relay.example.com", gemini: "https://relay.example.com/v1beta",
models: [{ id: "gemini-2.5-pro", name: "gemini-2.5-pro", on: true }, { id: "glm-5", name: "glm-5", on: true }],
key: { set: true, masked: "sk-…one" },
};
function serve(lang, posts) {
const providers = { providers: [relay], presets: [], excluded: [], gateway: { running: true, window: true } };
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const url = new URL(route.request().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:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/provider/save") { posts.push(route.request().postDataJSON()); return json(providers); }
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 words = {
en: { auto: "Asked on: Auto…", staged: "gemini-2.5-pro is asked on Gemini once saved" },
zh: { auto: "协议:自动…", staged: "保存后 gemini-2.5-pro 将使用 Gemini 协议" },
"zh-TW": { auto: "協議:自動…", staged: "儲存後 gemini-2.5-pro 將使用 Gemini 協議" },
ja: { auto: "API:自動…", staged: "保存後、gemini-2.5-pro は Gemini で要求されます" },
de: { auto: "Angefragt über: Automatisch…", staged: "gemini-2.5-pro wird nach dem Speichern über Gemini angefragt" },
};
async function rclick(loc) {
await loc.click({ button: "right", trial: true });
await loc.page().evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
await loc.click({ button: "right" });
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
for (const width of [900, 360]) {
const w = words[lang];
test(`${engine} ${lang} ${width}px: a custom provider's model asked on Gemini`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
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}-${lang}-${width}-model-api-gemini.png`), fullPage: true });
}
await browser.close();
});
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const posts = [];
await page.route("**/*", serve(lang, posts));
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider", { hasText: "Relay" }).first().click();
await page.locator(".editor .mchips .mchip").first().waitFor();
const chip = (id) => page.locator(".editor .mchips .mchip", { hasText: id });
// the chip's menu offers the provider's three APIs, Gemini among them
await rclick(chip("gemini-2.5-pro"));
await page.locator(".pop.row-menu").getByRole("menuitem", { name: w.auto }).click();
const apiMenu = page.locator(".pop.proto-menu.model-api-menu");
await apiMenu.waitFor();
const names = (await apiMenu.locator(".pm-name").allTextContents()).slice(1);
assert.deepEqual(names, ["OpenAI", "Anthropic", "Gemini"], "the APIs it has a URL for, Responses not");
await apiMenu.locator(".pm-item", { hasText: "Gemini" }).click();
await apiMenu.waitFor({ state: "detached" });
assert.equal(await chip("gemini-2.5-pro").locator(".mapi-tag").textContent(), "Gemini");
assert.equal(await page.locator("#status").textContent(), w.staged);
assert.equal(posts.length, 0, "staged, not saved");
// Names & levels' API row shows it, and has Gemini for the other model
await page.evaluate(() => [...document.querySelectorAll(".editor button.text.action")].find((b) => b.closest(".editor") && /Names|名称|名稱|名前|Namen/.test(b.textContent)).click());
const row = (id) => page.locator(".editor .mnames .mname", { has: page.locator(`input[placeholder="${id}"]`) });
await row("glm-5").locator(".mapi").waitFor();
assert.deepEqual(await row("glm-5").locator(".mapi .opt").evaluateAll((os) => os.map((o) => o.dataset.api)), ["", "chat", "anthropic", "gemini"]);
assert.equal(await row("gemini-2.5-pro").locator(".mapi .opt.on").getAttribute("data-api"), "gemini");
await row("glm-5").locator('.mapi .opt[data-api="gemini"]').click();
assert.equal(await row("glm-5").locator(".mapi .opt.on").getAttribute("data-api"), "gemini");
// inside the editor at a phone's width: no page scrolling sideways
const over = await page.evaluate(() => {
const ed = document.querySelector(".editor").getBoundingClientRect();
return [...document.querySelectorAll(".editor .mnames .mapi")].map((m) => m.getBoundingClientRect()).filter((r) => r.right > ed.right + 1 || r.left < ed.left - 1).length
+ (document.documentElement.scrollWidth > innerWidth + 1 ? 100 : 0);
});
assert.equal(over, 0, "the API choice stays inside the editor");
// its options inside its own box, a second row of them too: a
// phone's 44px options hung out of a 24px box over the levels
const out = await row("glm-5").locator(".mapi").evaluate((m) => {
const b = m.getBoundingClientRect();
return [...m.querySelectorAll(".opt")].filter((o) => { const r = o.getBoundingClientRect(); return r.bottom > b.bottom + 0.5 || r.right > b.right + 0.5; }).map((o) => o.dataset.api);
});
assert.deepEqual(out, [], "every option inside the API choice");
await page.locator(".editor button.text.primary").last().click();
for (let i = 0; i < 40 && !posts.length; i++) await page.waitForTimeout(50);
assert.deepEqual(posts[0]?.modelPrefs, { "gemini-2.5-pro": { api: "gemini" }, "glm-5": { api: "gemini" } });
assert.deepEqual(errors, []);
});
}
}
}
+5 -2
View File
@@ -266,8 +266,11 @@ func TestModelAPI(t *testing.T) {
if err := SetModelAPI("relay/mixed", "responses"); err == nil || !strings.Contains(err.Error(), "no responses URL") {
t.Fatalf("an API with no URL: %v", err)
}
if err := SetModelAPI("relay/mixed", "gemini"); err == nil {
t.Fatal("gemini was taken")
if err := SetModelAPI("relay/mixed", "gemini"); err == nil || !strings.Contains(err.Error(), "no gemini URL") {
t.Fatalf("gemini with no Gemini URL: %v", err)
}
if err := SetModelAPI("relay/mixed", "decide"); err == nil || !strings.Contains(err.Error(), "not \"decide\"") {
t.Fatalf("an API a model isn't asked on: %v", err)
}
if err := SetModelAPI("relay/nope", "anthropic"); err == nil {
t.Fatal("a model it hasn't was given an API")
+12 -4
View File
@@ -359,7 +359,7 @@ func setModelImage(ref string, images *bool) (bool, error) {
}
// SetModelAPI says which one of a provider's APIs a model is asked on —
// chat, responses or anthropic — for a relay whose one key serves some of
// chat, responses, anthropic or gemini — for a relay whose one key serves some of
// its models on one and others on another (01huadalang on Discord: 有的供应商
// 一个 api 里有很多模型但是不同协议); "" leaves it to the vendor's list and
// the URLs the provider has, as before. It must be an API the provider has
@@ -378,8 +378,8 @@ func setModelAPI(ref, api string) (bool, error) {
}
proto := Protocol(strings.TrimSpace(api))
if proto != "" {
if !slices.Contains(Protocols, proto) {
return false, fmt.Errorf("a model's API is chat, responses or anthropic, not %q", api)
if !modelAPI(proto) {
return false, fmt.Errorf("a model's API is chat, responses, anthropic or gemini, not %q", api)
}
if p.Base(proto) == "" {
return false, fmt.Errorf("%s has no %s URL to ask %s on: add it under More endpoints first", p.ID, proto, model)
@@ -414,12 +414,20 @@ func (p Provider) ModelAPI(model string) (Protocol, bool) {
return "", false
}
proto := Protocol(heldSettings().ModelAPIs[p.ID+"/"+model])
if proto == "" || !slices.Contains(Protocols, proto) || p.Base(proto) == "" {
if proto == "" || !modelAPI(proto) || p.Base(proto) == "" {
return "", false
}
return proto, true
}
// modelAPI is whether proto is one a model can be set to be asked on: the
// three magpie translates between, and a Gemini URL's generateContent
// (Kayphoon on Discord: a custom provider's Gemini format, which a model's
// own choice didn't offer)
func modelAPI(proto Protocol) bool {
return slices.Contains(Protocols, proto) || proto == Gemini
}
// ModelPref is what the provider editor's Names & levels changed of one
// model, sent with its Save: each part left nil is as it was. Name "" gives
// the model its own name back, Efforts [] all its levels, OwnImages the