side-pane-plugin-menu.test.mjs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. import { registerSidePaneWidthCases } from "./side-pane-width-motion.cases.mjs";
  2. import assert from "node:assert/strict";
  3. import { after, before, test } from "node:test";
  4. import { mkdir } from "node:fs/promises";
  5. import { join } from "node:path";
  6. import { tmpdir } from "node:os";
  7. import { fileURLToPath } from "node:url";
  8. import { createServer } from "vite";
  9. import react from "@vitejs/plugin-react";
  10. import tailwindcss from "@tailwindcss/vite";
  11. import { chromium } from "playwright-core";
  12. const root = fileURLToPath(new URL("../../../../../../", import.meta.url));
  13. const entry = "/packages/ui/test/browser/manual-review/pending/side-pane-plugin-menu.fixture.tsx";
  14. const surfaces = ["hello", "canvas", "development"].map((id) => ({
  15. id,
  16. pluginId: `${id}@example`,
  17. pluginName: id,
  18. title: {
  19. en: id === "hello" ? "Hello panel" : "Canvas",
  20. "zh-CN": id === "hello" ? "Hello 面板" : "画布",
  21. },
  22. server: `plugin:${id}:server`,
  23. resourceUri: `ui://${id}/panel.html`,
  24. }));
  25. const catalog = (entries, installed = true, enabled = true) => ({
  26. plugins: installed
  27. ? entries.map((surface) => ({
  28. id: surface.pluginId,
  29. name: surface.pluginName,
  30. marketplace: surface.pluginId.split("@")[1],
  31. enabled,
  32. uiSurfaces: [surface],
  33. }))
  34. : [],
  35. availablePlugins: entries.map((surface) => ({
  36. id: surface.pluginId,
  37. name: surface.pluginName,
  38. marketplace: surface.pluginId.split("@")[1],
  39. installed,
  40. })),
  41. marketplaces: [],
  42. installedPlugins: [],
  43. restorableBuiltins: [],
  44. diagnostics: [],
  45. });
  46. const add = "[data-side-pane-add-tab-trigger]";
  47. const activeLauncher = '[role="tabpanel"][data-state="active"]';
  48. const newTabItems = `${activeLauncher} [data-side-pane-open-tab-item^="plugin-ui:"]`;
  49. const launcherItems = '[data-side-pane-open-tab-item^="plugin-ui:"]';
  50. let server, browser, origin;
  51. before(async () => {
  52. server = await createServer({
  53. root,
  54. configFile: false,
  55. plugins: [
  56. react(),
  57. tailwindcss(),
  58. {
  59. name: "plugin-menu-fixture",
  60. configureServer(vite) {
  61. vite.middlewares.use(async (req, res, next) => {
  62. if (!req.url?.startsWith("/fixture?")) return next();
  63. res.setHeader("Content-Type", "text/html");
  64. res.end(
  65. await vite.transformIndexHtml(
  66. req.url,
  67. `<!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>`,
  68. ),
  69. );
  70. });
  71. },
  72. },
  73. ],
  74. resolve: { alias: { "@": `${root}packages/ui/src` } },
  75. optimizeDeps: { entries: [entry.slice(1)] },
  76. server: { host: "127.0.0.1", port: 0, watch: null, hmr: false },
  77. });
  78. await server.listen();
  79. origin = server.resolvedUrls.local[0];
  80. browser = await chromium.launch(
  81. process.env.CHROME_EXECUTABLE_PATH
  82. ? { executablePath: process.env.CHROME_EXECUTABLE_PATH }
  83. : { channel: "chrome" },
  84. );
  85. });
  86. after(async () => {
  87. await Promise.all([
  88. browser?.close().then(() => console.info("Fixture browser closed")),
  89. server?.close().then(() => console.info("Fixture server closed")),
  90. ]);
  91. });
  92. registerSidePaneWidthCases(
  93. () => browser,
  94. () => origin,
  95. );
  96. for (const [width, locale, theme] of [
  97. [1200, "en-US", "light"],
  98. [390, "zh-CN", "dark"],
  99. ]) {
  100. test(`SPT-E2E-007 ${width}/${locale}/${theme}`, async () => {
  101. const page = await browser.newPage({ viewport: { width, height: 800 } });
  102. page.setDefaultTimeout(15000);
  103. page.setDefaultNavigationTimeout(120000);
  104. const errors = [];
  105. const scopes = [];
  106. page.on("pageerror", (error) => errors.push(error.message));
  107. const query = `locale=${locale}&theme=${theme}${width < 500 ? "&mobile=1" : ""}`;
  108. await page.route("**/surfaces", (route) => {
  109. scopes.push(route.request().postDataJSON());
  110. return route.fulfill({ json: surfaces });
  111. });
  112. const configGate = Promise.withResolvers();
  113. const catalogGate = Promise.withResolvers();
  114. const configStarted = Promise.withResolvers();
  115. const catalogStarted = Promise.withResolvers();
  116. await page.route("**/client-config", async (route) => {
  117. configStarted.resolve();
  118. await configGate.promise;
  119. return route.fulfill({
  120. json: {
  121. code: 0,
  122. data: {
  123. configs: {
  124. uiPluginRecommendations: [...surfaces.slice(0, 2), surfaces[0]]
  125. .map((surface) => ({ pluginId: surface.pluginId, surfaceId: surface.id }))
  126. .concat([{ pluginId: "missing@example", surfaceId: "missing" }]),
  127. },
  128. },
  129. },
  130. });
  131. });
  132. await page.route("**/catalog", async (route) => {
  133. catalogStarted.resolve();
  134. await catalogGate.promise;
  135. return route.fulfill({ json: catalog(surfaces) });
  136. });
  137. const read = (id) => page.getByTestId(id).textContent().then(JSON.parse);
  138. try {
  139. await page.goto(`${origin}fixture?${query}`, { waitUntil: "domcontentloaded" });
  140. await Promise.all([configStarted.promise, catalogStarted.promise]);
  141. await page.getByTestId("side-pane-ui-loading").waitFor();
  142. assert.equal(await page.getByTestId("side-pane-ui-empty").count(), 0);
  143. const configResponse = page.waitForResponse("**/client-config");
  144. configGate.resolve();
  145. await (await configResponse).finished();
  146. // 配置先到、市场目录仍在途,也不能闪现空态。
  147. assert.equal(await page.getByTestId("side-pane-ui-empty").count(), 0);
  148. assert.equal(await page.getByTestId("side-pane-ui-loading").count(), 1);
  149. const loadingArtifacts = join(tmpdir(), "zcode-side-pane-plugin-menu");
  150. await mkdir(loadingArtifacts, { recursive: true });
  151. await page.screenshot({ path: join(loadingArtifacts, `loading-${width}-${theme}.png`) });
  152. catalogGate.resolve();
  153. await page.locator(launcherItems).first().waitFor();
  154. assert.equal(await page.locator(launcherItems).count(), 2);
  155. assert.equal(await page.getByTestId("side-pane-plugin-market").count(), 1);
  156. const artifacts = join(tmpdir(), "zcode-side-pane-plugin-menu");
  157. await mkdir(artifacts, { recursive: true });
  158. // 空态启动页与原型对照:横向行、短分割线、UI 插件区。
  159. await page.screenshot({ path: join(artifacts, `launcher-${width}-${locale}-${theme}.png`) });
  160. await page.locator(launcherItems).first().click();
  161. await page.waitForFunction(
  162. () => JSON.parse(document.querySelector('[data-testid="request"]').textContent) !== null,
  163. );
  164. const expected = await read("request");
  165. assert.deepEqual(expected, {
  166. parentSessionId: "session-fixture",
  167. surfaceId: "hello",
  168. serverName: "plugin:hello:server",
  169. pluginId: "hello@example",
  170. resourceUri: "ui://hello/panel.html",
  171. title: locale === "zh-CN" ? "Hello 面板" : "Hello panel",
  172. workspacePath: "/workspace/example",
  173. workspaceIdentity: "fixture-workspace",
  174. remoteSessionId: null,
  175. });
  176. await page.getByTestId("show-tabs").click();
  177. await page.locator(add).click();
  178. await page.locator(newTabItems).first().waitFor();
  179. assert.equal(await page.locator(newTabItems).count(), 2);
  180. assert.match(
  181. await page.locator(newTabItems).first().textContent(),
  182. new RegExp(expected.title),
  183. );
  184. const box = await page.locator(activeLauncher).boundingBox();
  185. assert.ok(box.x >= 0 && box.x + box.width <= width && box.y + box.height <= 800);
  186. await page.screenshot({ path: join(artifacts, `${width}-${locale}-${theme}.png`) });
  187. await page.locator(newTabItems).first().click();
  188. await page.locator(activeLauncher).waitFor();
  189. assert.deepEqual(await read("request"), expected);
  190. assert.equal((await read("opened")).tabs.length, 1);
  191. // 原菜单方向键合同已移除;新标签页启动行使用原生按钮的 Tab/Enter。
  192. await page.locator(add).focus();
  193. await page.keyboard.press("Enter");
  194. await page.locator(newTabItems).last().waitFor();
  195. await page.locator(newTabItems).first().focus();
  196. await page.keyboard.press("Tab");
  197. assert.equal(
  198. await page
  199. .locator(newTabItems)
  200. .last()
  201. .evaluate((element) => element === document.activeElement),
  202. true,
  203. );
  204. await page.keyboard.press("Enter");
  205. await page.waitForFunction(
  206. () =>
  207. JSON.parse(document.querySelector('[data-testid="request"]').textContent)?.surfaceId ===
  208. "canvas",
  209. );
  210. assert.equal((await read("request")).surfaceId, "canvas");
  211. assert.equal((await read("opened")).tabs.length, 2);
  212. assert.ok(scopes.every((scope) => scope.workspaceIdentity === "fixture-workspace"));
  213. assert.equal(
  214. await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
  215. true,
  216. );
  217. assert.deepEqual(errors, []);
  218. // 推荐区直接安装、启用;每次成功后必须另点打开,不能自动打开。
  219. let installed = false,
  220. enabled = false;
  221. const mutations = [];
  222. await page.unroute("**/catalog");
  223. await page.route("**/catalog", (route) =>
  224. route.fulfill({ json: catalog(surfaces, installed, enabled) }),
  225. );
  226. await page.route("**/install", (route) => {
  227. mutations.push(route.request().postDataJSON());
  228. installed = true;
  229. return route.fulfill({ json: { diagnostics: [] } });
  230. });
  231. await page.route("**/enable", (route) => {
  232. mutations.push(route.request().postDataJSON());
  233. enabled = true;
  234. return route.fulfill({ json: { enabled: true, diagnostics: [] } });
  235. });
  236. await page.goto(`${origin}fixture?${query}`);
  237. const first = page.locator(launcherItems).first();
  238. await first.getByText(locale === "zh-CN" ? "安装" : "Install", { exact: true }).waitFor();
  239. assert.equal(await page.locator(launcherItems).count(), 2);
  240. await page.screenshot({
  241. path: join(artifacts, `uninstalled-${width}-${locale}-${theme}.png`),
  242. });
  243. await first.click();
  244. await first.getByText(locale === "zh-CN" ? "启用" : "Enable", { exact: true }).waitFor();
  245. assert.equal(await read("request"), null);
  246. assert.equal(mutations[0].scope, "user");
  247. await page.screenshot({ path: join(artifacts, `disabled-${width}-${locale}-${theme}.png`) });
  248. await first.click();
  249. await first.getByText(locale === "zh-CN" ? "打开" : "Open", { exact: true }).waitFor();
  250. assert.equal(await read("request"), null);
  251. assert.equal(mutations[1].scope, "workspace");
  252. await first.click();
  253. await page.waitForFunction(
  254. () => JSON.parse(document.querySelector('[data-testid="request"]').textContent) !== null,
  255. );
  256. assert.equal((await read("request")).pluginId, surfaces[0].pluginId);
  257. installed = false;
  258. enabled = false;
  259. await page.goto(`${origin}fixture?${query}&existing=1`);
  260. await page.locator(add).click();
  261. const newTabFirst = page.locator(newTabItems).first();
  262. await newTabFirst
  263. .getByText(locale === "zh-CN" ? "安装" : "Install", { exact: true })
  264. .waitFor();
  265. await newTabFirst.click();
  266. await newTabFirst
  267. .getByText(locale === "zh-CN" ? "启用" : "Enable", { exact: true })
  268. .waitFor();
  269. assert.equal(await read("request"), null);
  270. await newTabFirst.click();
  271. await newTabFirst.getByText(locale === "zh-CN" ? "打开" : "Open", { exact: true }).waitFor();
  272. assert.equal(await read("request"), null);
  273. await newTabFirst.click();
  274. await page.locator(activeLauncher).waitFor();
  275. await page.waitForFunction(
  276. () => JSON.parse(document.querySelector('[data-testid="request"]').textContent) !== null,
  277. );
  278. for (const config of [{}, { uiPluginRecommendations: [] }, null]) {
  279. await page.unroute("**/client-config");
  280. await page.route("**/client-config", (route) =>
  281. route.fulfill(
  282. config === null ? { status: 503 } : { json: { code: 0, data: { configs: config } } },
  283. ),
  284. );
  285. await page.goto(`${origin}fixture?${query}`);
  286. await page.getByTestId("side-pane-ui-empty").waitFor();
  287. assert.equal(await page.locator(launcherItems).count(), 0);
  288. }
  289. await page.unroute("**/client-config");
  290. await page.route("**/client-config", (route) =>
  291. route.fulfill({
  292. json: {
  293. code: 0,
  294. data: {
  295. configs: {
  296. uiPluginRecommendations: surfaces
  297. .slice(0, 2)
  298. .map((surface) => ({ pluginId: surface.pluginId, surfaceId: surface.id })),
  299. },
  300. },
  301. },
  302. }),
  303. );
  304. for (const mode of ["draft", "noHost", "noBridge"]) {
  305. let calls = 0;
  306. await page.unroute("**/surfaces");
  307. await page.route("**/surfaces", (route) => {
  308. calls++;
  309. return route.fulfill({ json: [] });
  310. });
  311. await page.goto(`${origin}fixture?${query}&existing=1&${mode}=1`);
  312. await page.locator(add).click();
  313. await page.locator(activeLauncher).waitFor();
  314. assert.equal(await page.locator(newTabItems).count(), 0, mode);
  315. if (mode === "draft") {
  316. assert.equal(
  317. await page.locator('[data-testid="side-pane-ui-recommendations"]').count(),
  318. 0,
  319. );
  320. assert.equal(await page.locator('[data-testid="side-pane-plugin-market"]').count(), 0);
  321. }
  322. assert.equal(calls, 0, mode);
  323. }
  324. assert.deepEqual(errors, []);
  325. } catch (error) {
  326. const diagnostic = `${String(error)}; pageErrors=${JSON.stringify(errors)}; body=${(await page.locator("body").innerText()).slice(0, 1500)}`;
  327. console.error(diagnostic);
  328. throw new Error(diagnostic, { cause: error });
  329. } finally {
  330. await page.close();
  331. }
  332. });
  333. }
  334. if (process.env.ZCODE_UI_RECOMMENDATIONS_LIVE_CONFIG_URL) {
  335. test("staging client config drives side pane recommendations", async () => {
  336. const page = await browser.newPage({ viewport: { width: 1200, height: 800 } });
  337. page.setDefaultTimeout(15000);
  338. try {
  339. const response = await page.request.get(process.env.ZCODE_UI_RECOMMENDATIONS_LIVE_CONFIG_URL);
  340. assert.equal(response.status(), 200);
  341. const envelope = await response.json();
  342. assert.equal(envelope.code, 0);
  343. const entries = envelope.data.configs.uiPluginRecommendations;
  344. assert.ok(entries.length > 0);
  345. assert.ok(entries.every((entry) => entry.pluginId.endsWith("@zcode-plugins-official")));
  346. await page.route("**/client-config", (route) => route.fulfill({ json: envelope }));
  347. await page.route("**/catalog", (route) =>
  348. route.fulfill({
  349. json: catalog(
  350. entries.map((entry) => ({ pluginId: entry.pluginId, pluginName: entry.pluginId })),
  351. ),
  352. }),
  353. );
  354. // 此处只验证真实配置到组件的链路;工作区可用面板由夹具提供,不代表安装验证。
  355. await page.route("**/surfaces", (route) =>
  356. route.fulfill({
  357. json: entries.map((entry) => ({
  358. id: entry.surfaceId,
  359. pluginId: entry.pluginId,
  360. pluginName: entry.pluginId,
  361. title: entry.surfaceId,
  362. server: "fixture-server",
  363. resourceUri: "ui://fixture/panel.html",
  364. })),
  365. }),
  366. );
  367. await page.goto(`${origin}fixture?locale=zh-CN&theme=light`);
  368. await page.locator(launcherItems).first().waitFor();
  369. assert.equal(await page.locator(launcherItems).count(), entries.length);
  370. await page.screenshot({
  371. path: join(tmpdir(), "zcode-side-pane-plugin-menu", "staging-recommendations.png"),
  372. });
  373. await page.locator(launcherItems).first().click();
  374. await page.waitForFunction(
  375. () => JSON.parse(document.querySelector('[data-testid="request"]').textContent) !== null,
  376. );
  377. const request = JSON.parse(await page.getByTestId("request").textContent());
  378. assert.equal(request.pluginId, entries[0].pluginId);
  379. assert.equal(request.surfaceId, entries[0].surfaceId);
  380. } finally {
  381. await page.close();
  382. }
  383. });
  384. }
  385. test("cold new-tab launcher shows skeleton until config settles", async () => {
  386. const page = await browser.newPage({ viewport: { width: 1200, height: 800 } });
  387. const gate = Promise.withResolvers();
  388. try {
  389. await page.route("**/catalog", (route) => route.fulfill({ json: catalog(surfaces) }));
  390. await page.route("**/client-config", async (route) => {
  391. await gate.promise;
  392. return route.fulfill({ json: { code: 0, data: { configs: {} } } });
  393. });
  394. await page.goto(`${origin}fixture?existing=1`);
  395. await page.locator(add).click();
  396. await page.getByTestId("side-pane-ui-loading").waitFor();
  397. assert.equal(await page.getByTestId("side-pane-ui-empty").count(), 0);
  398. gate.resolve();
  399. await page.getByTestId("side-pane-ui-loading").waitFor({ state: "hidden" });
  400. assert.equal(await page.locator(newTabItems).count(), 0);
  401. } finally {
  402. gate.resolve();
  403. await page.close();
  404. }
  405. });
  406. test("SPT-E2E-007 same-plugin surfaces share progress and respect reduced motion", async () => {
  407. const page = await browser.newPage({ viewport: { width: 1200, height: 800 } });
  408. const gate = Promise.withResolvers();
  409. const entries = [surfaces[0], { ...surfaces[0], id: "details" }, surfaces[1]];
  410. let installed = false;
  411. let installCalls = 0;
  412. try {
  413. await page.route("**/catalog", (route) => {
  414. const result = catalog(surfaces.slice(0, 2), false);
  415. if (installed) {
  416. result.plugins = catalog([surfaces[0]]).plugins;
  417. result.plugins[0].uiSurfaces = entries.slice(0, 2);
  418. result.availablePlugins[0].installed = true;
  419. }
  420. return route.fulfill({ json: result });
  421. });
  422. await page.route("**/client-config", (route) =>
  423. route.fulfill({
  424. json: {
  425. code: 0,
  426. data: {
  427. configs: {
  428. uiPluginRecommendations: entries.map((surface) => ({
  429. pluginId: surface.pluginId,
  430. surfaceId: surface.id,
  431. })),
  432. },
  433. },
  434. },
  435. }),
  436. );
  437. await page.route("**/install", async (route) => {
  438. installCalls++;
  439. await gate.promise;
  440. installed = true;
  441. return route.fulfill({ json: { diagnostics: [] } });
  442. });
  443. await page.goto(`${origin}fixture?locale=en-US&theme=light`);
  444. const items = page.locator(launcherItems);
  445. await items.first().getByText("Install", { exact: true }).waitFor();
  446. await items.first().click();
  447. const spinners = items.getByTestId("side-pane-plugin-progress");
  448. await spinners.nth(1).waitFor();
  449. assert.equal(await spinners.count(), 2);
  450. assert.equal(await items.nth(2).getByText("Install", { exact: true }).count(), 1);
  451. assert.equal(await items.nth(2).getByTestId("side-pane-plugin-progress").count(), 0);
  452. assert.deepEqual(
  453. await items.evaluateAll((elements) =>
  454. elements.map((element) => element.getAttribute("aria-busy")),
  455. ),
  456. ["true", "true", null],
  457. );
  458. assert.equal(installCalls, 1);
  459. await page.emulateMedia({ reducedMotion: "reduce" });
  460. assert.equal(await spinners.first().isVisible(), true);
  461. assert.equal(
  462. await spinners.first().evaluate((element) => getComputedStyle(element).animationName),
  463. "none",
  464. );
  465. gate.resolve();
  466. await items.first().getByText("Open", { exact: true }).waitFor();
  467. await items.nth(1).getByText("Open", { exact: true }).waitFor();
  468. assert.equal(await spinners.count(), 0);
  469. assert.equal(await page.getByTestId("request").textContent(), "null");
  470. } finally {
  471. gate.resolve();
  472. await page.close();
  473. }
  474. });
  475. for (const [width, locale, theme] of [
  476. [1200, "en-US", "light"],
  477. [390, "zh-CN", "dark"],
  478. ]) {
  479. for (const existing of [false, true]) {
  480. for (const operation of ["install", "enable"]) {
  481. test(`SPT-E2E-007 progress ${operation}/${existing ? "new-tab" : "empty"}/${width}`, async () => {
  482. const page = await browser.newPage({ viewport: { width, height: 800 } });
  483. page.setDefaultTimeout(15000);
  484. const gates = [Promise.withResolvers(), Promise.withResolvers()];
  485. const attempts = [];
  486. const errors = [];
  487. const states = surfaces.map((_, index) => ({
  488. installed: index === 2 || operation === "enable",
  489. enabled: index === 2,
  490. }));
  491. const action =
  492. operation === "install"
  493. ? locale === "zh-CN"
  494. ? "安装"
  495. : "Install"
  496. : locale === "zh-CN"
  497. ? "启用"
  498. : "Enable";
  499. const loading = locale === "zh-CN" ? "加载中..." : "Loading...";
  500. const open = locale === "zh-CN" ? "打开" : "Open";
  501. const readCatalog = () => ({
  502. ...catalog([], false, false),
  503. plugins: surfaces.flatMap(
  504. (surface, index) =>
  505. catalog([surface], states[index].installed, states[index].enabled).plugins,
  506. ),
  507. availablePlugins: surfaces.flatMap(
  508. (surface, index) =>
  509. catalog([surface], states[index].installed, states[index].enabled).availablePlugins,
  510. ),
  511. });
  512. page.on("pageerror", (error) => errors.push(error.message));
  513. await page.route("**/surfaces", (route) => route.fulfill({ json: surfaces }));
  514. await page.route("**/catalog", (route) => route.fulfill({ json: readCatalog() }));
  515. await page.route("**/client-config", (route) =>
  516. route.fulfill({
  517. json: {
  518. code: 0,
  519. data: {
  520. configs: {
  521. uiPluginRecommendations: surfaces.map((surface) => ({
  522. pluginId: surface.pluginId,
  523. surfaceId: surface.id,
  524. })),
  525. },
  526. },
  527. },
  528. }),
  529. );
  530. await page.route(`**/${operation}`, async (route) => {
  531. const attempt = attempts.length;
  532. attempts.push(route.request().postDataJSON());
  533. await gates[attempt].promise;
  534. if (attempt === 0) return route.fulfill({ status: 503 });
  535. states[1][operation === "install" ? "installed" : "enabled"] = true;
  536. return route.fulfill({ json: { diagnostics: [] } });
  537. });
  538. const selector = existing ? newTabItems : launcherItems;
  539. const items = page.locator(selector);
  540. // 安装态会改变展示位置,操作进度按插件身份定位,不依赖列表索引。
  541. const itemSelector = (index) =>
  542. `${selector}[data-side-pane-open-tab-item="plugin-ui:${surfaces[index].pluginId}/${surfaces[index].id}"]`;
  543. const item = (index) => page.locator(itemSelector(index));
  544. const waitIdle = () =>
  545. page.waitForFunction(
  546. (selector) =>
  547. [...document.querySelectorAll(selector)].every((element) => !element.disabled),
  548. selector,
  549. );
  550. const assertProgress = async (index) => {
  551. await item(index).getByText(loading, { exact: true }).waitFor();
  552. assert.equal(await items.getByText(loading, { exact: true }).count(), 1);
  553. const spinner = item(index).getByTestId("side-pane-plugin-progress");
  554. assert.equal(await spinner.count(), 1, "操作中的插件应有加载图标");
  555. assert.equal(await spinner.isVisible(), true);
  556. assert.notEqual(
  557. await spinner.evaluate((element) => getComputedStyle(element).animationName),
  558. "none",
  559. );
  560. assert.equal(await items.getByTestId("side-pane-plugin-progress").count(), 1);
  561. assert.equal(await item(index).getAttribute("aria-busy"), "true");
  562. assert.equal(await page.locator(`${selector}[aria-busy="true"]`).count(), 1);
  563. assert.equal(
  564. await item(1 - index)
  565. .getByText(action, { exact: true })
  566. .count(),
  567. 1,
  568. );
  569. assert.equal(await item(2).getByText(open, { exact: true }).count(), 1);
  570. assert.deepEqual(
  571. await Promise.all([0, 1, 2].map((index) => item(index).isDisabled())),
  572. [0, 1, 2].map((candidate) => candidate === index),
  573. );
  574. };
  575. try {
  576. const query = `locale=${locale}&theme=${theme}${width < 500 ? "&mobile=1" : ""}${existing ? "&existing=1" : ""}`;
  577. await page.goto(`${origin}fixture?${query}`, { waitUntil: "domcontentloaded" });
  578. if (existing) await page.locator(add).click();
  579. await item(0).getByText(action, { exact: true }).waitFor();
  580. await item(0).click();
  581. await assertProgress(0);
  582. assert.equal(attempts.length, 1);
  583. gates[0].resolve();
  584. await waitIdle();
  585. await item(0).getByText(action, { exact: true }).waitFor();
  586. assert.equal(await items.getByTestId("side-pane-plugin-progress").count(), 0);
  587. assert.equal(await page.locator(`${selector}[aria-busy="true"]`).count(), 0);
  588. // 失败后换另一个插件重试,防止进度归属残留在第一次点击的插件上。
  589. await item(1).click();
  590. await assertProgress(1);
  591. assert.equal(attempts.length, 2);
  592. const artifacts = join(tmpdir(), "zcode-side-pane-plugin-menu");
  593. await mkdir(artifacts, { recursive: true });
  594. await page.screenshot({
  595. path: join(artifacts, `progress-${operation}-${existing}-${width}-${theme}.png`),
  596. });
  597. gates[1].resolve();
  598. await waitIdle();
  599. const completed =
  600. operation === "install" ? (locale === "zh-CN" ? "启用" : "Enable") : open;
  601. await item(1).getByText(completed, { exact: true }).waitFor();
  602. assert.equal(await items.getByText(loading, { exact: true }).count(), 0);
  603. assert.equal(await items.getByTestId("side-pane-plugin-progress").count(), 0);
  604. assert.equal(await page.locator(`${selector}[aria-busy="true"]`).count(), 0);
  605. assert.equal(await item(0).getByText(action, { exact: true }).count(), 1);
  606. assert.equal(await page.getByTestId("request").textContent(), "null");
  607. assert.deepEqual(errors, []);
  608. } finally {
  609. gates.forEach((gate) => gate.resolve());
  610. await page.close();
  611. }
  612. });
  613. }
  614. }
  615. }
  616. for (const [width, locale, theme] of [
  617. [1200, "en-US", "light"],
  618. [390, "zh-CN", "dark"],
  619. ]) {
  620. for (const existing of [false, true]) {
  621. test(`SPT-E2E-007 concurrent installs ${existing ? "new-tab" : "empty"}/${width}`, async () => {
  622. const page = await browser.newPage({ viewport: { width, height: 800 } });
  623. page.setDefaultTimeout(15000);
  624. const gates = [Promise.withResolvers(), Promise.withResolvers()];
  625. const entered = [Promise.withResolvers(), Promise.withResolvers()];
  626. const calls = [];
  627. const errors = [];
  628. page.on("pageerror", (error) => errors.push(error.message));
  629. let firstInstalled = false;
  630. const selector = existing ? newTabItems : launcherItems;
  631. const items = page.locator(selector);
  632. // 安装态会改变展示位置,操作进度按插件身份定位,不依赖列表索引。
  633. const itemSelector = (index) =>
  634. `${selector}[data-side-pane-open-tab-item="plugin-ui:${surfaces[index].pluginId}/${surfaces[index].id}"]`;
  635. const item = (index) => page.locator(itemSelector(index));
  636. try {
  637. await page.route("**/client-config", (route) =>
  638. route.fulfill({
  639. json: {
  640. code: 0,
  641. data: {
  642. configs: {
  643. uiPluginRecommendations: surfaces.map((surface) => ({
  644. pluginId: surface.pluginId,
  645. surfaceId: surface.id,
  646. })),
  647. },
  648. },
  649. },
  650. }),
  651. );
  652. await page.route("**/catalog", (route) =>
  653. route.fulfill({
  654. json: {
  655. ...catalog(surfaces, false),
  656. plugins: catalog([surfaces[2], ...(firstInstalled ? [surfaces[0]] : [])]).plugins,
  657. availablePlugins: surfaces.map((surface, index) => ({
  658. ...catalog([surface], index === 2 || (index === 0 && firstInstalled))
  659. .availablePlugins[0],
  660. })),
  661. },
  662. }),
  663. );
  664. await page.route("**/surfaces", (route) => route.fulfill({ json: surfaces }));
  665. await page.route("**/install", async (route) => {
  666. const input = route.request().postDataJSON();
  667. const index = surfaces.findIndex((surface) => surface.pluginName === input.pluginName);
  668. calls.push(input.pluginName);
  669. entered[index].resolve();
  670. await gates[index].promise;
  671. if (index === 1) return route.fulfill({ status: 503 });
  672. firstInstalled = true;
  673. return route.fulfill({ json: { diagnostics: [] } });
  674. });
  675. const query = `locale=${locale}&theme=${theme}${width < 500 ? "&mobile=1" : ""}${existing ? "&existing=1" : ""}`;
  676. await page.goto(`${origin}fixture?${query}`, { waitUntil: "domcontentloaded" });
  677. if (existing) await page.locator(add).click();
  678. await item(0).waitFor();
  679. await item(0).click();
  680. await entered[0].promise;
  681. assert.equal(await item(1).isEnabled(), true);
  682. assert.equal(await item(2).isEnabled(), true);
  683. await item(1).click();
  684. await entered[1].promise;
  685. assert.deepEqual(calls, ["hello", "canvas"]);
  686. assert.deepEqual(await Promise.all([0, 1, 2].map((index) => item(index).isDisabled())), [
  687. true,
  688. true,
  689. false,
  690. ]);
  691. assert.equal(await items.getByTestId("side-pane-plugin-progress").count(), 2);
  692. // 安装中仍可打开其他已启用插件,真实 surface 查询到 tab owner 的链路继续工作。
  693. await item(2).click();
  694. await page.waitForFunction(
  695. () =>
  696. JSON.parse(document.querySelector('[data-testid="request"]').textContent)?.pluginId ===
  697. "development@example",
  698. );
  699. gates[1].resolve();
  700. await page.waitForFunction(
  701. (selector) => !document.querySelector(selector).disabled,
  702. itemSelector(1),
  703. );
  704. assert.equal(await item(0).isDisabled(), true);
  705. assert.equal(await item(0).getByTestId("side-pane-plugin-progress").count(), 1);
  706. const artifacts = join(tmpdir(), "zcode-side-pane-plugin-menu");
  707. await mkdir(artifacts, { recursive: true });
  708. await page.screenshot({
  709. path: join(artifacts, `concurrent-${existing}-${width}-${theme}.png`),
  710. });
  711. gates[0].resolve();
  712. await page.waitForFunction(
  713. (selector) => !document.querySelector(selector).disabled,
  714. itemSelector(0),
  715. );
  716. assert.equal(await items.getByTestId("side-pane-plugin-progress").count(), 0);
  717. assert.deepEqual(calls, ["hello", "canvas"]);
  718. } catch (error) {
  719. throw new Error(
  720. `${String(error)}; pageErrors=${JSON.stringify(errors)}; body=${(await page.locator("body").innerText()).slice(0, 1500)}`,
  721. { cause: error },
  722. );
  723. } finally {
  724. gates.forEach((gate) => gate.resolve());
  725. await page.close();
  726. }
  727. });
  728. }
  729. }
  730. for (const [width, locale, theme] of [
  731. [1200, "en-US", "light"],
  732. [390, "zh-CN", "dark"],
  733. ]) {
  734. test(`SPT-E2E-007 installed priority and community tag ${width}/${locale}/${theme}`, async () => {
  735. const page = await browser.newPage({ viewport: { width, height: 800 } });
  736. page.setDefaultTimeout(15000);
  737. page.setDefaultNavigationTimeout(120000);
  738. const entries = ["new", "community", "official", "personal"].map((name) => ({
  739. ...surfaces[0],
  740. id: name,
  741. pluginName: name,
  742. pluginId: `${name}@${name === "personal" ? "example" : "zcode-plugins-official"}`,
  743. title: { en: name, "zh-CN": name },
  744. }));
  745. const snapshot = catalog(entries);
  746. snapshot.plugins = snapshot.plugins.filter((item) => item.name !== "new");
  747. snapshot.plugins[0].enabled = false;
  748. snapshot.availablePlugins = snapshot.availablePlugins.map((item) => ({
  749. ...item,
  750. installed: item.name !== "new",
  751. listing: {
  752. publisherType: ["community", "personal"].includes(item.name) ? "community" : "official",
  753. displayName: `${item.name} description`,
  754. },
  755. }));
  756. await page.route("**/catalog", (route) => route.fulfill({ json: snapshot }));
  757. await page.route("**/client-config", (route) =>
  758. route.fulfill({
  759. json: {
  760. code: 0,
  761. data: {
  762. configs: {
  763. uiPluginRecommendations: entries.map((entry) => ({
  764. pluginId: entry.pluginId,
  765. surfaceId: entry.id,
  766. })),
  767. },
  768. },
  769. },
  770. }),
  771. );
  772. try {
  773. await page.goto(
  774. `${origin}fixture?locale=${locale}&theme=${theme}${width < 500 ? "&mobile=1" : ""}`,
  775. );
  776. const rows = page.locator(launcherItems);
  777. await rows.first().waitFor();
  778. assert.deepEqual(
  779. await rows.evaluateAll((nodes) =>
  780. nodes.map((node) => node.getAttribute("data-side-pane-open-tab-item")),
  781. ),
  782. [entries[1], entries[2], entries[3], entries[0]].map(
  783. (entry) => `plugin-ui:${entry.pluginId}/${entry.id}`,
  784. ),
  785. );
  786. const tag = locale === "zh-CN" ? "社区" : "Community";
  787. assert.equal(await rows.getByText(tag, { exact: true }).count(), 1);
  788. const badge = rows.first().getByText(tag, { exact: true });
  789. assert.equal(await badge.isVisible(), true);
  790. const description = rows.first().getByText("community description", { exact: true });
  791. const badgeBox = await badge.boundingBox();
  792. const descriptionBox = await description.boundingBox();
  793. assert.ok(badgeBox.x + badgeBox.width <= descriptionBox.x);
  794. const artifacts = join(tmpdir(), "zcode-side-pane-plugin-menu");
  795. await mkdir(artifacts, { recursive: true });
  796. await page.screenshot({ path: join(artifacts, `community-${width}-${locale}-${theme}.png`) });
  797. } finally {
  798. await page.close();
  799. }
  800. });
  801. }