provider-settings-batch.test.mjs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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(`header name and option feedback ${width}/${theme}`, async () => {
  69. await mkdir(artifacts, { recursive: true });
  70. const page = await browser.newPage({ viewport: { width, height: 1100 } });
  71. const mutations = [],
  72. errors = [],
  73. visualEvidence = [];
  74. page.on("pageerror", (error) => errors.push(String(error)));
  75. await page.route("**/mutation", async (route) => {
  76. mutations.push(route.request().postDataJSON());
  77. await route.fulfill({ status: 200, body: "{}" });
  78. });
  79. try {
  80. await page.goto(
  81. `${origin}fixture?${new URLSearchParams({ locale, theme, access: "manual", tiles: "1" })}`,
  82. );
  83. const menu = page.getByTestId("model-provider-actions-button");
  84. const toggle = page.getByTestId("model-provider-enabled-switch");
  85. await menu.waitFor();
  86. const toggleBox = await toggle.boundingBox(),
  87. menuBox = await menu.boundingBox();
  88. assert.ok(toggleBox.x + toggleBox.width <= menuBox.x);
  89. assert.equal(
  90. await toggle.getAttribute("data-state"),
  91. "checked",
  92. "tooltip must not replace switch state",
  93. );
  94. assert.notEqual(
  95. await toggle.evaluate((node) => getComputedStyle(node).backgroundColor),
  96. "rgba(0, 0, 0, 0)",
  97. );
  98. const expansion = await toggle.evaluate((node) =>
  99. Number.parseFloat(getComputedStyle(node, "::after").right),
  100. );
  101. assert.ok(
  102. toggleBox.x + toggleBox.width - expansion < menuBox.x,
  103. "switch expanded hit area must not reach menu",
  104. );
  105. assert.equal(
  106. await toggle.getAttribute("aria-label"),
  107. locale === "zh-CN" ? "禁用供应商" : "Disable provider",
  108. );
  109. const rename = async () => {
  110. await menu.click();
  111. await page.getByTestId("model-provider-name-edit-button").click();
  112. const input = page.getByTestId("model-provider-name-input");
  113. await page.waitForFunction(
  114. () => document.activeElement?.dataset.testid === "model-provider-name-input",
  115. );
  116. return input;
  117. };
  118. let input = await rename();
  119. await input.fill("Cancelled name");
  120. await page.waitForTimeout(1600);
  121. assert.equal(mutations.length, 0, "name idle must not save");
  122. await input.press("Escape");
  123. await page.waitForTimeout(1300);
  124. assert.equal(mutations.length, 0, "cancel must not save later");
  125. input = await rename();
  126. await input.fill("Confirmed Provider with a deliberately long name");
  127. await input.press("Enter");
  128. await page
  129. .getByTestId("model-provider-header")
  130. .getByText("Confirmed Provider with a deliberately long name", { exact: true })
  131. .waitFor();
  132. assert.equal(mutations.length, 1);
  133. assert.equal(
  134. mutations[0].payload.providerNameUpdate,
  135. "Confirmed Provider with a deliberately long name",
  136. );
  137. assert.equal(mutations[0].payload.enabledUpdate, undefined);
  138. assert.equal(await toggle.getAttribute("aria-checked"), "true");
  139. assert.equal(
  140. await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
  141. true,
  142. );
  143. const style = (node) => {
  144. const css = getComputedStyle(node),
  145. icon = node.querySelector("svg");
  146. return {
  147. background: css.backgroundColor,
  148. color: css.color,
  149. border: css.borderColor,
  150. width: node.getBoundingClientRect().width,
  151. height: node.getBoundingClientRect().height,
  152. icon: icon ? getComputedStyle(icon).color : null,
  153. };
  154. };
  155. const checkIndicator = async (tile, selected) => {
  156. const box = tile.locator("[data-model-option-checkbox]");
  157. const actual = await box.evaluate(style);
  158. const reference = await page
  159. .getByTestId(selected ? "system-checkbox-on" : "system-checkbox-off")
  160. .evaluate(style);
  161. assert.equal(actual.border, reference.border, "indicator border matches system checkbox");
  162. assert.equal(
  163. actual.background,
  164. reference.background,
  165. "indicator fill matches system checkbox",
  166. );
  167. assert.equal(actual.width, 16);
  168. assert.equal(actual.height, 16);
  169. assert.equal(await box.getAttribute("aria-hidden"), "true");
  170. assert.equal(await box.locator("button, input, [tabindex]").count(), 0);
  171. if (selected) {
  172. assert.equal(actual.color, reference.color);
  173. assert.equal(
  174. actual.border,
  175. actual.background,
  176. "selected border must not follow tick color",
  177. );
  178. assert.notEqual(actual.icon, actual.background);
  179. assert.equal(
  180. await box.locator("svg").evaluate((node) => node.getBoundingClientRect().width),
  181. 12,
  182. );
  183. } else {
  184. assert.equal(actual.icon, null);
  185. }
  186. };
  187. for (const tile of [
  188. page.locator('[data-model-input-modality="image"]'),
  189. page.getByRole("checkbox", { name: "Capability" }),
  190. page.getByRole("checkbox", { name: "System messages" }),
  191. ]) {
  192. await tile.hover();
  193. await page.waitForTimeout(180);
  194. const off = await tile.evaluate(style);
  195. await checkIndicator(tile, false);
  196. await tile.click();
  197. await page.waitForTimeout(180);
  198. const on = await tile.evaluate(style);
  199. await checkIndicator(tile, true);
  200. assert.notEqual(on.background, off.background, "same-pointer click must change background");
  201. // Todo134:选中时出现勾选图标是新预期,外层控件的文字/边框/尺寸仍不得跳变。
  202. for (const key of ["color", "border", "width", "height"])
  203. assert.equal(on[key], off[key], key);
  204. await page.screenshot({
  205. path: join(artifacts, `selected-${width}-${visualEvidence.length}.png`),
  206. });
  207. await tile.click();
  208. await page.waitForTimeout(180);
  209. assert.equal((await tile.evaluate(style)).background, off.background);
  210. await tile.press("Space");
  211. await checkIndicator(tile, true);
  212. await tile.press("Space");
  213. await checkIndicator(tile, false);
  214. visualEvidence.push({ off, on });
  215. }
  216. assert.equal(await page.locator('[data-model-input-modality="text"]').isDisabled(), true);
  217. await page.screenshot({ path: join(artifacts, `header-options-${width}.png`) });
  218. assert.deepEqual(errors, []);
  219. await writeFile(
  220. join(artifacts, `header-options-${width}.json`),
  221. JSON.stringify({ mutations, visualEvidence }, null, 2),
  222. );
  223. } finally {
  224. await page.close();
  225. }
  226. });
  227. }
  228. for (const [width, locale, theme] of [
  229. [390, "zh-CN", "light"],
  230. [1200, "en-US", "dark"],
  231. ]) {
  232. test(`account has no provider toggle ${width}/${locale}/${theme}`, async () => {
  233. const page = await browser.newPage({ viewport: { width, height: 900 } });
  234. const mutations = [];
  235. await page.route("**/mutation", async (route) => {
  236. mutations.push(route.request().postDataJSON());
  237. await route.fulfill({ status: 200, body: "{}" });
  238. });
  239. try {
  240. await page.goto(
  241. `${origin}fixture?${new URLSearchParams({ locale, theme, access: "account" })}`,
  242. );
  243. await page.getByTestId("detail").getByText("GLM-5.3", { exact: true }).waitFor();
  244. assert.equal(await page.getByTestId("model-provider-enabled-switch").count(), 0);
  245. assert.ok(
  246. (await page.getByTestId("detail").getByRole("switch").count()) > 0,
  247. "model switches remain available",
  248. );
  249. assert.deepEqual(mutations, [], "rendering must not save an enable override");
  250. } finally {
  251. await page.close();
  252. }
  253. });
  254. }
  255. for (const [width, locale, theme] of [
  256. [390, "zh-CN", "light"],
  257. [1200, "en-US", "dark"],
  258. ])
  259. test(`provider batch ${width}/${locale}/${theme}`, async () => {
  260. await mkdir(artifacts, { recursive: true });
  261. const page = await browser.newPage({ viewport: { width, height: 900 } });
  262. const errors = [],
  263. logs = [],
  264. mutations = [];
  265. page.on("pageerror", (e) => errors.push(String(e)));
  266. page.on("console", (m) => logs.push(m.text()));
  267. page.setDefaultTimeout(15000);
  268. let failDelete = true;
  269. await page.route("**/mutation", async (route) => {
  270. const data = route.request().postDataJSON();
  271. mutations.push(data);
  272. const status = data.action === "delete" && failDelete ? 500 : 200;
  273. if (data.action === "delete") failDelete = false;
  274. await route.fulfill({ status, body: "{}", contentType: "application/json" });
  275. });
  276. try {
  277. await page.goto(`${origin}fixture?${new URLSearchParams({ locale, theme })}`);
  278. const group = page.locator('[data-provider-template-group="zhipu"]');
  279. await group.waitFor();
  280. assert.equal(await group.locator("button").count(), 4);
  281. assert.deepEqual(
  282. await group.locator("button").evaluateAll((nodes) => nodes.map((n) => n.dataset.testid)),
  283. ["bigmodel-api", "zai-api", "bigmodel-standard-api", "zai-standard-api"].map(
  284. (id) => "model-provider-template-item-" + id,
  285. ),
  286. );
  287. assert.equal(
  288. await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
  289. true,
  290. );
  291. await page.screenshot({ path: join(artifacts, `templates-${width}.png`) });
  292. await group.locator("button").first().click();
  293. const toggle = page.getByTestId("model-provider-enabled-switch");
  294. await toggle.waitFor();
  295. assert.equal(await toggle.getAttribute("aria-checked"), "true");
  296. assert.equal(await page.locator('[data-provider-status="ready"]').count(), 2);
  297. await toggle.click();
  298. await page.waitForFunction(
  299. () =>
  300. document
  301. .querySelector('[data-testid="model-provider-enabled-switch"]')
  302. .getAttribute("aria-checked") === "false",
  303. );
  304. assert.equal(await page.locator('[data-provider-status="disabled"]').count(), 2);
  305. const disabledTests = page.getByTitle(
  306. locale === "zh-CN" ? "请先启用供应商" : "Enable the provider first",
  307. { exact: true },
  308. );
  309. assert.ok((await disabledTests.count()) > 0);
  310. assert.equal(await disabledTests.first().isDisabled(), true);
  311. const save = mutations.find((m) => m.action === "save").payload;
  312. assert.equal(save.enabledUpdate, false);
  313. assert.equal(save.config.access.apiKey, "fixture-key");
  314. assert.equal("enabled" in save.personalConfig, false);
  315. await toggle.click();
  316. await page.waitForFunction(
  317. () =>
  318. document
  319. .querySelector('[data-testid="model-provider-enabled-switch"]')
  320. .getAttribute("aria-checked") === "true",
  321. );
  322. const keyLink = page.getByRole("button", {
  323. name: locale === "zh-CN" ? "获取 API Key" : "Get API key",
  324. exact: true,
  325. });
  326. const allKeyLinks = page.getByRole("button", { name: /获取.*Key|Get.*[Kk]ey/ });
  327. assert.equal(await allKeyLinks.count(), 1);
  328. await keyLink.click();
  329. assert.equal(
  330. await page.getByTestId("opened").textContent(),
  331. "https://bigmodel.cn/coding-plan/personal/overview",
  332. );
  333. const nav = page.getByRole("button", { name: "fixture", exact: true });
  334. const before = await nav.boundingBox();
  335. await page.mouse.move(before.x + before.width / 2, before.y + before.height / 2);
  336. await page.mouse.down();
  337. await page.mouse.move(before.x + before.width / 2 + 240, before.y + before.height / 2 + 8, {
  338. steps: 8,
  339. });
  340. const during = await nav.boundingBox();
  341. assert.ok(Math.abs(during.x - before.x) < 2, "horizontal drag must remain inside sidebar");
  342. await page.mouse.up();
  343. await page.getByTestId("model-provider-model-delete-button-2").click();
  344. await page.getByRole("alert").waitFor();
  345. assert.match(
  346. await page.getByRole("alert").innerText(),
  347. locale === "zh-CN" ? /删除失败/ : /delete/i,
  348. );
  349. await page
  350. .getByRole("button", { name: locale === "zh-CN" ? "重试" : "Retry", exact: true })
  351. .click();
  352. await page.waitForFunction(
  353. () => !document.querySelector('[data-testid="model-provider-model-delete-button-2"]'),
  354. );
  355. assert.match(
  356. await page.locator('[data-provider-detail-feedback-state="success"]').last().innerText(),
  357. locale === "zh-CN" ? /已删除/ : /deleted/i,
  358. );
  359. assert.equal(mutations.filter((m) => m.action === "delete").length, 2);
  360. await page
  361. .getByTitle(locale === "zh-CN" ? "测试模型" : "Test model", { exact: true })
  362. .first()
  363. .click();
  364. const success = page
  365. .locator('[data-provider-detail-feedback-state="success"]')
  366. .filter({ hasText: locale === "zh-CN" ? "连接成功" : "connected" });
  367. await success.waitFor();
  368. assert.match(await success.innerText(), /Fixture Provider/);
  369. const visual = await success.evaluate((node) => ({
  370. color: getComputedStyle(node).color,
  371. background: getComputedStyle(node).backgroundColor,
  372. border: getComputedStyle(node).borderColor,
  373. }));
  374. assert.ok(visual.background !== "rgba(0, 0, 0, 0)");
  375. assert.equal(
  376. await success.evaluate(
  377. (node) =>
  378. node.classList.contains("text-success") &&
  379. node.classList.contains("border-success/30") &&
  380. node.classList.contains("bg-success/10"),
  381. ),
  382. true,
  383. );
  384. assert.equal(await success.locator("button").count(), 1);
  385. await success.locator("button").click();
  386. await success.waitFor({ state: "hidden" });
  387. // 清空 Key 会触发异步草稿保存,放在独立操作完成后,避免与删除回归竞争保存门禁。
  388. const keyInput = page.getByPlaceholder(locale === "zh-CN" ? "输入 API Key" : "Enter API key");
  389. await keyInput.fill("");
  390. assert.equal(await allKeyLinks.count(), 1);
  391. await keyLink.click();
  392. assert.equal(
  393. await page.getByTestId("opened").textContent(),
  394. "https://bigmodel.cn/coding-plan/personal/overview",
  395. );
  396. assert.deepEqual(errors, []);
  397. await page.screenshot({ path: join(artifacts, `detail-${width}.png`) });
  398. } finally {
  399. await writeFile(join(artifacts, `${width}.log`), logs.concat(errors).join("\n"));
  400. await page.close();
  401. }
  402. });