providers: a setup pasted into Providers' own search opens the provider too (WJaunita45604 on X)

a44da380b (v0.1.4044) read a pasted vendor setup only in the Add sheet's
search box. With providers already there, the box in sight is the
Providers page's own "Find a provider" (#pvQ), and a paste there only
filtered the list: a real Cmd+V of export ANTHROPIC_BASE_URL / _AUTH_TOKEN
left the text in the box with "No provider matches", in Chromium and
WebKit alike. The reader also took the tweet's own shape wrong:
`export XXX_BASE_URL="…" export XXXAUTH_TOKEN="…"` on one line gave an
OpenAI URL with the second export in it and no key.

- pastedProvider (pasteread.js) opens the custom provider from either
  search box, for env lines, JSON, "address + key" lines and now a curl
  command too, and says what it filled. A setup with no web address (the
  tweet's example-xx) opens with its key and asks for the base URL,
  rather than doing nothing. "token plan" and other words after KEY or
  TOKEN open nothing.
- Both boxes also read a paste from its input event (insertFromPaste,
  insertFromDrop), for a paste whose event has no text or that came
  before pasteread.js loaded; the one-line box runs the lines together,
  so the reader takes several NAME=value on one line, glued or not.
- envOf reads what pages and Windows do to the text: zero-width
  characters, no-break and ideographic spaces, full-width = and :, curly
  quotes, cmd's set "NAME=value", CR-only lines, and a piece of
  settings.json ("env": {…}, or its lines, a trailing comma included).
- The site's icon arriving no longer wipes the note of what was filled.
- New string in zh, zh-TW, ja, de: "The pasted text gives no web
  address: type the base URL."

Run (mote, base origin/main 48e394146, rebased on 9e3b269c5, which
touches none of these files):
- provider-env-paste, Chromium and WebKit, en/zh at 900 and 440px:
  34 of 34. Red on the old app.js/pasteread.js/i18n.js with the new
  test: 18 of 34 (envOf's oneLine case, Providers' search, the input-event
  paste).
- A real keyboard paste (text copied from a textarea with Cmd+C, then
  Cmd+V into the box, CRLF lines), a scratch script not committed: on
  the old code #pvQ keeps the text, no editor, both engines; on the new,
  both boxes open the editor with the URL and key, both engines.
- add-sheet*, custom-*, i18n-keys, i18n-en-no-cjk, provider*, providers*
  (76 files, both engines): 1838 of 1890. The 52 reds are in
  provider-fetch-again, provider-many-keys, provider-max-output,
  provider-models-rest, provider-picks-stay and provider-typed, and the
  same 52 fail in a clean origin/main 9e3b269c5 copy: #6532, #6209.
- At the pushed head (rebased on 9e3b269c5): provider-env-paste,
  provider-curl-paste, i18n-keys, i18n-en-no-cjk: 52 of 52.
- go test -tags nogui ./internal/gui (mica): ok, TestCoreScriptBudget
  included (app.js is smaller; the opening moved to pasteread.js).

Not tried: the packaged app itself (the release build serves
pasteread.js from assets.zip as before), WebKitGTK, Windows WebView2's
context-menu paste.
This commit is contained in:
yetone
2026-11-13 20:28:54 +08:00
parent ea03a56518
commit 52c9880cbb
4 changed files with 183 additions and 22 deletions
+9 -15
View File
@@ -6088,6 +6088,13 @@ $("#foldOff").onclick = () => {
let providersBehind = false;
// the readers of a pasted curl command or environment lines (pasteread.js)
const pasteLoad = () => import("./pasteread.js").catch(() => {});
// a vendor's setup pasted into a search box opens a custom provider
// (pastedProvider); a paste with no text in its event, or before the reader
// loaded, is read from what the box took
const setupPaste = (q) => {
q.addEventListener("paste", (e) => window.pastedProvider?.(e.clipboardData?.getData("text") || "") && e.preventDefault());
q.addEventListener("input", (e) => /^insertFrom(Paste|Drop)/.test(e.inputType) && pasteLoad().then(() => window.pastedProvider?.(q.value) && (q.value = "", q.dispatchEvent(new Event("input")))));
};
function renderProviders(quiet) {
pasteLoad();
if (accountArranging || providerArranging) { accountRenderPending = true; return; }
@@ -6314,6 +6321,7 @@ function findProviders() {
const q = $("#pvQ");
if (q) {
q.oninput = () => { pvQuery = q.value.trim().toLowerCase(); findProviders(); };
setupPaste(q);
q.onkeydown = (e) => {
if (e.key !== "Escape" || !q.value) return;
e.preventDefault();
@@ -7135,21 +7143,7 @@ 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) => draft === d && r?.icon && (d.icon = r.icon, renderProviders(true))).catch(() => {});
};
setupPaste(q);
const c = el("button", "text custom" + (editing?.custom ? " on" : ""));
c.append(svg(PLUS, 11, 1.8), t("Custom provider"));
c.dataset.pick = "custom";
+4
View File
@@ -2273,6 +2273,7 @@ const I18N = {
"{n} keys": "{n} 个密钥",
"Filled in from the curl command: {what}.": "已从 curl 命令填入:{what}。",
"Filled in from the pasted text: {what}.": "已从粘贴的文本填入:{what}。",
"The pasted text gives no web address: type the base URL.": "粘贴的文本里没有网址:请填写 API 地址。",
"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 密钥。",
@@ -7475,6 +7476,7 @@ const I18N = {
"{n} keys": "{n} 個金鑰",
"Filled in from the curl command: {what}.": "已從 curl 指令填入:{what}。",
"Filled in from the pasted text: {what}.": "已從貼上的文字填入:{what}。",
"The pasted text gives no web address: type the base URL.": "貼上的文字裡沒有網址:請填寫 API 位址。",
"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 金鑰。",
@@ -12653,6 +12655,7 @@ const I18N = {
"{n} keys": "{n} 個のキー",
"Filled in from the curl command: {what}.": "curl コマンドから入力しました:{what}。",
"Filled in from the pasted text: {what}.": "貼り付けたテキストから入力しました:{what}。",
"The pasted text gives no web address: type the base URL.": "貼り付けたテキストに URL がありません。ベース URL を入力してください。",
"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キーを貼り付けてください。",
@@ -17862,6 +17865,7 @@ const I18N = {
"{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}.",
"The pasted text gives no web address: type the base URL.": "Der eingefügte Text enthält keine Webadresse: Gib die Basis-URL ein.",
"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.",
+60 -5
View File
@@ -6,7 +6,7 @@
// 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();
let s = pasteClean(text);
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);
@@ -88,17 +88,26 @@ window.curlOf = function curlOf(text) {
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();
const body = pasteClean(text);
// JSON whole, or a piece of one: "env": {…} or its lines, a comma after the last
let json = null;
try { json = JSON.parse(body); } catch {}
for (const b of [body, "{" + body + "}"]) {
try { json = JSON.parse(b.replace(/,\s*([}\]])/g, "$1").replace(/,\s*$/, "")); break; } 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);
for (let line of body.split(/\r\n?|\n/)) {
// cmd's set "NAME=value"
line = line.replace(/^(\s*set\s+)"([^"]*)"\s*$/i, "$1$2");
// two or more on one line: export A="…" export B="…", A=… B=… claude,
// or the lines a one-line box ran together
const many = [...line.matchAll(/(?:\b(?:export|set|setx)\s+|\$env:)?\b([A-Za-z_][A-Za-z0-9_]*)\s*=\s*("[^"]*"|'[^']*'|[^\s"';&]+)/gi)];
if (many.length > 1) { for (const [, k, v] of many) put(k, v.replace(/^(["'])(.*)\1$/, "$2")); continue; }
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+#.*$/, ""));
@@ -150,6 +159,52 @@ window.envOf = function envOf(text) {
return out;
};
// pasteClean undoes what a web page or a chat does to text copied from it:
// zero-width characters and a BOM inside the names, no-break and ideographic
// spaces, full-width = and :, and curly quotes
function pasteClean(text) {
return String(text || "").replace(/[\u200b-\u200d\u2060\ufeff]/g, "").replace(/[\u00a0\u2000-\u200a\u202f\u3000]/g, " ")
.replace(/=/g, "=").replace(/:/g, ":").replace(/[“”„]/g, '"').replace(/[‘’]/g, "'").trim();
}
// pastedProvider opens a new custom provider from a vendor's setup pasted
// into a search box: the Add sheet's, and Providers' own, the one in sight
// once there are providers (WJaunita45604 on X: v0.1.4044 read only the
// first). Env lines, JSON, plain "address + key" lines or a curl command
// give the name, URL, API and key; the site's icon is asked for with the URL
// and name only, and the key goes nowhere but the draft. A setup with no
// address still opens, saying so. False for text that is no setup.
window.pastedProvider = function pastedProvider(text) {
const c = window.curlOf(text) || window.envOf(text);
const bases = c?.bases || (c?.api && c.base ? [[c.api, c.base]] : []);
// a word after KEY or TOKEN ("token plan") is no key
if (!c || !bases.length && !(/^\S{8,}$/.test(c.key) || c.placeholder)) return false;
const name = c.name || siteName(c.base) || t("Custom provider");
const d = { id: slug(name), name, preset: "", chat: "", responses: "", anthropic: "", decide: "", catalog: "", key: c.key, api: c.api || "openai", chosen: [], extra: c.model ? [c.model] : [], headers: [], icon: "" };
for (const [a, base] of bases) d[apiField[a]] = base;
editing = { custom: true }; draft = d; presetQuery = "";
renderProviders();
const took = bases.map(([a]) => t("Base URL") + " (" + t(API_NAMES[a]) + ")");
if (c.key) took.push(t("API key"));
if (c.model) took.push(t("model {model}", { model: c.model }));
const notes = took.length ? [t("Filled in from the pasted text: {what}.", { what: took.join(" · ") })] : [];
if (!bases.length) notes.push(t("The pasted text gives no web address: type the base URL."));
if (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 }));
const note = notes.join(" ");
editorError(note, "note");
// the site's own icon, when it has one; the draft may be gone by then, and
// the note stays while it is still in sight
if (bases.length) api("icons/favicon", { url: bases[0][1], name }).then((r) => {
if (draft !== d || !r?.icon) return;
const shown = document.querySelector(".editor .editor-error.note")?.textContent === note;
d.icon = r.icon;
renderProviders(true);
if (shown) editorError(note, "note");
}).catch(() => {});
return true;
};
// standIn: a key a page gives only to stand for the reader's own
const standIn = (v) => /^\$|^%\w+%$|^<.*>$|^\{\{.*\}\}$|^\[.*\]$|your[_-]?|api[_-]?key|x{6,}|\.\.\.|…/i.test(v);
+110 -2
View File
@@ -45,8 +45,8 @@ function serve(lang, posts) {
}
const words = {
en: { add: "Add", find: "Find a vendor, or paste a URL and key…", note: "Filled in from the pasted text: Base URL (Anthropic compatible) · API key." },
zh: { add: "添加", find: "查找供应商,或粘贴地址和密钥…", note: "已从粘贴的文本填入:API 地址 (Anthropic 兼容) · API 密钥。" },
en: { add: "Add", find: "Find a vendor, or paste a URL and key…", note: "Filled in from the pasted text: Base URL (Anthropic compatible) · API key.", noURL: "no web address" },
zh: { add: "添加", find: "查找供应商,或粘贴地址和密钥…", note: "已从粘贴的文本填入:API 地址 (Anthropic 兼容) · API 密钥。", noURL: "没有网址" },
};
const launch = (engine) => engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" });
@@ -98,6 +98,27 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
for (const s of ["DATABASE_URL=postgres://db/x\nGITHUB_TOKEN=ghp_0123456789abcdef", "HTTPS_PROXY=http://127.0.0.1:7890", "see https://example.com for docs"]) {
assert.equal(await page.evaluate((x) => envOf(x), s), null, JSON.stringify(s));
}
// as people paste it (WJaunita45604 on X, v0.1.4044): two exports on
// one line, a one-line box's run-together lines, Windows' forms, a
// web page's no-break and zero-width spaces, full-width signs and curly
// quotes, a piece of settings.json
const pasted = {
oneLine: `export XXX_BASE_URL="https://relay.foo.com/anthropic" export XXXAUTH_TOKEN="${own}"`,
glued: `export ANTHROPIC_BASE_URL="https://relay.foo.com/anthropic"export ANTHROPIC_AUTH_TOKEN="${own}"`,
command: `ANTHROPIC_BASE_URL=https://relay.foo.com/anthropic ANTHROPIC_API_KEY=${own} claude`,
crlf: `export ANTHROPIC_BASE_URL='https://relay.foo.com/anthropic'\r\nexport ANTHROPIC_API_KEY='${own}'\r\n`,
cmdQuoted: `set "ANTHROPIC_BASE_URL=https://relay.foo.com/anthropic"\r\nset "ANTHROPIC_AUTH_TOKEN=${own}"`,
ps: `$env:ANTHROPIC_BASE_URL="https://relay.foo.com/anthropic"; $env:ANTHROPIC_AUTH_TOKEN="${own}"`,
web: `export\u00a0ANTHROPIC_\u200bBASE_URL=“https://relay.foo.com/anthropic”\nexport\u00a0ANTHROPIC_AUTH_TOKEN\uff1d\u201c${own}\u201d\u200b`,
envPiece: `"env": {\n "ANTHROPIC_BASE_URL": "https://relay.foo.com/anthropic",\n "ANTHROPIC_AUTH_TOKEN": "${own}",\n},`,
envLines: `"ANTHROPIC_BASE_URL": "https://relay.foo.com/anthropic",\n"ANTHROPIC_AUTH_TOKEN": "${own}"`,
};
for (const [name, text] of Object.entries(pasted)) {
const c = await page.evaluate((s) => envOf(s), text);
assert.deepEqual([c?.api, c?.base, c?.key, c?.name], ["anthropic", "https://relay.foo.com/anthropic", own, "Foo"], name);
}
const openai = await page.evaluate((s) => envOf(s), `export OPENAI_BASE_URL=https://api.relay.io/v1 export OPENAI_API_KEY=${own}`);
assert.deepEqual([openai.api, openai.base, openai.key], ["openai", "https://api.relay.io/v1", own]);
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"]);
});
@@ -150,6 +171,93 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual(errors, []);
});
test(`${engine} ${lang} ${width}px: a setup pasted into Providers' own search opens 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 q = page.locator("#pvQ");
const paste = (text) => q.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.waitForFunction(() => typeof pastedProvider === "function");
// the box in sight once there are providers, not the Add sheet's
assert.equal(await page.locator("#addSheet").isHidden(), true);
assert.equal(await paste("plain"), false);
assert.equal(await paste("token plan"), false);
assert.equal(await ed.count(), 0);
assert.equal(await paste(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");
assert.equal((await ed.locator(".editor-error.note").textContent()).trim(), w.note);
assert.equal(await q.inputValue(), "");
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.equal(body?.anthropic, "https://api.moonshot.cn/anthropic");
assert.equal(body?.key, own);
assert.ok(!JSON.stringify(posts.filter((p) => p.path !== "/api/provider/save")).includes(own), "the key is sent only when saved");
assert.deepEqual(errors, []);
});
test(`${engine} ${lang} ${width}px: a paste the box took without its event's text still opens 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 = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, []));
const w = words[lang];
const ed = page.locator(".editor");
await page.goto("http://magpie.test/?view=providers");
await page.locator("#addProvider").click();
await page.waitForFunction(() => typeof pastedProvider === "function");
// a one-line box runs the lines together; no paste event text to read
const flat = `export ANTHROPIC_BASE_URL="https://api.moonshot.cn/anthropic"export ANTHROPIC_AUTH_TOKEN="${own}"`;
await page.locator("#addSheet .find").evaluate((i, s) => {
i.focus();
i.value = s;
i.dispatchEvent(new InputEvent("input", { inputType: "insertFromPaste", bubbles: true }));
}, flat);
await ed.waitFor();
assert.equal(await ed.locator(".base-url").inputValue(), "https://api.moonshot.cn/anthropic");
assert.equal(await ed.locator(".pair input[type=password]").first().inputValue(), own);
// the tweet's own example has no address: it opens, saying so
await page.goto("http://magpie.test/?view=providers");
await page.locator("#addProvider").click();
await page.waitForFunction(() => typeof pastedProvider === "function");
const took = await page.locator("#addSheet .find").evaluate((i, s) => {
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;
}, `export xxx_BASE_URL="example-xx" export xxxAUTH_TOKEN="sk-xxxxxxxxxxxx"`);
assert.equal(took, true);
await ed.waitFor();
assert.equal(await ed.locator(".base-url").inputValue(), "");
assert.match(await ed.locator(".editor-error.note").textContent(), new RegExp(w.noURL));
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());