From 2f5ff69d3d8a2bbf4c43ddc2d739d50536b55358 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 4 Oct 2026 22:59:16 +0800 Subject: [PATCH] =?UTF-8?q?gui:=20the=20Gateway=20page's=20Connect=20speak?= =?UTF-8?q?s=20System=20One=20too,=20with=20a=20decision=20model=20(ARNO?= =?UTF-8?q?=20on=20Discord:=20gateway=E6=B7=BB=E5=8A=A0system=20one=20api?= =?UTF-8?q?=20=E6=9C=89=E6=83=B3=E6=B3=95=E5=90=97)=20=E2=80=94=20magpie's?= =?UTF-8?q?=20gateway=20has=20served=20POST=20/v1/systemone,=20but=20Conne?= =?UTF-8?q?ct=20showed=20only=20OpenAI,=20Responses,=20Anthropic=20and=20G?= =?UTF-8?q?emini,=20so=20nothing=20on=20the=20page=20said=20so=20or=20how?= =?UTF-8?q?=20to=20ask=20it.=20Connect=20has=20a=20System=20One=20tab:=20b?= =?UTF-8?q?ase=20=E2=80=A6/v1,=20curl,=20Python=20(requests)=20and=20Node?= =?UTF-8?q?=20(fetch)=20snippets=20that=20POST=20=E2=80=A6/v1/systemone=20?= =?UTF-8?q?with=20Authorization:=20Bearer,=20a=20state=20and=20a=20choice?= =?UTF-8?q?=20question,=20printing=20the=20answer's=20choice=20and=20confi?= =?UTF-8?q?dence;=20the=20note=20says=20Clef=20also=20reads=20images=20("i?= =?UTF-8?q?mages":=20[data=20URLs]).=20No=20SDK=20speaks=20it,=20so=20it?= =?UTF-8?q?=20has=20no=20Shell=20tab,=20and=20the=20base=20URL=20and=20key?= =?UTF-8?q?=20hints=20say=20where=20the=20request=20goes=20and=20how=20the?= =?UTF-8?q?=20key=20is=20sent=20instead=20of=20naming=20env=20variables.?= =?UTF-8?q?=20Its=20model=20is=20a=20decision=20model=20only=20(decidesMod?= =?UTF-8?q?el:=20a=20decision-only=20provider's,=20or=20a=20Jev),=20and=20?= =?UTF-8?q?the=20other=20tabs=20no=20longer=20take=20one;=20a=20click=20on?= =?UTF-8?q?=20a=20decision=20model=20in=20the=20list=20switches=20Connect?= =?UTF-8?q?=20to=20System=20One,=20a=20click=20on=20any=20other=20model=20?= =?UTF-8?q?back=20to=20OpenAI,=20each=20tab=20keeping=20its=20own=20pick?= =?UTF-8?q?=20(magpie.decideModel).=20The=20head=20says=20five=20APIs;=20C?= =?UTF-8?q?onnect's=20tab=20strips=20scroll=20in=20themselves=20on=20a=20n?= =?UTF-8?q?arrow=20window,=20as=20the=20region=20strip=20does,=20rather=20?= =?UTF-8?q?than=20widening=20the=20card.=20zh=20and=20ja=20strings.=20gate?= =?UTF-8?q?way-systemone.test.cjs=20(WebKit,=20en=20and=20zh,=20light=20an?= =?UTF-8?q?d=20dark)=20fails=20on=20the=20old=20code;=20gateway-connect-ke?= =?UTF-8?q?ys,=20-model-info,=20-fold,=20-older,=20-caller-keys,=20-key-li?= =?UTF-8?q?mit=20and=20gui-ja=20pass=20on=20WebKit;=20Chromium=20doesn't?= =?UTF-8?q?=20launch=20in=20this=20sandbox.=20The=20snippet's=20request,?= =?UTF-8?q?=20sent=20to=20the=20gateway's=20handler,=20reached=20a=20Worke?= =?UTF-8?q?rs=20AI=20Jev=20and=20Clef=20in=20their=20own=20shapes,=20and?= =?UTF-8?q?=20with=20the=20owner's=20real=20TypeSafe=20key=20in=20a=20sand?= =?UTF-8?q?box=20HOME,=20jev-latest=20answered=20200=20with=20choice=20bil?= =?UTF-8?q?ling,=20confidence=200.55.=20go=20vet,=20builds=20(darwin,=20GO?= =?UTF-8?q?OS=3Dlinux=20nogui,=20GOOS=3Dwindows)=20and=20go=20test=20-tags?= =?UTF-8?q?=20nogui=20-count=3D1=20./...=20under=20a=20temp=20HOME=20pass.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gui/assets/app.css | 10 +- internal/gui/assets/app.js | 97 ++++++++++++--- internal/gui/assets/i18n.js | 16 ++- internal/gui/tests/gateway-systemone.test.cjs | 117 ++++++++++++++++++ 4 files changed, 218 insertions(+), 22 deletions(-) create mode 100644 internal/gui/tests/gateway-systemone.test.cjs diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 075f5bcdf..59fb03ee4 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2048,13 +2048,15 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } pointer-events: none; } .segs .thumb { border-radius: 5px; } -.segs.regions { max-width: 100%; overflow-x: auto; } +/* a strip too wide for the window scrolls in itself: the regions, and + Connect's five APIs on a narrow one */ +.segs.regions, .connect .segs { max-width: 100%; overflow-x: auto; } /* no scrollbar-width here: Chromium (WebView2) then drops every ::-webkit-scrollbar rule and draws Windows' classic bar, arrows and all, under the strip; the app's thin thumb instead, slimmer still */ -:where(body:not(.mac)) .segs.regions::-webkit-scrollbar { height: 6px; } -:where(body:not(.mac)) .segs.regions::-webkit-scrollbar-thumb { border-width: 1px; } -.segs.regions .opt { flex: none; } +:where(body:not(.mac)) :is(.segs.regions, .connect .segs)::-webkit-scrollbar { height: 6px; } +:where(body:not(.mac)) :is(.segs.regions, .connect .segs)::-webkit-scrollbar-thumb { border-width: 1px; } +.segs.regions .opt, .connect .segs .opt { flex: none; } /* an installed list's order (#481): small, beside the list's heading */ .segs.sortby { align-self: center; flex: none; } .segs.sortby .opt { height: 20px; padding: 0 8px; font-size: 11px; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 422784cf8..dc577bd83 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -57,6 +57,7 @@ let importingApps = null; // the Import from other apps dialog: { sources, picks let flavor = params.get("flavor") || localStorage.getItem("magpie.flavor") || "openai"; // which API the snippets speak let lang = params.get("lang") || localStorage.getItem("magpie.lang") || "shell"; // which snippet let exampleModel = localStorage.getItem("magpie.model") || ""; // the model in the snippets +let decideModel = localStorage.getItem("magpie.decideModel") || ""; // the System One snippets' decision model let connectFolded = false; // Connect folded away under its heading try { connectFolded = localStorage.getItem("magpie.gwConnectFolded") === "1"; } catch {} const expandedCalls = new Set(); // recent-call ids whose wire bodies are open @@ -4411,7 +4412,7 @@ function accountPlan(a) { // ---------- gateway view ---------- // -// The gateway is one local endpoint speaking four APIs; this tab is the +// The gateway is one local endpoint speaking five APIs; this tab is the // page that gets anything else connected to it: base URL, key, model ids, // and a snippet in whichever language the reader is holding. @@ -4552,7 +4553,7 @@ function renderGateway() { if (older) { who.append(name, el("div", "sub old", t("Agents' requests go through magpie {v} and are sent as it sends them, without this version's fixes. Quit that magpie (a magpie serve, another copy) and this one takes the gateway over within 15 seconds.", { v: g.version }))); } else who.append(name, el("div", "sub", g.running - ? [t(g.models === 1 ? "{n} model" : "{n} models", { n: g.models }), n ? t(n === 1 ? "{n} agent routed through it" : "{n} agents routed through it", { n }) : t("no agent routed through it yet"), t("four APIs, one URL")].join(" · ") + ? [t(g.models === 1 ? "{n} model" : "{n} models", { n: g.models }), n ? t(n === 1 ? "{n} agent routed through it" : "{n} agents routed through it", { n }) : t("no agent routed through it yet"), t("five APIs, one URL")].join(" · ") : t("start it with magpie serve, or open magpie at login"))); const url = el("button", "url"); url.append(el("code", "", g.url)); @@ -4647,6 +4648,45 @@ const ai = new GoogleGenAI({ const r = await ai.models.generateContent({ model: "${m}", contents: "hi" }); console.log(r.text);`, }, + // magpie's own System One API (ARNO on Discord: gateway添加system one + // api 有想法吗): a decision model — Jev, Clef, Bailian's — answers typed + // questions about a state; no SDK speaks it, so no shell variables + systemone: { + name: "System One", base: (u) => u + "/v1", decide: true, + note: "TypeSafe's decision API: a Jev or Clef model answers typed questions (choice, noul, score) about a state, with how sure it is. Clef also reads images: add \"images\": [\"data:image/png;base64,…\"].", + curl: (b, m, k = "magpie") => ({ url: `${b}/systemone`, headers: [`Authorization: Bearer ${k}`], + body: `{"model": "${m}",\n "state": {"message": "My order never arrived, refund it"},\n "questions": {"team": {"type": "choice",\n "instructions": "Which team should answer the message?",\n "criteria": {"billing": "Payments and refunds", "shipping": "Deliveries", "other": "Anything else"}}}}` }), + python: (b, m, k = "magpie") => `import requests + +r = requests.post("${b}/systemone", + headers={"Authorization": "Bearer ${k}"}, + json={ + "model": "${m}", + "state": {"message": "My order never arrived, refund it"}, + "questions": {"team": { + "type": "choice", + "instructions": "Which team should answer the message?", + "criteria": {"billing": "Payments and refunds", "shipping": "Deliveries", "other": "Anything else"}, + }}, + }) +a = r.json()["answers"]["team"] +print(a["choice"], a["confidence"])`, + node: (b, m, k = "magpie") => `const r = await fetch("${b}/systemone", { + method: "POST", + headers: { Authorization: "Bearer ${k}", "Content-Type": "application/json" }, + body: JSON.stringify({ + model: "${m}", + state: { message: "My order never arrived, refund it" }, + questions: { team: { + type: "choice", + instructions: "Which team should answer the message?", + criteria: { billing: "Payments and refunds", shipping: "Deliveries", other: "Anything else" }, + } }, + }), +}); +const a = (await r.json()).answers.team; +console.log(a.choice, a.confidence);`, + }, }; // Windows gets PowerShell: $env: in place of export, and the curl.exe that // ships with it (plain curl there is Invoke-WebRequest). The body goes in @@ -4664,6 +4704,9 @@ function envSnippet(vars) { return vars.map(([k, v]) => (WIN ? `$env:${k}="${v}"` : `export ${k}=${v}`)).join("\n"); } +// a decision model on the list: one only System One asks, never an agent +const decideEntry = (m) => !m.group && !!m.provider?.id && decidesModel(m.provider, m.id.slice(m.provider.id.length + 1)); + // every exposed model, as the ids agents use function gatewayModels() { // the routing groups first, as the agents' pickers list them @@ -4746,10 +4789,20 @@ function renderConnect() { const g = providers.gateway; const box = $("#connect"); box.replaceChildren(); - const models = gatewayModels(); - if (!models.some((m) => m.id === exampleModel)) exampleModel = models[0]?.id || ""; - const model = exampleModel || "provider/model"; const f = FLAVORS[flavor] || FLAVORS.openai; + // System One's snippets take a decision model, the others any other + const models = gatewayModels().filter((m) => decideEntry(m) === !!f.decide); + let model; + if (f.decide) { + if (!models.some((m) => m.id === decideModel)) decideModel = models[0]?.id || ""; + model = decideModel || "provider/jev-latest"; + } else { + if (!models.some((m) => m.id === exampleModel)) exampleModel = models[0]?.id || ""; + model = exampleModel || "provider/model"; + } + // no SDK speaks System One, so it has no shell variables to set + const langs = f.baseEnv ? LANGS : LANGS.filter(([id]) => id !== "shell"); + const snipLang = langs.some(([id]) => id === lang) ? lang : "curl"; const urls = [g.url, ...(g.lanURLs || [])]; if (!urls.includes(connectURL)) connectURL = g.url; const remote = connectURL !== g.url; @@ -4783,7 +4836,7 @@ function renderConnect() { (u) => { connectURL = u; renderConnect(); })); else b.append(el("code", "", base)); b.append(copyBtn(base, "Base URL")); - box.append(...field("Base URL", b, t("What {env} takes.", { env: f.baseEnv }))); + box.append(...field("Base URL", b, f.baseEnv ? t("What {env} takes.", { env: f.baseEnv }) : t("Requests go to POST {url}.", { url: base + "/systemone" }))); const k = el("div", "val"); const options = keys.map((k) => ({ v: k.id, name: k.name, literalName: true, note: k.masked })); @@ -4795,30 +4848,34 @@ function renderConnect() { else k.append(el("code", "", t("Create a gateway key above to connect"))); if (key) k.append(copyCallerKeyBtn(key)); else if (!remote) k.append(copyBtn("magpie", t("Key"))); - box.append(...field(t(keyLabel), k, t(g.lan && (remote || gatewayKeys?.length) + box.append(...field(t(keyLabel), k, !f.keyEnv ? t(g.lan && (remote || gatewayKeys?.length) + ? "Choose a gateway key to send as Authorization: Bearer; usage is tracked by key." + : "Sent as Authorization: Bearer. The gateway trusts everything on loopback, so any value works.") : t(g.lan && (remote || gatewayKeys?.length) ? "Choose a gateway key to use as {env}; usage is tracked by key." : "{env}=magpie. The gateway trusts everything on loopback, so any value works.", { env: f.keyEnv }))); const m = el("div", "val"); m.append(el("code", "", model), copyBtn(model, t("Model id"))); - box.append(...field(t("Model"), m, t(models.length ? "provider/model, as listed below. Click a model there to put it in the snippets." : "No models yet. Add a provider, or sign in to Codex or Copilot."))); + box.append(...field(t("Model"), m, f.decide + ? t(models.length ? "A decision model (Jev, Clef), as listed below. Click one there to put it in the snippets." : "No decision models yet. Add a System One, Jev or Workers AI provider.") + : t(models.length ? "provider/model, as listed below. Click a model there to put it in the snippets." : "No models yet. Add a provider, or sign in to Codex or Copilot."))); const ex = el("div", "stack"); - ex.append(segs(LANGS, lang, (id) => { lang = id; localStorage.setItem("magpie.lang", id); renderConnect(); })); + ex.append(segs(langs, snipLang, (id) => { lang = id; localStorage.setItem("magpie.lang", id); renderConnect(); })); const code = !secret ? t(key ? "Loading gateway key…" : "Create a gateway key above to connect") - : lang === "shell" ? envSnippet([[f.baseEnv, base], [f.keyEnv, secret]]) - : lang === "curl" ? curlSnippet(f.curl(base, model, secret)) - : f[lang](base, model, secret); + : snipLang === "shell" ? envSnippet([[f.baseEnv, base], [f.keyEnv, secret]]) + : snipLang === "curl" ? curlSnippet(f.curl(base, model, secret)) + : f[snipLang](base, model, secret); const pre = el("pre", "snip"); const c = el("code"); - c.append(highlight(code, lang)); + c.append(highlight(code, snipLang)); pre.append(c); // the button sits outside the scrolling box, so a long line doesn't carry it off const wrap = el("div", "snip-wrap"); wrap.append(pre); if (secret) wrap.append(copyBtn(code, t("Snippet"))); ex.append(wrap); - box.append(...field(t("Example"), ex, lang === "shell" ? t("Put these in the shell (or the tool's settings) and the tool talks to magpie instead of the vendor.") : "")); + box.append(...field(t("Example"), ex, snipLang === "shell" ? t("Put these in the shell (or the tool's settings) and the tool talks to magpie instead of the vendor.") : "")); } // A small highlighter for the four snippet dialects: strings, comments, @@ -4917,14 +4974,22 @@ function renderGatewayModels() { return; } for (const m of models) { - const row = el("div", "row model" + (m.id === exampleModel ? " selected" : "")); + const row = el("div", "row model" + (m.id === (FLAVORS[flavor]?.decide ? decideModel : exampleModel) ? " selected" : "")); const who = el("div", "who"); const name = el("div", "name", m.id); if (namedFree(m.id, m.name)) name.append(freeBadge(false)); who.append(name, el("div", "sub", m.name && m.name !== m.id.split("/")[1] ? `${m.name} · ${m.provider.name}` : m.provider.name)); row.append(m.group ? stackIcon(m.icons) : icon(m.provider.icon || "generic"), who, modelInfo(m), copyBtn(m.id, t("Model id"))); row.title = t("Use this model in the snippets"); - row.onclick = () => { exampleModel = m.id; localStorage.setItem("magpie.model", m.id); renderConnect(); renderGatewayModels(); }; + // a decision model is put in System One's snippets, any other in the + // other APIs'; the API follows the model clicked + row.onclick = () => { + const so = decideEntry(m); + if (so) { decideModel = m.id; localStorage.setItem("magpie.decideModel", m.id); } + else { exampleModel = m.id; localStorage.setItem("magpie.model", m.id); } + if (so !== !!FLAVORS[flavor]?.decide) { flavor = so ? "systemone" : "openai"; localStorage.setItem("magpie.flavor", flavor); } + renderConnect(); renderGatewayModels(); + }; list.append(row); } } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 60f3afa50..5e4f7bb3c 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1255,7 +1255,6 @@ const I18N = { "{n} agent routed through it": "{n} 个 Agent 经由此路由", "{n} agents routed through it": "{n} 个 Agent 经由此路由", "no agent routed through it yet": "尚无 Agent 经由此路由", - "four APIs, one URL": "四种 API,一个地址", "start it with magpie serve, or open magpie at login": "用 magpie serve 启动,或让 magpie 开机自启", "Copy the gateway URL": "复制网关地址", "Gateway URL": "网关地址", @@ -1390,6 +1389,13 @@ const I18N = { "Messages API. Claude Code reads ANTHROPIC_AUTH_TOKEN instead of the key; the Agents tab sets that for you.": "Messages API。Claude Code 读取 ANTHROPIC_AUTH_TOKEN 而非密钥;Agent 页会替你设置。", "Google's generateContent API, v1beta. Gemini CLI and the google-genai SDKs speak this.": "Google 的 generateContent API(v1beta)。Gemini CLI 和 google-genai SDK 使用它。", "What {env} takes.": "填入 {env}。", + "five APIs, one URL": "五种 API,一个地址", + "TypeSafe's decision API: a Jev or Clef model answers typed questions (choice, noul, score) about a state, with how sure it is. Clef also reads images: add \"images\": [\"data:image/png;base64,…\"].": "TypeSafe 的决策 API:Jev 或 Clef 模型按类型(choice、noul、score)回答关于一段 state 的问题,并给出把握有多大。Clef 还能读图:加上 \"images\": [\"data:image/png;base64,…\"]。", + "Requests go to POST {url}.": "请求发到 POST {url}。", + "Choose a gateway key to send as Authorization: Bearer; usage is tracked by key.": "选一个网关密钥作为 Authorization: Bearer 发送;用量按密钥统计。", + "Sent as Authorization: Bearer. The gateway trusts everything on loopback, so any value works.": "作为 Authorization: Bearer 发送。网关信任本机回环上的所有请求,填什么都行。", + "A decision model (Jev, Clef), as listed below. Click one there to put it in the snippets.": "决策模型(Jev、Clef),见下方列表。点一个即可填进示例。", + "No decision models yet. Add a System One, Jev or Workers AI provider.": "还没有决策模型。添加一个 System One、Jev 或 Workers AI 供应商。", "Key": "密钥", "{env}=magpie. The gateway trusts everything on loopback, so any value works.": "{env}=magpie。网关信任本机回环上的一切请求,随便填什么都行。", "Model": "模型", @@ -4208,7 +4214,6 @@ const I18N = { "{n} agent routed through it": "{n} 個のエージェントが経由", "{n} agents routed through it": "{n} 個のエージェントが経由", "no agent routed through it yet": "経由しているエージェントはまだありません", - "four APIs, one URL": "4つの API、1つの URL", "start it with magpie serve, or open magpie at login": "magpie serve で起動するか、ログイン時に magpie を開くよう設定してください", "Copy the gateway URL": "ゲートウェイ URL をコピー", "Gateway URL": "ゲートウェイ URL", @@ -4365,6 +4370,13 @@ const I18N = { "Messages API. Claude Code reads ANTHROPIC_AUTH_TOKEN instead of the key; the Agents tab sets that for you.": "Messages API。Claude Code はキーの代わりに ANTHROPIC_AUTH_TOKEN を読みます。「エージェント」タブが設定します。", "Google's generateContent API, v1beta. Gemini CLI and the google-genai SDKs speak this.": "Google の generateContent API(v1beta)。Gemini CLI と google-genai SDK はこれを使います。", "What {env} takes.": "{env} に設定する値。", + "five APIs, one URL": "5つの API、1つの URL", + "TypeSafe's decision API: a Jev or Clef model answers typed questions (choice, noul, score) about a state, with how sure it is. Clef also reads images: add \"images\": [\"data:image/png;base64,…\"].": "TypeSafe の判定 API:Jev や Clef のモデルが state についての型付きの質問(choice、noul、score)に、確信度つきで答えます。Clef は画像も読めます:\"images\": [\"data:image/png;base64,…\"] を加えてください。", + "Requests go to POST {url}.": "リクエストは POST {url} に送られます。", + "Choose a gateway key to send as Authorization: Bearer; usage is tracked by key.": "Authorization: Bearer として送るゲートウェイキーを選びます。使用量はキーごとに記録されます。", + "Sent as Authorization: Bearer. The gateway trusts everything on loopback, so any value works.": "Authorization: Bearer として送ります。ゲートウェイはループバックをすべて信頼するので、値は何でも構いません。", + "A decision model (Jev, Clef), as listed below. Click one there to put it in the snippets.": "判定モデル(Jev、Clef)。下の一覧でクリックするとスニペットに入ります。", + "No decision models yet. Add a System One, Jev or Workers AI provider.": "判定モデルはまだありません。System One、Jev、Workers AI のプロバイダを追加してください。", "Key": "キー", "{env}=magpie. The gateway trusts everything on loopback, so any value works.": "{env}=magpie。ゲートウェイはループバック上のすべてを信頼するため、どんな値でも動作します。", "Model": "モデル", diff --git a/internal/gui/tests/gateway-systemone.test.cjs b/internal/gui/tests/gateway-systemone.test.cjs new file mode 100644 index 000000000..b73aaff81 --- /dev/null +++ b/internal/gui/tests/gateway-systemone.test.cjs @@ -0,0 +1,117 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Gateway page's Connect speaks magpie's own System One API too (ARNO on +// Discord: gateway添加system one api 有想法吗): a System One tab whose +// snippets POST …/v1/systemone with a decision model, picked from the +// decision models alone; a click on one in the list switches to it, a click +// on any other model back to OpenAI's. No SDK speaks it, so it has no +// shell variables. +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 providers = { + providers: [ + { id: "acme", name: "Acme", icon: "generic", agents: [], chat: "https://acme.test/v1", models: [ + { id: "gpt-5.5", name: "GPT-5.5", on: true, context: 400000 }, + ] }, + { id: "cf", name: "Workers AI", icon: "generic", agents: [], decide: "https://api.cloudflare.com/client/v4/accounts/a/ai/run", models: [ + { id: "@cf/typesafe/jev", name: "Jev", on: true }, + { id: "@cf/cloudflare/clef", name: "Clef", on: true }, + ] }, + ], + gateway: { running: true, window: true, mine: true, url: "http://127.0.0.1:3999", models: 3, calls: [], groups: [] }, +}; + +function serve(lang, theme) { + 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:"${theme}",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({ agents: [], profiles: [], settings: { lang, theme } }); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3)); + return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + 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: { five: "five APIs, one URL", note: "TypeSafe's decision API", hint: "A decision model (Jev, Clef)" }, + zh: { five: "五种 API,一个地址", note: "TypeSafe 的决策 API", hint: "决策模型(Jev、Clef)" }, +}; +const rowOf = (page, id) => page.locator("#gwModels .row.model").filter({ has: page.locator(".name", { hasText: new RegExp("^" + id.replace(/[./@]/g, "\\$&") + "$") }) }); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + for (const theme of ["light", "dark"]) { + test(`${engine} ${lang} ${theme}: Connect speaks System One with a decision model`, async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const w = words[lang]; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const context = await browser.newContext({ viewport: { width: 900, height: 1000 }, reducedMotion: "reduce", colorScheme: theme }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, theme)); + 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}-${theme}-gateway-systemone.png`), fullPage: true }); + } + await browser.close(); + }); + + await page.goto("http://magpie.test/?view=gateway&lang=curl"); + await page.locator("#gwModels .row.model").first().waitFor(); + assert(await page.getByText(w.five).first().isVisible(), "the head counts five APIs"); + const connect = page.locator("#connect"); + const modelCode = () => connect.locator(".val").nth(2).locator("code").textContent(); + const snippet = () => connect.locator("pre.snip").textContent(); + const tabs = connect.locator(".segs").first().locator(".opt"); + assert.deepEqual(await tabs.allTextContents(), ["OpenAI", "Responses", "Anthropic", "Gemini", "System One"]); + // OpenAI's snippets never take a decision model + assert.equal(await modelCode(), "acme/gpt-5.5"); + + await tabs.filter({ hasText: "System One" }).click(); + assert.equal(await modelCode(), "cf/@cf/typesafe/jev", "a decision model"); + assert(await connect.getByText(w.note).isVisible()); + assert(await connect.getByText(w.hint).isVisible()); + const langs = await connect.locator(".segs").nth(1).locator(".opt").allTextContents(); + assert.deepEqual(langs, ["curl", "Python", "Node"], "no shell variables"); + let s = await snippet(); + assert.match(s, /curl http:\/\/127\.0\.0\.1:3999\/v1\/systemone/); + assert.match(s, /"model": "cf\/@cf\/typesafe\/jev"/); + assert.match(s, /"questions"/); + assert.match(s, /Authorization: Bearer magpie/); + await connect.locator(".segs").nth(1).locator(".opt", { hasText: "Python" }).click(); + assert.match(await snippet(), /requests\.post\("http:\/\/127\.0\.0\.1:3999\/v1\/systemone"/); + await connect.locator(".segs").nth(1).locator(".opt", { hasText: "Node" }).click(); + assert.match(await snippet(), /fetch\("http:\/\/127\.0\.0\.1:3999\/v1\/systemone"/); + + // a click on a decision model puts it in, a click on another model + // goes back to OpenAI's + await rowOf(page, "cf/@cf/cloudflare/clef").click(); + assert.equal(await modelCode(), "cf/@cf/cloudflare/clef"); + assert(await rowOf(page, "cf/@cf/cloudflare/clef").evaluate((r) => r.classList.contains("selected"))); + await rowOf(page, "acme/gpt-5.5").click(); + assert.equal(await connect.locator(".segs").first().locator(".opt.on").textContent(), "OpenAI"); + assert.equal(await modelCode(), "acme/gpt-5.5"); + await rowOf(page, "cf/@cf/cloudflare/clef").click(); + assert.equal(await connect.locator(".segs").first().locator(".opt.on").textContent(), "System One"); + assert.equal(await modelCode(), "cf/@cf/cloudflare/clef", "the decision model picked is kept"); + assert.deepEqual(errors, []); + }); + } + } +}