plugin-management-lifecycle.ts 47 KB

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