Files
magpie/internal/gui/tests/import-row.test.cjs
T
yetone 4b1994ad31 agent: AionUi, added through its add-provider link
seven7032 on Discord asked how to connect AionUi to magpie. AionUi
keeps its providers in its own SQLite database
(<userData>/aionui/aionui-backend.db, WAL mode), each key encrypted, so
there is no config file for magpie to write. The one supported way in
is its deeplink. AionUi 2.2.2's main process parses it
(parseDeepLinkUrl), and its renderer opens Settings -> Model with the
add form filled in, which the user confirms:

  aionui://add-provider?api_key=magpie-aionui&base_url=<gw>/v1&name=magpie&platform=custom

The AionUi row works the way Cindy's and Lody's do:
- Add magpie opens that link. /api/open allows the aionui://add-provider?
  prefix only. `magpie aionui add` opens it from the CLI.
- The key is agentKeyAt("aionui"), so it becomes the LAN key while
  sharing is on (added to TestPinnedGatewayKeyForEveryWriter).
- "custom" is AionUi's OpenAI-compatible platform. Its base URLs end in
  /v1, as its own OpenAI preset's does.
- Added reads providers.base_url for the gateway's address without
  touching the database (sessions.OpenUntouched, from the previous
  commit). A database that can't be read is unknown, never "not added".
  The last read is kept while the database and its log keep their size
  and time, for 15s at most, so the Agents poll doesn't copy a running
  AionUi's database every time.
- It is detected by userData/aionui (os.UserConfigDir()/AionUi on every
  OS).
- As with Cindy and Lody, the TUI leaves the row out (nothing to pick).

Tests:
- TestAionUiLink: the link's exact bytes.
- TestAionUiLinkParsedAs2_2_2: runs the link through
  testdata/aionui/deeplink-2.2.2.js, which is parseDeepLinkUrl copied
  byte for byte from 2.2.2's app.asar (out/main/index.js 50995-51021)
  plus the renderer's add-provider mapping and the form prefill. The
  result is action add-provider, route /settings/model, and the form gets
  platform custom, the /v1 base URL and the key.
- TestAionUiHas: a fixture database built from 2.2.2's real providers
  schema (taken from the database 2.2.2 made at first start). It covers
  none, another gateway, a row present only in the log of a running app,
  and a closed app, and checks that AionUi's folder is unchanged each
  time.
