Files
magpie/internal/gui/tests/key-plan.test.cjs
T
yetone 6e6aba51c8 providers: a key may be for another plan of its vendor, sent to that plan's endpoints
yckonnnn on X uses Volcengine's pay as you go and its Agent Plan, and
wants a key of each in one provider. Each plan takes its own keys at its
own endpoints (/api/v3, /api/plan/v3, /api/coding/v3), and every key of
a provider went to the provider's one plan, so only one kind worked.

A key now may say which of its preset's Regions it is for
(KeyAccount.Plan; Provider.KeyPlan for the first key, as KeyProtocol).
None, or the provider's own plan, is the provider's plan, stored as
none: old configs read and write as before. Presets whose plans take
keys of their own (PresetDef.KeyPlans): zhipu, zai, stepfun,
stepfun-cn, xiaomi, baidu-qianfan, tencent-cloud, huaweicloud,
volcengine, siliconflow. Not: yylx (one key everywhere),
bailian-decision (decide only), bedrock and bedrock-mantle (regions of
one account).

Every reader of the region or a base URL, and what it does now:
- WithKey (keys.go): moves the key's copy to its plan (atKeyPlan:
  Chat, Responses, Anthropic, Decide, KeysURL, Website, Catalog via
  atRegionOf; a provider at a host of its own keeps that host) and marks
  it keyView. Every gateway key path goes through it: chat, Responses,
  Messages, count_tokens, failover, embeddings (serveRetrieval via
  onKeys), drawing (drawOnAccounts via perKeyBarred), key tests
  (test.go), key_models.go, gui/groups.go, markedKey.
- perKeyBarred (gateway/fallback.go): a key whose plan's list lacks the
  model (PlanServing) is not asked; only when no key's plan has it.
- fetch / fetchPerKey / planOnly (models.go): a mixed provider lists
  each key's plan, a NoList plan from its preset list with no request,
  pay as you go from /api/v3/models with its own key.
- planMedia (PlanEmbeddings, PlanDrawers, PlanVideos): every plan's.
- PlanQuotas (planquota.go): each key read at its own plan's source.
- volcPlanQuotas, tencentPlanQuotas: one view per plan (planViews).
- KeyBalances (balance.go): each key at its plan's host (SiliconFlow).
- startVideo / videoMaker (gateway/video.go): a mixed provider starts on
  a key whose plan makes the model (onKeys) and names it in the id
  (keyMark), so the poll goes to that key's plan.
- GUI: POST /api/keys/plan (SetKeyPlan, then the lists are read again);
  the editor keeps KeyPlan with an unchanged first key, typed() clears
  it with a new one; KeepSecrets, AddCopy, backup's withoutKeys carry it.
- app.js: planPicker, a plan chip in each key row (the app's own menu,
  openProtoMenu, through pickPill, which protoPicker now shares), shown
  for a KeyPlans preset while the provider has several keys or the key
  has a plan; i18n zh, zh-TW, ja, de.

A key's plan is not guessed from the key: Volcengine's keys carry
nothing that says their plan. Xiaomi's tp-, Tencent's sk-tp-, MiniMax's
sk-cp- and Bailian's sk-sp- are noted in code but not used.

Not done: a gateway key held to some keys (videoAsker) on a mixed
provider's video may pick another key; a mixed provider whose own plan
has no balance source while a key's plan has one is not read; keys left
out for their plan don't show in the Routing trace; StepFun's plan
windows are a sign-in per site, unchanged.

Credit: yckonnnn on X (tweet 2114657701305487483).

