gui: the Gateway page's Connect speaks System One too, with a decision model (ARNO on Discord: gateway添加system one api 有想法吗) — magpie's gateway has served POST /v1/systemone, but Connect showed only OpenAI, Responses, Anthropic and Gemini, so nothing on the page said so or how to ask it. Connect has a System One tab: base …/v1, curl, Python (requests) and Node (fetch) snippets that POST …/v1/systemone with Authorization: Bearer, a state and a choice question, printing the answer's choice and confidence; the note says Clef also reads images ("images": [data URLs]). No SDK speaks it, so it has no Shell tab, and the base URL and key hints say where the request goes and how the key is sent instead of naming env variables. Its model is a decision model only (decidesModel: a decision-only provider's, or a Jev), and the other tabs no longer take one; a click on a decision model in the list switches Connect to System One, a click on any other model back to OpenAI, each tab keeping its own pick (magpie.decideModel). The head says five APIs; Connect's tab strips scroll in themselves on a narrow window, as the region strip does, rather than widening the card. zh and ja strings. gateway-systemone.test.cjs (WebKit, en and zh, light and dark) fails on the old code; gateway-connect-keys, -model-info, -fold, -older, -caller-keys, -key-limit and gui-ja pass on WebKit; Chromium doesn't launch in this sandbox. The snippet's request, sent to the gateway's handler, reached a Workers AI Jev and Clef in their own shapes, and with the owner's real TypeSafe key in a sandbox HOME, jev-latest answered 200 with choice billing, confidence 0.55. go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass.
This commit is contained in:
@@ -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; }
|
||||
|
||||
+81
-16
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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": "モデル",
|
||||
|
||||
@@ -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, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user