hzh_1119 on Discord: ChatGPT Pro and Business now come with monthly API credit, and they want an OpenAI API key spent before the ChatGPT subscription where both serve a model, the subscription taking over after. Smart had no way to say so: an API key tells no allowance, so it went after every account with room, in every model's found group (auto/<model>). The only way round was a group set to In order with its members dragged, one group at a time, which nothing pointed to. A provider row's right-click has Use first (provider/usefirst, provider.SetUseFirst, Provider.UseFirst, copied onto its accounts by accountSettings, kept by the editor's Save). Its keys and accounts are routes.Seat.Lead, and Smart (leadFirst) puts those not all but used up ahead of every other seat, each side in Smart's own order. A resting one is passed over as before, so a 429 insufficient_quota (out of credit) or a failure moves the request on to the subscription. Off by default; within one provider nothing changes. The Routing page says why the first went first (Weighed.UseFirst, firstWhy) and doesn't call the one behind it "renewing later" (behindWhy). The menu shows a tick when it is on. Free quota by expiry orders its paid seats with Smart and so follows it; other strategies don't read it. The core's script budget is met by cutting three Providers-page comments in app.js, no raise. Run (on mote via mote-run, atda548b454= origin/main): - go test ./internal/routes ./internal/provider: ok. ./internal/gui: ok but TestMainWindowCorners/macOS_26_SDK, red the same on a fresh origin/mainda548b454checkout (#3949, macOS 27). - go test -run 'TestUseFirstLeadsTheGroup|TestRoutingGroups' ./internal/gateway: ok. - node --test use-first.test.cjs (new: 40 cases, Chromium and WebKit, 1100 and 420 wide, en zh zh-TW ja de) and provider-find.test.cjs (its menu now lists Use first): 52 pass. - i18n-keys, i18n-en-no-cjk, routing-behind-why: pass but i18n-keys' "a plugin's words are its own", red the same on origin/main (#5327, #5426, #5482; none of its keys are this change's). - GOOS=linux and GOOS=windows go vet -tags nogui ./...: ok. gofmt -l: none. Broken by hand: - Lead left out of weighRouted's seat: TestUseFirstLeadsTheGroup red (served from ksub with api set to Use first). - Smart without leadFirst: TestSmartLeadFirst red ([plus pro api ...], want api first). - firstWhy's Use first case off: use-first.test.cjs's Routing cases red in every language. Not tried: a real ChatGPT account beside a real OpenAI key with API credit; the 429 insufficient_quota fallthrough is from the fake vendor's body (carriedQuotaBody). The full suite runs after the push. Reported-by: hzh_1119
143 lines
8.3 KiB
JavaScript
143 lines
8.3 KiB
JavaScript
// Run with Node's test runner and Playwright on the module path; see README.md.
|
|
// hzh_1119 on Discord: an OpenAI API key's monthly credit spent before the
|
|
// ChatGPT subscription where both serve a model. A provider row's
|
|
// right-click has Use first: it posts provider/usefirst, and once on the
|
|
// item shows a tick and posts it off again. On the Routing page, a request
|
|
// whose first went first for it says so, not that its allowance renews
|
|
// sooner. The page doesn't move. Every language, Chromium and WebKit, at
|
|
// 1100 and 420 wide; no backend, the API is faked here.
|
|
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 CHECK = "m3.5 8.5 3 3 6-7";
|
|
const now = new Date();
|
|
const ago = (minutes) => new Date(now.getTime() - minutes * 60e3).toISOString();
|
|
const prov = (id, name, extra = {}) => ({
|
|
id, name, icon: "generic", host: id + ".example.com", chat: "https://" + id + ".example.com/v1", responses: "", anthropic: "", catalog: "",
|
|
models: [{ id: "gpt-5.5", name: "GPT-5.5", on: true }], agents: [], fallback: [], headers: {},
|
|
key: { set: true, masked: "sk-…" + id }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", ...extra,
|
|
});
|
|
const order = [
|
|
{ id: "openai#k", provider: "openai", name: "OpenAI", who: "OpenAI", kind: "key", model: "gpt-5.5", routing: "", useFirst: true },
|
|
{ id: "codex#u", provider: "codex", name: "Codex", who: "me@example.com", kind: "account", model: "gpt-5.5", routing: "", known: true, used: 10,
|
|
windows: [{ used: 10, resets: new Date(now.getTime() + 2 * 3600e3).toISOString() }] },
|
|
];
|
|
|
|
function serve(lang, posts) {
|
|
let list = [prov("codex", "Codex"), prov("openai", "OpenAI")];
|
|
const providers = () => ({ providers: list, presets: [], excluded: [], gateway: { running: true, window: true } });
|
|
const route = {
|
|
id: 1, seq: 1, time: ago(1), agent: "codex", model: "auto/gpt-5.5", provider: "openai", done: true, status: 200, ms: 900, tokens: 1200, order,
|
|
tries: [{ id: "openai#k", model: "gpt-5.5", start: ago(1), done: true, status: 200, ms: 900 }],
|
|
};
|
|
return async (request) => {
|
|
const url = new URL(request.request().url());
|
|
const json = (data) => request.fulfill({ json: data });
|
|
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(providers());
|
|
if (url.pathname === "/api/provider/usefirst") {
|
|
const body = request.request().postDataJSON();
|
|
posts.push(body);
|
|
list = list.map((p) => p.id === body.id ? { ...p, useFirst: body.useFirst } : p);
|
|
return json(providers());
|
|
}
|
|
if (url.pathname === "/api/gateway/trace") {
|
|
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
|
|
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 1 }, routes: [route] });
|
|
}
|
|
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), contentType });
|
|
};
|
|
}
|
|
|
|
const strings = [
|
|
"Use first",
|
|
"{name} is used first",
|
|
"{name} takes its turn with the others",
|
|
"{who} goes first: its provider is set to be used first.",
|
|
"its provider is set to be used first.",
|
|
];
|
|
|
|
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
|
for (const width of [1100, 420]) {
|
|
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
|
const open = async (t, view) => {
|
|
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);
|
|
page.setDefaultNavigationTimeout(60000);
|
|
const errors = [], posts = [];
|
|
page.on("pageerror", (e) => errors.push(e.message));
|
|
await page.route("**/*", serve(lang, posts));
|
|
await page.goto("http://magpie.test/?view=" + view);
|
|
const say = (key, vars = {}) => page.evaluate(([lang, key, vars]) => {
|
|
const s = (lang !== "en" && I18N[lang]?.[key]) || key;
|
|
return s.replace(/\{(\w+)\}/g, (_, k) => vars[k] ?? `{${k}}`);
|
|
}, [lang, key, vars]);
|
|
return { page, errors, posts, say };
|
|
};
|
|
|
|
test(`${engine} ${width} ${lang}: a provider's right-click turns Use first on and off`, async (t) => {
|
|
const { page, errors, posts, say } = await open(t, "providers");
|
|
await page.locator(".row.provider").first().waitFor();
|
|
if (lang === "en") {
|
|
const missing = await page.evaluate((ks) => ["zh", "zh-TW", "ja", "de"].flatMap((l) => ks.filter((k) => !I18N[l][k]).map((k) => `${l}: ${k}`)), strings);
|
|
assert.deepEqual(missing, [], "every string has its translations");
|
|
}
|
|
const scrollers = () => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => e.scrollTop).concat(document.scrollingElement.scrollTop));
|
|
const before = await scrollers();
|
|
const row = page.locator('#providers > .row.provider[data-id="openai"]');
|
|
const menu = page.locator(".pop.row-menu");
|
|
const item = menu.locator(".rm-item", { hasText: await say("Use first") });
|
|
await row.locator(".name").click({ button: "right" });
|
|
await menu.waitFor();
|
|
assert.equal(await item.count(), 1);
|
|
assert.notEqual(await item.locator("path").getAttribute("d"), CHECK, "off, no tick");
|
|
const box = await menu.boundingBox();
|
|
assert.ok(box.x >= 0 && box.x + box.width <= width, `the menu fits across ${width}`);
|
|
await item.click();
|
|
await page.waitForFunction(() => !document.querySelector(".pop.row-menu"));
|
|
assert.deepEqual(posts, [{ id: "openai", useFirst: true }]);
|
|
assert.equal(await page.locator("#providers > .row.provider.selected").count(), 0, "the right-click opened the row");
|
|
|
|
await row.locator(".name").click({ button: "right" });
|
|
await menu.waitFor();
|
|
assert.equal(await item.locator("path").getAttribute("d"), CHECK, "on, a tick");
|
|
await item.click();
|
|
await page.waitForFunction(() => !document.querySelector(".pop.row-menu"));
|
|
assert.deepEqual(posts, [{ id: "openai", useFirst: true }, { id: "openai", useFirst: false }]);
|
|
|
|
await page.locator('#providers > .row.provider[data-id="codex"] .name').click({ button: "right" });
|
|
await menu.waitFor();
|
|
assert.notEqual(await item.locator("path").getAttribute("d"), CHECK, "another provider is off");
|
|
await page.keyboard.press("Escape");
|
|
assert.deepEqual(await scrollers(), before, "the page doesn't move");
|
|
assert.deepEqual(errors, []);
|
|
});
|
|
|
|
test(`${engine} ${width} ${lang}: the Routing page says the first went first for Use first`, async (t) => {
|
|
const { page, errors, say } = await open(t, "routing");
|
|
const req = page.locator(".rt-req").first();
|
|
await req.waitFor();
|
|
if (await req.getAttribute("aria-pressed") !== "true") await req.click();
|
|
const why = page.locator(".rt-steps li.why").first();
|
|
await why.waitFor();
|
|
assert.equal((await why.textContent()).trim(), await say("{who} goes first: its provider is set to be used first.", { who: "OpenAI" }));
|
|
assert.deepEqual(errors, []);
|
|
});
|
|
}
|
|
}
|
|
}
|