Files
magpie/internal/gui/tests/plugin-checkin.test.cjs
T
yetone 8f9bc3fccf gui tests: the 37 other Settings tests act on rows once the page has drawn its last read of the settings, as the masking-rules tests do since #1653 (#1659)
Opening Settings reads the settings twice: the page's own read
(showView), then the window's load() once the state is in. Each read
redraws every row. A test that found a row after the first draw, and
then called scrollIntoViewIfNeeded or boundingBox on it, failed when the
second read landed in between. The errors were "Element is not
attached", or a null box. #1653 fixed the three masking-rules tests and
listed these 37 in #1659.

Each of the 37 now calls watchSettingsReads(page) before every
page.goto, and settingsDrawn(page) right after it. Right after goto is
exact for ?view=settings: at boot, show(view) asks for showView's read
before load() runs. load() sets load.done in the same run that then asks
for its own read, so settingsDrawn's "load.done and every read asked
for drawn" holds only once the second read is drawn. For a test opened
on another page that clicks into Settings later, load is done by then,
the click makes the only read, and the wait passes at once.
watchSettingsReads now watches a page once, however many times it is
opened, since some of these tests open one page several times. The
page is unchanged.

Reproduced with a generic injection (scratchpad inject1659.cjs, loaded
with NODE_OPTIONS=--require). A route added at each goto holds the
page's second GET /api/settings. It lets the read go just as the test
calls scrollIntoViewIfNeeded or boundingBox, or waits on the page with
waitForFunction (which settingsDrawn is), with a 4s timer as a backstop.
This is #1653's injection, made generic.

Before, injected, both engines, all languages:
- 5 files red with the issue's error:
  - github-token: null box.
  - member-model-setting, searcher-pick, search-first and update-wait:
    "Element is not attached to the DOM".
- 4 files red on a check of a row drawn from the first read:
  model-suffix-own, otel, readable-focus and warm-at-times.
- 28 green.

After, injected: 36 of the 37 files green, every held read let go by
settingsDrawn's wait. otel stays red in WebKit at 360px. It is red the
same way with no injection, on origin/main's own copy of the test. That
cause is separate (the narrow nav laid out after setViewportSize
returns) and has its own commit next.

Plain (no injection), both engines, all 37 files: 460 cases passed and
2 failed, both otel's WebKit 360px check above.

The 8 files red under injection before, injected again after,
5 rounds: 390 of 390 cases passed.
2026-10-12 03:25:47 +08:00

160 lines
10 KiB
JavaScript

