gui: env lines pasted into the Add sheet or a key box open a provider (WJaunita45604 on X)

Pasting `export ANTHROPIC_BASE_URL=... / export ANTHROPIC_AUTH_TOKEN=...`
(also set, setx, $env:, Docker ENV, .env lines, and a JSON object of them
such as Claude Code's settings.json env) into the Add sheet's search box
opens a custom provider: name from the URL's site (api.moonshot.cn ->
Moonshot), API from the variable names (ANTHROPIC_* Anthropic, OPENAI_*
OpenAI chat, GEMINI_* Gemini), key, model, and the site's icon through the
existing /api/icons/favicon (it is sent the URL and name only; the key stays
in the draft until Save). Pasted into a custom provider's key or Base URL it
fills the form, as a curl command already did (curlOf). A key that only
stands for one (sk-xxxx, $VAR) is left out with a note. A bare host without a
scheme is https; a name with no dot (the tweet's example-xxx) is no address.

The curl and env readers moved to assets/pasteread.js, loaded when the
Providers page first draws, because the core script budget had no room and
raising it moves nothing out.

Run (mote, origin/main 8bc46b407 base, rebased clean): new
provider-env-paste.test.cjs, 18 cases (envOf on six forms plus a two-API
text, non-env text; Add sheet and key-box paste in en/zh at 900 and 440px,
chromium and webkit): all pass. provider-curl-paste, i18n-keys,
i18n-en-no-cjk, TestCoreScriptBudget pass. Broken by hand: with the search
box paste handler returning early, 8 of 18 go red. Provider/add/editor/custom
GUI files (92 files, both engines): 12 reds, all in provider-picks-stay
(#4397), provider-typed (#4673) and reset-providers (new #6196), and
all 12 fail the same in a clean origin/main worktree.

Not tried: a real vendor account with this paste, the favicon fetch against
the live site (the test stubs it), the full Go suite, Linux WebKitGTK.
This commit is contained in:
yetone
2026-11-12 00:43:45 +08:00
parent 4b1f3eca4a
commit 2bb2011621
4 changed files with 355 additions and 80 deletions
+34 -80
View File
@@ -6054,7 +6054,10 @@ $("#foldOff").onclick = () => {
// One row per provider: logo, name, the agents pointed at it, key status.
// Everything else lives in the editor, a dialog over the page.
let providersBehind = false;
// the readers of a pasted curl command or environment lines (pasteread.js)
const pasteLoad = () => import("./pasteread.js").catch(() => {});
function renderProviders(quiet) {
pasteLoad();
if (accountArranging || providerArranging) { accountRenderPending = true; return; }
providersBehind = false;
// a rebuild clamps the scroll to the top: put it back
@@ -7107,6 +7110,25 @@ function renderAdd() {
if (q.value) { q.value = presetQuery = ""; drawTiles(); } else if (providers.providers.length) closeAddSheet();
};
q.oninput = () => { presetQuery = q.value; drawTiles(); };
// environment lines from a vendor's page (envOf) pasted here open a custom
// provider with the name, URL, API and key they give, and the icon of the
// site (WJaunita45604 on X); the key goes nowhere but into the draft
q.onpaste = (e) => {
const c = window.envOf?.(e.clipboardData?.getData("text") || "");
if (!c || !c.bases.length) return;
e.preventDefault();
const name = c.name || t("Custom provider");
const d = { id: slug(name), name, preset: "", chat: "", responses: "", anthropic: "", decide: "", catalog: "", key: c.key, api: c.api, chosen: [], extra: c.model ? [c.model] : [], headers: [], icon: "" };
for (const [a, base] of c.bases) d[apiField[a]] = base;
editing = { custom: true }; draft = d; presetQuery = "";
renderProviders();
// the site's own icon, when it has one; the draft may be gone by then
api("icons/favicon", { url: c.base, name }).then((r) => {
if (draft !== d || !r?.icon) return;
d.icon = r.icon;
renderProviders(true);
}).catch(() => {});
};
const c = el("button", "text custom" + (editing?.custom ? " on" : ""));
c.append(svg(PLUS, 11, 1.8), t("Custom provider"));
c.dataset.pick = "custom";
@@ -9644,19 +9666,25 @@ function drawEditor(p, presetID) {
key.oninput = () => { draft.key = key.value; countKeys(); };
// a pasted curl command fills the form (@mark_li21 on X)
const fromCurl = (e) => {
const c = curlOf(e.clipboardData?.getData("text") || "");
const text = e.clipboardData?.getData("text") || "";
const c = window.curlOf?.(text) || window.envOf?.(text);
if (!c) return false;
const env = !!c.bases;
e.preventDefault();
const took = [], notes = [];
if (curlBase && c.api) { curlBase(c.api, c.base); took.push(t("Base URL") + " (" + t(API_NAMES[c.api]) + ")"); }
// no key box when keys are Accounts: none taken unseen
if (c.key && key.isConnected) { key.value = draft.key = c.key; countKeys(); took.push(t("API key")); }
if (curlBase) {
for (const [api, base] of env ? c.bases : c.api ? [[c.api, c.base]] : []) {
curlBase(api, base);
took.push(t("Base URL") + " (" + t(API_NAMES[api]) + ")");
}
}
if (c.key) { key.value = draft.key = c.key; countKeys(); took.push(t("API key")); }
if (curlModel && c.model) { curlModel(c.model); took.push(t("model {model}", { model: c.model })); }
if (took.length) notes.push(t("Filled in from the curl command: {what}.", { what: took.join(" · ") }));
if (took.length) notes.push(env ? t("Filled in from the pasted text: {what}.", { what: took.join(" · ") }) : t("Filled in from the curl command: {what}.", { what: took.join(" · ") }));
if (curlBase && !c.api) notes.push(t("Its URL isn't an address ending in /chat/completions, /messages or /responses: type the base URL."));
if (curlBase && c.urlHole) notes.push(t("Replace {part} in the base URL.", { part: c.urlHole }));
if (c.placeholder) notes.push(t("Its key, {key}, only stands for one: paste your own API key.", { key: c.placeholder }));
if (!c.key) shown(key)?.focus(NO_SCROLL);
if (!c.key) shown(key)?.focus({ preventScroll: true });
editorError(notes.join(" "), "note");
return true;
};
@@ -15395,80 +15423,6 @@ function respellURL(u, api) {
return /\/v\d+[a-z]*$/.test(u) || !/^https?:\/\/[^/]+$/.test(u) ? u : u + "/v1";
}
// curlOf reads a pasted curl command (@mark_li21) into the editor's API,
// base URL, key and model; a stand-in key ($KEY, <API_KEY>) is the
// placeholder; null if it isn't curl
function curlOf(text) {
let s = String(text || "").trim();
const head = /^curl(?:\.exe)?(?=\s)/i.exec(s);
if (!head) return null;
const cmd = /\^[ \t]*\r?\n/.test(s), ps = /`[ \t]*\r?\n/.test(s) || /^curl\.exe/i.test(s);
s = s.slice(head[0].length).replace(/(?:\\|\^|`)[ \t]*\r?\n/g, " ");
// the words as the shell hands them to curl: quotes taken off, escapes read
const words = [];
let w = null;
for (let i = 0; i < s.length;) {
const c = s[i];
if (/\s/.test(c)) { if (w !== null) words.push(w); w = null; i++; continue; }
w ??= "";
if (c === "'") {
// PowerShell doubles a quote inside single quotes
let j = i + 1;
for (;;) {
const k = s.indexOf("'", j);
if (k < 0) { w += s.slice(j); i = s.length; break; }
if (ps && s[k + 1] === "'") { w += s.slice(j, k) + "'"; j = k + 2; continue; }
w += s.slice(j, k); i = k + 1; break;
}
} else if (c === '"') {
for (i++; i < s.length && s[i] !== '"'; i++) {
const esc = (s[i] === "\\" && /["\\$`]/.test(s[i + 1] || "")) || (ps && s[i] === "`");
if (esc) i++;
w += s[i] ?? "";
}
i++;
} else if ((c === "\\" && !cmd && !ps) || (c === "^" && cmd)) { w += s[i + 1] ?? ""; i += 2; }
else { w += c; i++; }
}
if (w !== null) words.push(w);
// the options curl reads a value after; the others stand alone
const valued = /^(-[HdXuoAeFbcmT]|--(header|data|data-raw|data-binary|data-ascii|data-urlencode|json|request|url|user|output|user-agent|referer|form|cookie|max-time|connect-timeout|proxy|upload-file|retry|cert|key|cacert))$/;
let url = "", body = "";
const headers = [];
for (let i = 0; i < words.length; i++) {
const x = words[i];
let opt = x, val = null;
if (/^-[Hd]./.test(x)) { opt = x.slice(0, 2); val = x.slice(2); }
else if (valued.test(x)) val = words[++i] ?? "";
else if (x.startsWith("-")) continue;
else { if (!url) url = x; continue; }
if (opt === "-H" || opt === "--header") headers.push(val);
else if (opt === "--url") url = val;
else if (/^(-d|--data(-raw|-binary|-ascii)?|--json)$/.test(opt) && !val.startsWith("@")) body = val;
}
const out = { url, api: "", base: "", urlHole: "", key: "", placeholder: "", model: "" };
const at = /^(https?:\/\/[^?#]*?)\/*(\/chat\/completions|\/messages|\/responses)\/*(?:[?#].*)?$/i.exec(url);
if (at) {
out.api = { "/chat/completions": "openai", "/messages": "anthropic", "/responses": "responses" }[at[2].toLowerCase()];
out.base = respellURL(at[1], out.api);
out.urlHole = (/\{[^}]*\}|<[^>]*>|\$\{?\w+\}?|%\w+%/.exec(out.base) || [""])[0];
}
for (const h of headers) {
const m = /^\s*(authorization|x-api-key|api-key)\s*:\s*(.*?)\s*$/i.exec(h);
if (!m) continue;
const v = m[1].toLowerCase() === "authorization" ? m[2].replace(/^bearer\s+/i, "") : m[2];
if (!v) continue;
if (/^\$|^%\w+%$|^<.*>$|^\{\{.*\}\}$|^\[.*\]$|your[_-]?|api[_-]?key|x{6,}|\.\.\.|…/i.test(v)) out.placeholder = v;
else out.key = v;
break;
}
// a body for PowerShell 5 often escapes its quotes for curl.exe: '{\"model\": …}'
for (const b of [body, body.replace(/\\"/g, '"')]) {
try { const j = JSON.parse(b); if (typeof j?.model === "string") out.model = j.model.trim(); break; } catch {}
}
return out;
}
// renderMove: a built-in subscription a community plugin can run — which
// of the two runs it, and the way to the other. Accounts, models and the
// agents on them stay as they are either way.
+4
View File
@@ -2229,6 +2229,7 @@ const I18N = {
"Resume: the gateway uses this account first again": "恢复:网关重新优先使用这个账号",
"{n} keys": "{n} 个密钥",
"Filled in from the curl command: {what}.": "已从 curl 命令填入:{what}。",
"Filled in from the pasted text: {what}.": "已从粘贴的文本填入:{what}。",
"Its URL isn't an address ending in /chat/completions, /messages or /responses: type the base URL.": "其 URL 不是以 /chat/completions、/messages 或 /responses 结尾的地址:请填写 API 地址。",
"Replace {part} in the base URL.": "请替换 API 地址中的 {part}。",
"Its key, {key}, only stands for one: paste your own API key.": "其中的密钥 {key} 只是占位符:请粘贴你自己的 API 密钥。",
@@ -7312,6 +7313,7 @@ const I18N = {
"Resume: the gateway uses this account first again": "恢復:閘道重新優先使用這個帳號",
"{n} keys": "{n} 個金鑰",
"Filled in from the curl command: {what}.": "已從 curl 指令填入:{what}。",
"Filled in from the pasted text: {what}.": "已從貼上的文字填入:{what}。",
"Its URL isn't an address ending in /chat/completions, /messages or /responses: type the base URL.": "其 URL 不是以 /chat/completions、/messages 或 /responses 結尾的位址:請填寫 API 位址。",
"Replace {part} in the base URL.": "請替換 API 位址中的 {part}。",
"Its key, {key}, only stands for one: paste your own API key.": "其中的金鑰 {key} 只是預留位置:請貼上你自己的 API 金鑰。",
@@ -12371,6 +12373,7 @@ const I18N = {
"Resume: the gateway uses this account first again": "再開:ゲートウェイは再びこのアカウントを最初に使います",
"{n} keys": "{n} 個のキー",
"Filled in from the curl command: {what}.": "curl コマンドから入力しました:{what}。",
"Filled in from the pasted text: {what}.": "貼り付けたテキストから入力しました:{what}。",
"Its URL isn't an address ending in /chat/completions, /messages or /responses: type the base URL.": "URL が /chat/completions、/messages、/responses で終わるアドレスではありません。ベース URL を入力してください。",
"Replace {part} in the base URL.": "ベース URL の {part} を置き換えてください。",
"Its key, {key}, only stands for one: paste your own API key.": "キー {key} はプレースホルダーです。ご自身の APIキーを貼り付けてください。",
@@ -17461,6 +17464,7 @@ const I18N = {
"Resume: the gateway uses this account first again": "Fortsetzen: Der Zugangspunkt verwendet dieses Konto wieder zuerst",
"{n} keys": "{n} Schlüssel",
"Filled in from the curl command: {what}.": "Aus dem curl-Befehl übernommen: {what}.",
"Filled in from the pasted text: {what}.": "Aus dem eingefügten Text übernommen: {what}.",
"Its URL isn't an address ending in /chat/completions, /messages or /responses: type the base URL.": "Seine URL ist keine Adresse, die auf /chat/completions, /messages oder /responses endet: Gib die Basis-URL ein.",
"Replace {part} in the base URL.": "Ersetze {part} in der Basis-URL.",
"Its key, {key}, only stands for one: paste your own API key.": "Sein Schlüssel {key} ist nur ein Platzhalter: Füge deinen eigenen API-Schlüssel ein.",
+149
View File
@@ -0,0 +1,149 @@
// What a paste of a curl command or environment lines is read as (curlOf,
// envOf): loaded when the Providers page is first drawn rather than with the
// core, as the editor and the Add sheet need them only at a paste. They are
// on window, for the Providers page and its tests.
// curlOf reads a pasted curl command (@mark_li21) into the editor's API,
// base URL, key and model; a stand-in key ($KEY, <API_KEY>) is the
// placeholder; null if it isn't curl
window.curlOf = function curlOf(text) {
let s = String(text || "").trim();
const head = /^curl(?:\.exe)?(?=\s)/i.exec(s);
if (!head) return null;
const cmd = /\^[ \t]*\r?\n/.test(s), ps = /`[ \t]*\r?\n/.test(s) || /^curl\.exe/i.test(s);
s = s.slice(head[0].length).replace(/(?:\\|\^|`)[ \t]*\r?\n/g, " ");
// the words as the shell hands them to curl: quotes taken off, escapes read
const words = [];
let w = null;
for (let i = 0; i < s.length;) {
const c = s[i];
if (/\s/.test(c)) { if (w !== null) words.push(w); w = null; i++; continue; }
w ??= "";
if (c === "'") {
// PowerShell doubles a quote inside single quotes
let j = i + 1;
for (;;) {
const k = s.indexOf("'", j);
if (k < 0) { w += s.slice(j); i = s.length; break; }
if (ps && s[k + 1] === "'") { w += s.slice(j, k) + "'"; j = k + 2; continue; }
w += s.slice(j, k); i = k + 1; break;
}
} else if (c === '"') {
for (i++; i < s.length && s[i] !== '"'; i++) {
const esc = (s[i] === "\\" && /["\\$`]/.test(s[i + 1] || "")) || (ps && s[i] === "`");
if (esc) i++;
w += s[i] ?? "";
}
i++;
} else if ((c === "\\" && !cmd && !ps) || (c === "^" && cmd)) { w += s[i + 1] ?? ""; i += 2; }
else { w += c; i++; }
}
if (w !== null) words.push(w);
// the options curl reads a value after; the others stand alone
const valued = /^(-[HdXuoAeFbcmT]|--(header|data|data-raw|data-binary|data-ascii|data-urlencode|json|request|url|user|output|user-agent|referer|form|cookie|max-time|connect-timeout|proxy|upload-file|retry|cert|key|cacert))$/;
let url = "", body = "";
const headers = [];
for (let i = 0; i < words.length; i++) {
const x = words[i];
let opt = x, val = null;
if (/^-[Hd]./.test(x)) { opt = x.slice(0, 2); val = x.slice(2); }
else if (valued.test(x)) val = words[++i] ?? "";
else if (x.startsWith("-")) continue;
else { if (!url) url = x; continue; }
if (opt === "-H" || opt === "--header") headers.push(val);
else if (opt === "--url") url = val;
else if (/^(-d|--data(-raw|-binary|-ascii)?|--json)$/.test(opt) && !val.startsWith("@")) body = val;
}
const out = { url, api: "", base: "", urlHole: "", key: "", placeholder: "", model: "" };
const at = /^(https?:\/\/[^?#]*?)\/*(\/chat\/completions|\/messages|\/responses)\/*(?:[?#].*)?$/i.exec(url);
if (at) {
out.api = { "/chat/completions": "openai", "/messages": "anthropic", "/responses": "responses" }[at[2].toLowerCase()];
out.base = respellURL(at[1], out.api);
out.urlHole = (/\{[^}]*\}|<[^>]*>|\$\{?\w+\}?|%\w+%/.exec(out.base) || [""])[0];
}
for (const h of headers) {
const m = /^\s*(authorization|x-api-key|api-key)\s*:\s*(.*?)\s*$/i.exec(h);
if (!m) continue;
const v = m[1].toLowerCase() === "authorization" ? m[2].replace(/^bearer\s+/i, "") : m[2];
if (!v) continue;
if (/^\$|^%\w+%$|^<.*>$|^\{\{.*\}\}$|^\[.*\]$|your[_-]?|api[_-]?key|x{6,}|\.\.\.|…/i.test(v)) out.placeholder = v;
else out.key = v;
break;
}
// a body for PowerShell 5 often escapes its quotes for curl.exe: '{\"model\": …}'
for (const b of [body, body.replace(/\\"/g, '"')]) {
try { const j = JSON.parse(b); if (typeof j?.model === "string") out.model = j.model.trim(); break; } catch {}
}
return out;
};
// envOf reads the environment lines a vendor's page or a README gives for
// its API (WJaunita45604 on X): export ANTHROPIC_BASE_URL="…", set and
// setx, $env:NAME = "…", Docker's ENV, NAME=value in a .env file, or a
// JSON object of them (Claude Code's settings.json "env"). The names say
// the API: ANTHROPIC_* Anthropic's, OPENAI_* OpenAI's chat, GEMINI_* Gemini's.
// It gives what curlOf does (api, base, urlHole, key, placeholder, model),
// with bases, every API the text names a URL for, and name, the site's
// name taken from the first. A key that only stands for one is placeholder.
// null for text with none of those names.
window.envOf = function envOf(text) {
const vars = {};
const put = (k, v) => { if (typeof v === "string" && v.trim() && !(k in vars)) vars[k] = v.trim(); };
const body = String(text || "").trim();
let json = null;
try { json = JSON.parse(body); } catch {}
const walk = (o, depth) => {
if (!o || typeof o !== "object" || depth > 3) return;
for (const [k, v] of Object.entries(o)) { if (typeof v === "string") put(k, v); else walk(v, depth + 1); }
};
if (json) walk(json, 0);
else {
for (const line of body.split(/\r?\n/)) {
const m = /^\s*(?:export\s+|set\s+|setx\s+|env\s+|\$env:)?([A-Za-z_][A-Za-z0-9_]*)\s*(?:=|\s)\s*(.*?)\s*;?\s*$/i.exec(line);
if (!m) continue;
const q = /^(["'])(.*)\1$/.exec(m[2]);
put(m[1], q ? q[2] : m[2].replace(/\s+#.*$/, ""));
}
}
const base = /^(ANTHROPIC|OPENAI|GEMINI|GOOGLE_GEMINI)_(?:BASE_URL|API_BASE|API_URL|BASE|ENDPOINT)$/i;
const keyOf = /^(ANTHROPIC|OPENAI|GEMINI|GOOGLE)_(?:AUTH_TOKEN|API_KEY)$/i;
const modelOf = /^(ANTHROPIC|OPENAI|GEMINI)_MODEL$/i;
const apiOf = (name) => /^ANTHROPIC/i.test(name) ? "anthropic" : /^OPENAI/i.test(name) ? "openai" : "gemini";
const out = { url: "", api: "", base: "", bases: [], urlHole: "", key: "", placeholder: "", model: "", name: "" };
for (const [k, v] of Object.entries(vars)) {
if (base.test(k)) {
const api = apiOf(k);
// a host written without its scheme is https
const u = /^[a-z][a-z0-9+.-]*:\/\//i.test(v) ? v : /^[^\s/]+\.[^\s/]+|^localhost\b/i.test(v) ? "https://" + v : "";
if (!u || out.bases.some(([a]) => a === api)) continue;
// …/v1/chat/completions given whole is cut back to the base
const cut = u.replace(/\/+$/, "").replace(/\/(?:chat\/completions|messages|responses)$/i, "");
out.bases.push([api, respellURL(cut, api)]);
} else if (keyOf.test(k)) {
if (out.key || out.placeholder) continue;
if (/^\$|^%\w+%$|^<.*>$|^\{\{.*\}\}$|^\[.*\]$|your[_-]?|api[_-]?key|x{6,}|\.\.\.|…/i.test(v)) out.placeholder = v;
else out.key = v;
} else if (modelOf.test(k) && !out.model) out.model = v;
}
if (!out.bases.length && !out.key && !out.placeholder) return null;
if (out.bases.length) {
[out.api, out.base] = out.bases[0];
out.url = out.base;
out.urlHole = (/\{[^}]*\}|<[^>]*>|\$\{?\w+\}?|%\w+%/.exec(out.base) || [""])[0];
out.name = siteName(out.base);
}
return out;
};
// siteName is what to call the provider at a URL: the name in its host,
// api.moonshot.cn → Moonshot, open.bigmodel.cn → Bigmodel; an address
// stays as it is.
window.siteName = function siteName(u) {
let h = "";
try { h = new URL(u).hostname; } catch { return ""; }
if (/^[\d.]+$|:|^localhost$/.test(h)) return h;
let l = h.split(".");
if (l.length > 1) l = l.slice(0, -1); // the top-level domain
if (l.length > 1 && /^(co|com|org|net|ac|gov|edu)$/.test(l[l.length - 1])) l = l.slice(0, -1);
const w = l.filter((x) => !/^(www|api|open|openapi|gateway|llm)$/.test(x)).pop() || l.pop() || h;
return w.charAt(0).toUpperCase() + w.slice(1);
};
@@ -0,0 +1,168 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Environment lines from a vendor's page, pasted into the Add sheet's search
// box, open a custom provider with the name from the URL's site, its API from
// the variable names (ANTHROPIC_* Anthropic's, OPENAI_* OpenAI's) and the key
// (WJaunita45604 on X). Pasted into a custom provider's key or Base URL they
// fill the form. A key that only stands for one is left out. The site's icon
// is asked for with the URL and name only: the key goes nowhere but the draft.
// English and Chinese, Chromium and WebKit, at a narrow window too.
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 own = "sk-ant-api03-Qx7vT2mK9pLw4RzN8bYc";
const forms = {
export: `export ANTHROPIC_BASE_URL="https://api.moonshot.cn/anthropic"\nexport ANTHROPIC_AUTH_TOKEN="${own}"\n`,
tweet: `export ANTHROPIC_BASE_URL="example-xxx"\nexport ANTHROPIC_AUTH_TOKEN="sk-xxxxxxxxxxxxxxx"`,
cmd: `set ANTHROPIC_BASE_URL=https://api.moonshot.cn/anthropic\r\nset ANTHROPIC_AUTH_TOKEN=${own}`,
ps: `$env:ANTHROPIC_BASE_URL = "https://api.moonshot.cn/anthropic"\n$env:ANTHROPIC_AUTH_TOKEN = '${own}'`,
json: JSON.stringify({ env: { ANTHROPIC_BASE_URL: "https://api.moonshot.cn/anthropic", ANTHROPIC_AUTH_TOKEN: own, ANTHROPIC_MODEL: "kimi-k3" } }),
dotenv: `# my relay\nANTHROPIC_BASE_URL=https://api.moonshot.cn/anthropic # note\nANTHROPIC_API_KEY=${own}\n`,
};
function serve(lang, posts) {
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
const plain = { id: "plain", name: "Plain", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", models: [{ id: "m", name: "m", on: true }], agents: [], fallback: [], headers: {}, key: { set: true, masked: "sk-…1234" }, keyList: [], ready: true };
const providers = { providers: [plain], presets: [], excluded: [], gateway: { running: true, window: true } };
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:${JSON.stringify(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.startsWith("/api/icons/favicon")) { posts.push({ path: url.pathname, body: route.request().postDataJSON() }); return json({ icon: "generic" }); }
if (url.pathname.startsWith("/api/provider/")) { posts.push({ path: url.pathname, body: route.request().postDataJSON() }); return json(providers); }
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
await route.fulfill({ body: await fs.readFile(file), contentType: { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)] });
};
}
const words = {
en: { add: "Add", note: "Filled in from the pasted text: Base URL (Anthropic compatible) · API key." },
zh: { add: "添加", note: "已从粘贴的文本填入:API 地址 (Anthropic 兼容) · API 密钥。" },
};
const launch = (engine) => engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" });
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: envOf reads each form`, async (t) => {
const browser = await launch(engine);
t.after(() => browser.close());
const page = await (await browser.newContext()).newPage();
await page.route("**/*", serve("en", []));
await page.goto("http://magpie.test/?view=providers");
await page.waitForFunction(() => typeof envOf === "function");
for (const [name, text] of Object.entries(forms)) {
const c = await page.evaluate((s) => envOf(s), text);
if (name === "tweet") {
// the page's own stand-in, "example-xxx", is no address
assert.deepEqual([c.bases, c.key, c.placeholder], [[], "", "sk-xxxxxxxxxxxxxxx"], name);
continue;
}
assert.deepEqual(c.bases, [["anthropic", "https://api.moonshot.cn"]].map(([a]) => [a, "https://api.moonshot.cn/anthropic"]), name);
assert.equal(c.key, own, name);
assert.equal(c.name, "Moonshot", name);
assert.equal(c.api, "anthropic", name);
if (name === "json") assert.equal(c.model, "kimi-k3");
}
const both = await page.evaluate((s) => envOf(s), `export OPENAI_BASE_URL=https://openrouter.ai/api/v1\nexport OPENAI_API_KEY=sk-or-v1-abcdef0123\nexport ANTHROPIC_BASE_URL=https://openrouter.ai/api`);
assert.deepEqual(both.bases, [["openai", "https://openrouter.ai/api/v1"], ["anthropic", "https://openrouter.ai/api"]]);
assert.equal(both.api, "openai");
assert.equal(both.name, "Openrouter");
for (const s of ["", "sk-a\nsk-b", "https://api.moonshot.cn/v1", "PATH=/usr/bin\nHOME=/root", "export FOO=bar"]) {
assert.equal(await page.evaluate((x) => envOf(x), s), null, JSON.stringify(s));
}
assert.deepEqual(await page.evaluate(() => ["https://open.bigmodel.cn/api/paas/v4", "https://api.example.co.uk/v1", "http://127.0.0.1:8888/v1"].map(siteName)), ["Bigmodel", "Example", "127.0.0.1"]);
});
for (const [lang, width] of [["en", 900], ["zh", 900], ["en", 440], ["zh", 440]]) {
test(`${engine} ${lang} ${width}px: env lines pasted into the Add sheet open a provider`, async (t) => {
const browser = await launch(engine);
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts));
const w = words[lang];
const ed = page.locator(".editor");
const key = ed.locator(".pair input[type=password]").first();
const paste = (loc, text) => loc.evaluate((i, s) => {
i.focus();
const dt = new DataTransfer();
dt.setData("text/plain", s);
const e = new ClipboardEvent("paste", { clipboardData: dt, bubbles: true, cancelable: true });
i.dispatchEvent(e);
return e.defaultPrevented;
}, text);
await page.goto("http://magpie.test/?view=providers");
await page.locator("#addProvider").click();
// text that isn't env lines is typed as before
assert.equal(await paste(page.locator("#addSheet .find"), "moonshot"), false);
assert.equal(await paste(page.locator("#addSheet .find"), forms.export), true);
await ed.waitFor();
assert.equal(await ed.locator(".base-url").inputValue(), "https://api.moonshot.cn/anthropic");
assert.equal(await ed.locator(".base-apis .opt.on").getAttribute("data-api"), "anthropic");
assert.equal(await key.inputValue(), own);
assert.equal(await ed.locator("input[placeholder]").first().inputValue(), "Moonshot");
for (let i = 0; i < 40 && !posts.some((p) => p.path === "/api/icons/favicon"); i++) await page.waitForTimeout(50);
const ask = posts.find((p) => p.path === "/api/icons/favicon");
assert.deepEqual(ask.body, { url: "https://api.moonshot.cn/anthropic", name: "Moonshot" });
assert.ok(!JSON.stringify(posts).includes(own), "the key is sent only when saved");
assert.deepEqual(await page.evaluate(() => ({ page: document.documentElement.scrollWidth <= innerWidth })), { page: true });
await ed.locator(":scope > .bar").getByRole("button", { name: w.add, exact: true }).click();
for (let i = 0; i < 60 && !posts.some((p) => p.path === "/api/provider/save"); i++) await page.waitForTimeout(50);
const body = posts.find((p) => p.path === "/api/provider/save")?.body;
assert.ok(body, "saved");
assert.equal(body.anthropic, "https://api.moonshot.cn/anthropic");
assert.equal(body.key, own);
assert.equal(body.name, "Moonshot");
assert.deepEqual(errors, []);
});
test(`${engine} ${lang} ${width}px: env lines pasted into a custom provider's key fill it`, async (t) => {
const browser = await launch(engine);
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts));
const w = words[lang];
const ed = page.locator(".editor");
const key = ed.locator(".pair input[type=password]").first();
const note = ed.locator(".editor-error.note");
const paste = (loc, text) => loc.evaluate((i, s) => {
i.focus();
const dt = new DataTransfer();
dt.setData("text/plain", s);
const e = new ClipboardEvent("paste", { clipboardData: dt, bubbles: true, cancelable: true });
i.dispatchEvent(e);
return e.defaultPrevented;
}, text);
await page.goto("http://magpie.test/?view=providers");
await page.locator("#addProvider").click();
await page.locator("#addSheet .row-head .custom").click();
await ed.locator(".base-url").waitFor();
assert.equal(await paste(key, forms.export), true);
assert.equal(await ed.locator(".base-url").inputValue(), "https://api.moonshot.cn/anthropic");
assert.equal(await key.inputValue(), own);
assert.equal((await note.textContent()).trim(), w.note);
// a placeholder key is no key
await key.fill("");
assert.equal(await paste(key, forms.tweet), true);
assert.equal(await key.inputValue(), "");
assert.match(await note.textContent(), /sk-xxxxxxxxxxxxxxx/);
assert.deepEqual(errors, []);
});
}
}