- TestAionUiUnreadableIsUnknown, TestAionUiStatusRereadsOnChange,
  TestAionUiDetect, TestAionUiImportRow (GUI: the row, unknown status,
  and /api/open refusing other aionui:// links).
- import-row.test.cjs gains the AionUi row (icon, known status in each
  language, the click opens the exact link, and it fits at 420px), in
  chromium and webkit across en, zh, zh-TW, ja and de. The same file
  now waits for the rows to settle before its alignment check: under
  load 105 one run caught Cindy's button mid-resize at 193.4px beside
  the picker's 194.4px. The old file passed 3/3 alone, so it is a
  timing assumption, not a layout bug.

Run at 18041fc5b (this change on origin/main 714ab8e8b):
- go test ./... -timeout 45m, through the suite lock: every package ok
  except internal/proc's TestNoCommandBypassesProc, red on
  internal/tui/keep.go:102 from 75e78a5a0 on main (#3567, which has a
  fix on skygunner's fork).
- gofmt -l clean; GOOS=linux go vet -tags nogui ./... and GOOS=windows
  go vet of agent, gui, cli and sessions clean.
- import-row.test.cjs: 20/20 in chromium and webkit.
- The whole GUI suite (make test-ui, 882 files) was still running at
  push, so it is not recorded here.
Rebased onto cbbf3163c, which changes GUI assets and api.go. At the
pushed head: go vet of the four packages is clean; go test
./internal/gui ok; the AionUi, Cindy and pinned-key agent tests are ok.
import-row.test.cjs at load ~210: one run had 19/20, and that run's
output wasn't kept, so I can't name the failing case. The next three
runs were 20/20.

Tried: magpie built at this commit with -tags nogui under a sandbox
HOME. `magpie aionui` printed "magpie aionui add  to add magpie" with
AionUi's folder and no database. With a copy of the real 2.2.2 database
holding one row at the gateway's /v1, it printed "magpie added".

Broken by hand:
- Dropping the aionui prefix from /api/open: TestAionUiImportRow red
  ("AionUi's link was not handed to the desktop").
- The reader put back to a plain mode=ro open: TestAionUiHas red
  ("AionUi's folder changed: aionui-backend.db ->
  aionui-backend.db,aionui-backend.db-shm,aionui-backend.db-wal").
Both were restored and are green.

Not tried: the add form, the saved row and gateway traffic. The
released AionUi 2.2.2 desktop app asks for an aionui.com sign-in before
any page, Settings included. That sign-in was not faked, and no
aionui.com account was available, so the link has never been opened in
a signed-in AionUi end to end. Also not tried: what AionUi saves for
platform custom when it is confirmed, AionUi's User-Agent (so none is
matched), and the aionui:// handler on Linux and Windows (Electron's
setAsDefaultProtocolClient, unverified there).
2026-10-25 16:49:29 +08:00

149 lines
9.4 KiB
JavaScript

// An app magpie is added to by a link of its own (Cindy, Lody, AionUi) is a row like the
// others on the Agents page (the owner: its wide button, with no line under
// the name, sat apart from every other): a line under its name says whether
// magpie is added, and its button stands where the others' model picker
// does, as wide and lined up with it.
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");
// connected when Cindy has magpie, so neither is folded under Show more
const crush = (wired) => ({
id: "crush", name: "Crush", path: "/test/crush.json", icon: "crush", wired,
fields: [{ key: "model", label: "model", value: wired ? "magpie/deepseek-flash" : "", options: [{ value: "magpie/deepseek-flash", label: "DeepSeek Flash", ref: "deepseek/deepseek-flash" }] }],
});
const cindy = (added) => ({ id: "cindy", name: "Cindy", path: "", icon: "cindy", import: "cindy://import?x=1", added, fields: [] });
// AionUi's link as magpie makes it (agent.AionUiLink), its status the
// other way round from Cindy's so each run has both
const AIONUI_LINK = "aionui://add-provider?api_key=magpie-aionui&base_url=http%3A%2F%2F127.0.0.1%3A3425%2Fv1&name=magpie&platform=custom";
const aionui = (added) => ({ id: "aionui", name: "AionUi", path: "", icon: "aionui", import: AIONUI_LINK, added, fields: [] });
async function serve(route, lang, added) {
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:false,textSize:100};` });
}
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [crush(added), cindy(added), aionui(!added), { id: "lody", name: "Lody", path: "", icon: "lody", import: "lody://provider/import?v=1&data=fixture", fields: [] }], profiles: [], settings: { lang, theme: "light", textSize: 100 } });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, window: true } });
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 route.fulfill({ body: await fs.readFile(file), contentType });
}
const SAID = {
en: [/^Not added · Cindy asks to add magpie/, /^Added · magpie is a provider in Cindy/],
zh: [/^未添加 · /, /^已添加 · /],
"zh-TW": [/^未新增 · /, /^已新增 · /],
ja: [/^未追加 · /, /^追加済み · /],
de: [/^Nicht hinzugefügt · /, /^Hinzugefügt · /],
};
// Lody has no status magpie can read: its line asks to confirm in Lody, in
// the reader's language, and never says added or not
const UNKNOWN = {
en: "Opens Lody to add magpie as a provider — confirm it there",
zh: "打开 Lody 添加 magpie 供应商,在其中确认",
"zh-TW": "開啟 Lody 新增 magpie 供應商,在其中確認",
ja: "Lody を開いて magpie をプロバイダとして追加します。そちらで確認してください",
de: "Öffnet Lody, um magpie als Anbieter hinzuzufügen — dort bestätigen",
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(SAID)) {
for (const added of [false, true]) {
test(`${engine} ${lang} ${added ? "added" : "not added"}: import rows show known or unknown status and open their app`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await browser.newPage({ viewport: { width: 960, height: 600 } });
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${added}-import-row.png`) });
}
await browser.close();
});
page.setDefaultTimeout(5000);
await page.route("**/*", (route) => serve(route, lang, added));
await page.goto("http://magpie.test/");
await page.waitForLoadState("networkidle");
const more = page.locator('.agent-more[aria-expanded="false"]');
if (await more.count()) await more.click();
const lody = page.locator('.row.agent[data-id="lody"]');
await lody.scrollIntoViewIfNeeded();
await lody.locator(".ag-st-t").waitFor();
const hint = await lody.locator(".ag-st-t").innerText();
assert.equal(hint, UNKNOWN[lang]);
for (const said of Object.values(SAID).flat()) assert.doesNotMatch(hint, said);
assert.equal(await lody.locator(".ag-st").evaluate((e) => e.classList.contains("on")), false);
const lodyOpened = page.waitForRequest((r) => r.url().includes("/api/open"));
await lody.locator(".ag-start").click();
assert.equal(JSON.parse((await lodyOpened).postData()).url, "lody://provider/import?v=1&data=fixture");
const row = page.locator('.row.agent[data-id="cindy"]');
await row.locator(".ag-st").waitFor();
assert.match(await row.locator(".ag-st-t").innerText(), SAID[lang][added ? 1 : 0]);
assert.equal(await row.locator(".ag-st").evaluate((e) => e.classList.contains("on")), added);
for (const width of [960, 700]) {
await page.setViewportSize({ width, height: 600 });
const box = (sel) => page.locator(sel).evaluate((e) => { const r = e.getBoundingClientRect(); return { x: r.x, right: r.right, width: r.width, y: r.y, bottom: r.bottom }; });
// the rows settle a moment after a resize (under load one was
// caught mid-way, 194.4px beside 193.4px), so wait for them to line
// up before calling them apart
let pick, link;
for (const until = Date.now() + 3000; ;) {
pick = await box('.row.agent[data-id="crush"] > .ag-start');
link = await box('.row.agent[data-id="cindy"] > .ag-start');
if ((Math.abs(pick.right - link.right) < 1 && Math.abs(pick.width - link.width) < 1) || Date.now() > until) break;
await page.waitForTimeout(50);
}
assert(Math.abs(pick.right - link.right) < 1 && Math.abs(pick.width - link.width) < 1, `Cindy's button lines up with the model picker at ${width}px: ${JSON.stringify({ pick, link })}`);
const who = await box('.row.agent[data-id="cindy"] > .who');
assert(link.x >= who.right, `the button stays clear of the name at ${width}px`);
}
// AionUi: its own icon, its known status in the reader's language,
// and its add-provider link as the button opens it
const aion = page.locator('.row.agent[data-id="aionui"]');
await aion.locator(".ag-st").waitFor();
const aionSaid = await aion.locator(".ag-st-t").innerText();
assert.match(aionSaid, new RegExp(SAID[lang][added ? 0 : 1].source.replace("Cindy", "AionUi")));
assert.equal(await aion.locator(".ag-st").evaluate((e) => e.classList.contains("on")), !added);
assert.equal(await aion.locator('.ic[data-icon="aionui"]').count() > 0, true, "AionUi's row has its icon");
const aionIcon = await page.evaluate(async () => (await fetch("/icons/aionui.svg")).status);
assert.equal(aionIcon, 200);
const aionOpened = page.waitForRequest((r) => r.url().includes("/api/open"));
await aion.locator(".ag-start").click();
assert.equal(JSON.parse((await aionOpened).postData()).url, AIONUI_LINK);
// narrow: no page scroll sideways, and every import row keeps its
// line and button inside the window
await page.setViewportSize({ width: 420, height: 700 });
// the header's segments settle a moment after a resize, so wait for
// the state rather than reading it at once
await page.waitForFunction(() => document.documentElement.scrollWidth <= window.innerWidth, null, { timeout: 3000 }).catch(async () => {
assert.fail(`sideways scroll at 420px: ${await page.evaluate(() => document.documentElement.scrollWidth)}`);
});
for (const id of ["lody", "cindy", "aionui"]) {
const r = page.locator(`.row.agent[data-id="${id}"]`);
for (const sel of [".ag-start", ".ag-st-t"]) {
const b = await r.locator(sel).evaluate((e) => { const x = e.getBoundingClientRect(); return { left: x.left, right: x.right, width: x.width }; });
assert(b.width > 0 && b.left >= 0 && b.right <= 420 + 0.5, `${id} ${sel} inside the window at 420px: ${JSON.stringify(b)}`);
}
}
await page.setViewportSize({ width: 960, height: 600 });
// a click opens the app's link, the row's one control
const opened = page.waitForRequest((r) => r.url().includes("/api/open"));
await row.locator(".ag-start").click();
const req = await opened;
assert.equal(JSON.parse(req.postData() || "{}").url, "cindy://import?x=1");
});
}
}
}