plugin-management-lifecycle.ts 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  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. // 管理列表行已改为复用 PluginStoreCard(整卡 role=button),行内第一个 <button> 是更新/菜单等子按钮,
  536. // 点它进不了详情;必须点卡片本身。
  537. await $(
  538. `[data-testid="plugin-settings-plugin-row"][data-plugin-id="${PLUGIN_LIFECYCLE_ID}"] [data-testid="plugin-store-card"]`,
  539. ).click();
  540. }
  541. await clickPluginControl("plugin-store-advanced");
  542. await setPluginControlValue(
  543. "plugin-store-config-input",
  544. { configKey: PLUGIN_LIFECYCLE_CONFIG_KEY },
  545. value,
  546. );
  547. await clickPluginControl("plugin-store-config-save", {
  548. pluginId: PLUGIN_LIFECYCLE_ID,
  549. });
  550. await browser.waitUntil(
  551. async () => (await readPluginConfigOptions())[PLUGIN_LIFECYCLE_CONFIG_KEY] === value,
  552. { timeout: 30000, timeoutMsg: "Plugin configuration did not persist" },
  553. );
  554. if (fromStore) {
  555. await clickPluginControl("plugin-settings-detail-back");
  556. // 管理页「浏览全部」按钮已改为返回图标。
  557. await clickPluginControl("plugin-store-manage-back");
  558. await clickPluginControl("plugin-store-segment-personal");
  559. await openPluginCard(PLUGIN_LIFECYCLE_ID);
  560. }
  561. }
  562. export async function uninstallPluginThroughUi(pluginId: string, confirm: boolean): Promise<void> {
  563. await clickPluginControl("plugin-store-item-menu", { pluginId });
  564. await clickPluginControl("plugin-store-menu-uninstall", { pluginId });
  565. await waitForPluginControl("plugin-store-uninstall-dialog");
  566. await clickPluginControl(
  567. confirm ? "plugin-store-uninstall-confirm" : "plugin-store-uninstall-cancel",
  568. );
  569. if (confirm) {
  570. await waitUntilPluginOverview(
  571. (overview) => !overview.installedPlugins.some((plugin) => plugin.id === pluginId),
  572. `Plugin remained installed after confirmation: ${pluginId}`,
  573. 120000,
  574. );
  575. } else {
  576. await waitUntilPluginOverview(
  577. (overview) => overview.installedPlugins.some((plugin) => plugin.id === pluginId),
  578. `Cancelling uninstall changed installation: ${pluginId}`,
  579. );
  580. }
  581. }
  582. export async function openManageView(): Promise<void> {
  583. await clickPluginControl("plugin-store-manage-open");
  584. await waitForPluginControl("plugin-store-manage");
  585. }
  586. export async function openSourcesDialog(): Promise<void> {
  587. await clickPluginControl("plugin-store-sources-open");
  588. await waitForPluginControl("plugin-store-sources-dialog");
  589. }
  590. export async function removeMarketplaceSourceThroughUi(marketplaceId: string): Promise<void> {
  591. await openSourcesDialog();
  592. await clickPluginControl("plugin-store-source-remove", { marketplaceId });
  593. await browser.waitUntil(
  594. async () => !(await hasPluginControl("plugin-store-source-row", { marketplaceId })),
  595. {
  596. timeout: 30000,
  597. timeoutMsg: `Marketplace source was not removed: ${marketplaceId}`,
  598. },
  599. );
  600. // 来源删除完成后通过弹窗标准 Escape 入口返回商店;否则 overlay 会拦截后续管理入口。
  601. await browser.keys(["Escape"]);
  602. await browser.waitUntil(async () => !(await hasPluginControl("plugin-store-sources-dialog")), {
  603. timeout: 10000,
  604. timeoutMsg: "Marketplace sources dialog did not close",
  605. });
  606. }
  607. export async function clickPluginControl(
  608. testIdValue: string,
  609. attributes: PluginControlAttributes = {},
  610. ): Promise<void> {
  611. let latest = "not-started";
  612. const selector = pluginControlSelector(testIdValue, attributes);
  613. try {
  614. await browser.waitUntil(
  615. async () => {
  616. const elements = await browser.$$(selector);
  617. if ((await elements.length) === 0) {
  618. latest = "missing";
  619. return false;
  620. }
  621. let sawHidden = false;
  622. let sawDisabled = false;
  623. for (const element of elements) {
  624. if (!(await element.isDisplayed())) {
  625. sawHidden = true;
  626. continue;
  627. }
  628. if (!(await element.isEnabled())) {
  629. sawDisabled = true;
  630. continue;
  631. }
  632. try {
  633. await element.scrollIntoView();
  634. await element.click();
  635. latest = "clicked";
  636. return true;
  637. } catch (error) {
  638. latest = error instanceof Error ? error.message : String(error);
  639. }
  640. }
  641. latest = sawDisabled ? "disabled" : sawHidden ? "hidden" : latest;
  642. return false;
  643. },
  644. { timeout: 30000 },
  645. );
  646. } catch (error) {
  647. const dialogs = await browser.execute(() =>
  648. Array.from(document.querySelectorAll<HTMLElement>('[role="alertdialog"], [role="dialog"]'))
  649. .filter((element) => element.getBoundingClientRect().height > 0)
  650. .map((element) => element.innerText.slice(0, 1000)),
  651. );
  652. await capturePluginManualReview("PLM-UI-FAIL", testIdValue).catch(() => {});
  653. throw new Error(
  654. `Could not click ${testIdValue}: ${latest}; dialogs=${JSON.stringify(dialogs)}`,
  655. { cause: error },
  656. );
  657. }
  658. }
  659. function pluginControlSelector(testIdValue: string, attributes: PluginControlAttributes): string {
  660. const selectors = [`[data-testid=${JSON.stringify(testIdValue)}]`];
  661. const attributeEntries: Array<[string, string | undefined]> = [
  662. ["data-plugin-id", attributes.pluginId],
  663. ["data-marketplace-id", attributes.marketplaceId],
  664. ["data-group-key", attributes.groupKey],
  665. ["data-component-kind", attributes.componentKind],
  666. ["data-config-key", attributes.configKey],
  667. ];
  668. for (const [name, value] of attributeEntries) {
  669. if (value) selectors.push(`[${name}=${JSON.stringify(value)}]`);
  670. }
  671. return selectors.join("");
  672. }
  673. export async function waitForPluginControl(
  674. testIdValue: string,
  675. attributes: PluginControlAttributes = {},
  676. timeout = 15000,
  677. ): Promise<void> {
  678. await browser.waitUntil(() => hasPluginControl(testIdValue, attributes), {
  679. timeout,
  680. timeoutMsg: `Plugin UI did not render ${testIdValue} ${JSON.stringify(attributes)}`,
  681. });
  682. }
  683. export async function hasPluginControl(
  684. testIdValue: string,
  685. attributes: PluginControlAttributes = {},
  686. ): Promise<boolean> {
  687. return browser.execute(
  688. (id, expected) =>
  689. Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).some(
  690. (candidate) =>
  691. candidate.dataset.testid === id &&
  692. (!expected.pluginId || candidate.dataset.pluginId === expected.pluginId) &&
  693. (!expected.marketplaceId || candidate.dataset.marketplaceId === expected.marketplaceId) &&
  694. (!expected.groupKey || candidate.dataset.groupKey === expected.groupKey) &&
  695. (!expected.componentKind || candidate.dataset.componentKind === expected.componentKind) &&
  696. (!expected.configKey || candidate.dataset.configKey === expected.configKey),
  697. ),
  698. testIdValue,
  699. attributes,
  700. );
  701. }
  702. async function waitForPluginScopeSelection(
  703. triggerTestId: string,
  704. scope: "user" | "workspace",
  705. ): Promise<void> {
  706. await browser.waitUntil(
  707. () =>
  708. browser.execute(
  709. (id, expectedScope) => {
  710. const trigger = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  711. (candidate) => candidate.dataset.testid === id,
  712. );
  713. const selectedKey = trigger?.dataset.pluginScopeKey;
  714. return expectedScope === "user"
  715. ? selectedKey === "user"
  716. : Boolean(selectedKey && selectedKey !== "user");
  717. },
  718. triggerTestId,
  719. scope,
  720. ),
  721. {
  722. timeout: 15000,
  723. timeoutMsg: `Plugin scope trigger did not select ${scope}: ${triggerTestId}`,
  724. },
  725. );
  726. }
  727. export async function getPluginControlText(
  728. testIdValue: string,
  729. attributes: PluginControlAttributes = {},
  730. ): Promise<string> {
  731. return browser.execute(
  732. (id, expected) =>
  733. Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  734. (candidate) =>
  735. candidate.dataset.testid === id &&
  736. (!expected.pluginId || candidate.dataset.pluginId === expected.pluginId) &&
  737. (!expected.marketplaceId || candidate.dataset.marketplaceId === expected.marketplaceId),
  738. )?.textContent ?? "",
  739. testIdValue,
  740. attributes,
  741. );
  742. }
  743. export async function setPluginPresentation(input: {
  744. locale: "zh-CN" | "en-US";
  745. theme: "zai-light" | "zai-dark";
  746. width: number;
  747. height: number;
  748. }): Promise<void> {
  749. await setCurrentElectronRendererContentSize(input.width, input.height);
  750. await browser.executeAsync((next, done: (result?: string) => void) => {
  751. const actions = (
  752. window as typeof window & {
  753. __testActions?: Record<string, unknown>;
  754. }
  755. ).__testActions;
  756. const setLocale = actions?.setLocale;
  757. const setTheme = actions?.setTheme;
  758. if (typeof setLocale !== "function" || typeof setTheme !== "function") {
  759. done("missing locale/theme test action");
  760. return;
  761. }
  762. (setLocale as (value: string) => void)(next.locale);
  763. (setTheme as (value: string) => void)(next.theme);
  764. requestAnimationFrame(() => done());
  765. }, input);
  766. }
  767. export async function assertPluginStoreFitsViewport(): Promise<void> {
  768. const layout = await browser.execute(() => {
  769. const root = document.querySelector<HTMLElement>('[data-testid="plugin-store-root"]');
  770. return {
  771. clientWidth: root?.clientWidth ?? 0,
  772. scrollWidth: root?.scrollWidth ?? 0,
  773. viewportWidth: window.innerWidth,
  774. overflow: root
  775. ? Array.from(root.querySelectorAll<HTMLElement>("*"))
  776. .filter(
  777. (element) =>
  778. element.getBoundingClientRect().right > root.getBoundingClientRect().right + 1,
  779. )
  780. .map((element) => ({
  781. tag: element.tagName,
  782. testId: element.dataset.testid,
  783. className: element.className,
  784. text: element.textContent?.slice(0, 80),
  785. }))
  786. .slice(0, 10)
  787. : [],
  788. };
  789. });
  790. expect(layout.clientWidth).toBeGreaterThan(0);
  791. if (layout.scrollWidth > layout.clientWidth + 1) {
  792. throw new Error(`Plugin store overflows: ${JSON.stringify(layout)}`);
  793. }
  794. expect(layout.clientWidth).toBeLessThanOrEqual(layout.viewportWidth);
  795. }
  796. export async function capturePluginManualReview(caseId: string, label: string): Promise<string> {
  797. const artifactDir = join(
  798. process.cwd(),
  799. ".e2e-artifacts",
  800. "plugin-management",
  801. caseId.toLowerCase(),
  802. );
  803. await mkdir(artifactDir, { recursive: true });
  804. const path = join(artifactDir, `${label.replaceAll(/[^a-z0-9-]/giu, "-")}.png`);
  805. // 人工评审截图要反映稳定态:等有限时长的过渡/动画(分段切换、面板展开)结束,
  806. // 否则会截到旧选中态与新内容并存的中间帧。无限循环的加载动画不参与判断。
  807. await browser
  808. .waitUntil(
  809. async () =>
  810. browser.execute(
  811. () =>
  812. document
  813. .getAnimations()
  814. .filter(
  815. (animation) =>
  816. animation.playState === "running" &&
  817. animation.effect?.getTiming().iterations !== Infinity,
  818. ).length === 0,
  819. ),
  820. { timeout: 3000, interval: 100 },
  821. )
  822. .catch(() => undefined);
  823. await browser.saveScreenshot(path);
  824. return path;
  825. }
  826. export async function restartPluginLifecycleApp(): Promise<void> {
  827. await browser.reloadSession();
  828. await browser.waitUntil(
  829. async () => {
  830. try {
  831. return (await browser.getUrl()).startsWith("file://");
  832. } catch {
  833. return false;
  834. }
  835. },
  836. {
  837. timeout: 60000,
  838. timeoutMsg: "Electron renderer did not recover after reloadSession",
  839. },
  840. );
  841. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  842. }
  843. export async function getPluginOverview(
  844. workspacePath = DEFAULT_WORKSPACE,
  845. configScope?: "user" | "workspace",
  846. ): Promise<ZCodePluginsOverviewResult> {
  847. return callPluginTestAction("getPluginsOverview", {
  848. workspacePath,
  849. ...(configScope ? { configScope } : {}),
  850. });
  851. }
  852. export async function addMarketplaceSourceThroughAgent(
  853. source: string,
  854. workspacePath = DEFAULT_WORKSPACE,
  855. ): Promise<ZCodePluginsMarketplaceMutationResult> {
  856. return callPluginTestAction("addPluginMarketplace", {
  857. source,
  858. workspacePath,
  859. });
  860. }
  861. export async function updateMarketplaceThroughAgent(
  862. marketplace: string,
  863. workspacePath = DEFAULT_WORKSPACE,
  864. ): Promise<ZCodePluginsMarketplaceMutationResult> {
  865. return callPluginTestAction("updatePluginMarketplace", {
  866. marketplace,
  867. workspacePath,
  868. });
  869. }
  870. export async function installMarketplacePluginThroughAgent(
  871. pluginName: string,
  872. marketplace: string,
  873. workspacePath = DEFAULT_WORKSPACE,
  874. ): Promise<ZCodePluginsInstallResult> {
  875. return callPluginTestAction("installPlugin", {
  876. marketplace,
  877. pluginName,
  878. scope: "user",
  879. workspacePath,
  880. });
  881. }
  882. export async function getPluginList(
  883. workspacePath = DEFAULT_WORKSPACE,
  884. workspaceIdentity?: string,
  885. configScope?: "user" | "workspace",
  886. ): Promise<ZCodePluginsListResult> {
  887. return callPluginTestAction("listPlugins", {
  888. workspacePath,
  889. ...(workspaceIdentity ? { workspaceIdentity } : {}),
  890. ...(configScope ? { configScope } : {}),
  891. });
  892. }
  893. export async function getPluginReferenceCatalog(
  894. options: {
  895. sessionId?: string;
  896. workspaceIdentity?: string;
  897. workspacePath?: string;
  898. } = {},
  899. ): Promise<ZCodePluginsReferenceCatalogResult> {
  900. return callPluginTestAction("getPluginReferenceCatalog", {
  901. workspacePath: options.workspacePath ?? DEFAULT_WORKSPACE,
  902. ...(options.workspaceIdentity ? { workspaceIdentity: options.workspaceIdentity } : {}),
  903. ...(options.sessionId ? { sessionId: options.sessionId } : {}),
  904. });
  905. }
  906. export async function waitUntilPluginOverview(
  907. predicate: (overview: ZCodePluginsOverviewResult) => boolean,
  908. timeoutMsg: string,
  909. timeout = 30000,
  910. ): Promise<void> {
  911. await browser.waitUntil(async () => predicate(await getPluginOverview()), {
  912. timeout,
  913. timeoutMsg,
  914. });
  915. }
  916. export async function waitUntilPluginList(
  917. predicate: (list: ZCodePluginsListResult) => boolean,
  918. timeoutMsg: string,
  919. timeout = 30000,
  920. ): Promise<void> {
  921. let latest: ZCodePluginsListResult | undefined;
  922. try {
  923. await browser.waitUntil(
  924. async () => {
  925. latest = await getPluginList();
  926. return predicate(latest);
  927. },
  928. { timeout, timeoutMsg },
  929. );
  930. } catch (error) {
  931. // 只保留启停与来源事实,便于区分配置范围错误和保存失败,不输出插件 secret/options。
  932. const plugins = latest?.plugins.map(({ id, enabled, enabledSource }) => ({
  933. id,
  934. enabled,
  935. enabledSource,
  936. }));
  937. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(plugins)}`, { cause: error });
  938. }
  939. }
  940. export async function readPluginConfigOptions(): Promise<Record<string, unknown>> {
  941. const config = await readJsonRecord(
  942. join(getE2EAppDataPaths().homeDir, ".zcode", "cli", "config.json"),
  943. );
  944. const plugins = isRecord(config.plugins) ? config.plugins : {};
  945. const options = isRecord(plugins.options) ? plugins.options : {};
  946. return isRecord(options[PLUGIN_LIFECYCLE_ID]) ? options[PLUGIN_LIFECYCLE_ID] : {};
  947. }
  948. export function pluginStoragePath(...segments: string[]): string {
  949. return join(getE2EAppDataPaths().homeDir, ".zcode", "cli", "plugins", ...segments);
  950. }
  951. export function pluginDataPath(pluginId: string): string {
  952. return pluginStoragePath("data", pluginId);
  953. }
  954. export function pluginPathExists(path: string): boolean {
  955. return existsSync(path);
  956. }
  957. async function readPluginControlChecked(
  958. testIdValue: string,
  959. attributes: PluginControlAttributes,
  960. ): Promise<boolean> {
  961. await waitForPluginControl(testIdValue, attributes);
  962. return browser.execute(
  963. (id, expected) => {
  964. const element = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  965. (candidate) =>
  966. candidate.dataset.testid === id &&
  967. (!expected.pluginId || candidate.dataset.pluginId === expected.pluginId),
  968. );
  969. return element?.getAttribute("data-state") === "checked";
  970. },
  971. testIdValue,
  972. attributes,
  973. );
  974. }
  975. async function setPluginControlValue(
  976. testIdValue: string,
  977. attributes: PluginControlAttributes,
  978. value: string,
  979. ): Promise<void> {
  980. await waitForPluginControl(testIdValue, attributes);
  981. const result = await browser.execute(
  982. (id, expected, nextValue) => {
  983. const element = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  984. (candidate) =>
  985. candidate.dataset.testid === id &&
  986. (!expected.configKey || candidate.dataset.configKey === expected.configKey),
  987. );
  988. if (!(element instanceof HTMLInputElement)) return false;
  989. const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
  990. setter?.call(element, nextValue);
  991. element.dispatchEvent(new InputEvent("input", { bubbles: true, data: nextValue }));
  992. element.dispatchEvent(new Event("change", { bubbles: true }));
  993. return true;
  994. },
  995. testIdValue,
  996. attributes,
  997. value,
  998. );
  999. if (!result) throw new Error(`Could not set ${testIdValue} to ${value}`);
  1000. }
  1001. async function callPluginTestAction<T>(
  1002. actionName: PluginTestActionName,
  1003. params: unknown,
  1004. ): Promise<T> {
  1005. // 这些 action 随应用页面挂载,首次职业引导尚未退出时不存在。
  1006. await waitForPluginSettingsEntry();
  1007. await browser.waitUntil(
  1008. () =>
  1009. browser.execute(
  1010. (name) =>
  1011. typeof (
  1012. window as typeof window & {
  1013. __testActions?: Record<string, unknown>;
  1014. }
  1015. ).__testActions?.[name] === "function",
  1016. actionName,
  1017. ),
  1018. {
  1019. timeout: 30_000,
  1020. timeoutMsg: `plugin test action did not become ready: ${actionName}`,
  1021. },
  1022. );
  1023. const result = (await browser.executeAsync(
  1024. (
  1025. name: PluginTestActionName,
  1026. input: unknown,
  1027. done: (result: SerializedActionResult<unknown>) => void,
  1028. ) => {
  1029. const actions = (
  1030. window as typeof window & {
  1031. __testActions?: Record<string, unknown>;
  1032. }
  1033. ).__testActions;
  1034. const action = actions?.[name];
  1035. if (typeof action !== "function") {
  1036. done({ ok: false, error: `missing test action: ${name}` });
  1037. return;
  1038. }
  1039. Promise.resolve((action as (value: unknown) => Promise<unknown>)(input))
  1040. .then((value) => done({ ok: true, value }))
  1041. .catch((error: unknown) =>
  1042. done({
  1043. ok: false,
  1044. error: error instanceof Error ? error.message : String(error),
  1045. }),
  1046. );
  1047. },
  1048. actionName,
  1049. params,
  1050. )) as SerializedActionResult<unknown>;
  1051. if (!result.ok) throw new Error(result.error ?? `test action failed: ${actionName}`);
  1052. return result.value as T;
  1053. }
  1054. async function writeLifecyclePlugin(
  1055. pluginRoot: string,
  1056. version: string,
  1057. withUi = false,
  1058. ): Promise<void> {
  1059. await writeJson(join(pluginRoot, ".zcode-plugin", "plugin.json"), {
  1060. name: PLUGIN_LIFECYCLE_NAME,
  1061. version,
  1062. description: `E2E plugin management lifecycle fixture ${version}`,
  1063. author: { name: "ZCode E2E" },
  1064. homepage: "https://example.com/e2e-plugin-lifecycle",
  1065. commands: "commands",
  1066. agents: "agents",
  1067. skills: "skills",
  1068. hooks: "hooks/hooks.json",
  1069. mcpServers: {
  1070. lifecycle: {
  1071. type: "stdio",
  1072. command: "node",
  1073. args: ["${ZCODE_PLUGIN_ROOT}/server.mjs", version],
  1074. },
  1075. },
  1076. ...(withUi
  1077. ? {
  1078. ui: {
  1079. surfaces: [
  1080. {
  1081. id: "panel",
  1082. title: "Lifecycle Panel",
  1083. server: "lifecycle",
  1084. resourceUri: "ui://lifecycle/panel.html",
  1085. availability: "session",
  1086. },
  1087. ],
  1088. },
  1089. }
  1090. : {}),
  1091. userConfig: {
  1092. [PLUGIN_LIFECYCLE_CONFIG_KEY]: {
  1093. type: "string",
  1094. title: "Lifecycle label",
  1095. default: `fixture-${version}`,
  1096. description: "Non-sensitive E2E lifecycle option",
  1097. },
  1098. [PLUGIN_LIFECYCLE_INHERITED_CONFIG_KEY]: {
  1099. type: "number",
  1100. title: "Timeout seconds",
  1101. default: 30,
  1102. description: "Inherited non-sensitive E2E lifecycle option",
  1103. },
  1104. },
  1105. });
  1106. await writeText(
  1107. join(pluginRoot, "skills", "lifecycle-version", "SKILL.md"),
  1108. [
  1109. "---",
  1110. "name: lifecycle-version",
  1111. `description: ${PLUGIN_LIFECYCLE_RUNTIME_MARKER}_${version}`,
  1112. "---",
  1113. "",
  1114. "# Lifecycle version",
  1115. "",
  1116. `${PLUGIN_LIFECYCLE_RUNTIME_MARKER}_${version}`,
  1117. ].join("\n"),
  1118. );
  1119. await writeText(
  1120. join(pluginRoot, "commands", "lifecycle-command.md"),
  1121. `---\ndescription: Lifecycle command ${version}\n---\n\nReport ${PLUGIN_LIFECYCLE_RUNTIME_MARKER}_${version}.\n`,
  1122. );
  1123. await writeText(
  1124. join(pluginRoot, "agents", "lifecycle-reviewer.md"),
  1125. `---\nname: lifecycle-reviewer\ndescription: Lifecycle subagent ${version}\ntools:\n - Read\n---\nReport ${PLUGIN_LIFECYCLE_RUNTIME_MARKER}_${version}.\n`,
  1126. );
  1127. await writeJson(join(pluginRoot, "hooks", "hooks.json"), {
  1128. hooks: {
  1129. SessionStart: [
  1130. {
  1131. matcher: "startup",
  1132. hooks: [{ type: "command", command: "echo E2E_PLUGIN_LIFECYCLE_HOOK" }],
  1133. },
  1134. ],
  1135. },
  1136. });
  1137. await writeText(join(pluginRoot, "server.mjs"), buildDependencyFreeMcpServer(version, withUi));
  1138. }
  1139. async function writeSimplePlugin(
  1140. pluginRoot: string,
  1141. index: number,
  1142. version = "1.0.0",
  1143. ): Promise<void> {
  1144. await writeJson(join(pluginRoot, ".zcode-plugin", "plugin.json"), {
  1145. name: `e2e-lifecycle-extra-${index}`,
  1146. version,
  1147. description: `E2E lifecycle category expansion plugin ${index}`,
  1148. skills: "skills",
  1149. });
  1150. await writeText(
  1151. join(pluginRoot, "skills", `extra-${index}`, "SKILL.md"),
  1152. `---\ndescription: E2E extra lifecycle skill ${index}\n---\n\n# Extra ${index}\n`,
  1153. );
  1154. }
  1155. async function writeMarketplaceManifest(marketplaceRoot: string, version: string): Promise<void> {
  1156. const extras = Array.from({ length: 7 }, (_, offset) => {
  1157. const index = offset + 1;
  1158. return {
  1159. name: `e2e-lifecycle-extra-${index}`,
  1160. version: "1.0.0",
  1161. description: `E2E lifecycle category expansion plugin ${index}`,
  1162. category: "productivity",
  1163. source: `./plugins/e2e-lifecycle-extra-${index}`,
  1164. };
  1165. });
  1166. await writeJson(join(marketplaceRoot, ".claude-plugin", "marketplace.json"), {
  1167. name: PLUGIN_LIFECYCLE_MARKETPLACE_ID,
  1168. description: PLUGIN_LIFECYCLE_MARKETPLACE_NAME,
  1169. plugins: [
  1170. {
  1171. name: PLUGIN_LIFECYCLE_NAME,
  1172. version,
  1173. displayName: "Lifecycle Fixture",
  1174. displayName_i18n: { "zh-CN": "生命周期测试插件" },
  1175. description: `Deterministic plugin lifecycle fixture ${version}`,
  1176. description_i18n: { "zh-CN": `确定性插件生命周期测试 ${version}` },
  1177. category: "productivity",
  1178. author: { name: "ZCode E2E", url: "https://example.com" },
  1179. homepage: "https://example.com/e2e-plugin-lifecycle",
  1180. privacyPolicy: "https://example.com/privacy",
  1181. termsOfService: "https://example.com/terms",
  1182. examplePrompts: [PLUGIN_LIFECYCLE_EXAMPLE_PROMPT],
  1183. source: `./plugins/${PLUGIN_LIFECYCLE_NAME}`,
  1184. },
  1185. ...extras,
  1186. ],
  1187. });
  1188. }
  1189. function buildDependencyFreeMcpServer(version: string, withUi = false): string {
  1190. const html =
  1191. '<!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>';
  1192. return `#!/usr/bin/env node
  1193. import readline from "node:readline";
  1194. const version = process.argv[2] || ${JSON.stringify(version)};
  1195. const input = readline.createInterface({ input: process.stdin });
  1196. function send(message) { process.stdout.write(JSON.stringify(message) + "\\n"); }
  1197. input.on("line", (line) => {
  1198. let request;
  1199. try { request = JSON.parse(line); } catch { return; }
  1200. if (request.method === "initialize") {
  1201. send({ jsonrpc: "2.0", id: request.id, result: { protocolVersion: "2024-11-05", capabilities: { tools: {}, ${withUi ? "resources: {}," : ""} }, serverInfo: { name: "e2e-plugin-lifecycle", version } } });
  1202. return;
  1203. }
  1204. if (request.method === "tools/list") {
  1205. send({ jsonrpc: "2.0", id: request.id, result: { tools: [{ name: "version_marker", description: "Return the deterministic lifecycle version marker", inputSchema: { type: "object", properties: {} } }] } });
  1206. return;
  1207. }
  1208. if (request.method === "tools/call") {
  1209. send({ jsonrpc: "2.0", id: request.id, result: { content: [{ type: "text", text: ${JSON.stringify(PLUGIN_LIFECYCLE_RUNTIME_MARKER)} + "_" + version }] } });
  1210. return;
  1211. }
  1212. ${
  1213. withUi
  1214. ? `if (request.method === "resources/list") {
  1215. send({ jsonrpc: "2.0", id: request.id, result: { resources: [{ uri: "ui://lifecycle/panel.html", name: "Lifecycle Panel", mimeType: "text/html;profile=mcp-app" }] } }); return;
  1216. }
  1217. if (request.method === "resources/read") {
  1218. send({ jsonrpc: "2.0", id: request.id, result: { contents: [{ uri: request.params.uri, mimeType: "text/html;profile=mcp-app", text: ${JSON.stringify(html)} }] } }); return;
  1219. }`
  1220. : ""
  1221. }
  1222. if (request.id !== undefined) send({ jsonrpc: "2.0", id: request.id, result: {} });
  1223. });
  1224. `;
  1225. }
  1226. async function readJsonRecord(path: string): Promise<Record<string, unknown>> {
  1227. try {
  1228. const parsed = JSON.parse(await readFile(path, "utf-8")) as unknown;
  1229. return isRecord(parsed) ? parsed : {};
  1230. } catch (error) {
  1231. if (
  1232. typeof error === "object" &&
  1233. error !== null &&
  1234. "code" in error &&
  1235. (error as { code?: unknown }).code === "ENOENT"
  1236. ) {
  1237. return {};
  1238. }
  1239. throw error;
  1240. }
  1241. }
  1242. async function writeJson(path: string, value: unknown): Promise<void> {
  1243. await writeText(path, `${JSON.stringify(value, null, 2)}\n`);
  1244. }
  1245. async function writeText(path: string, value: string): Promise<void> {
  1246. await mkdir(dirname(path), { recursive: true });
  1247. await writeFile(path, value, "utf-8");
  1248. }
  1249. function isRecord(value: unknown): value is Record<string, unknown> {
  1250. return typeof value === "object" && value !== null && !Array.isArray(value);
  1251. }