plugin-management-lifecycle.ts 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  1. /* eslint-disable max-lines -- 插件 lifecycle E2E 的确定性文件夹 fixture、UI 驱动和第二层证据集中维护,避免各 pending spec 重复脆弱 DOM/存储逻辑。 */
  2. import { existsSync } from "node:fs";
  3. import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
  4. import { dirname, join } from "node:path";
  5. import {
  6. type ZCodePluginsInstallResult,
  7. type ZCodePluginsListResult,
  8. type ZCodePluginsMarketplaceMutationResult,
  9. type ZCodePluginsOverviewResult,
  10. type ZCodePluginsReferenceCatalogResult,
  11. } from "@zcode/shared";
  12. import {
  13. TID_PLUGIN_STORE_BROWSE,
  14. TID_SETTINGS_PAGE,
  15. TID_SETTINGS_SECTION_NAV,
  16. TID_TASK_SETTINGS_BUTTON,
  17. testId,
  18. } from "@zcode/shared/test-ids";
  19. import {
  20. DEFAULT_WORKSPACE,
  21. clickTestIdByDom,
  22. getE2EAppDataPaths,
  23. setCurrentElectronRendererContentSize,
  24. setInputValueByTestIdDom,
  25. waitForDefaultWorkspaceReady,
  26. waitForTestIdByDom,
  27. waitForWorkspaceApp,
  28. } from "./desktop-app.js";
  29. export const PLUGIN_LIFECYCLE_MARKETPLACE_ID = "e2e-plugin-lifecycle-market";
  30. export const PLUGIN_LIFECYCLE_MARKETPLACE_NAME = "E2E Plugin Lifecycle Market";
  31. export const PLUGIN_LIFECYCLE_NAME = "e2e-plugin-lifecycle";
  32. export const PLUGIN_LIFECYCLE_ID = `${PLUGIN_LIFECYCLE_NAME}@${PLUGIN_LIFECYCLE_MARKETPLACE_ID}`;
  33. export const PLUGIN_LIFECYCLE_EXAMPLE_PROMPT =
  34. "E2E_PLUGIN_LIFECYCLE_EXAMPLE_PROMPT: summarize the fixture lifecycle";
  35. export const PLUGIN_LIFECYCLE_CONFIG_KEY = "display_label";
  36. export const PLUGIN_LIFECYCLE_CONFIG_VALUE = "configured-by-plugin-lifecycle-e2e";
  37. export const PLUGIN_LIFECYCLE_INHERITED_CONFIG_KEY = "timeout_seconds";
  38. export const PLUGIN_LIFECYCLE_MCP_TOOL_NAME =
  39. "mcp__plugin_e2e-plugin-lifecycle_lifecycle__version_marker";
  40. export const PLUGIN_LIFECYCLE_RUNTIME_MARKER = "E2E_PLUGIN_LIFECYCLE_RUNTIME";
  41. export const PLUGIN_INLINE_NAME = "e2e-inline-lifecycle";
  42. export const PLUGIN_INLINE_ID = `${PLUGIN_INLINE_NAME}@inline`;
  43. export const PLUGIN_INLINE_SUBAGENT_NAME = `${PLUGIN_INLINE_NAME}:inline-reviewer`;
  44. export interface PluginLifecycleFixture {
  45. marketplaceRoot: string;
  46. pluginRoot: string;
  47. version: string;
  48. }
  49. type PluginTestActionName =
  50. | "addPluginMarketplace"
  51. | "getPluginsOverview"
  52. | "installPlugin"
  53. | "listPlugins"
  54. | "getPluginReferenceCatalog"
  55. | "updatePluginMarketplace";
  56. interface SerializedActionResult<T> {
  57. ok: boolean;
  58. error?: string;
  59. value?: T;
  60. }
  61. interface PluginControlAttributes {
  62. componentKind?: string;
  63. configKey?: string;
  64. groupKey?: string;
  65. marketplaceId?: string;
  66. pluginId?: string;
  67. }
  68. export function requirePluginManualReview(): void {
  69. const runningPendingSpec = process.argv.some((arg) =>
  70. arg.replaceAll("\\", "/").includes("/plugins/manual-review/"),
  71. );
  72. if (runningPendingSpec && process.env.ZCODE_E2E_MANUAL_REVIEW !== "1") {
  73. throw new Error("Plugin lifecycle pending specs require ZCODE_E2E_MANUAL_REVIEW=1");
  74. }
  75. }
  76. export async function createPluginLifecycleFixture(
  77. version = "1.0.0",
  78. withUi = false,
  79. ): Promise<PluginLifecycleFixture> {
  80. const { homeDir } = getE2EAppDataPaths();
  81. const marketplaceRoot = join(homeDir, "fixtures", "plugin-management-lifecycle-market");
  82. const pluginRoot = join(marketplaceRoot, "plugins", PLUGIN_LIFECYCLE_NAME);
  83. await rm(marketplaceRoot, { force: true, recursive: true });
  84. await writeLifecyclePlugin(pluginRoot, version, withUi);
  85. for (let index = 1; index <= 7; index += 1) {
  86. await writeSimplePlugin(
  87. join(marketplaceRoot, "plugins", `e2e-lifecycle-extra-${index}`),
  88. index,
  89. );
  90. }
  91. await writeMarketplaceManifest(marketplaceRoot, version);
  92. if (withUi) {
  93. const path = join(marketplaceRoot, ".claude-plugin", "marketplace.json");
  94. const catalog = await readJsonRecord(path);
  95. const entries = catalog.plugins as Array<Record<string, unknown>>;
  96. entries.find((entry) => entry.name === PLUGIN_LIFECYCLE_NAME)!.componentTypes = ["mcp", "ui"];
  97. await writeJson(path, catalog);
  98. }
  99. const managedPluginRoot = lifecycleManagedPluginRoot(homeDir);
  100. if (existsSync(dirname(dirname(managedPluginRoot)))) {
  101. // 已登记的 directory marketplace 会复制进 managed storage;失败恢复必须同步修复该副本。
  102. await rm(managedPluginRoot, { force: true, recursive: true });
  103. await mkdir(dirname(managedPluginRoot), { recursive: true });
  104. await cp(pluginRoot, managedPluginRoot, { force: true, recursive: true });
  105. }
  106. return { marketplaceRoot, pluginRoot, version };
  107. }
  108. export async function updatePluginLifecycleFixture(
  109. fixture: PluginLifecycleFixture,
  110. version: string,
  111. ): Promise<PluginLifecycleFixture> {
  112. await writeLifecyclePlugin(fixture.pluginRoot, version);
  113. await writeMarketplaceManifest(fixture.marketplaceRoot, version);
  114. return { ...fixture, version };
  115. }
  116. export async function removeLifecyclePluginSource(fixture: PluginLifecycleFixture): Promise<void> {
  117. const { homeDir } = getE2EAppDataPaths();
  118. await rm(fixture.marketplaceRoot, { force: true, recursive: true });
  119. // directory marketplace 在添加时会复制到 managed storage;仅删除原目录不会触发
  120. // describe/install/update 失败,因此故障注入必须同时移除权威 managed plugin 副本。
  121. await rm(lifecycleManagedPluginRoot(homeDir), {
  122. force: true,
  123. recursive: true,
  124. });
  125. }
  126. export async function removeLifecyclePluginPayload(fixture: PluginLifecycleFixture): Promise<void> {
  127. const { homeDir } = getE2EAppDataPaths();
  128. // 保留 marketplace manifest 与登记关系,只移除其声明的插件 payload。这样 Manage 仍展示
  129. // update 入口,而安装器会在真正复制版本时确定性失败,正好覆盖“关联存在但升级源损坏”。
  130. await rm(fixture.pluginRoot, { force: true, recursive: true });
  131. await rm(lifecycleManagedPluginRoot(homeDir), {
  132. force: true,
  133. recursive: true,
  134. });
  135. }
  136. export async function corruptLifecycleMarketplaceManifest(
  137. fixture: PluginLifecycleFixture,
  138. ): Promise<void> {
  139. await writeText(
  140. join(fixture.marketplaceRoot, ".claude-plugin", "marketplace.json"),
  141. "{ invalid plugin lifecycle marketplace fixture",
  142. );
  143. }
  144. function lifecycleManagedPluginRoot(homeDir: string): string {
  145. return join(
  146. homeDir,
  147. ".zcode",
  148. "cli",
  149. "plugins",
  150. "marketplaces",
  151. PLUGIN_LIFECYCLE_MARKETPLACE_ID,
  152. "plugins",
  153. PLUGIN_LIFECYCLE_NAME,
  154. );
  155. }
  156. export async function createInvalidOfficialCollisionFixture(): Promise<string> {
  157. const { homeDir } = getE2EAppDataPaths();
  158. const root = join(homeDir, "fixtures", "plugin-official-name-collision");
  159. await writeJson(join(root, ".claude-plugin", "marketplace.json"), {
  160. name: "zcode-plugins-official",
  161. plugins: [],
  162. });
  163. return root;
  164. }
  165. export async function seedInlineLifecyclePlugin(): Promise<string> {
  166. const { homeDir } = getE2EAppDataPaths();
  167. const root = join(homeDir, "fixtures", PLUGIN_INLINE_NAME);
  168. await writeJson(join(root, ".zcode-plugin", "plugin.json"), {
  169. name: PLUGIN_INLINE_NAME,
  170. version: "1.0.0",
  171. description: "E2E inline plugin lifecycle smoke fixture",
  172. agents: "agents",
  173. skills: "skills",
  174. });
  175. await writeText(
  176. join(root, "agents", "inline-reviewer.md"),
  177. [
  178. "---",
  179. "name: inline-reviewer",
  180. "description: E2E inline Plugin reviewer profile",
  181. "tools:",
  182. " - Read",
  183. "---",
  184. "",
  185. "Review the requested files for the inline Plugin fixture.",
  186. ].join("\n"),
  187. );
  188. await writeText(
  189. join(root, "skills", "inline-lifecycle", "SKILL.md"),
  190. [
  191. "---",
  192. "name: inline-lifecycle",
  193. "description: E2E inline lifecycle runtime marker",
  194. "---",
  195. "",
  196. "# Inline lifecycle",
  197. "",
  198. "E2E_PLUGIN_INLINE_LIFECYCLE_RUNTIME",
  199. ].join("\n"),
  200. );
  201. const configPath = join(homeDir, ".zcode", "cli", "config.json");
  202. const config = await readJsonRecord(configPath);
  203. const plugins = isRecord(config.plugins) ? config.plugins : {};
  204. const enabledPlugins = isRecord(plugins.enabledPlugins) ? plugins.enabledPlugins : {};
  205. await writeJson(configPath, {
  206. ...config,
  207. plugins: {
  208. ...plugins,
  209. dirs: [root],
  210. enabled: true,
  211. enabledPlugins: { ...enabledPlugins, [PLUGIN_INLINE_ID]: true },
  212. },
  213. });
  214. return root;
  215. }
  216. export async function openPluginSettings(scope: "user" | "workspace" = "user"): Promise<void> {
  217. if (scope === "workspace") {
  218. await openPluginManagementSettings();
  219. await selectPluginSettingsScope("workspace");
  220. return;
  221. }
  222. await waitForDefaultWorkspaceReady();
  223. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  224. timeout: 15000,
  225. timeoutMsg: "Plugin lifecycle E2E could not open Settings",
  226. });
  227. await waitForTestIdByDom(TID_SETTINGS_PAGE, { timeout: 15000 });
  228. // Settings 路由已统一使用单数 section id;"plugins" 是旧导航契约。
  229. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "plugin"), {
  230. timeout: 15000,
  231. timeoutMsg: "Settings did not expose the Plugins section",
  232. });
  233. // Plugin 设置页现在只管理已安装插件;商店作为 WorkspaceShell 主视图,由
  234. // “浏览插件/创建”入口进入。旧用例直接等待商店根节点会绕过真实导航路径。
  235. // 该入口有稳定 testid,不按可见文案匹配——否则 i18n 改文案就会断。
  236. await clickTestIdByDom(TID_PLUGIN_STORE_BROWSE, {
  237. timeout: 15000,
  238. timeoutMsg: "Plugins 设置页没有进入商店的真实入口",
  239. });
  240. await waitForPluginControl("plugin-store-root", {}, 30000);
  241. await waitForPluginControl("plugin-store-list", {}, 30000);
  242. }
  243. export async function openPluginManagementSettings(): Promise<void> {
  244. await waitForDefaultWorkspaceReady();
  245. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  246. timeout: 15000,
  247. timeoutMsg: "Workspace Plugin E2E could not open Settings",
  248. });
  249. await waitForTestIdByDom(TID_SETTINGS_PAGE, { timeout: 15000 });
  250. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "plugin"), {
  251. timeout: 15000,
  252. timeoutMsg: "Settings did not expose the Plugin management section",
  253. });
  254. await waitForPluginControl("plugin-settings-scope-trigger", {}, 30000);
  255. }
  256. export async function selectPluginSettingsScope(scope: "user" | "workspace"): Promise<void> {
  257. await browser.waitUntil(
  258. async () =>
  259. browser.execute(() => {
  260. const trigger = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  261. (element) => element.dataset.testid === "plugin-settings-scope-trigger",
  262. );
  263. if (!trigger) return false;
  264. if (trigger.getAttribute("aria-expanded") === "true") return true;
  265. // Radix DropdownMenu 在 pointerdown 上切换 open;仅调用 click 不会打开菜单,
  266. // 这会让 Workspace scope E2E 误判为没有 Workspace 选项。
  267. trigger.dispatchEvent(
  268. new PointerEvent("pointerdown", {
  269. bubbles: true,
  270. button: 0,
  271. ctrlKey: false,
  272. pointerType: "mouse",
  273. }),
  274. );
  275. return true;
  276. }),
  277. { timeout: 10000, timeoutMsg: "Plugin scope trigger did not render" },
  278. );
  279. if (scope === "user") {
  280. await clickTestIdByDom("plugin-settings-scope-user-option");
  281. } else {
  282. await browser.waitUntil(
  283. async () =>
  284. browser.execute(() =>
  285. Boolean(document.querySelector('[data-testid^="plugin-settings-scope-option"]')),
  286. ),
  287. {
  288. timeout: 15000,
  289. timeoutMsg: `Workspace Plugin scope option did not render: ${JSON.stringify(
  290. await browser.execute(() => {
  291. const tabStore = (
  292. window as typeof window & {
  293. __zcodeTabStoreE2E?: {
  294. getState?: () => {
  295. activeWorkspacePath?: string | null;
  296. activeWorkspaceIdentity?: string | null;
  297. tabs?: Array<Record<string, unknown>>;
  298. };
  299. };
  300. }
  301. ).__zcodeTabStoreE2E;
  302. const state = tabStore?.getState?.();
  303. return {
  304. activeWorkspacePath: state?.activeWorkspacePath ?? null,
  305. activeWorkspaceIdentity: state?.activeWorkspaceIdentity ?? null,
  306. tabs: state?.tabs ?? [],
  307. };
  308. }),
  309. )}`,
  310. },
  311. );
  312. await browser.execute(() => {
  313. document.querySelector<HTMLElement>('[data-testid^="plugin-settings-scope-option"]')?.click();
  314. });
  315. }
  316. await waitForPluginScopeSelection("plugin-settings-scope-trigger", scope);
  317. }
  318. export async function waitForPluginSettingsScope(scope: "user" | "workspace"): Promise<void> {
  319. await waitForPluginScopeSelection("plugin-settings-scope-trigger", scope);
  320. }
  321. export async function clickPluginSettingsListBreadcrumb(): Promise<void> {
  322. await browser.waitUntil(
  323. async () =>
  324. browser.execute(() => {
  325. // Marketplace 来源详情的 breadcrumb 是
  326. // Plugin Marketplace > Plugins > 当前插件;这里必须回到中间的 Plugins
  327. // 配置视图,不能点击最左侧 Marketplace 再绕一圈。
  328. const listButton = document.querySelector<HTMLButtonElement>(
  329. '[data-testid="settings-breadcrumb-item"]',
  330. );
  331. if (!listButton) return false;
  332. listButton.click();
  333. return true;
  334. }),
  335. {
  336. timeout: 15000,
  337. timeoutMsg: "Plugin settings breadcrumb did not expose the installed-list back action",
  338. },
  339. );
  340. await waitForPluginControl("plugin-settings-scope-trigger", {}, 30000);
  341. }
  342. export async function openInstalledPluginSettingsDetail(pluginId: string): Promise<void> {
  343. const rowSelector = pluginControlSelector("plugin-settings-plugin-row", {
  344. pluginId,
  345. });
  346. const opened = await browser.execute((selector) => {
  347. const row = document.querySelector<HTMLElement>(selector);
  348. const button = row?.querySelector<HTMLButtonElement>("button");
  349. button?.click();
  350. return Boolean(button);
  351. }, rowSelector);
  352. if (!opened) {
  353. throw new Error(`Could not open installed Plugin detail: ${pluginId}`);
  354. }
  355. await waitForPluginControl("plugin-store-detail", { pluginId });
  356. }
  357. export async function openInstalledPluginSettingsAdvanced(pluginId: string): Promise<void> {
  358. await openInstalledPluginSettingsDetail(pluginId);
  359. const detailSelector = pluginControlSelector("plugin-store-detail", {
  360. pluginId,
  361. });
  362. const expanded = await browser.execute((selector) => {
  363. const details = document.querySelector<HTMLDetailsElement>(`${selector} details`);
  364. if (!details) return false;
  365. details.open = true;
  366. return true;
  367. }, detailSelector);
  368. if (!expanded) {
  369. throw new Error(`Installed Plugin detail has no advanced section: ${pluginId}`);
  370. }
  371. }
  372. export async function waitForDisplayedPluginControl(
  373. testIdValue: string,
  374. attributes: PluginControlAttributes = {},
  375. timeout = 15000,
  376. ): Promise<void> {
  377. const selector = pluginControlSelector(testIdValue, attributes);
  378. await browser.waitUntil(
  379. async () => {
  380. const element = await browser.$(selector);
  381. return (await element.isExisting()) && (await element.isDisplayed());
  382. },
  383. {
  384. timeout,
  385. timeoutMsg: `Plugin UI did not display ${testIdValue} ${JSON.stringify(attributes)}`,
  386. },
  387. );
  388. }
  389. export async function addMarketplaceSourceThroughUi(source: string): Promise<void> {
  390. await waitForPluginControl("plugin-store-create");
  391. await browser.execute(() => {
  392. document
  393. .querySelector<HTMLElement>('[data-testid="plugin-store-create"]')
  394. ?.dispatchEvent(
  395. new PointerEvent("pointerdown", { bubbles: true, button: 0, pointerType: "mouse" }),
  396. );
  397. });
  398. await waitForPluginControl("plugin-store-add-source-menu-item");
  399. await clickPluginControl("plugin-store-add-source-menu-item");
  400. await waitForPluginControl("plugin-store-add-source-dialog");
  401. await setInputValueByTestIdDom("plugin-store-add-source-input", source, {
  402. timeout: 15000,
  403. });
  404. await clickPluginControl("plugin-store-add-source-submit");
  405. }
  406. export async function addLifecycleMarketplaceThroughUi(
  407. fixture: PluginLifecycleFixture,
  408. ): Promise<void> {
  409. await addMarketplaceSourceThroughUi(fixture.marketplaceRoot);
  410. await waitUntilPluginOverview(
  411. (overview) =>
  412. overview.marketplaces.some(
  413. (marketplace) => marketplace.id === PLUGIN_LIFECYCLE_MARKETPLACE_ID,
  414. ),
  415. "Lifecycle marketplace was not persisted after the UI submission",
  416. 60000,
  417. );
  418. await browser.waitUntil(async () => !(await hasPluginControl("plugin-store-add-source-dialog")), {
  419. timeout: 60000,
  420. timeoutMsg: "Lifecycle marketplace completed but the source dialog remained open",
  421. });
  422. }
  423. export async function waitForPluginCard(pluginId: string, timeout = 30000): Promise<void> {
  424. if (!(await hasPluginControl("plugin-store-card", { pluginId }))) {
  425. const marketplaceSeparator = pluginId.lastIndexOf("@");
  426. const marketplaceId =
  427. marketplaceSeparator >= 0 ? pluginId.slice(marketplaceSeparator + 1) : undefined;
  428. const groupKey = marketplaceId ? `marketplace:${marketplaceId}` : undefined;
  429. if (groupKey) {
  430. await browser.waitUntil(
  431. async () =>
  432. (await hasPluginControl("plugin-store-card", { pluginId })) ||
  433. (await hasPluginControl("plugin-store-group-toggle", { groupKey })),
  434. {
  435. timeout,
  436. timeoutMsg: `Plugin marketplace group did not render: ${groupKey}`,
  437. },
  438. );
  439. if (
  440. !(await hasPluginControl("plugin-store-card", { pluginId })) &&
  441. (await hasPluginControl("plugin-store-group-toggle", { groupKey }))
  442. ) {
  443. // 折叠分组只渲染前六张卡片;测试仍通过真实展开入口寻找目标插件。
  444. await clickPluginControl("plugin-store-group-toggle", { groupKey });
  445. }
  446. }
  447. }
  448. await waitForPluginControl("plugin-store-card", { pluginId }, timeout);
  449. }
  450. export async function openPluginCard(pluginId: string): Promise<void> {
  451. await waitForPluginCard(pluginId);
  452. await clickPluginControl("plugin-store-card", { pluginId });
  453. await waitForPluginControl("plugin-store-detail", { pluginId }, 30000);
  454. }
  455. export async function installPluginThroughUi(pluginId: string): Promise<void> {
  456. await clickPluginControl("plugin-store-install", { pluginId });
  457. await waitUntilPluginOverview(
  458. (overview) => overview.installedPlugins.some((plugin) => plugin.id === pluginId),
  459. `Plugin did not install through UI: ${pluginId}`,
  460. 120000,
  461. );
  462. }
  463. export async function setPluginEnabledThroughUi(
  464. pluginId: string,
  465. enabled: boolean,
  466. entry: "detail" | "manage" = "detail",
  467. ): Promise<void> {
  468. if (entry === "manage") {
  469. const current = await readPluginControlChecked("plugin-settings-enabled-switch", { pluginId });
  470. if (current !== enabled)
  471. await clickPluginControl("plugin-settings-enabled-switch", { pluginId });
  472. } else {
  473. const list = await getPluginList();
  474. if (list.plugins.find((plugin) => plugin.id === pluginId)?.enabled !== enabled) {
  475. await clickPluginControl("plugin-store-item-menu", { pluginId });
  476. await clickPluginControl("plugin-store-menu-enabled", { pluginId });
  477. }
  478. }
  479. await waitUntilPluginList(
  480. (list) => list.plugins.some((plugin) => plugin.id === pluginId && plugin.enabled === enabled),
  481. `Plugin enabled state did not become ${enabled}: ${pluginId}`,
  482. );
  483. }
  484. export async function configureLifecyclePluginThroughUi(value: string): Promise<void> {
  485. await clickPluginControl("plugin-store-advanced");
  486. await setPluginControlValue(
  487. "plugin-store-config-input",
  488. { configKey: PLUGIN_LIFECYCLE_CONFIG_KEY },
  489. value,
  490. );
  491. await clickPluginControl("plugin-store-config-save", {
  492. pluginId: PLUGIN_LIFECYCLE_ID,
  493. });
  494. await browser.waitUntil(
  495. async () => (await readPluginConfigOptions())[PLUGIN_LIFECYCLE_CONFIG_KEY] === value,
  496. { timeout: 30000, timeoutMsg: "Plugin configuration did not persist" },
  497. );
  498. }
  499. export async function uninstallPluginThroughUi(pluginId: string, confirm: boolean): Promise<void> {
  500. await clickPluginControl("plugin-store-item-menu", { pluginId });
  501. await clickPluginControl("plugin-store-menu-uninstall", { pluginId });
  502. await waitForPluginControl("plugin-store-uninstall-dialog");
  503. await clickPluginControl(
  504. confirm ? "plugin-store-uninstall-confirm" : "plugin-store-uninstall-cancel",
  505. );
  506. if (confirm) {
  507. await waitUntilPluginOverview(
  508. (overview) => !overview.installedPlugins.some((plugin) => plugin.id === pluginId),
  509. `Plugin remained installed after confirmation: ${pluginId}`,
  510. 120000,
  511. );
  512. } else {
  513. await waitUntilPluginOverview(
  514. (overview) => overview.installedPlugins.some((plugin) => plugin.id === pluginId),
  515. `Cancelling uninstall changed installation: ${pluginId}`,
  516. );
  517. }
  518. }
  519. export async function openManageView(): Promise<void> {
  520. await clickPluginControl("plugin-store-manage-open");
  521. await waitForPluginControl("plugin-store-manage");
  522. }
  523. export async function openSourcesDialog(): Promise<void> {
  524. await clickPluginControl("plugin-store-sources-open");
  525. await waitForPluginControl("plugin-store-sources-dialog");
  526. }
  527. export async function removeMarketplaceSourceThroughUi(marketplaceId: string): Promise<void> {
  528. await openSourcesDialog();
  529. await clickPluginControl("plugin-store-source-remove", { marketplaceId });
  530. await browser.waitUntil(
  531. async () => !(await hasPluginControl("plugin-store-source-row", { marketplaceId })),
  532. {
  533. timeout: 30000,
  534. timeoutMsg: `Marketplace source was not removed: ${marketplaceId}`,
  535. },
  536. );
  537. // 来源删除完成后通过弹窗标准 Escape 入口返回商店;否则 overlay 会拦截后续管理入口。
  538. await browser.keys(["Escape"]);
  539. await browser.waitUntil(async () => !(await hasPluginControl("plugin-store-sources-dialog")), {
  540. timeout: 10000,
  541. timeoutMsg: "Marketplace sources dialog did not close",
  542. });
  543. }
  544. export async function clickPluginControl(
  545. testIdValue: string,
  546. attributes: PluginControlAttributes = {},
  547. ): Promise<void> {
  548. let latest = "not-started";
  549. const selector = pluginControlSelector(testIdValue, attributes);
  550. try {
  551. await browser.waitUntil(
  552. async () => {
  553. const elements = await browser.$$(selector);
  554. if ((await elements.length) === 0) {
  555. latest = "missing";
  556. return false;
  557. }
  558. let sawHidden = false;
  559. let sawDisabled = false;
  560. for (const element of elements) {
  561. if (!(await element.isDisplayed())) {
  562. sawHidden = true;
  563. continue;
  564. }
  565. if (!(await element.isEnabled())) {
  566. sawDisabled = true;
  567. continue;
  568. }
  569. try {
  570. await element.scrollIntoView();
  571. await element.click();
  572. latest = "clicked";
  573. return true;
  574. } catch (error) {
  575. latest = error instanceof Error ? error.message : String(error);
  576. }
  577. }
  578. latest = sawDisabled ? "disabled" : sawHidden ? "hidden" : latest;
  579. return false;
  580. },
  581. { timeout: 30000 },
  582. );
  583. } catch (error) {
  584. const dialogs = await browser.execute(() =>
  585. Array.from(document.querySelectorAll<HTMLElement>('[role="alertdialog"], [role="dialog"]'))
  586. .filter((element) => element.getBoundingClientRect().height > 0)
  587. .map((element) => element.innerText.slice(0, 1000)),
  588. );
  589. await capturePluginManualReview("PLM-UI-FAIL", testIdValue).catch(() => {});
  590. throw new Error(
  591. `Could not click ${testIdValue}: ${latest}; dialogs=${JSON.stringify(dialogs)}`,
  592. { cause: error },
  593. );
  594. }
  595. }
  596. function pluginControlSelector(testIdValue: string, attributes: PluginControlAttributes): string {
  597. const selectors = [`[data-testid=${JSON.stringify(testIdValue)}]`];
  598. const attributeEntries: Array<[string, string | undefined]> = [
  599. ["data-plugin-id", attributes.pluginId],
  600. ["data-marketplace-id", attributes.marketplaceId],
  601. ["data-group-key", attributes.groupKey],
  602. ["data-component-kind", attributes.componentKind],
  603. ["data-config-key", attributes.configKey],
  604. ];
  605. for (const [name, value] of attributeEntries) {
  606. if (value) selectors.push(`[${name}=${JSON.stringify(value)}]`);
  607. }
  608. return selectors.join("");
  609. }
  610. export async function waitForPluginControl(
  611. testIdValue: string,
  612. attributes: PluginControlAttributes = {},
  613. timeout = 15000,
  614. ): Promise<void> {
  615. await browser.waitUntil(() => hasPluginControl(testIdValue, attributes), {
  616. timeout,
  617. timeoutMsg: `Plugin UI did not render ${testIdValue} ${JSON.stringify(attributes)}`,
  618. });
  619. }
  620. export async function hasPluginControl(
  621. testIdValue: string,
  622. attributes: PluginControlAttributes = {},
  623. ): Promise<boolean> {
  624. return browser.execute(
  625. (id, expected) =>
  626. Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).some(
  627. (candidate) =>
  628. candidate.dataset.testid === id &&
  629. (!expected.pluginId || candidate.dataset.pluginId === expected.pluginId) &&
  630. (!expected.marketplaceId || candidate.dataset.marketplaceId === expected.marketplaceId) &&
  631. (!expected.groupKey || candidate.dataset.groupKey === expected.groupKey) &&
  632. (!expected.componentKind || candidate.dataset.componentKind === expected.componentKind) &&
  633. (!expected.configKey || candidate.dataset.configKey === expected.configKey),
  634. ),
  635. testIdValue,
  636. attributes,
  637. );
  638. }
  639. async function waitForPluginScopeSelection(
  640. triggerTestId: string,
  641. scope: "user" | "workspace",
  642. ): Promise<void> {
  643. await browser.waitUntil(
  644. () =>
  645. browser.execute(
  646. (id, expectedScope) => {
  647. const trigger = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  648. (candidate) => candidate.dataset.testid === id,
  649. );
  650. const selectedKey = trigger?.dataset.pluginScopeKey;
  651. return expectedScope === "user"
  652. ? selectedKey === "user"
  653. : Boolean(selectedKey && selectedKey !== "user");
  654. },
  655. triggerTestId,
  656. scope,
  657. ),
  658. {
  659. timeout: 15000,
  660. timeoutMsg: `Plugin scope trigger did not select ${scope}: ${triggerTestId}`,
  661. },
  662. );
  663. }
  664. export async function getPluginControlText(
  665. testIdValue: string,
  666. attributes: PluginControlAttributes = {},
  667. ): Promise<string> {
  668. return browser.execute(
  669. (id, expected) =>
  670. Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  671. (candidate) =>
  672. candidate.dataset.testid === id &&
  673. (!expected.pluginId || candidate.dataset.pluginId === expected.pluginId) &&
  674. (!expected.marketplaceId || candidate.dataset.marketplaceId === expected.marketplaceId),
  675. )?.textContent ?? "",
  676. testIdValue,
  677. attributes,
  678. );
  679. }
  680. export async function setPluginPresentation(input: {
  681. locale: "zh-CN" | "en-US";
  682. theme: "zai-light" | "zai-dark";
  683. width: number;
  684. height: number;
  685. }): Promise<void> {
  686. await setCurrentElectronRendererContentSize(input.width, input.height);
  687. await browser.executeAsync((next, done: (result?: string) => void) => {
  688. const actions = (
  689. window as typeof window & {
  690. __testActions?: Record<string, unknown>;
  691. }
  692. ).__testActions;
  693. const setLocale = actions?.setLocale;
  694. const setTheme = actions?.setTheme;
  695. if (typeof setLocale !== "function" || typeof setTheme !== "function") {
  696. done("missing locale/theme test action");
  697. return;
  698. }
  699. (setLocale as (value: string) => void)(next.locale);
  700. (setTheme as (value: string) => void)(next.theme);
  701. requestAnimationFrame(() => done());
  702. }, input);
  703. }
  704. export async function assertPluginStoreFitsViewport(): Promise<void> {
  705. const layout = await browser.execute(() => {
  706. const root = document.querySelector<HTMLElement>('[data-testid="plugin-store-root"]');
  707. return {
  708. clientWidth: root?.clientWidth ?? 0,
  709. scrollWidth: root?.scrollWidth ?? 0,
  710. viewportWidth: window.innerWidth,
  711. };
  712. });
  713. expect(layout.clientWidth).toBeGreaterThan(0);
  714. expect(layout.scrollWidth).toBeLessThanOrEqual(layout.clientWidth + 1);
  715. expect(layout.clientWidth).toBeLessThanOrEqual(layout.viewportWidth);
  716. }
  717. export async function capturePluginManualReview(caseId: string, label: string): Promise<string> {
  718. const artifactDir = join(
  719. process.cwd(),
  720. ".e2e-artifacts",
  721. "plugin-management",
  722. caseId.toLowerCase(),
  723. );
  724. await mkdir(artifactDir, { recursive: true });
  725. const path = join(artifactDir, `${label.replaceAll(/[^a-z0-9-]/giu, "-")}.png`);
  726. // 人工评审截图要反映稳定态:等有限时长的过渡/动画(分段切换、面板展开)结束,
  727. // 否则会截到旧选中态与新内容并存的中间帧。无限循环的加载动画不参与判断。
  728. await browser
  729. .waitUntil(
  730. async () =>
  731. browser.execute(
  732. () =>
  733. document
  734. .getAnimations()
  735. .filter(
  736. (animation) =>
  737. animation.playState === "running" &&
  738. animation.effect?.getTiming().iterations !== Infinity,
  739. ).length === 0,
  740. ),
  741. { timeout: 3000, interval: 100 },
  742. )
  743. .catch(() => undefined);
  744. await browser.saveScreenshot(path);
  745. return path;
  746. }
  747. export async function restartPluginLifecycleApp(): Promise<void> {
  748. await browser.reloadSession();
  749. await browser.waitUntil(
  750. async () => {
  751. try {
  752. return (await browser.getUrl()).startsWith("file://");
  753. } catch {
  754. return false;
  755. }
  756. },
  757. {
  758. timeout: 60000,
  759. timeoutMsg: "Electron renderer did not recover after reloadSession",
  760. },
  761. );
  762. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  763. }
  764. export async function getPluginOverview(
  765. workspacePath = DEFAULT_WORKSPACE,
  766. configScope?: "user" | "workspace",
  767. ): Promise<ZCodePluginsOverviewResult> {
  768. return callPluginTestAction("getPluginsOverview", {
  769. workspacePath,
  770. ...(configScope ? { configScope } : {}),
  771. });
  772. }
  773. export async function addMarketplaceSourceThroughAgent(
  774. source: string,
  775. workspacePath = DEFAULT_WORKSPACE,
  776. ): Promise<ZCodePluginsMarketplaceMutationResult> {
  777. return callPluginTestAction("addPluginMarketplace", {
  778. source,
  779. workspacePath,
  780. });
  781. }
  782. export async function updateMarketplaceThroughAgent(
  783. marketplace: string,
  784. workspacePath = DEFAULT_WORKSPACE,
  785. ): Promise<ZCodePluginsMarketplaceMutationResult> {
  786. return callPluginTestAction("updatePluginMarketplace", {
  787. marketplace,
  788. workspacePath,
  789. });
  790. }
  791. export async function installMarketplacePluginThroughAgent(
  792. pluginName: string,
  793. marketplace: string,
  794. workspacePath = DEFAULT_WORKSPACE,
  795. ): Promise<ZCodePluginsInstallResult> {
  796. return callPluginTestAction("installPlugin", {
  797. marketplace,
  798. pluginName,
  799. scope: "user",
  800. workspacePath,
  801. });
  802. }
  803. export async function getPluginList(
  804. workspacePath = DEFAULT_WORKSPACE,
  805. workspaceIdentity?: string,
  806. configScope?: "user" | "workspace",
  807. ): Promise<ZCodePluginsListResult> {
  808. return callPluginTestAction("listPlugins", {
  809. workspacePath,
  810. ...(workspaceIdentity ? { workspaceIdentity } : {}),
  811. ...(configScope ? { configScope } : {}),
  812. });
  813. }
  814. export async function getPluginReferenceCatalog(
  815. options: {
  816. sessionId?: string;
  817. workspaceIdentity?: string;
  818. workspacePath?: string;
  819. } = {},
  820. ): Promise<ZCodePluginsReferenceCatalogResult> {
  821. return callPluginTestAction("getPluginReferenceCatalog", {
  822. workspacePath: options.workspacePath ?? DEFAULT_WORKSPACE,
  823. ...(options.workspaceIdentity ? { workspaceIdentity: options.workspaceIdentity } : {}),
  824. ...(options.sessionId ? { sessionId: options.sessionId } : {}),
  825. });
  826. }
  827. export async function waitUntilPluginOverview(
  828. predicate: (overview: ZCodePluginsOverviewResult) => boolean,
  829. timeoutMsg: string,
  830. timeout = 30000,
  831. ): Promise<void> {
  832. await browser.waitUntil(async () => predicate(await getPluginOverview()), {
  833. timeout,
  834. timeoutMsg,
  835. });
  836. }
  837. export async function waitUntilPluginList(
  838. predicate: (list: ZCodePluginsListResult) => boolean,
  839. timeoutMsg: string,
  840. timeout = 30000,
  841. ): Promise<void> {
  842. await browser.waitUntil(async () => predicate(await getPluginList()), {
  843. timeout,
  844. timeoutMsg,
  845. });
  846. }
  847. export async function waitForPluginDraftRuntimeInvalidation(
  848. workspacePath = DEFAULT_WORKSPACE,
  849. timeout = 30000,
  850. ): Promise<void> {
  851. await browser.waitUntil(
  852. () =>
  853. browser.execute((path) => {
  854. const store = (
  855. window as typeof window & {
  856. __zcodeSessionStoreE2E?: {
  857. getState: () => {
  858. getWorkspaceState: (workspacePath: string) => {
  859. draftSessionId: string | null;
  860. };
  861. };
  862. };
  863. }
  864. ).__zcodeSessionStoreE2E;
  865. return store?.getState().getWorkspaceState(path).draftSessionId === null;
  866. }, workspacePath),
  867. {
  868. timeout,
  869. timeoutMsg: "Plugin runtime refresh did not invalidate the deferred draft session",
  870. },
  871. );
  872. }
  873. export async function readPluginConfigOptions(): Promise<Record<string, unknown>> {
  874. const config = await readJsonRecord(
  875. join(getE2EAppDataPaths().homeDir, ".zcode", "cli", "config.json"),
  876. );
  877. const plugins = isRecord(config.plugins) ? config.plugins : {};
  878. const options = isRecord(plugins.options) ? plugins.options : {};
  879. return isRecord(options[PLUGIN_LIFECYCLE_ID]) ? options[PLUGIN_LIFECYCLE_ID] : {};
  880. }
  881. export function pluginStoragePath(...segments: string[]): string {
  882. return join(getE2EAppDataPaths().homeDir, ".zcode", "cli", "plugins", ...segments);
  883. }
  884. export function pluginDataPath(pluginId: string): string {
  885. return pluginStoragePath("data", pluginId);
  886. }
  887. export function pluginPathExists(path: string): boolean {
  888. return existsSync(path);
  889. }
  890. async function readPluginControlChecked(
  891. testIdValue: string,
  892. attributes: PluginControlAttributes,
  893. ): Promise<boolean> {
  894. await waitForPluginControl(testIdValue, attributes);
  895. return browser.execute(
  896. (id, expected) => {
  897. const element = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  898. (candidate) =>
  899. candidate.dataset.testid === id &&
  900. (!expected.pluginId || candidate.dataset.pluginId === expected.pluginId),
  901. );
  902. return element?.getAttribute("data-state") === "checked";
  903. },
  904. testIdValue,
  905. attributes,
  906. );
  907. }
  908. async function setPluginControlValue(
  909. testIdValue: string,
  910. attributes: PluginControlAttributes,
  911. value: string,
  912. ): Promise<void> {
  913. await waitForPluginControl(testIdValue, attributes);
  914. const result = await browser.execute(
  915. (id, expected, nextValue) => {
  916. const element = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  917. (candidate) =>
  918. candidate.dataset.testid === id &&
  919. (!expected.configKey || candidate.dataset.configKey === expected.configKey),
  920. );
  921. if (!(element instanceof HTMLInputElement)) return false;
  922. const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
  923. setter?.call(element, nextValue);
  924. element.dispatchEvent(new InputEvent("input", { bubbles: true, data: nextValue }));
  925. element.dispatchEvent(new Event("change", { bubbles: true }));
  926. return true;
  927. },
  928. testIdValue,
  929. attributes,
  930. value,
  931. );
  932. if (!result) throw new Error(`Could not set ${testIdValue} to ${value}`);
  933. }
  934. async function callPluginTestAction<T>(
  935. actionName: PluginTestActionName,
  936. params: unknown,
  937. ): Promise<T> {
  938. await browser.waitUntil(
  939. () =>
  940. browser.execute(
  941. (name) =>
  942. typeof (
  943. window as typeof window & {
  944. __testActions?: Record<string, unknown>;
  945. }
  946. ).__testActions?.[name] === "function",
  947. actionName,
  948. ),
  949. {
  950. timeout: 30_000,
  951. timeoutMsg: `plugin test action did not become ready: ${actionName}`,
  952. },
  953. );
  954. const result = (await browser.executeAsync(
  955. (
  956. name: PluginTestActionName,
  957. input: unknown,
  958. done: (result: SerializedActionResult<unknown>) => void,
  959. ) => {
  960. const actions = (
  961. window as typeof window & {
  962. __testActions?: Record<string, unknown>;
  963. }
  964. ).__testActions;
  965. const action = actions?.[name];
  966. if (typeof action !== "function") {
  967. done({ ok: false, error: `missing test action: ${name}` });
  968. return;
  969. }
  970. Promise.resolve((action as (value: unknown) => Promise<unknown>)(input))
  971. .then((value) => done({ ok: true, value }))
  972. .catch((error: unknown) =>
  973. done({
  974. ok: false,
  975. error: error instanceof Error ? error.message : String(error),
  976. }),
  977. );
  978. },
  979. actionName,
  980. params,
  981. )) as SerializedActionResult<unknown>;
  982. if (!result.ok) throw new Error(result.error ?? `test action failed: ${actionName}`);
  983. return result.value as T;
  984. }
  985. async function writeLifecyclePlugin(
  986. pluginRoot: string,
  987. version: string,
  988. withUi = false,
  989. ): Promise<void> {
  990. await writeJson(join(pluginRoot, ".zcode-plugin", "plugin.json"), {
  991. name: PLUGIN_LIFECYCLE_NAME,
  992. version,
  993. description: `E2E plugin management lifecycle fixture ${version}`,
  994. author: { name: "ZCode E2E" },
  995. homepage: "https://example.com/e2e-plugin-lifecycle",
  996. commands: "commands",
  997. agents: "agents",
  998. skills: "skills",
  999. hooks: "hooks/hooks.json",
  1000. mcpServers: {
  1001. lifecycle: {
  1002. type: "stdio",
  1003. command: "node",
  1004. args: ["${ZCODE_PLUGIN_ROOT}/server.mjs", version],
  1005. },
  1006. },
  1007. ...(withUi
  1008. ? {
  1009. ui: {
  1010. surfaces: [
  1011. {
  1012. id: "panel",
  1013. title: "Lifecycle Panel",
  1014. server: "lifecycle",
  1015. resourceUri: "ui://lifecycle/panel.html",
  1016. availability: "session",
  1017. },
  1018. ],
  1019. },
  1020. }
  1021. : {}),
  1022. userConfig: {
  1023. [PLUGIN_LIFECYCLE_CONFIG_KEY]: {
  1024. type: "string",
  1025. title: "Lifecycle label",
  1026. default: `fixture-${version}`,
  1027. description: "Non-sensitive E2E lifecycle option",
  1028. },
  1029. [PLUGIN_LIFECYCLE_INHERITED_CONFIG_KEY]: {
  1030. type: "number",
  1031. title: "Timeout seconds",
  1032. default: 30,
  1033. description: "Inherited non-sensitive E2E lifecycle option",
  1034. },
  1035. },
  1036. });
  1037. await writeText(
  1038. join(pluginRoot, "skills", "lifecycle-version", "SKILL.md"),
  1039. [
  1040. "---",
  1041. "name: lifecycle-version",
  1042. `description: ${PLUGIN_LIFECYCLE_RUNTIME_MARKER}_${version}`,
  1043. "---",
  1044. "",
  1045. "# Lifecycle version",
  1046. "",
  1047. `${PLUGIN_LIFECYCLE_RUNTIME_MARKER}_${version}`,
  1048. ].join("\n"),
  1049. );
  1050. await writeText(
  1051. join(pluginRoot, "commands", "lifecycle-command.md"),
  1052. `---\ndescription: Lifecycle command ${version}\n---\n\nReport ${PLUGIN_LIFECYCLE_RUNTIME_MARKER}_${version}.\n`,
  1053. );
  1054. await writeText(
  1055. join(pluginRoot, "agents", "lifecycle-reviewer.md"),
  1056. `---\nname: lifecycle-reviewer\ndescription: Lifecycle subagent ${version}\ntools:\n - Read\n---\nReport ${PLUGIN_LIFECYCLE_RUNTIME_MARKER}_${version}.\n`,
  1057. );
  1058. await writeJson(join(pluginRoot, "hooks", "hooks.json"), {
  1059. hooks: {
  1060. SessionStart: [
  1061. {
  1062. matcher: "startup",
  1063. hooks: [{ type: "command", command: "echo E2E_PLUGIN_LIFECYCLE_HOOK" }],
  1064. },
  1065. ],
  1066. },
  1067. });
  1068. await writeText(join(pluginRoot, "server.mjs"), buildDependencyFreeMcpServer(version, withUi));
  1069. }
  1070. async function writeSimplePlugin(pluginRoot: string, index: number): Promise<void> {
  1071. await writeJson(join(pluginRoot, ".zcode-plugin", "plugin.json"), {
  1072. name: `e2e-lifecycle-extra-${index}`,
  1073. version: "1.0.0",
  1074. description: `E2E lifecycle category expansion plugin ${index}`,
  1075. skills: "skills",
  1076. });
  1077. await writeText(
  1078. join(pluginRoot, "skills", `extra-${index}`, "SKILL.md"),
  1079. `---\ndescription: E2E extra lifecycle skill ${index}\n---\n\n# Extra ${index}\n`,
  1080. );
  1081. }
  1082. async function writeMarketplaceManifest(marketplaceRoot: string, version: string): Promise<void> {
  1083. const extras = Array.from({ length: 7 }, (_, offset) => {
  1084. const index = offset + 1;
  1085. return {
  1086. name: `e2e-lifecycle-extra-${index}`,
  1087. version: "1.0.0",
  1088. description: `E2E lifecycle category expansion plugin ${index}`,
  1089. category: "productivity",
  1090. source: `./plugins/e2e-lifecycle-extra-${index}`,
  1091. };
  1092. });
  1093. await writeJson(join(marketplaceRoot, ".claude-plugin", "marketplace.json"), {
  1094. name: PLUGIN_LIFECYCLE_MARKETPLACE_ID,
  1095. description: PLUGIN_LIFECYCLE_MARKETPLACE_NAME,
  1096. plugins: [
  1097. {
  1098. name: PLUGIN_LIFECYCLE_NAME,
  1099. version,
  1100. displayName: "Lifecycle Fixture",
  1101. displayName_i18n: { "zh-CN": "生命周期测试插件" },
  1102. description: `Deterministic plugin lifecycle fixture ${version}`,
  1103. description_i18n: { "zh-CN": `确定性插件生命周期测试 ${version}` },
  1104. category: "productivity",
  1105. author: { name: "ZCode E2E", url: "https://example.com" },
  1106. homepage: "https://example.com/e2e-plugin-lifecycle",
  1107. privacyPolicy: "https://example.com/privacy",
  1108. termsOfService: "https://example.com/terms",
  1109. examplePrompts: [PLUGIN_LIFECYCLE_EXAMPLE_PROMPT],
  1110. source: `./plugins/${PLUGIN_LIFECYCLE_NAME}`,
  1111. },
  1112. ...extras,
  1113. ],
  1114. });
  1115. }
  1116. function buildDependencyFreeMcpServer(version: string, withUi = false): string {
  1117. const html =
  1118. '<!doctype html><html><body><h1 id="market-ui-ready">Connecting</h1><script>window.zcode.ready().then(() => { document.getElementById("market-ui-ready").textContent = "PLUGIN_MARKET_UI_READY"; });</script></body></html>';
  1119. return `#!/usr/bin/env node
  1120. import readline from "node:readline";
  1121. const version = process.argv[2] || ${JSON.stringify(version)};
  1122. const input = readline.createInterface({ input: process.stdin });
  1123. function send(message) { process.stdout.write(JSON.stringify(message) + "\\n"); }
  1124. input.on("line", (line) => {
  1125. let request;
  1126. try { request = JSON.parse(line); } catch { return; }
  1127. if (request.method === "initialize") {
  1128. send({ jsonrpc: "2.0", id: request.id, result: { protocolVersion: "2024-11-05", capabilities: { tools: {}, ${withUi ? "resources: {}," : ""} }, serverInfo: { name: "e2e-plugin-lifecycle", version } } });
  1129. return;
  1130. }
  1131. if (request.method === "tools/list") {
  1132. send({ jsonrpc: "2.0", id: request.id, result: { tools: [{ name: "version_marker", description: "Return the deterministic lifecycle version marker", inputSchema: { type: "object", properties: {} } }] } });
  1133. return;
  1134. }
  1135. if (request.method === "tools/call") {
  1136. send({ jsonrpc: "2.0", id: request.id, result: { content: [{ type: "text", text: ${JSON.stringify(PLUGIN_LIFECYCLE_RUNTIME_MARKER)} + "_" + version }] } });
  1137. return;
  1138. }
  1139. ${
  1140. withUi
  1141. ? `if (request.method === "resources/list") {
  1142. send({ jsonrpc: "2.0", id: request.id, result: { resources: [{ uri: "ui://lifecycle/panel.html", name: "Lifecycle Panel", mimeType: "text/html;profile=mcp-app" }] } }); return;
  1143. }
  1144. if (request.method === "resources/read") {
  1145. send({ jsonrpc: "2.0", id: request.id, result: { contents: [{ uri: request.params.uri, mimeType: "text/html;profile=mcp-app", text: ${JSON.stringify(html)} }] } }); return;
  1146. }`
  1147. : ""
  1148. }
  1149. if (request.id !== undefined) send({ jsonrpc: "2.0", id: request.id, result: {} });
  1150. });
  1151. `;
  1152. }
  1153. async function readJsonRecord(path: string): Promise<Record<string, unknown>> {
  1154. try {
  1155. const parsed = JSON.parse(await readFile(path, "utf-8")) as unknown;
  1156. return isRecord(parsed) ? parsed : {};
  1157. } catch (error) {
  1158. if (
  1159. typeof error === "object" &&
  1160. error !== null &&
  1161. "code" in error &&
  1162. (error as { code?: unknown }).code === "ENOENT"
  1163. ) {
  1164. return {};
  1165. }
  1166. throw error;
  1167. }
  1168. }
  1169. async function writeJson(path: string, value: unknown): Promise<void> {
  1170. await writeText(path, `${JSON.stringify(value, null, 2)}\n`);
  1171. }
  1172. async function writeText(path: string, value: string): Promise<void> {
  1173. await mkdir(dirname(path), { recursive: true });
  1174. await writeFile(path, value, "utf-8");
  1175. }
  1176. function isRecord(value: unknown): value is Record<string, unknown> {
  1177. return typeof value === "object" && value !== null && !Array.isArray(value);
  1178. }