composer-menu-dismiss.test.mjs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. import assert from "node:assert/strict";
  2. import { before, after, test } from "node:test";
  3. import { mkdir, writeFile, mkdtemp, rm } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { fileURLToPath } from "node:url";
  7. import { createRequire } from "node:module";
  8. import { createServer } from "vite";
  9. import react from "@vitejs/plugin-react";
  10. import tailwindcss from "@tailwindcss/vite";
  11. import { chromium, _electron } from "playwright-core";
  12. const root = fileURLToPath(new URL("../../../../../../", import.meta.url));
  13. const entry = "/packages/ui/test/browser/manual-review/pending/composer-menu-dismiss.fixture.tsx";
  14. const artifacts = join(root, "packages/desktop/.e2e-artifacts/composer-menu-dismiss");
  15. let server, browser, electron, origin, temporary;
  16. before(async () => {
  17. await mkdir(artifacts, { recursive: true });
  18. temporary = await mkdtemp(join(tmpdir(), "composer-menu-dismiss-"));
  19. server = await createServer({
  20. root,
  21. configFile: false,
  22. plugins: [
  23. react(),
  24. tailwindcss(),
  25. {
  26. name: "composer-dismiss-fixture",
  27. configureServer(vite) {
  28. vite.middlewares.use(async (req, res, next) => {
  29. if (req.url === "/guest") {
  30. res.setHeader("Content-Type", "text/html");
  31. res.end(
  32. '<html><body style="margin:0;background:#ddd"><button style="position:fixed;inset:0" onclick="this.dataset.clicks=String(Number(this.dataset.clicks)+1)" data-clicks="0">Plugin action</button></body></html>',
  33. );
  34. } else if (req.url?.startsWith("/fixture?")) {
  35. res.setHeader("Content-Type", "text/html");
  36. res.end(
  37. await vite.transformIndexHtml(
  38. req.url,
  39. `<!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>`,
  40. ),
  41. );
  42. } else next();
  43. });
  44. },
  45. },
  46. ],
  47. resolve: { alias: { "@": `${root}packages/ui/src` } },
  48. optimizeDeps: { entries: [entry.slice(1)] },
  49. server: { host: "127.0.0.1", port: 0, hmr: false },
  50. });
  51. await server.listen();
  52. origin = server.resolvedUrls.local[0];
  53. browser = await chromium.launch(
  54. process.env.CHROME_EXECUTABLE_PATH
  55. ? { executablePath: process.env.CHROME_EXECUTABLE_PATH }
  56. : { channel: "chrome" },
  57. );
  58. const main = join(temporary, "main.cjs");
  59. await writeFile(
  60. main,
  61. `const { app, BrowserWindow } = require('electron'); app.on('window-all-closed', () => app.quit()); app.whenReady().then(() => { const win = new BrowserWindow({width:1200,height:800,webPreferences:{webviewTag:true}}); win.loadURL(${JSON.stringify(origin + "fixture?electron&theme=light")}); });`,
  62. );
  63. const require = createRequire(new URL("../../../../../desktop/package.json", import.meta.url));
  64. electron = await _electron.launch({
  65. executablePath: require("electron"),
  66. args: [main, `--user-data-dir=${join(temporary, "profile")}`],
  67. });
  68. await (await electron.firstWindow()).waitForLoadState("load");
  69. });
  70. after(async () => {
  71. await electron?.close();
  72. await browser?.close();
  73. await server?.close();
  74. if (temporary) await rm(temporary, { recursive: true, force: true });
  75. });
  76. for (const surface of ["electron", "mobile"])
  77. for (const locale of ["en-US", "zh-CN"])
  78. for (const theme of ["light", "dark"]) {
  79. test(`SPFV-MODEL-001 ${surface}/${theme}/${locale}`, async () => {
  80. const page =
  81. surface === "electron"
  82. ? await electron.firstWindow()
  83. : await browser.newPage({
  84. viewport: { width: 390, height: 800 },
  85. hasTouch: true,
  86. isMobile: true,
  87. });
  88. const trace = [];
  89. try {
  90. await page.goto(
  91. `${origin}fixture?${surface === "electron" ? "electron&" : ""}theme=${theme}&locale=${locale}`,
  92. );
  93. await page.waitForSelector(surface === "electron" ? "webview" : "iframe");
  94. const guestClicks = () =>
  95. page.evaluate(
  96. async (native) =>
  97. native
  98. ? await document
  99. .querySelector("webview")
  100. .executeJavaScript('document.querySelector("button").dataset.clicks')
  101. : document.querySelector("iframe").contentDocument.querySelector("button").dataset
  102. .clicks,
  103. surface === "electron",
  104. );
  105. await page.waitForFunction(async (native) => {
  106. try {
  107. return native
  108. ? await document
  109. .querySelector("webview")
  110. ?.executeJavaScript('Boolean(document.querySelector("button"))')
  111. : Boolean(
  112. document.querySelector("iframe")?.contentDocument?.querySelector("button"),
  113. );
  114. } catch {
  115. return false;
  116. }
  117. }, surface === "electron");
  118. await page.evaluate(() => {
  119. window.__menuEvents = [];
  120. for (const type of ["pointerdown", "pointerout", "focusin", "focusout"])
  121. document.addEventListener(
  122. type,
  123. (event) =>
  124. window.__menuEvents.push({
  125. type,
  126. target: event.target.tagName,
  127. testid: event.target.dataset?.testid,
  128. }),
  129. true,
  130. );
  131. });
  132. const trigger = page.getByTestId("chat-model-select-trigger");
  133. const open = async () => {
  134. await trigger.click();
  135. await page.getByTestId("composer-model-panel").waitFor();
  136. };
  137. const closed = async () => {
  138. await page
  139. .getByTestId("composer-model-panel")
  140. .waitFor({ state: "hidden", timeout: 3000 });
  141. assert.equal(await trigger.getAttribute("aria-expanded"), "false");
  142. };
  143. await open();
  144. trace.push(
  145. await page.evaluate(() => ({
  146. bodyPointerEvents: getComputedStyle(document.body).pointerEvents,
  147. hit: document.elementFromPoint(80, 80)?.tagName,
  148. events: window.__menuEvents,
  149. })),
  150. );
  151. const before = await guestClicks();
  152. if (surface === "mobile") await page.touchscreen.tap(80, 80);
  153. else await page.mouse.click(80, 80);
  154. trace.push({
  155. guestBefore: before,
  156. guestAfter: await guestClicks(),
  157. events: await page.evaluate(() => window.__menuEvents),
  158. expanded: await trigger.getAttribute("aria-expanded"),
  159. });
  160. await closed();
  161. assert.equal(await guestClicks(), before, "dismissal must not activate the plugin");
  162. await page.mouse.click(80, 80);
  163. assert.equal(
  164. Number(await guestClicks()),
  165. Number(before) + 1,
  166. "plugin remains interactive after dismissal",
  167. );
  168. await open();
  169. const search = page.getByTestId("composer-model-search");
  170. await page.getByTestId("composer-provider-trigger").focus();
  171. await page.keyboard.press("Tab");
  172. await page.waitForFunction(
  173. () => document.activeElement?.getAttribute("data-testid") === "composer-model-search",
  174. );
  175. assert.equal(
  176. await search.getAttribute("placeholder"),
  177. locale === "zh-CN" ? "搜索模型..." : "Search models...",
  178. );
  179. await page.screenshot({
  180. path: join(artifacts, `${surface}-${theme}-${locale}-search.png`),
  181. });
  182. await search.fill(" tWO ");
  183. assert.equal(await page.getByRole("option").count(), 1);
  184. assert.equal(await page.getByTestId("selection").textContent(), "one");
  185. const searchShape = await search.evaluate((el) => ({
  186. radius: parseFloat(getComputedStyle(el).borderRadius),
  187. height: el.getBoundingClientRect().height,
  188. }));
  189. assert.ok(searchShape.radius >= searchShape.height / 2, "search uses capsule corners");
  190. const clear = page.getByTestId("composer-model-search-clear");
  191. await clear.waitFor();
  192. await page.screenshot({
  193. path: join(artifacts, `${surface}-${theme}-${locale}-query.png`),
  194. });
  195. if (surface === "mobile") await clear.tap();
  196. else await clear.click();
  197. assert.equal(await search.inputValue(), "");
  198. assert.equal(await clear.count(), 0);
  199. assert.equal(await page.getByRole("option").count(), 3);
  200. assert.equal(
  201. await search.evaluate((element) => element === document.activeElement),
  202. true,
  203. );
  204. assert.equal(await trigger.getAttribute("aria-expanded"), "true");
  205. await search.fill("missing-model");
  206. assert.equal(await page.getByRole("option").count(), 0);
  207. await page.locator("[data-composer-model-list] [role=status]").waitFor();
  208. await search.fill("Model");
  209. await search.press("ArrowRight");
  210. await search.press("Space");
  211. assert.equal((await search.inputValue()).trim(), "Model");
  212. assert.equal(
  213. await search.evaluate((element) => element === document.activeElement),
  214. true,
  215. );
  216. if (surface === "electron") {
  217. const row = page.getByRole("option", { name: "Model Two", exact: true });
  218. await page.mouse.move(10, 10);
  219. const background = await row.evaluate(
  220. (element) => getComputedStyle(element).backgroundColor,
  221. );
  222. await row.hover();
  223. // 等待浏览器完成指针命中与样式更新,避免首帧读取到 hover 前的颜色。
  224. await page.waitForFunction(
  225. ({ element, background }) => getComputedStyle(element).backgroundColor !== background,
  226. { element: await row.elementHandle(), background },
  227. );
  228. assert.equal(
  229. await search.evaluate((element) => element === document.activeElement),
  230. true,
  231. );
  232. assert.equal(await page.getByTestId("selection").textContent(), "one");
  233. await page.keyboard.type("Two");
  234. assert.equal((await search.inputValue()).trim(), "Model Two");
  235. await page.mouse.move(10, 10);
  236. assert.equal(
  237. await row.evaluate((element) => getComputedStyle(element).backgroundColor),
  238. background,
  239. );
  240. }
  241. await search.fill("two");
  242. await search.press("ArrowDown");
  243. await page.keyboard.press("Enter");
  244. assert.equal(await page.getByTestId("selection").textContent(), "two");
  245. await search.fill("");
  246. await page.getByRole("option", { name: "Model Two", exact: true }).click();
  247. assert.equal(await trigger.getAttribute("aria-expanded"), "true");
  248. assert.equal(await page.getByTestId("selection").textContent(), "two");
  249. await page.getByRole("option", { name: "Model Two", exact: true }).focus();
  250. await page.keyboard.press("Enter");
  251. assert.equal(await trigger.getAttribute("aria-expanded"), "true");
  252. const waitFocusedModel = async (name) => {
  253. const element = await page.getByRole("option", { name, exact: true }).elementHandle();
  254. await page.waitForFunction((el) => el === document.activeElement, element);
  255. };
  256. await page.keyboard.press("Home");
  257. await waitFocusedModel("Model One");
  258. await page.keyboard.press("ArrowDown");
  259. await waitFocusedModel("Model Two");
  260. await page.keyboard.press("ArrowUp");
  261. await waitFocusedModel("Model One");
  262. await page.keyboard.press("End");
  263. await waitFocusedModel("Model Two");
  264. await page.keyboard.press("Space");
  265. assert.equal(await page.getByTestId("selection").textContent(), "two");
  266. trace.push({
  267. afterSelection: await page.getByTestId("selection").textContent(),
  268. expanded: await trigger.getAttribute("aria-expanded"),
  269. });
  270. const clicksAfterSelection = await guestClicks();
  271. if (surface === "mobile") await page.touchscreen.tap(80, 80);
  272. else await page.mouse.click(80, 80);
  273. await closed();
  274. assert.equal(await guestClicks(), clicksAfterSelection);
  275. await open();
  276. assert.equal(await search.inputValue(), "");
  277. await search.fill("locked");
  278. await page.getByRole("option", { name: "Locked Model" }).click({ force: true });
  279. assert.equal(await page.getByTestId("selection").textContent(), "two");
  280. assert.equal(await trigger.getAttribute("aria-expanded"), "true");
  281. if (surface === "electron") {
  282. await search.focus();
  283. await page.getByTestId("composer-provider-trigger").hover();
  284. const providerPanel = page.getByTestId("composer-provider-panel");
  285. await providerPanel.waitFor();
  286. assert.equal(await search.evaluate((el) => el === document.activeElement), true);
  287. const providerRow = page.getByRole("option", { name: "Provider B", exact: true });
  288. const bounds = await providerRow.boundingBox();
  289. await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2, {
  290. steps: 8,
  291. });
  292. assert.equal(await providerPanel.isVisible(), true);
  293. assert.equal(await search.evaluate((el) => el === document.activeElement), true);
  294. await search.hover();
  295. await providerPanel.waitFor({ state: "hidden" });
  296. assert.equal(await search.evaluate((el) => el === document.activeElement), true);
  297. }
  298. await page.getByTestId("composer-provider-trigger").click();
  299. await page.getByRole("option", { name: "Provider B", exact: true }).click();
  300. assert.equal(await page.getByTestId("selection").textContent(), "three");
  301. assert.equal(await search.inputValue(), "");
  302. assert.equal(await trigger.getAttribute("aria-expanded"), "true");
  303. await search.focus();
  304. await page.getByRole("slider").hover();
  305. assert.equal(
  306. await search.evaluate((element) => element === document.activeElement),
  307. true,
  308. );
  309. await page.getByRole("slider").click();
  310. await page.keyboard.press("Home");
  311. assert.equal(await page.getByRole("slider").getAttribute("aria-valuetext"), "Low");
  312. await page.keyboard.press("End");
  313. assert.equal(await page.getByRole("slider").getAttribute("aria-valuetext"), "High");
  314. const sliderBox = await page.getByRole("slider").boundingBox();
  315. await page.mouse.move(
  316. sliderBox.x + sliderBox.width - 14,
  317. sliderBox.y + sliderBox.height / 2,
  318. );
  319. await page.mouse.down();
  320. await page.mouse.move(sliderBox.x + 14, sliderBox.y + sliderBox.height / 2, { steps: 5 });
  321. await page.mouse.up();
  322. assert.equal(await page.getByRole("slider").getAttribute("aria-valuetext"), "Low");
  323. assert.equal(await trigger.getAttribute("aria-expanded"), "true");
  324. await page.screenshot({ path: join(artifacts, `${surface}-${theme}-${locale}.png`) });
  325. await page.keyboard.press("Escape");
  326. await closed();
  327. } finally {
  328. trace.push({
  329. finalEvents: await page.evaluate(() => window.__menuEvents),
  330. active: await page.evaluate(() => document.activeElement?.getAttribute("data-testid")),
  331. });
  332. await writeFile(
  333. join(artifacts, `${surface}-${theme}-${locale}.json`),
  334. JSON.stringify(trace, null, 2),
  335. );
  336. if (surface !== "electron") await page.close();
  337. }
  338. });
  339. }