gateway keys: model search box, re: patterns and Model names in the key editor (tsingchao on X)

The model picker of a gateway key gets a search box (name or id) and takes
"re:<regexp>" typed then Enter; the row menu gets Model names (aliases-key).
Docs: gateway-routing.md "A key's model patterns and names".

Run (mote): go vet darwin, windows, linux nogui on access/gateway/cli/gui;
go test internal/access, gateway (937s), cli, gui all ok at the pre-rebase
base; after rebasing on origin/main: go build ./..., the new Go tests,
TestCoreScriptBudget, and GUI gateway-key-search-names + gateway-key-models
+ i18n-keys (28 ok, chromium and webkit, en/zh/zh-TW/ja/de, 1100 and 440).
Broken by hand: pattern match off (gateway + access tests red), aliasRequest
off (alias test red), search argument removed (all 20 chromium GUI red).
Not tried: Windows/Linux GUI run, a real client against a real key; the
full suite runs after the tag.
This commit is contained in:
yetone
2026-11-11 06:26:47 +08:00
parent bf4d8f3e5d
commit ce5e5964db
7 changed files with 223 additions and 5 deletions
+6
View File
@@ -1212,6 +1212,12 @@ when nothing else makes videos. Covered by `TestMiniMaxKeysMakeH3Videos`,
`TestMiniMaxComesAfterOtherVideomakers` and
`TestMiniMaxVideoMovesPastATokenPlanKey`.
## A key's model patterns and names
A gateway key's models (`Key.Models`, [`access/models.go`](../../internal/access/models.go), tsingchao on X) are named one by one (`provider/model`), by a provider's whole list (`provider/*`), or by a pattern: an entry that starts with `re:` is a regular expression, RE2 syntax (Go's `regexp`), case-insensitive and not anchored (`re:^gpt-`, `re:claude.*(sonnet|opus)`). It is tried on the whole `provider/model` id and on the model part alone, so `re:^gpt-` and `re:^openai/gpt-` both take `openai/gpt-5`. It never takes a routing group (`group/…`), which a key names itself. Every route that holds a key to its models asks `access.ModelAllowed` (through `Identity.Allows`, `allows`, `modelAllowed`, `keyAllowed`), so a pattern holds chat, Responses, Messages, `count_tokens`, Gemini's path, `/v1/systemone`, the decision models and every list alike (`TestGatewayKeyModelPatternHoldsEveryRoute`). `CleanModels` compiles a pattern when a key is saved and refuses one that is empty or isn't a regular expression; one that fails to compile later (a hand-edited file) matches nothing, never every model. A pattern is for the keys the user makes: `IssueKey` refuses one, since an issued key's models are named one by one or with `*`. The model picker (Gateway page, the key's models badge) has a search box over a model's name and id; typing `re:` and a pattern and pressing Enter adds the pattern; `magpie gateway-key models <id> 're:^gpt-'` does the same.
A key may also name a model its own way (`Key.Aliases`, `aliases-key`, the row menu's Model names, `magpie gateway-key aliases <id> name=provider/model …`): `/v1/models` for that key lists the name in the model's place, and a request that names it goes to the model. A name is a single word (no space, `*` or `re:`) and a name differing only in case is one name; the model must be one the key may use (`ModelAllowed` over its own models and accounts), and when the key later loses the model the name is refused (403) and unlisted. `identifyCaller` rewrites the name once, where the caller's `Identity` is attached to the request ([`gateway/key_aliases.go`](../../internal/gateway/key_aliases.go)): the JSON body's `model` (any route, a body of up to 32MB that isn't compressed), Gemini's `/v1beta/models/<name>:method`, and `GET /v1/models/<name>`; so every later check sees the real model. Limits: a reply still names the real model, Gemini's list (`/v1beta/models`) is not renamed, a non-JSON or compressed body is not read for a name, and an issued key has no names (`TestGatewayKeyAliasRenamesAModel`).
## Short-lived gateway keys
A gateway key may expire (`access.Key.Expires`), and one issued under another
+1 -1
View File
@@ -15278,7 +15278,7 @@ function openProtoMenu(anchor, opts, value, choose, head = "Protocol this key sp
bareTicks(box, items);
if (filter) filter.oninput = () => {
const q = filter.value.trim().toLocaleLowerCase();
items.forEach((b, i) => { b.hidden = !opts[i].always && !opts[i].name.toLocaleLowerCase().includes(q); });
items.forEach((b, i) => { b.hidden = !opts[i].always && !(opts[i].name + " " + (opts[i].find || "")).toLocaleLowerCase().includes(q); });
};
document.body.append(box);
placeMenu(box, anchor, align);
+16
View File
@@ -576,6 +576,10 @@ const I18N = {
"Only these MCP servers and tools: {list}": "仅限这些 MCP 服务器和工具:{list}",
"MCP servers this key may use": "这个密钥可用的 MCP 服务器",
"Keep accounts out": "排除账号",
"Search models, or type re: and a pattern": "搜索模型,或输入 re: 加正则",
"Pattern: models whose name it matches": "模式:名称匹配的模型",
"One name a line: name = provider/model": "每行一个:名称 = provider/model",
"Model names saved": "模型名称已保存",
"Account groups": "账号组",
"Account group": "账号组",
"Account group name": "账号组名称",
@@ -5589,6 +5593,10 @@ const I18N = {
"Only these MCP servers and tools: {list}": "僅限這些 MCP 伺服器和工具:{list}",
"MCP servers this key may use": "這個金鑰可用的 MCP 伺服器",
"Keep accounts out": "排除帳號",
"Search models, or type re: and a pattern": "搜尋模型,或輸入 re: 加正規表示式",
"Pattern: models whose name it matches": "模式:名稱符合的模型",
"One name a line: name = provider/model": "每行一個:名稱 = provider/model",
"Model names saved": "模型名稱已儲存",
"Account groups": "帳號組",
"Account group": "帳號組",
"Account group name": "帳號組名稱",
@@ -10563,6 +10571,10 @@ const I18N = {
"Only these MCP servers and tools: {list}": "この MCP サーバーとツールのみ:{list}",
"MCP servers this key may use": "このキーが使える MCP サーバー",
"Keep accounts out": "アカウントを除外",
"Search models, or type re: and a pattern": "モデルを検索、または re: と正規表現を入力",
"Pattern: models whose name it matches": "パターン:名前が一致するモデル",
"One name a line: name = provider/model": "1行に1つ:名前 = provider/model",
"Model names saved": "モデル名を保存しました",
"Account groups": "アカウントグループ",
"Account group": "アカウントグループ",
"Account group name": "アカウントグループ名",
@@ -15555,6 +15567,10 @@ const I18N = {
"Only these MCP servers and tools: {list}": "Nur diese MCP-Server und Werkzeuge: {list}",
"MCP servers this key may use": "MCP-Server, die dieser Schlüssel nutzen darf",
"Keep accounts out": "Konten ausschließen",
"Search models, or type re: and a pattern": "Modelle suchen, oder re: und ein Muster eingeben",
"Pattern: models whose name it matches": "Muster: Modelle, auf deren Namen es passt",
"One name a line: name = provider/model": "Ein Name pro Zeile: Name = provider/model",
"Model names saved": "Modellnamen gespeichert",
"Account groups": "Kontogruppen",
"Account group": "Kontogruppe",
"Account group name": "Name der Kontogruppe",
+60 -4
View File
@@ -346,6 +346,8 @@ function gatewayKeyMore(k) {
...(k.browser ? [] : [{ name: "MCP servers", icon: MCP_GLYPH, run: () => gatewayMCPPick(k, more) }]),
// every account but some, those signed in later too (LeiWang_2000
// on X); the Browser key uses no account
// a name of the key's own for a model it may use (tsingchao on X)
...(k.browser || k.readOnly ? [] : [{ name: "Model names", icon: MCP_GLYPH, run: () => gatewayAliasesAsk(k) }]),
...(k.browser ? [] : [{ name: "Keep accounts out", icon: KEEP_OUT_GLYPH, run: () => gatewayKeptOutPick(k, more) }]),
{ name: "Rotate key", icon: ROTATE_GLYPH, run: () => askGatewayKey(k, true) },
{ name: "Remove", icon: REMOVE_GLYPH, sep: true, run: () => askGatewayKey(k, false) },
@@ -375,6 +377,50 @@ function gatewayBrowserTag() {
return tag;
}
// gatewayAliasesAsk edits the names a key gives its models: one
// "name = provider/model" a line. /v1/models lists the name in the model's
// place and a request by it goes to the model.
function gatewayAliasesAsk(k) {
const ed = el("div", "editor");
const head = el("div", "ehead");
head.append(el("b", "", t("Model names")));
const ta = el("textarea", "json");
ta.value = Object.entries(k.aliases || {}).map(([n, m]) => n + " = " + m).join("\n");
ta.placeholder = "gpt-4 = openai/gpt-5";
ta.spellcheck = false;
ta.rows = 6;
ta.setAttribute("aria-label", t("Model names"));
ta.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape") closeConfirmAsk(); };
const why = el("div", "why");
why.setAttribute("aria-live", "polite");
const bar = el("div", "bar");
const cancel = el("button", "text", t("Cancel"));
cancel.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); };
const go = el("button", "text primary", t("Save"));
go.onclick = async (e) => {
e.stopPropagation();
if (go.disabled) return;
const aliases = {};
for (const line of ta.value.split("\n")) {
if (!line.trim()) continue;
const at = line.indexOf("=");
if (at < 1 || !line.slice(at + 1).trim()) { why.textContent = t("One name a line: name = provider/model"); return; }
aliases[line.slice(0, at).trim()] = line.slice(at + 1).trim();
}
go.disabled = true;
const out = await gatewayKeyAction("aliases-key", { key: k.id, aliases });
if (!out) { go.disabled = false; return; }
closeConfirmAsk();
status(t("Model names saved"), "ok");
};
bar.append(el("span", "grow"), cancel, go);
ed.append(head, ta, why, bar);
confirmAsk = ed;
openModal(ed);
$("#modal").classList.add("lib");
ta.focus({ preventScroll: true });
}
function askGatewayKey(k, rotate) {
const ed = el("div", "editor");
const head = el("div", "ehead");
@@ -626,7 +672,7 @@ function gatewayModelsBadge(k) {
// asks it whatever the key may use, and the key may ask it itself
// (/v1/systemone, another magpie's list) only when it is picked
// (Kautism on Discord)
opts.push({ v: m.id, name: m.name, note: m.decides ? m.id + " · " + t("Decision model: a routing group asks it whatever this key may use; pick it so the key may ask it itself") : m.id, literalName: true });
opts.push({ v: m.id, find: m.id, name: m.name, note: m.decides ? m.id + " · " + t("Decision model: a routing group asks it whatever this key may use; pick it so the key may ask it itself") : m.id, literalName: true });
}
endBlock();
// a provider with accounts and no model in the list (one kept
@@ -638,7 +684,7 @@ function gatewayModelsBadge(k) {
// what the CLI kept that the list hasn't, a pattern, a model gone or
// an account signed out: behind every live entry, a model gone
// before an account signed out
for (const v of ms) if (!opts.some((o) => o.v === v)) opts.push({ v, name: v, note: "Not served now", literalName: true });
for (const v of ms) if (!opts.some((o) => o.v === v)) opts.push({ v, name: v, note: /^re:/i.test(v) ? "Pattern: models whose name it matches" : "Not served now", literalName: true });
for (const v of as) if (!accountsSet.has(v)) { accountsSet.add(v); opts.push({ v, name: v, note: v.startsWith("@") ? "Account group removed" : "Not signed in now", literalName: true }); }
openProtoMenu(b, opts, [...ms, ...as], (picked) => {
// one action at a time: gatewayKeyAction is busy while one is sent.
@@ -658,7 +704,17 @@ function gatewayModelsBadge(k) {
await gatewayKeyAction("accounts-key", { key: k.id, accounts: [...pickedAccounts, ...out] });
}
})();
}, "Models this key may use", "sess-menu", "right");
}, "Models this key may use", "sess-menu", "right", false, "Search models, or type re: and a pattern");
// "re:^gpt-" and Enter adds the pattern (a regular expression the
// gateway checks every model id against); the server refuses a bad one
const q = document.querySelector(".proto-menu .sc-q");
if (q) q.addEventListener("keydown", (e) => {
const v = q.value.trim();
if (e.key !== "Enter" || !/^re:./i.test(v)) return;
e.preventDefault(); e.stopPropagation();
closeProtoMenu();
if (!ms.includes(v)) gatewayKeyAction("models-key", { key: k.id, models: [...ms, v] });
}, true);
};
b.onclick = async (e) => {
e.preventDefault();
@@ -753,7 +809,7 @@ async function gatewayMCPPick(k, anchor) {
}
// what the CLI kept that the list hasn't: a server gone, or a tool it
// no longer lists
for (const v of ms) if (!opts.some((o) => o.v === v)) opts.push({ v, name: v, note: "Not served now", literalName: true });
for (const v of ms) if (!opts.some((o) => o.v === v)) opts.push({ v, name: v, note: /^re:/i.test(v) ? "Pattern: models whose name it matches" : "Not served now", literalName: true });
openProtoMenu(anchor, opts, [...ms], (picked) => {
// "No MCP server" just ticked is none; left ticked beside a server
// ticked since, the server
+48
View File
@@ -0,0 +1,48 @@
package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
)
// A key's model may be a pattern ("re:<regular expression>"), refused when
// it isn't one rather than kept to allow every model, and a key keeps the
// names it gives models (tsingchao on X).
func TestCallerKeyPatternsAndNames(t *testing.T) {
sandboxHome(t)
mux := http.NewServeMux()
callerKeyRoutes(mux)
request := func(path, body string) *httptest.ResponseRecorder {
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", path, strings.NewReader(body)))
return w
}
var s struct{ Keys []access.Key }
if w := request("/api/caller-keys/add-key", `{"name":"Phone"}`); w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &s) != nil {
t.Fatal(w.Code, w.Body)
}
id := s.Keys[0].ID
if w := request("/api/caller-keys/models-key", `{"key":"`+id+`","models":["re:^gpt-","openai/o3"]}`); w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &s) != nil || !slices.Equal(s.Keys[0].Models, []string{"re:^gpt-", "openai/o3"}) {
t.Fatal("pattern", w.Code, w.Body)
}
if w := request("/api/caller-keys/models-key", `{"key":"`+id+`","models":["re:("]}`); w.Code != 400 || !strings.Contains(w.Body.String(), "regular expression") {
t.Fatal("kept a bad pattern", w.Code, w.Body)
}
if w := request("/api/caller-keys/aliases-key", `{"key":"`+id+`","aliases":{"fast":"openai/gpt-5"}}`); w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &s) != nil || s.Keys[0].Aliases["fast"] != "openai/gpt-5" {
t.Fatal("alias", w.Code, w.Body)
}
// a model the key may not use can't be named
if w := request("/api/caller-keys/aliases-key", `{"key":"`+id+`","aliases":{"x":"anthropic/claude"}}`); w.Code != 400 {
t.Fatal("named a model the key may not use", w.Code, w.Body)
}
var none struct{ Keys []access.Key }
if w := request("/api/caller-keys/aliases-key", `{"key":"`+id+`","aliases":{}}`); w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &none) != nil || len(none.Keys[0].Aliases) != 0 {
t.Fatal("names not taken off", w.Code, w.Body)
}
}
+4
View File
@@ -216,6 +216,10 @@ function fixture(lang, theme, events, options = {}) {
else k.used = reset(k.used);
}
if (action === "models-key") k.models = body.models?.length ? body.models : undefined;
if (action === "aliases-key") {
if (Object.values(body.aliases || {}).some((v) => !String(v).includes("/"))) return route.fulfill({ status: 400, json: { error: "An alias names a model as provider/model" } });
k.aliases = Object.keys(body.aliases || {}).length ? body.aliases : undefined;
}
if (action === "accounts-key") k.accounts = body.accounts?.length ? body.accounts : undefined;
if (action === "mcp-key") k.mcp = body.mcp?.length ? body.mcp : undefined;
if (action === "quotas-key") k.quotas = body.quotas || undefined;
@@ -0,0 +1,88 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A gateway key's model picker has a search box (it narrows by a model's
// name or its id), takes a regular expression typed as "re:<pattern>"
// and Enter, and the key's row menu gives the key's own names for models
// ("Model names", one "name = provider/model" a line, sent as
// "aliases-key"). tsingchao on X. In every language, Chromium and WebKit,
// wide and narrow.
const assert = require("node:assert/strict");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { fixture } = require("./fixtures/caller-keys.cjs");
const words = {
en: { label: "Models this key may use", search: "Search models, or type re: and a pattern", names: "Model names", save: "Save", bad: "One name a line: name = provider/model", saved: "Model names saved", model: "Model mini" },
zh: { label: "此密钥可用的模型", search: "搜索模型,或输入 re: 加正则", names: "模型名", save: "保存", bad: "每行一个:名称 = provider/model", saved: "模型名称已保存", model: "Model mini" },
"zh-TW": { label: "此金鑰可用的模型", search: "搜尋模型,或輸入 re: 加正規表示式", names: "模型名稱", save: "儲存", bad: "每行一個:名稱 = provider/model", saved: "模型名稱已儲存", model: "Model mini" },
ja: { label: "このキーで使えるモデル", search: "モデルを検索、または re: と正規表現を入力", names: "モデル名", save: "保存", bad: "1行に1つ:名前 = provider/model", saved: "モデル名を保存しました", model: "Model mini" },
de: { label: "Modelle, die dieser Schlüssel nutzen darf", search: "Modelle suchen, oder re: und ein Muster eingeben", names: "Modellnamen", save: "Speichern", bad: "Ein Name pro Zeile: Name = provider/model", saved: "Modellnamen gespeichert", model: "Model mini" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const width of [1100, 440]) {
for (const [lang, w] of Object.entries(words)) {
test(`${engine} ${width} ${lang}: a key's models are searched, matched by a pattern and named`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(6000);
page.setDefaultNavigationTimeout(60000);
const events = [], errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", fixture(lang, "light", events, { lan: true }));
await page.goto("http://magpie.test/?view=gateway");
await page.locator("#gatewayKeys .acc[data-key]").last().waitFor();
const row = page.locator('#gatewayKeys .acc[data-key="work"]');
const sent = (a) => events.filter((e) => e.action === a).map((e) => e.body);
const until = async (fn) => {
for (let i = 0; i < 150 && !fn(); i++) await new Promise((r) => setTimeout(r, 20));
};
// the search box narrows by name, and by id
await row.hover();
await row.getByRole("button", { name: w.label, exact: true }).click();
const menu = page.locator(".proto-menu");
await menu.waitFor();
const q = menu.locator(".sc-q");
assert.equal(await q.getAttribute("placeholder"), w.search);
const shown = async () => (await menu.locator(".pm-item:not([hidden]) .pm-name").allTextContents()).map((s) => s.trim());
await q.fill("mini");
assert.deepEqual(await shown(), [w.model]);
await q.fill("openai/gpt");
assert.deepEqual(await shown(), ["GPT-5"]);
// a pattern typed as re: and Enter is added, and closes the menu
await q.fill("re:^gpt-");
await q.press("Enter");
await menu.waitFor({ state: "detached" });
await until(() => sent("models-key").length);
assert.deepEqual(sent("models-key"), [{ key: "work", models: ["re:^gpt-"] }]);
await page.waitForFunction(() => document.querySelector('#gatewayKeys .acc[data-key="work"] .key-models.set')?.textContent.trim() === "re:^gpt-");
// the key's names for models: a line that isn't one is said, not sent
await row.hover();
await row.locator(".gw-key-more").click();
await page.locator(".row-menu").getByRole("menuitem", { name: w.names, exact: true }).click();
const modal = page.locator("#modal");
const ta = modal.locator("textarea");
await ta.waitFor();
await ta.fill("oops");
await modal.getByRole("button", { name: w.save, exact: true }).click();
await modal.getByText(w.bad).waitFor();
assert.equal(sent("aliases-key").length, 0);
await ta.fill("fast = relay/m\n\ngpt-4 = openai/gpt-5");
await modal.getByRole("button", { name: w.save, exact: true }).click();
await until(() => sent("aliases-key").length);
assert.deepEqual(sent("aliases-key"), [{ key: "work", aliases: { fast: "relay/m", "gpt-4": "openai/gpt-5" } }]);
await modal.waitFor({ state: "hidden" });
// opened again, the names are in it
await row.hover();
await row.locator(".gw-key-more").click();
await page.locator(".row-menu").getByRole("menuitem", { name: w.names, exact: true }).click();
await ta.waitFor();
assert.equal(await ta.inputValue(), "fast = relay/m\ngpt-4 = openai/gpt-5");
await page.keyboard.press("Escape");
await page.waitForFunction(() => document.documentElement.scrollWidth <= window.innerWidth);
assert.deepEqual(errors, []);
});
}
}
}