providers: a provider with keys has no second "API key" box under its Accounts

Kylin_Cloud on X reported that the editor of an API-key provider lists every key
under Accounts, each with copy, replace (the pencil, keys/replace, #1869) and
remove buttons. Below the list was also an "API key" box to "paste a new key to
replace it". That was the same action twice, and the box replaced the first key
without saying which one.

The box is now shown only for a provider with no key yet (an empty keyList: a
new provider, or a local one with no key). A provider with keys changes them in
Accounts.

The curl import filled the key box too. With the box gone, a pasted command's
key went into draft.key unseen and was saved over the first key. A key from the
command is now taken only while the box is on the page.

Run:
- gofmt -l: clean. go vet -tags nogui for darwin, linux and windows on mote: ok.
- key-box-once.test.cjs (new), en/zh/zh-TW/ja/de at 900px and 420px, covering
  one key, two keys (one on), no key, and a curl paste with a Bearer key:
  Chromium 10/10 and WebKit 10/10, both on the Windows box (mote's browsers
  hang, #4125).
- provider-many-keys' "several keys pasted into the API key field are
  counted" pasted into the box of a provider that has a key. Its Solo
  fixture now has no key yet, which is the case the box is for.
- At this stack's head, at concurrency 1 on the Windows box: key-box-once,
  agent-hides-editor, provider-many-keys, i18n-keys, redact-rule-edit and
  old-webkit: Chromium 48/48 and WebKit 48/48.
- go test -tags nogui ./internal/gui ./internal/provider on mote at this
  head: ok.
- WebKit on the Windows box, the 48 GUI files red in an earlier whole-suite
  run, at the head before the rebase (no GUI file changed on main since)
  and at origin/main 2f5a3f1c0: 178 reds at the head, 173 at main, all in
  the same files except provider-many-keys (fixed above). Four more files
  (provider-max-output, context-picks, connect-address-kept,
  library-backups-top) were red at the head only. Run alone, they were red
  at main too. Filed as #4430 (a .row.provider click hits the five loading
  skeletons, 837923c43) and #4431 (21 files that #4124 doesn't list). The
  rest are in #4124.
- Full Go suite (-tags nogui, -timeout 45m) on the Linux box, before the
  budget move: red only in TestCoreScriptBudget (fixed by the ruleedit.js
  move two commits before, not raised) and internal/agent's box-specific reds
  (#4033, #3548). internal/agent is not touched.

Broken by hand:
- With the box back for every provider (`else`), "no second key box" was red.
- Without the isConnected guard in fromCurl, "no key saved over the first:
  sk-from-curl-0123456789" was red.

Not tried: the real app, a whole GUI suite in Chromium (mote's browsers
fail at launch, #4125), and the full Go suite at this exact head.
Only fixtures were used.
This commit is contained in:
yetone
2026-10-30 18:03:55 +08:00
parent 53a2e385e7
commit 0a9d9702f3
3 changed files with 113 additions and 4 deletions
+4 -2
View File
@@ -9627,7 +9627,8 @@ function drawEditor(p, presetID) {
e.preventDefault();
const took = [], notes = [];
if (curlBase && c.api) { curlBase(c.api, c.base); took.push(t("Base URL") + " (" + t(API_NAMES[c.api]) + ")"); }
if (c.key) { key.value = draft.key = c.key; countKeys(); took.push(t("API key")); }
// 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 (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 (curlBase && !c.api) notes.push(t("Its URL isn't an address ending in /chat/completions, /messages or /responses: type the base URL."));
@@ -9707,7 +9708,8 @@ function drawEditor(p, presetID) {
if (p?.keyList?.length) ed.append(...field(t("Accounts"), renderKeyAccounts(p), p.routing ? t("Tick every key to use; Routing says how requests spread over them.") : t("Tick every key to use. Requests go to the first; when it runs out of quota or hits a rate limit, the next ticked key takes over.")));
if (p?.keyList?.filter((k) => k.on).length > 1) ed.append(...renderRouting(p));
else if (vertex) ed.append(...vertexFields());
else ed.append(...field(t("API key"), keyWrap, isNew ? t("Kept in ~/.config/magpie/providers.json, readable by you alone. Nothing is read from your shell.") : ""));
// keys are replaced in Accounts; the box is for no key yet (Kylin_Cloud on X)
else if (!p?.keyList?.length) ed.append(...field(t("API key"), keyWrap, isNew ? t("Kept in ~/.config/magpie/providers.json, readable by you alone. Nothing is read from your shell.") : ""));
// A user-defined provider can have its own picture; presets keep theirs.
if (custom) ed.append(...field(t("Icon"), iconPicker(ed), ""));
+106
View File
@@ -0,0 +1,106 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Kylin_Cloud on X: a provider's key was in its Accounts list, with Copy,
// the pencil that replaces it and Remove, and again below in an "API key"
// box to "paste a new key to replace it": the same thing twice. A provider
// with a key now has its Accounts alone; the box is for one with no key
// yet (a local server's, a new one). A curl command pasted into such a
// provider's Base URL fills what it can and leaves the keys alone: the
// key it carries isn't saved over the first one unseen.
// Chromium and WebKit, wide and narrow, in every language.
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 base = { icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", models: [{ id: "m", name: "m", on: true }], agents: [], fallback: [], headers: {}, routing: "", balanceToken: { takes: false, set: false }, proxy: "", ready: true };
const relay = { ...base, id: "relay", name: "Relay", key: { set: true, masked: "sk-…one" }, keyList: [{ id: "aaaaaaaaaa", name: "", masked: "sk-…one", on: true, active: true }] };
const twoOneOn = { ...base, id: "pair", name: "Pair", key: { set: true, masked: "sk-…one" }, keyList: [{ id: "aaaaaaaaaa", name: "", masked: "sk-…one", on: true, active: true }, { id: "bbbbbbbbbb", name: "", masked: "sk-…two", on: false }] };
const local = { ...base, id: "local", name: "Local", chat: "http://127.0.0.1:11434/v1", key: { set: false, optional: true }, keyList: [] };
const curl = `curl https://relay.example.com/v1/chat/completions -H "Authorization: Bearer sk-from-curl-0123456789" -H "Content-Type: application/json" -d '{"model":"m2","messages":[]}'`;
function serve(lang, posts) {
const providers = { providers: [relay, twoOneOn, local], presets: [], excluded: [], gateway: { running: true, window: true } };
return async (route) => {
const req = route.request(), url = new URL(req.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({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (req.method() === "POST" && url.pathname.startsWith("/api/provider")) posts.push({ path: url.pathname, body: req.postDataJSON() });
if (url.pathname.startsWith("/api/provider/")) return json(providers);
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).catch(() => ""), contentType });
};
}
const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [900, 420]) {
test(`${engine} ${lang} ${width}px: a provider's key is in its Accounts once, not in a box below too`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts));
await page.goto("http://magpie.test/?view=providers");
const w = await page.evaluate((lang) => Object.fromEntries(["API key", "Accounts", "Save"].map((k) => [k, lang === "en" ? k : I18N[lang][k]])), lang);
assert.deepEqual(Object.entries(w).filter(([, v]) => !v).map(([k]) => k), []);
const ed = page.locator(".editor");
const label = (k) => ed.locator("label", { hasText: new RegExp(`^${esc(w[k])}$`) });
const open = async (name) => {
await page.locator(".row.provider", { hasText: name }).first().click();
await ed.waitFor();
};
for (const name of ["Relay", "Pair"]) {
await open(name);
await label("Accounts").waitFor();
assert.equal(await ed.locator(".accts.keys .acc .key-edit").first().count(), 1, `${name}: its key is replaced from its row`);
assert.equal(await label("API key").count(), 0, `${name}: no second key box`);
assert.equal(await ed.locator('input[placeholder*="sk-…one"]').count(), 0, `${name}: no box to paste a key over the first`);
assert.equal(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), true, "no sideways scroll");
await page.keyboard.press("Escape");
await ed.waitFor({ state: "detached" }).catch(() => {});
}
// with no key, the box is where one goes
await open("Local");
await label("API key").waitFor();
assert.equal(await label("Accounts").count(), 0);
await page.keyboard.press("Escape");
await ed.waitFor({ state: "detached" }).catch(() => {});
// a curl pasted into a keyed provider's Base URL leaves its keys
await open("Relay");
const took = await ed.locator(".base-url").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;
}, curl);
assert.ok(took, "the curl command is read");
const y = await page.evaluate(() => document.scrollingElement.scrollTop);
await ed.locator("button.primary", { hasText: w.Save }).click();
for (let i = 0; i < 40 && !posts.some((p) => p.path === "/api/provider/save"); i++) await page.waitForTimeout(50);
const saved = posts.find((p) => p.path === "/api/provider/save")?.body;
assert.ok(saved, "saved");
assert.ok(!saved.key, `no key saved over the first: ${JSON.stringify(saved.key)}`);
assert.equal(await page.evaluate(() => document.scrollingElement.scrollTop), y, "a click never scrolls the page");
assert.deepEqual(errors, []);
});
}
}
}
@@ -33,8 +33,9 @@ const relay = () => ({
const solo = () => ({
id: "solo", name: "Solo", icon: "generic", chat: "https://solo.example.com/v1", responses: "", anthropic: "", catalog: "",
models: [{ id: "small", name: "", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…solo" }, balanceToken: { takes: false, set: false }, proxy: "",
keyList: [{ id: "5050505050", name: "", masked: "sk-…solo", on: true, active: true }],
// no key yet: the API key box is shown only then (keys are replaced in Accounts)
key: { set: false }, balanceToken: { takes: false, set: false }, proxy: "",
keyList: [],
});
function serve(lang, posts) {