// Run with Node's test runner and Playwright on the module path; see README.md.
// Lemon on Discord: "provider 每日签到的方法能放到插件里面去做吗". A plugin
// whose auth hook has checkin presses its vendor's daily check-in itself, and
// magpie shows it as it shows its own: the account's Usage card has the row
// (checkinBy "plugin:<provider>"), with Auto check-in posting
// /api/settings/plugin-checkin {provider, on} and Check in now posting
// /api/usage/plugin-checkin {provider}; a captcha the vendor asks for is said
// as such, never as a failure, as magpie never solves one. Settings' check-in
// tabs gain Plugins while such a plugin is signed in, a row a provider with
// Off/On. English, Chinese, Japanese and German, the window and the panel's
// 440px; 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 { watchSettingsReads, settingsDrawn } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const today = new Date(Date.now() + 8 * 3600e3).toISOString().slice(0, 10);
const quotas = () => [
{ provider: "plugin:fakeco", name: "FakeCo", plan: "Pro", user: "ann", windows: [{ name: "Credits", used: 12 }],
checkins: true, checkinBy: "plugin:fakeco", checkin: { user: "ann", by: "plugin:fakeco", vendor: "FakeCo", day: today, outcome: "claimed", credit: 50, streak: 3 } },
{ provider: "plugin:fakeco", name: "FakeCo", plan: "Free", user: "bob", windows: [{ name: "Credits", used: 2 }],
checkins: true, checkinBy: "plugin:fakeco", checkin: { user: "bob", by: "plugin:fakeco", vendor: "FakeCo", day: today, outcome: "captcha", msg: "slide the puzzle" } },
{ provider: "codex", name: "Codex", icon: "openai", plan: "Plus", windows: [{ name: "5 hours", used: 20 }] },
];
function serve(lang, asked) {
const settings = { theme: "light", lang, quotaLeft: false, currency: "usd",
checkinPlugins: [{ id: "fakeco", name: "FakeCo", on: false, checkins: [
{ user: "ann", by: "plugin:fakeco", vendor: "FakeCo", day: today, outcome: "claimed", credit: 50, streak: 3 },
{ user: "bob", by: "plugin:fakeco", vendor: "FakeCo", day: today, outcome: "captcha" },
] }] };
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:"${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 });
if (url.pathname === "/api/settings/plugin-checkin") {
const b = route.request().postDataJSON();
asked.push(["set", b]);
settings.checkinPlugins = settings.checkinPlugins.map((p) => (p.id === b.provider ? { ...p, on: b.on } : p));
return json(settings);
}
if (url.pathname === "/api/usage/plugin-checkin") {
asked.push(["now", route.request().postDataJSON()]);
return json([{ user: "bob", by: "plugin:fakeco", day: today, outcome: "captcha" }]);
}
if (url.pathname === "/api/settings") return json(settings);
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/usage/quotas") return json(quotas());
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const words = {
en: { done: "Checked in today +50 · 3-day streak", captcha: "Asks for a captcha; check in in its own app · slide the puzzle", auto: "Auto check-in", tab: "Plugins", sub: /FakeCo plugin check each signed-in account.*bob is asked for a captcha/ },
zh: { done: "今日已签到 +50 · 连续 3 天", captcha: "需要验证码,请在它自己的 App 里签到 · slide the puzzle", auto: "自动签到", tab: "插件", sub: /FakeCo 插件.*bob 需要验证码/ },
ja: { captcha: "CAPTCHA が必要です。公式アプリでチェックインしてください · slide the puzzle", tab: "プラグイン", sub: /FakeCo プラグイン.*bob は CAPTCHA が必要です/ },
de: { captcha: "Verlangt ein Captcha; in der eigenen App einchecken · slide the puzzle", tab: "Erweiterungen", sub: /FakeCo-Plugin.*bob soll ein Captcha lösen/ },
};
const scrolls = (page) => page.evaluate(() => [scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => e.scrollTop)].join(","));
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "ja", "de"]) {
const w = words[lang];
test(`${engine} ${lang}: a plugin's own check-in on its Usage card`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width: 900, height: 900 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [], asked = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, asked));
await watchSettingsReads(page);
await page.goto("http://magpie.test/?view=usage");
await settingsDrawn(page); // rows found are the ones that stay (#1659)
const card = page.locator(".subscription-card", { hasText: "FakeCo" });
await card.locator(".wb-checkin").first().waitFor();
const rows = card.locator(".wb-checkin");
assert.equal(await rows.count(), 2, "one line an account");
const says = (await rows.locator(".ci-say").allInnerTexts()).map((s) => s.trim());
if (w.done) assert.equal(says[0], w.done);
assert.equal(says[1], w.captcha, "a captcha is said as such");
assert.notEqual(await rows.nth(1).getAttribute("data-state"), "bad", "a captcha isn't a failure");
assert.match(await rows.first().locator(".ci-say").getAttribute("title"), /FakeCo/);
assert.equal(await page.locator(".subscription-card", { hasText: "Codex" }).locator(".wb-checkin").count(), 0);
const auto = card.locator(".ci-auto");
assert.equal(await auto.count(), 1);
if (w.auto) assert.equal((await auto.innerText()).trim(), w.auto);
assert.match(await auto.getAttribute("title"), /FakeCo/);
assert.equal(await auto.getAttribute("aria-pressed"), "false");
const y = await scrolls(page);
await auto.click();
await page.waitForFunction(() => document.querySelector(".ci-auto")?.getAttribute("aria-pressed") === "true");
assert.deepEqual(asked, [["set", { provider: "fakeco", on: true }]]);
assert.equal(await scrolls(page), y, "the toggle moved the page");
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: Settings has a Plugins check-in tab at 440px`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width: 440, height: 900 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [], asked = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, asked));
await watchSettingsReads(page);
await page.goto("http://magpie.test/?view=settings&tab=usage");
await settingsDrawn(page); // rows found are the ones that stay (#1659)
const tab = page.locator("#warmTab-plugins");
await tab.waitFor();
assert.equal(await tab.isHidden(), false);
assert.equal((await tab.textContent()).trim(), w.tab);
assert.equal(await page.locator("#warmTab-qoder").isHidden(), true, "Qoder's tab with no Qoder account");
// at 440x900 the tabs are below the fold: the reader scrolls to them
await page.mouse.move(220, 400);
for (let i = 0; i < 10; i++) {
const r = await tab.boundingBox(), foot = await page.locator("footer.foot").boundingBox();
if (r.y + r.height < foot.y - 8) break;
await page.mouse.wheel(0, 200);
await page.waitForTimeout(100);
}
await tab.click();
const row = page.locator('#pluginCheckinList .row[data-provider="fakeco"]');
await row.waitFor();
assert.match(await row.locator(".name").innerText(), /FakeCo/);
assert.match((await row.locator(".sub").innerText()).replace(/\s+/g, " "), w.sub);
const box = await row.boundingBox();
assert(box.width > 0 && box.x + box.width <= 440, "the row fits at 440px");
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "no sideways scroll");
if (process.env.ARTIFACT_DIR) await row.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `plugin-checkin-${engine}-${lang}.png`) });
// and on to its switch, under the foot in a long language
const on = row.locator(".segs button").nth(1);
for (let i = 0; i < 10; i++) {
const r = await on.boundingBox(), foot = await page.locator("footer.foot").boundingBox();
if (r.y + r.height < foot.y - 8) break;
await page.mouse.wheel(0, 200);
await page.waitForTimeout(100);
}
const saved = page.waitForRequest((r) => new URL(r.url()).pathname === "/api/settings/plugin-checkin");
await on.click();
await saved;
assert.deepEqual(asked, [["set", { provider: "fakeco", on: true }]]);
assert.equal(await page.locator("select").count(), 0);
assert.deepEqual(errors, []);
});
}
}