provider-settings-batch.test.mjs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. import assert from "node:assert/strict";
  2. import { mkdir, writeFile } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { tmpdir } from "node:os";
  5. import { after, before, test } from "node:test";
  6. import { fileURLToPath } from "node:url";
  7. import { createServer } from "vite";
  8. import react from "@vitejs/plugin-react";
  9. import tailwindcss from "@tailwindcss/vite";
  10. import { chromium } from "playwright-core";
  11. import { registerProviderPresentationCases } from "./provider-settings-presentation-cases.mjs";
  12. import { registerProviderModelEditorCases } from "./provider-model-editor-cases.mjs";
  13. import { registerProgressiveModelEditorCases } from "./provider-model-editor-progressive-cases.mjs";
  14. import { registerOffPeakEligibilityCases } from "./offpeak-eligibility-cases.mjs";
  15. const root = fileURLToPath(new URL("../../../../../../", import.meta.url));
  16. const entry = "/packages/ui/test/browser/manual-review/pending/provider-settings-batch.fixture.tsx";
  17. let server;
  18. let browser;
  19. let origin;
  20. before(async () => {
  21. server = await createServer({
  22. root,
  23. configFile: false,
  24. plugins: [
  25. react(),
  26. tailwindcss(),
  27. {
  28. name: "provider-settings-batch-fixture",
  29. configureServer(vite) {
  30. vite.middlewares.use(async (req, res, next) => {
  31. if (!req.url?.startsWith("/fixture?")) return next();
  32. res.setHeader("Content-Type", "text/html");
  33. res.end(
  34. await vite.transformIndexHtml(
  35. req.url,
  36. `<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1" /></head><body><div id="root"></div><script type="module" src="${entry}"></script></body></html>`,
  37. ),
  38. );
  39. });
  40. },
  41. },
  42. ],
  43. resolve: { alias: { "@": `${root}packages/ui/src` } },
  44. optimizeDeps: { entries: [entry.slice(1)] },
  45. server: { host: "127.0.0.1", port: 0 },
  46. });
  47. await server.listen();
  48. origin = server.resolvedUrls.local[0];
  49. browser = await chromium.launch(
  50. process.env.CHROME_EXECUTABLE_PATH
  51. ? { executablePath: process.env.CHROME_EXECUTABLE_PATH }
  52. : {},
  53. );
  54. });
  55. after(async () => {
  56. await browser?.close();
  57. await server?.close();
  58. });
  59. const artifacts = join(tmpdir(), "zcode-provider-settings-batch");
  60. registerOffPeakEligibilityCases(() => ({ browser, origin }));
  61. registerProviderPresentationCases(() => ({ browser, origin, artifacts }));
  62. registerProviderModelEditorCases(() => ({ browser, origin, artifacts }));
  63. registerProgressiveModelEditorCases(() => ({ browser, origin, artifacts }));
  64. for (const [width, locale, theme] of [
  65. [390, "zh-CN", "light"],
  66. [1200, "en-US", "dark"],
  67. ]) {
  68. test(`provider rename keeps focus after pointer movement ${width}/${theme}`, async () => {
  69. const page = await browser.newPage({ viewport: { width, height: 1100 } });
  70. const mutations = [];
  71. await page.route("**/mutation", async (route) => {
  72. mutations.push(route.request().postDataJSON());
  73. await route.fulfill({ status: 200, body: "{}" });
  74. });
  75. try {
  76. await page.goto(
  77. `${origin}fixture?${new URLSearchParams({ locale, theme, access: "manual" })}`,
  78. );
  79. const trigger = page.getByTestId("model-provider-actions-button");
  80. await trigger.click();
  81. const menu = page.getByRole("menu");
  82. // 暂停真实退场动画,保证鼠标移动命中尚未卸载的菜单,不靠固定延时碰竞态。
  83. await menu.evaluate((node) => {
  84. window.renamePointerMoves = 0;
  85. node.addEventListener("pointermove", () => {
  86. if (node.dataset.state === "closed") window.renamePointerMoves += 1;
  87. });
  88. node.addEventListener("animationstart", () => {
  89. if (node.dataset.state === "closed") {
  90. window.renameExitAnimations = node.getAnimations();
  91. window.renameExitAnimations.forEach((animation) => animation.pause());
  92. }
  93. });
  94. });
  95. await page.getByTestId("model-provider-name-edit-button").click();
  96. await page.waitForFunction(() =>
  97. window.renameExitAnimations?.some((animation) => animation.playState === "paused"),
  98. );
  99. const itemBox = await page.getByTestId("model-provider-name-edit-button").boundingBox();
  100. await page.mouse.move(itemBox.x + itemBox.width / 2 + 2, itemBox.y + itemBox.height / 2);
  101. assert.ok(await page.evaluate(() => window.renamePointerMoves > 0));
  102. await page.mouse.move(itemBox.x - 8, itemBox.y - 8);
  103. await page.evaluate(() =>
  104. window.renameExitAnimations.forEach((animation) => animation.finish()),
  105. );
  106. await menu.waitFor({ state: "detached" });
  107. await page.waitForFunction(
  108. () => document.activeElement?.dataset.testid === "model-provider-name-input",
  109. undefined,
  110. { timeout: 3000 },
  111. );
  112. // 直接向当前焦点输入,不能用 locator.fill/press 自动聚焦掩盖输入框闪退。
  113. await page.keyboard.press("ControlOrMeta+A");
  114. await page.keyboard.type("Renamed after pointer movement");
  115. await page.keyboard.press("Enter");
  116. await page
  117. .getByTestId("model-provider-header")
  118. .getByText("Renamed after pointer movement")
  119. .waitFor();
  120. assert.equal(mutations.length, 1);
  121. assert.equal(mutations[0].payload.providerNameUpdate, "Renamed after pointer movement");
  122. assert.equal(mutations[0].payload.enabledUpdate, undefined);
  123. await trigger.focus();
  124. await page.keyboard.press("ArrowDown");
  125. await page.waitForFunction(
  126. () => document.activeElement?.dataset.testid === "model-provider-name-edit-button",
  127. );
  128. await page.keyboard.press("Enter");
  129. await page.waitForFunction(
  130. () => document.activeElement?.dataset.testid === "model-provider-name-input",
  131. );
  132. await page.keyboard.type(" cancelled");
  133. await page.keyboard.press("Escape");
  134. assert.equal(await page.getByTestId("model-provider-name-input").count(), 0);
  135. assert.equal(mutations.length, 1);
  136. assert.equal(
  137. await page.getByTestId("model-provider-enabled-switch").getAttribute("aria-checked"),
  138. "true",
  139. );
  140. } finally {
  141. await page.close();
  142. }
  143. });
  144. test(`header name and option feedback ${width}/${theme}`, async () => {
  145. await mkdir(artifacts, { recursive: true });
  146. const page = await browser.newPage({ viewport: { width, height: 1100 } });
  147. const mutations = [],
  148. errors = [],
  149. visualEvidence = [];
  150. page.on("pageerror", (error) => errors.push(String(error)));
  151. await page.route("**/mutation", async (route) => {
  152. mutations.push(route.request().postDataJSON());
  153. await route.fulfill({ status: 200, body: "{}" });
  154. });
  155. try {
  156. await page.goto(
  157. `${origin}fixture?${new URLSearchParams({ locale, theme, access: "manual", tiles: "1" })}`,
  158. );
  159. const menu = page.getByTestId("model-provider-actions-button");
  160. const toggle = page.getByTestId("model-provider-enabled-switch");
  161. await menu.waitFor();
  162. const toggleBox = await toggle.boundingBox(),
  163. menuBox = await menu.boundingBox();
  164. assert.ok(toggleBox.x + toggleBox.width <= menuBox.x);
  165. assert.equal(
  166. await toggle.getAttribute("data-state"),
  167. "checked",
  168. "tooltip must not replace switch state",
  169. );
  170. assert.notEqual(
  171. await toggle.evaluate((node) => getComputedStyle(node).backgroundColor),
  172. "rgba(0, 0, 0, 0)",
  173. );
  174. const expansion = await toggle.evaluate((node) =>
  175. Number.parseFloat(getComputedStyle(node, "::after").right),
  176. );
  177. assert.ok(
  178. toggleBox.x + toggleBox.width - expansion < menuBox.x,
  179. "switch expanded hit area must not reach menu",
  180. );
  181. assert.equal(
  182. await toggle.getAttribute("aria-label"),
  183. locale === "zh-CN" ? "禁用供应商" : "Disable provider",
  184. );
  185. const rename = async () => {
  186. await menu.click();
  187. await page.getByTestId("model-provider-name-edit-button").click();
  188. const input = page.getByTestId("model-provider-name-input");
  189. await page.waitForFunction(
  190. () => document.activeElement?.dataset.testid === "model-provider-name-input",
  191. );
  192. return input;
  193. };
  194. let input = await rename();
  195. await input.fill("Cancelled name");
  196. await page.waitForTimeout(1600);
  197. assert.equal(mutations.length, 0, "name idle must not save");
  198. await input.press("Escape");
  199. await page.waitForTimeout(1300);
  200. assert.equal(mutations.length, 0, "cancel must not save later");
  201. input = await rename();
  202. await input.fill("Confirmed Provider with a deliberately long name");
  203. await input.press("Enter");
  204. await page
  205. .getByTestId("model-provider-header")
  206. .getByText("Confirmed Provider with a deliberately long name", { exact: true })
  207. .waitFor();
  208. assert.equal(mutations.length, 1);
  209. assert.equal(
  210. mutations[0].payload.providerNameUpdate,
  211. "Confirmed Provider with a deliberately long name",
  212. );
  213. assert.equal(mutations[0].payload.enabledUpdate, undefined);
  214. assert.equal(await toggle.getAttribute("aria-checked"), "true");
  215. assert.equal(
  216. await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
  217. true,
  218. );
  219. const style = (node) => {
  220. const css = getComputedStyle(node),
  221. icon = node.querySelector("svg");
  222. return {
  223. background: css.backgroundColor,
  224. color: css.color,
  225. border: css.borderColor,
  226. width: node.getBoundingClientRect().width,
  227. height: node.getBoundingClientRect().height,
  228. icon: icon ? getComputedStyle(icon).color : null,
  229. };
  230. };
  231. const checkIndicator = async (tile, selected) => {
  232. const box = tile.locator("[data-model-option-checkbox]");
  233. const actual = await box.evaluate(style);
  234. const reference = await page
  235. .getByTestId(selected ? "system-checkbox-on" : "system-checkbox-off")
  236. .evaluate(style);
  237. assert.equal(actual.border, reference.border, "indicator border matches system checkbox");
  238. assert.equal(
  239. actual.background,
  240. reference.background,
  241. "indicator fill matches system checkbox",
  242. );
  243. assert.equal(actual.width, 16);
  244. assert.equal(actual.height, 16);
  245. assert.equal(await box.getAttribute("aria-hidden"), "true");
  246. assert.equal(await box.locator("button, input, [tabindex]").count(), 0);
  247. if (selected) {
  248. assert.equal(actual.color, reference.color);
  249. assert.equal(
  250. actual.border,
  251. actual.background,
  252. "selected border must not follow tick color",
  253. );
  254. assert.notEqual(actual.icon, actual.background);
  255. assert.equal(
  256. await box.locator("svg").evaluate((node) => node.getBoundingClientRect().width),
  257. 12,
  258. );
  259. } else {
  260. assert.equal(actual.icon, null);
  261. }
  262. };
  263. for (const tile of [
  264. page.locator('[data-model-input-modality="image"]'),
  265. page.getByRole("checkbox", { name: "Capability" }),
  266. page.getByRole("checkbox", { name: "System messages" }),
  267. ]) {
  268. await tile.hover();
  269. await page.waitForTimeout(180);
  270. const off = await tile.evaluate(style);
  271. await checkIndicator(tile, false);
  272. await tile.click();
  273. await page.waitForTimeout(180);
  274. const on = await tile.evaluate(style);
  275. await checkIndicator(tile, true);
  276. assert.notEqual(on.background, off.background, "same-pointer click must change background");
  277. // Todo134:选中时出现勾选图标是新预期,外层控件的文字/边框/尺寸仍不得跳变。
  278. for (const key of ["color", "border", "width", "height"])
  279. assert.equal(on[key], off[key], key);
  280. await page.screenshot({
  281. path: join(artifacts, `selected-${width}-${visualEvidence.length}.png`),
  282. });
  283. await tile.click();
  284. await page.waitForTimeout(180);
  285. assert.equal((await tile.evaluate(style)).background, off.background);
  286. await tile.press("Space");
  287. await checkIndicator(tile, true);
  288. await tile.press("Space");
  289. await checkIndicator(tile, false);
  290. visualEvidence.push({ off, on });
  291. }
  292. assert.equal(await page.locator('[data-model-input-modality="text"]').isDisabled(), true);
  293. await page.screenshot({ path: join(artifacts, `header-options-${width}.png`) });
  294. assert.deepEqual(errors, []);
  295. await writeFile(
  296. join(artifacts, `header-options-${width}.json`),
  297. JSON.stringify({ mutations, visualEvidence }, null, 2),
  298. );
  299. } finally {
  300. await page.close();
  301. }
  302. });
  303. }
  304. for (const [width, locale, theme] of [
  305. [390, "zh-CN", "light"],
  306. [1200, "en-US", "dark"],
  307. ]) {
  308. test(`account has no provider toggle ${width}/${locale}/${theme}`, async () => {
  309. const page = await browser.newPage({ viewport: { width, height: 900 } });
  310. const mutations = [];
  311. await page.route("**/mutation", async (route) => {
  312. mutations.push(route.request().postDataJSON());
  313. await route.fulfill({ status: 200, body: "{}" });
  314. });
  315. try {
  316. await page.goto(
  317. `${origin}fixture?${new URLSearchParams({ locale, theme, access: "account" })}`,
  318. );
  319. await page.getByTestId("detail").getByText("GLM-5.3", { exact: true }).waitFor();
  320. assert.equal(await page.getByTestId("model-provider-enabled-switch").count(), 0);
  321. assert.ok(
  322. (await page.getByTestId("detail").getByRole("switch").count()) > 0,
  323. "model switches remain available",
  324. );
  325. assert.deepEqual(mutations, [], "rendering must not save an enable override");
  326. } finally {
  327. await page.close();
  328. }
  329. });
  330. }
  331. for (const [width, locale, theme] of [
  332. [390, "zh-CN", "light"],
  333. [1200, "en-US", "dark"],
  334. ])
  335. test(`provider batch ${width}/${locale}/${theme}`, async () => {
  336. await mkdir(artifacts, { recursive: true });
  337. const page = await browser.newPage({ viewport: { width, height: 900 } });
  338. const errors = [],
  339. logs = [],
  340. mutations = [];
  341. page.on("pageerror", (e) => errors.push(String(e)));
  342. page.on("console", (m) => logs.push(m.text()));
  343. page.setDefaultTimeout(15000);
  344. let failDelete = true;
  345. await page.route("**/mutation", async (route) => {
  346. const data = route.request().postDataJSON();
  347. mutations.push(data);
  348. const status = data.action === "delete" && failDelete ? 500 : 200;
  349. if (data.action === "delete") failDelete = false;
  350. await route.fulfill({ status, body: "{}", contentType: "application/json" });
  351. });
  352. try {
  353. await page.goto(`${origin}fixture?${new URLSearchParams({ locale, theme })}`);
  354. const group = page.locator('[data-provider-template-group="zhipu"]');
  355. await group.waitFor();
  356. assert.equal(await group.locator("button").count(), 4);
  357. assert.deepEqual(
  358. await group.locator("button").evaluateAll((nodes) => nodes.map((n) => n.dataset.testid)),
  359. ["bigmodel-api", "zai-api", "bigmodel-standard-api", "zai-standard-api"].map(
  360. (id) => "model-provider-template-item-" + id,
  361. ),
  362. );
  363. assert.equal(
  364. await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
  365. true,
  366. );
  367. await page.screenshot({ path: join(artifacts, `templates-${width}.png`) });
  368. await group.locator("button").first().click();
  369. const toggle = page.getByTestId("model-provider-enabled-switch");
  370. await toggle.waitFor();
  371. assert.equal(await toggle.getAttribute("aria-checked"), "true");
  372. assert.equal(await page.locator('[data-provider-status="ready"]').count(), 2);
  373. await toggle.click();
  374. await page.waitForFunction(
  375. () =>
  376. document
  377. .querySelector('[data-testid="model-provider-enabled-switch"]')
  378. .getAttribute("aria-checked") === "false",
  379. );
  380. assert.equal(await page.locator('[data-provider-status="disabled"]').count(), 2);
  381. const disabledTests = page.getByTitle(
  382. locale === "zh-CN" ? "请先启用供应商" : "Enable the provider first",
  383. { exact: true },
  384. );
  385. assert.ok((await disabledTests.count()) > 0);
  386. assert.equal(await disabledTests.first().isDisabled(), true);
  387. const save = mutations.find((m) => m.action === "save").payload;
  388. assert.equal(save.enabledUpdate, false);
  389. assert.equal(save.config.access.apiKey, "fixture-key");
  390. assert.equal("enabled" in save.personalConfig, false);
  391. await toggle.click();
  392. await page.waitForFunction(
  393. () =>
  394. document
  395. .querySelector('[data-testid="model-provider-enabled-switch"]')
  396. .getAttribute("aria-checked") === "true",
  397. );
  398. const keyLink = page.getByRole("button", {
  399. name: locale === "zh-CN" ? "获取 API Key" : "Get API key",
  400. exact: true,
  401. });
  402. const allKeyLinks = page.getByRole("button", { name: /获取.*Key|Get.*[Kk]ey/ });
  403. assert.equal(await allKeyLinks.count(), 1);
  404. await keyLink.click();
  405. assert.equal(
  406. await page.getByTestId("opened").textContent(),
  407. "https://bigmodel.cn/coding-plan/personal/overview",
  408. );
  409. const nav = page.getByRole("button", { name: "fixture", exact: true });
  410. const before = await nav.boundingBox();
  411. await page.mouse.move(before.x + before.width / 2, before.y + before.height / 2);
  412. await page.mouse.down();
  413. await page.mouse.move(before.x + before.width / 2 + 240, before.y + before.height / 2 + 8, {
  414. steps: 8,
  415. });
  416. const during = await nav.boundingBox();
  417. assert.ok(Math.abs(during.x - before.x) < 2, "horizontal drag must remain inside sidebar");
  418. await page.mouse.up();
  419. await page.getByTestId("model-provider-model-delete-button-2").click();
  420. await page.getByRole("alert").waitFor();
  421. assert.match(
  422. await page.getByRole("alert").innerText(),
  423. locale === "zh-CN" ? /删除失败/ : /delete/i,
  424. );
  425. await page
  426. .getByRole("button", { name: locale === "zh-CN" ? "重试" : "Retry", exact: true })
  427. .click();
  428. await page.waitForFunction(
  429. () => !document.querySelector('[data-testid="model-provider-model-delete-button-2"]'),
  430. );
  431. assert.match(
  432. await page.locator('[data-provider-detail-feedback-state="success"]').last().innerText(),
  433. locale === "zh-CN" ? /已删除/ : /deleted/i,
  434. );
  435. assert.equal(mutations.filter((m) => m.action === "delete").length, 2);
  436. await page
  437. .getByTitle(locale === "zh-CN" ? "测试模型" : "Test model", { exact: true })
  438. .first()
  439. .click();
  440. const success = page
  441. .locator('[data-provider-detail-feedback-state="success"]')
  442. .filter({ hasText: locale === "zh-CN" ? "连接成功" : "connected" });
  443. await success.waitFor();
  444. assert.match(await success.innerText(), /Fixture Provider/);
  445. const visual = await success.evaluate((node) => ({
  446. color: getComputedStyle(node).color,
  447. background: getComputedStyle(node).backgroundColor,
  448. border: getComputedStyle(node).borderColor,
  449. }));
  450. assert.ok(visual.background !== "rgba(0, 0, 0, 0)");
  451. assert.equal(
  452. await success.evaluate(
  453. (node) =>
  454. node.classList.contains("text-success") &&
  455. node.classList.contains("border-success/30") &&
  456. node.classList.contains("bg-success/10"),
  457. ),
  458. true,
  459. );
  460. assert.equal(await success.locator("button").count(), 1);
  461. await success.locator("button").click();
  462. await success.waitFor({ state: "hidden" });
  463. // 清空 Key 会触发异步草稿保存,放在独立操作完成后,避免与删除回归竞争保存门禁。
  464. const keyInput = page.getByPlaceholder(locale === "zh-CN" ? "输入 API Key" : "Enter API key");
  465. await keyInput.fill("");
  466. assert.equal(await allKeyLinks.count(), 1);
  467. await keyLink.click();
  468. assert.equal(
  469. await page.getByTestId("opened").textContent(),
  470. "https://bigmodel.cn/coding-plan/personal/overview",
  471. );
  472. assert.deepEqual(errors, []);
  473. await page.screenshot({ path: join(artifacts, `detail-${width}.png`) });
  474. } finally {
  475. await writeFile(join(artifacts, `${width}.log`), logs.concat(errors).join("\n"));
  476. await page.close();
  477. }
  478. });