Run at this commit on origin/main 1bb8143b3 (macOS, go1.26.8):
- gofmt -l internal: clean. go vet ./..., GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean.
- go test -count=1 -skip TestUnreadLoginsWriteErrorsKeepCredentials
  ./internal/provider/ ./internal/gateway/: ok (103s, 421s). The skipped
  test crashes the whole provider package on main (#3632, from 091153bf).
- TestCoreScriptBudget: ok, budgets not raised (app.js 1,307,430 bytes).
- GUI, chromium and webkit: key-*, provider*-*, add-sheet, i18n-keys,
  gui-de, gui-ja, gui-zh-tw (58 files): 956 of 956 pass. key-plan.test.cjs
  covers en, zh, zh-TW, ja and de at 420 and 1000px.
Earlier, at the same change on origin/main 9120acaff:
- go test -timeout 45m ./...: 71 packages ok, internal/gateway and
  internal/gui among them. internal/provider crashed on #3632 only; run
  again with that one test skipped, it passed.
- The whole GUI suite (node --test tests/*.test.cjs) did not finish: the
  disk ran out at about 319 tests and the run was stopped. Up to then the
  only reds were account-discovery in both engines, #3497, red on main.
Broken by hand: without atKeyPlan in WithKey, TestKeyPlanEndpoints,
TestKeyPlanModelList and TestKeyPlansEachToItsOwnEndpoint go red; without
the planless filter in perKeyBarred the gateway test goes red; without
the plan chip key-plan.test.cjs goes red.
Not tried: real Volcengine (or any other vendor's) keys of two plans in
one provider; the video path (startVideo with mixed plans) has no test of
its own; Windows and Linux were vetted, not run.
2026-10-26 20:37:07 +08:00

149 lines
9.7 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// yckonnnn on X: Volcengine's pay as you go and its Agent Plan, a key of
// each in one provider. Each key row of a vendor whose plans take keys of
// their own (keyPlans) has a plan chip saying which plan it is for; a
// click opens the app's own menu of the plans, and a pick saves it
// (keys/plan), the provider's own plan as none. A key alone on the
// provider's plan, and a provider whose keys are on one plan, have no
// chip. A click scrolls nothing, nothing runs off a 420px window. In
// every language, Chromium and WebKit.
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 ark = "https://ark.cn-beijing.volces.com";
const preset = {
id: "volcengine", name: "Volcengine Ark", icon: "volcengine-color", kind: "vendor", keyPlans: true, regionLabel: "Plan",
chat: ark + "/api/coding/v3", responses: ark + "/api/coding/v3", anthropic: ark + "/api/coding",
regions: [
{ id: "coding", name: "Coding Plan", chat: ark + "/api/coding/v3", responses: ark + "/api/coding/v3", anthropic: ark + "/api/coding" },
{ id: "agent", name: "Agent Plan", chat: ark + "/api/plan/v3", responses: ark + "/api/plan/v3", anthropic: ark + "/api/plan" },
{ id: "api", name: "Pay as you go", chat: ark + "/api/v3", responses: ark + "/api/v3" },
],
};
const volc = (keys) => ({
id: "volc", name: "Volc", preset: "volcengine", icon: "volcengine-color", chat: ark + "/api/coding/v3", responses: ark + "/api/coding/v3", anthropic: ark + "/api/coding", catalog: "",
models: [{ id: "kimi-k3", name: "", on: true }], agents: [], fallback: [], headers: {}, routing: "",
key: { set: true, masked: "sk-…one" }, balanceToken: { takes: false, set: false }, proxy: "",
keyList: keys,
});
const relay = {
id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "",
models: [{ id: "gpt-5.5", name: "", on: true }], agents: [], fallback: [], headers: {}, routing: "",
key: { set: true, masked: "sk-…r1" }, balanceToken: { takes: false, set: false }, proxy: "",
keyList: [{ id: "rrrrrrrrr1", name: "r1", masked: "sk-…r1", on: true, active: true, plan: "api" }, { id: "rrrrrrrrr2", name: "r2", masked: "sk-…r2", on: true }],
};
function serve(lang, st) {
return async (request) => {
const url = new URL(request.request().url());
const json = (data) => request.fulfill({ json: data });
const list = () => ({ providers: [volc(st.keys), relay], presets: [preset], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/boot.js") return request.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return request.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json(list());
if (url.pathname === "/api/keys/plan") {
const body = request.request().postDataJSON();
st.posts.push(body);
st.keys = st.keys.map((k) => (k.id === body.ref ? { ...k, plan: body.plan || undefined } : k));
return json(list());
}
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) return new Promise(() => {});
return json({ mine: true, now: new Date().toISOString(), seq: 0, totals: { requests: 0 }, routes: [] });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
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 request.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType });
};
}
async function open(t, engine, lang, width, keys) {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const st = { keys, posts: [] };
await page.route("**/*", serve(lang, st));
await page.goto("http://magpie.test/?view=providers");
const say = (key) => page.evaluate(([lang, key]) => (lang !== "en" && I18N[lang]?.[key]) || key, [lang, key]);
return { page, errors, say, st };
}
const sideways = (page) => page.evaluate(() => document.documentElement.scrollWidth > innerWidth);
const scrolled = (page) => page.evaluate(() => [window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop > 0).map((e) => `${e.className}:${e.scrollTop}`)].join(" "));
const three = () => [
{ id: "aaaaaaaaaa", name: "coding", masked: "sk-…one", on: true, active: true },
{ id: "bbbbbbbbbb", name: "payg", masked: "sk-…two", on: true, plan: "api" },
{ id: "cccccccccc", name: "agent", masked: "sk-…three", on: true, plan: "agent" },
];
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 [420, 1000]) {
test(`${engine} ${lang} ${width}px: each key says its plan, and a pick saves it`, async (t) => {
const { page, errors, say, st } = await open(t, engine, lang, width, three());
await page.locator(".row.provider", { hasText: "Volc" }).first().click();
const row = (id) => page.locator(`.editor .accts.keys .acc[data-account-id="${id}"]`);
await row("aaaaaaaaaa").waitFor();
const names = {};
for (const r of preset.regions) names[r.id] = await say(r.name);
for (const [id, plan] of [["aaaaaaaaaa", "coding"], ["bbbbbbbbbb", "api"], ["cccccccccc", "agent"]]) {
// a key on the provider's own plan shows its chip on hover, as Any protocol does
await row(id).hover();
const c = row(id).locator("button.proto").filter({ hasText: names[plan] });
assert.equal(await c.count(), 1, `${id}: no chip saying ${names[plan]}`);
assert.equal(await c.getAttribute("title"), await say("The plan this key is for: its requests go to that plan's endpoints, and it is asked only for that plan's models."));
const box = await c.boundingBox();
assert.ok(box && box.x >= 0 && box.x + box.width <= width, `the chip runs off the window: ${JSON.stringify(box)}`);
}
// the coding key moved to the Agent Plan
const c = row("aaaaaaaaaa").locator("button.proto").filter({ hasText: names.coding });
await c.scrollIntoViewIfNeeded();
await row("aaaaaaaaaa").hover();
const sc = await scrolled(page);
await c.click();
const menu = page.locator(".proto-menu");
await menu.waitFor();
assert.equal((await menu.locator(".pm-head").textContent()).trim(), await say("Plan this key is for"));
assert.equal(await menu.locator(".pm-item").count(), 3);
assert.equal(await scrolled(page), sc, "a click scrolled");
const mb = await menu.boundingBox();
assert.ok(mb.x >= 0 && mb.x + mb.width <= width, `the menu runs off the window: ${JSON.stringify(mb)}`);
await menu.locator(".pm-item", { hasText: names.agent }).click();
await page.waitForFunction(() => !document.querySelector(".proto-menu"));
await row("aaaaaaaaaa").locator("button.proto").filter({ hasText: names.agent }).waitFor();
assert.deepEqual(st.posts, [{ id: "volc", ref: "aaaaaaaaaa", plan: "agent" }]);
// the agent key back to the provider's own plan: saved as none
await row("cccccccccc").locator("button.proto").filter({ hasText: names.agent }).click();
await page.locator(".proto-menu .pm-item", { hasText: names.coding }).click();
await row("cccccccccc").locator("button.proto:not(.set)").filter({ hasText: names.coding }).waitFor({ state: "attached" });
assert.deepEqual(st.posts[1], { id: "volc", ref: "cccccccccc", plan: "" });
assert.equal(await sideways(page), false, "the page scrolls sideways");
assert.deepEqual(errors, []);
});
}
}
test(`${engine}: no chip for one key on the provider's plan, nor a preset of one plan`, async (t) => {
const { page, errors } = await open(t, engine, "en", 420, [{ id: "aaaaaaaaaa", name: "coding", masked: "sk-…one", on: true, active: true }]);
await page.locator(".row.provider", { hasText: "Volc" }).first().click();
await page.locator(`.editor .accts.keys .acc[data-account-id="aaaaaaaaaa"]`).waitFor();
assert.equal(await page.locator(".editor .accts.keys button.proto", { hasText: "Coding Plan" }).count(), 0);
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider", { hasText: "Relay" }).first().click();
await page.locator(`.editor .accts.keys .acc[data-account-id="rrrrrrrrr1"]`).waitFor();
assert.equal(await page.locator(".editor .accts.keys button.proto", { hasText: "Pay as you go" }).count(), 0);
assert.deepEqual(errors, []);
});
}