plugin-picker-order.test.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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/plugin-picker-order.fixture.tsx";
  13. let server;
  14. let browser;
  15. let origin;
  16. before(async () => {
  17. server = await createServer({
  18. root,
  19. configFile: false,
  20. plugins: [
  21. {
  22. name: "unrelated-picker-data-sources",
  23. load(id) {
  24. if (id.endsWith("/hooks/useWorkspaceServices.tsx"))
  25. return 'import {useServices} from "@/hooks/useServices.js"; export function useWorkspaceServicesResolution(){ return {services:useServices(),rpcReady:true,remoteSessionId:"attachment"}; }';
  26. if (id.endsWith("/v4/activeTaskProvider.ts"))
  27. return 'export function useChatViewActiveTaskProvider(){return "zcode";}';
  28. for (const [file, fn] of [
  29. ["fileMentionProvider", "useFileMentionProvider"],
  30. ["sessionsMentionProvider", "useSessionsMentionProvider"],
  31. ["skillsMentionProvider", "useSkillsMentionProvider"],
  32. ["subagentsMentionProvider", "useSubagentsMentionProvider"],
  33. ]) {
  34. if (id.endsWith("/providers/" + file + ".ts"))
  35. return (
  36. "export const mapSkillsToMentionItemsForTest=()=>[]; export const mapSubagentsToMentionItemsForTest=()=>[]; export function " +
  37. fn +
  38. '(){return {items:[],loading:false,error:null,title:"",emptyText:""};}'
  39. );
  40. }
  41. },
  42. },
  43. react(),
  44. tailwindcss(),
  45. {
  46. name: "responsive-fixture",
  47. configureServer(vite) {
  48. vite.middlewares.use(async (req, res, next) => {
  49. if (!req.url?.startsWith("/fixture?")) return next();
  50. res.setHeader("Content-Type", "text/html");
  51. res.end(
  52. await vite.transformIndexHtml(
  53. req.url,
  54. `<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>`,
  55. ),
  56. );
  57. });
  58. },
  59. },
  60. ],
  61. resolve: { alias: { "@": `${root}packages/ui/src` } },
  62. optimizeDeps: { entries: [entry.slice(1)] },
  63. server: { host: "127.0.0.1", port: 0 },
  64. });
  65. await server.listen();
  66. origin = server.resolvedUrls.local[0];
  67. browser = await chromium.launch(
  68. process.env.CHROME_EXECUTABLE_PATH
  69. ? { executablePath: process.env.CHROME_EXECUTABLE_PATH }
  70. : { channel: "chrome" },
  71. );
  72. });
  73. after(async () => {
  74. await browser?.close();
  75. await server?.close();
  76. });
  77. const official = "zcode-plugins-official";
  78. const plugin = (name, category, extra = {}) => ({
  79. pluginId: `${name}@${official}`,
  80. name,
  81. marketplace: official,
  82. category,
  83. enabled: true,
  84. conflictingPluginIds: [],
  85. skillQualifiedNames: [],
  86. mcpServerNames: [],
  87. subagentNames: [],
  88. ...extra,
  89. });
  90. const frozen = [
  91. plugin("beta", "utilities"),
  92. plugin("alpha", "utilities"),
  93. plugin("dev", "developer-tools"),
  94. plugin("disabled", "utilities", { enabled: false }),
  95. plugin("conflict", "utilities", { conflictingPluginIds: ["conflict@personal"] }),
  96. plugin("personal", "utilities", { pluginId: "personal@personal", marketplace: "personal" }),
  97. ];
  98. const config = {
  99. code: {
  100. categoryOrder: ["developer-tools", "utilities"],
  101. pluginOrder: { utilities: [`beta@${official}`, `alpha@${official}`] },
  102. },
  103. work: {
  104. categoryOrder: ["utilities", "developer-tools"],
  105. pluginOrder: { utilities: [`alpha@${official}`, `beta@${official}`] },
  106. },
  107. };
  108. for (const [width, locale, theme] of [
  109. [1200, "en-US", "light"],
  110. [390, "zh-CN", "dark"],
  111. ]) {
  112. test(`PSO-10/11/14 @/+ ${width}/${locale}/${theme}`, async () => {
  113. const page = await browser.newPage({ viewport: { width, height: 900 } });
  114. page.setDefaultTimeout(10000);
  115. const errors = [];
  116. page.on("pageerror", (e) => errors.push(e.message));
  117. const calls = [];
  118. let requests = 0;
  119. let release;
  120. const pending = new Promise((resolve) => (release = resolve));
  121. await page.route("**/catalog", async (route) => {
  122. const params = route.request().postDataJSON();
  123. calls.push(params);
  124. assert.equal(params.workspaceIdentity, "ssh:fixture");
  125. assert.equal(params.remoteSessionId, "attachment");
  126. await route.fulfill({
  127. json: {
  128. authority: params.sessionId ? "session" : "workspace",
  129. plugins: params.sessionId ? frozen : [...frozen, plugin("new", "developer-tools")],
  130. },
  131. });
  132. });
  133. await page.route("**/order", async (route) => {
  134. requests++;
  135. if (requests === 1) await pending;
  136. await route.fulfill({ json: config });
  137. });
  138. const options = () => page.locator('[role="option"][data-section-id="plugins"]');
  139. const names = () =>
  140. options().evaluateAll((es) =>
  141. es.map((e) => e.getAttribute("data-option-id").replace("plugin:", "").split("@")[0]),
  142. );
  143. const editor = page.getByTestId("editor");
  144. try {
  145. await page.goto(`${origin}fixture?locale=${locale}&theme=${theme}`);
  146. await editor.waitFor();
  147. assert.equal(requests, 0);
  148. await editor.fill("@");
  149. await options().first().waitFor();
  150. assert.deepEqual(await names(), ["beta", "alpha", "dev", "conflict", "personal"]);
  151. release();
  152. await page.waitForFunction(() =>
  153. document
  154. .querySelector('[role="option"][data-section-id="plugins"]')
  155. ?.getAttribute("data-option-id")
  156. ?.startsWith("plugin:dev@"),
  157. );
  158. assert.deepEqual(await names(), ["dev", "beta", "alpha", "conflict", "personal"]);
  159. // 模式按钮点击不让编辑器失焦,验证打开菜单期间的本地重排。
  160. await page.getByTestId("work").evaluate((e) => e.click());
  161. await page.waitForFunction(() =>
  162. document
  163. .querySelector('[role="option"][data-section-id="plugins"]')
  164. ?.getAttribute("data-option-id")
  165. ?.startsWith("plugin:alpha@"),
  166. );
  167. assert.deepEqual(await names(), ["alpha", "beta", "conflict", "dev", "personal"]);
  168. assert.equal(requests, 1);
  169. assert.equal(
  170. await page
  171. .locator('[data-option-id="plugin:conflict@zcode-plugins-official"]')
  172. .getAttribute("data-disabled"),
  173. "true",
  174. );
  175. await editor.fill("@dev");
  176. await options().first().waitFor();
  177. await page.waitForFunction(
  178. () => document.querySelectorAll('[role="option"][data-section-id="plugins"]').length === 1,
  179. );
  180. assert.deepEqual(await names(), ["dev"]);
  181. await editor.fill("");
  182. await page.getByRole("button", { name: "Add", exact: true }).click();
  183. await options().first().waitFor();
  184. assert.deepEqual(await names(), ["alpha", "beta", "conflict", "dev", "personal"]);
  185. const afterOpen = requests;
  186. await page.getByTestId("code").evaluate((e) => e.click());
  187. await page.waitForFunction(() =>
  188. document
  189. .querySelector('[role="option"][data-section-id="plugins"]')
  190. ?.getAttribute("data-option-id")
  191. ?.startsWith("plugin:dev@"),
  192. );
  193. assert.deepEqual(await names(), ["dev", "beta", "alpha", "conflict", "personal"]);
  194. assert.equal(requests, afterOpen);
  195. await options().first().click();
  196. assert.equal(await page.getByTestId("selected").textContent(), `dev@${official}`);
  197. await page.getByTestId("draft").click();
  198. await editor.fill("@");
  199. await options().first().waitFor();
  200. await page.waitForFunction(
  201. () => !!document.querySelector('[data-option-id="plugin:new@zcode-plugins-official"]'),
  202. );
  203. assert.ok(calls.some((x) => x.sessionId === "frozen-session"));
  204. assert.ok(calls.some((x) => !x.sessionId));
  205. assert.deepEqual(errors, []);
  206. await mkdir(join(tmpdir(), "zcode-plugin-picker-order"), { recursive: true });
  207. await page.screenshot({
  208. path: join(tmpdir(), "zcode-plugin-picker-order", `${width}-${locale}.png`),
  209. });
  210. } catch (error) {
  211. console.error(error, { errors, calls, requests }, await page.locator("body").innerText());
  212. throw error;
  213. } finally {
  214. release();
  215. await page.close();
  216. }
  217. });
  218. }
  219. for (const width of [1200, 390]) {
  220. for (const locale of ["en-US", "zh-CN"]) {
  221. for (const theme of ["light", "dark"]) {
  222. test(`PLUGIN-CREATOR-ICON @ token ${width}/${locale}/${theme}`, async () => {
  223. const page = await browser.newPage({ viewport: { width, height: 900 } });
  224. page.setDefaultTimeout(10000);
  225. try {
  226. await page.route("**/catalog", (route) =>
  227. route.fulfill({
  228. json: {
  229. authority: "session",
  230. plugins: [plugin("plugin-creator", "utilities")],
  231. },
  232. }),
  233. );
  234. await page.route("**/order", (route) => route.fulfill({ json: config }));
  235. await page.goto(`${origin}fixture?locale=${locale}&theme=${theme}`);
  236. const editor = page.getByTestId("editor");
  237. await editor.fill("@");
  238. const option = page.locator(
  239. '[role="option"][data-option-id="plugin:plugin-creator@zcode-plugins-official"]',
  240. );
  241. await option.waitFor();
  242. const image = option.locator("img");
  243. assert.match(await image.getAttribute("src"), /plugin-creator\.png/u);
  244. await page.waitForFunction(() => {
  245. const image = document.querySelector('[role="option"] img');
  246. return image?.complete && image.naturalWidth > 0;
  247. });
  248. await option.click();
  249. const token = editor.locator(
  250. '[data-mention-id="plugin:plugin-creator@zcode-plugins-official"]',
  251. );
  252. await token.waitFor();
  253. assert.match(
  254. await token.evaluate((node) => node.style.getPropertyValue("--mention-image")),
  255. /plugin-creator\.png/u,
  256. );
  257. assert.equal(await editor.innerText(), "plugin-creator ");
  258. } finally {
  259. await page.close();
  260. }
  261. });
  262. }
  263. }
  264. }