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

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