plugin-management-lifecycle.ts 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  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. workspacePath = DEFAULT_WORKSPACE,
  512. ): Promise<void> {
  513. if (entry === "manage" || entry === "market") {
  514. const testId =
  515. entry === "manage" ? "plugin-settings-enabled-switch" : "plugin-store-enabled-switch";
  516. const current = await readPluginControlChecked(testId, { pluginId });
  517. if (current !== enabled) await clickPluginControl(testId, { pluginId });
  518. } else {
  519. const list = await getPluginList(workspacePath);
  520. if (list.plugins.find((plugin) => plugin.id === pluginId)?.enabled !== enabled) {
  521. await clickPluginControl("plugin-store-item-menu", { pluginId });
  522. await clickPluginControl("plugin-store-menu-enabled", { pluginId });
  523. }
  524. }
  525. await waitUntilPluginList(
  526. (list) => list.plugins.some((plugin) => plugin.id === pluginId && plugin.enabled === enabled),
  527. `Plugin enabled state did not become ${enabled}: ${pluginId}`,
  528. 30000,
  529. workspacePath,
  530. );
  531. }
  532. export async function configureLifecyclePluginThroughUi(value: string): Promise<void> {
  533. // 当前市场详情只展示信息;配置写入归管理页详情,必须走真实管理入口。
  534. const fromStore = !(await hasPluginControl("plugin-settings-detail-back"));
  535. if (fromStore) {
  536. await clickPluginControl("plugin-store-detail-back");
  537. await openManageView();
  538. // 整行卡片负责打开详情,行内第一个 button 是菜单,会误打开卸载操作。
  539. await clickPluginControl("plugin-store-card", { pluginId: PLUGIN_LIFECYCLE_ID });
  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. workspacePath = DEFAULT_WORKSPACE,
  921. ): Promise<void> {
  922. // 启停属于操作时的 workspace;未归类任务不能用默认项目的状态确认 UI 已生效。
  923. let latest: ZCodePluginsListResult | undefined;
  924. try {
  925. await browser.waitUntil(
  926. async () => {
  927. latest = await getPluginList(workspacePath);
  928. return predicate(latest);
  929. },
  930. { timeout, timeoutMsg },
  931. );
  932. } catch (error) {
  933. // 只保留启停与来源事实,便于区分配置范围错误和保存失败,不输出插件 secret/options。
  934. const plugins = latest?.plugins.map(({ id, enabled, enabledSource }) => ({
  935. id,
  936. enabled,
  937. enabledSource,
  938. }));
  939. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(plugins)}`, { cause: error });
  940. }
  941. }
  942. export async function waitForPluginDraftRuntimeInvalidation(
  943. workspacePath = DEFAULT_WORKSPACE,
  944. timeout = 30000,
  945. ): Promise<void> {
  946. await browser.waitUntil(
  947. () =>
  948. browser.execute((path) => {
  949. const store = (
  950. window as typeof window & {
  951. __zcodeSessionStoreE2E?: {
  952. getState: () => {
  953. getWorkspaceState: (workspacePath: string) => {
  954. draftSessionId: string | null;
  955. };
  956. };
  957. };
  958. }
  959. ).__zcodeSessionStoreE2E;
  960. return store?.getState().getWorkspaceState(path).draftSessionId === null;
  961. }, workspacePath),
  962. {
  963. timeout,
  964. timeoutMsg: "Plugin runtime refresh did not invalidate the deferred draft session",
  965. },
  966. );
  967. }
  968. export async function readPluginConfigOptions(): Promise<Record<string, unknown>> {
  969. const config = await readJsonRecord(
  970. join(getE2EAppDataPaths().homeDir, ".zcode", "cli", "config.json"),
  971. );
  972. const plugins = isRecord(config.plugins) ? config.plugins : {};
  973. const options = isRecord(plugins.options) ? plugins.options : {};
  974. return isRecord(options[PLUGIN_LIFECYCLE_ID]) ? options[PLUGIN_LIFECYCLE_ID] : {};
  975. }
  976. export function pluginStoragePath(...segments: string[]): string {
  977. return join(getE2EAppDataPaths().homeDir, ".zcode", "cli", "plugins", ...segments);
  978. }
  979. export function pluginDataPath(pluginId: string): string {
  980. return pluginStoragePath("data", pluginId);
  981. }
  982. export function pluginPathExists(path: string): boolean {
  983. return existsSync(path);
  984. }
  985. async function readPluginControlChecked(
  986. testIdValue: string,
  987. attributes: PluginControlAttributes,
  988. ): Promise<boolean> {
  989. await waitForPluginControl(testIdValue, attributes);
  990. return browser.execute(
  991. (id, expected) => {
  992. const element = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  993. (candidate) =>
  994. candidate.dataset.testid === id &&
  995. (!expected.pluginId || candidate.dataset.pluginId === expected.pluginId),
  996. );
  997. return element?.getAttribute("data-state") === "checked";
  998. },
  999. testIdValue,
  1000. attributes,
  1001. );
  1002. }
  1003. export async function setPluginControlValue(
  1004. testIdValue: string,
  1005. attributes: PluginControlAttributes,
  1006. value: string,
  1007. ): Promise<void> {
  1008. await waitForPluginControl(testIdValue, attributes);
  1009. const result = await browser.execute(
  1010. (id, expected, nextValue) => {
  1011. const element = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  1012. (candidate) =>
  1013. candidate.dataset.testid === id &&
  1014. (!expected.configKey || candidate.dataset.configKey === expected.configKey),
  1015. );
  1016. if (!(element instanceof HTMLInputElement)) return false;
  1017. const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
  1018. setter?.call(element, nextValue);
  1019. element.dispatchEvent(new InputEvent("input", { bubbles: true, data: nextValue }));
  1020. element.dispatchEvent(new Event("change", { bubbles: true }));
  1021. return true;
  1022. },
  1023. testIdValue,
  1024. attributes,
  1025. value,
  1026. );
  1027. if (!result) throw new Error(`Could not set ${testIdValue} to ${value}`);
  1028. }
  1029. async function callPluginTestAction<T>(
  1030. actionName: PluginTestActionName,
  1031. params: unknown,
  1032. ): Promise<T> {
  1033. // 这些 action 随应用页面挂载,首次职业引导尚未退出时不存在。
  1034. await waitForPluginSettingsEntry();
  1035. await browser.waitUntil(
  1036. () =>
  1037. browser.execute(
  1038. (name) =>
  1039. typeof (
  1040. window as typeof window & {
  1041. __testActions?: Record<string, unknown>;
  1042. }
  1043. ).__testActions?.[name] === "function",
  1044. actionName,
  1045. ),
  1046. {
  1047. timeout: 30_000,
  1048. timeoutMsg: `plugin test action did not become ready: ${actionName}`,
  1049. },
  1050. );
  1051. const result = (await browser.executeAsync(
  1052. (
  1053. name: PluginTestActionName,
  1054. input: unknown,
  1055. done: (result: SerializedActionResult<unknown>) => void,
  1056. ) => {
  1057. const actions = (
  1058. window as typeof window & {
  1059. __testActions?: Record<string, unknown>;
  1060. }
  1061. ).__testActions;
  1062. const action = actions?.[name];
  1063. if (typeof action !== "function") {
  1064. done({ ok: false, error: `missing test action: ${name}` });
  1065. return;
  1066. }
  1067. Promise.resolve((action as (value: unknown) => Promise<unknown>)(input))
  1068. .then((value) => done({ ok: true, value }))
  1069. .catch((error: unknown) =>
  1070. done({
  1071. ok: false,
  1072. error: error instanceof Error ? error.message : String(error),
  1073. }),
  1074. );
  1075. },
  1076. actionName,
  1077. params,
  1078. )) as SerializedActionResult<unknown>;
  1079. if (!result.ok) throw new Error(result.error ?? `test action failed: ${actionName}`);
  1080. return result.value as T;
  1081. }
  1082. async function writeLifecyclePlugin(
  1083. pluginRoot: string,
  1084. version: string,
  1085. withUi = false,
  1086. ): Promise<void> {
  1087. await writeJson(join(pluginRoot, ".zcode-plugin", "plugin.json"), {
  1088. name: PLUGIN_LIFECYCLE_NAME,
  1089. version,
  1090. description: `E2E plugin management lifecycle fixture ${version}`,
  1091. author: { name: "ZCode E2E" },
  1092. homepage: "https://example.com/e2e-plugin-lifecycle",
  1093. commands: "commands",
  1094. agents: "agents",
  1095. skills: "skills",
  1096. hooks: "hooks/hooks.json",
  1097. mcpServers: {
  1098. lifecycle: {
  1099. type: "stdio",
  1100. command: "node",
  1101. args: ["${ZCODE_PLUGIN_ROOT}/server.mjs", version],
  1102. },
  1103. },
  1104. ...(withUi
  1105. ? {
  1106. ui: {
  1107. surfaces: [
  1108. {
  1109. id: "panel",
  1110. title: "Lifecycle Panel",
  1111. server: "lifecycle",
  1112. resourceUri: "ui://lifecycle/panel.html",
  1113. availability: "session",
  1114. },
  1115. ],
  1116. },
  1117. }
  1118. : {}),
  1119. userConfig: {
  1120. [PLUGIN_LIFECYCLE_CONFIG_KEY]: {
  1121. type: "string",
  1122. title: "Lifecycle label",
  1123. default: `fixture-${version}`,
  1124. description: "Non-sensitive E2E lifecycle option",
  1125. },
  1126. [PLUGIN_LIFECYCLE_INHERITED_CONFIG_KEY]: {
  1127. type: "number",
  1128. title: "Timeout seconds",
  1129. default: 30,
  1130. description: "Inherited non-sensitive E2E lifecycle option",
  1131. },
  1132. },
  1133. });
  1134. await writeText(
  1135. join(pluginRoot, "skills", "lifecycle-version", "SKILL.md"),
  1136. [
  1137. "---",
  1138. "name: lifecycle-version",
  1139. `description: ${PLUGIN_LIFECYCLE_RUNTIME_MARKER}_${version}`,
  1140. "---",
  1141. "",
  1142. "# Lifecycle version",
  1143. "",
  1144. `${PLUGIN_LIFECYCLE_RUNTIME_MARKER}_${version}`,
  1145. ].join("\n"),
  1146. );
  1147. await writeText(
  1148. join(pluginRoot, "commands", "lifecycle-command.md"),
  1149. `---\ndescription: Lifecycle command ${version}\n---\n\nReport ${PLUGIN_LIFECYCLE_RUNTIME_MARKER}_${version}.\n`,
  1150. );
  1151. await writeText(
  1152. join(pluginRoot, "agents", "lifecycle-reviewer.md"),
  1153. `---\nname: lifecycle-reviewer\ndescription: Lifecycle subagent ${version}\ntools:\n - Read\n---\nReport ${PLUGIN_LIFECYCLE_RUNTIME_MARKER}_${version}.\n`,
  1154. );
  1155. await writeJson(join(pluginRoot, "hooks", "hooks.json"), {
  1156. hooks: {
  1157. SessionStart: [
  1158. {
  1159. matcher: "startup",
  1160. hooks: [{ type: "command", command: "echo E2E_PLUGIN_LIFECYCLE_HOOK" }],
  1161. },
  1162. ],
  1163. },
  1164. });
  1165. await writeText(join(pluginRoot, "server.mjs"), buildDependencyFreeMcpServer(version, withUi));
  1166. }
  1167. async function writeSimplePlugin(
  1168. pluginRoot: string,
  1169. index: number,
  1170. version = "1.0.0",
  1171. ): Promise<void> {
  1172. await writeJson(join(pluginRoot, ".zcode-plugin", "plugin.json"), {
  1173. name: `e2e-lifecycle-extra-${index}`,
  1174. version,
  1175. description: `E2E lifecycle category expansion plugin ${index}`,
  1176. skills: "skills",
  1177. });
  1178. await writeText(
  1179. join(pluginRoot, "skills", `extra-${index}`, "SKILL.md"),
  1180. `---\ndescription: E2E extra lifecycle skill ${index}\n---\n\n# Extra ${index}\n`,
  1181. );
  1182. }
  1183. async function writeMarketplaceManifest(marketplaceRoot: string, version: string): Promise<void> {
  1184. const extras = Array.from({ length: 7 }, (_, offset) => {
  1185. const index = offset + 1;
  1186. return {
  1187. name: `e2e-lifecycle-extra-${index}`,
  1188. version: "1.0.0",
  1189. description: `E2E lifecycle category expansion plugin ${index}`,
  1190. category: "productivity",
  1191. source: `./plugins/e2e-lifecycle-extra-${index}`,
  1192. };
  1193. });
  1194. await writeJson(join(marketplaceRoot, ".claude-plugin", "marketplace.json"), {
  1195. name: PLUGIN_LIFECYCLE_MARKETPLACE_ID,
  1196. description: PLUGIN_LIFECYCLE_MARKETPLACE_NAME,
  1197. plugins: [
  1198. {
  1199. name: PLUGIN_LIFECYCLE_NAME,
  1200. version,
  1201. displayName: "Lifecycle Fixture",
  1202. displayName_i18n: { "zh-CN": "生命周期测试插件" },
  1203. description: `Deterministic plugin lifecycle fixture ${version}`,
  1204. description_i18n: { "zh-CN": `确定性插件生命周期测试 ${version}` },
  1205. category: "productivity",
  1206. author: { name: "ZCode E2E", url: "https://example.com" },
  1207. homepage: "https://example.com/e2e-plugin-lifecycle",
  1208. privacyPolicy: "https://example.com/privacy",
  1209. termsOfService: "https://example.com/terms",
  1210. examplePrompts: [PLUGIN_LIFECYCLE_EXAMPLE_PROMPT],
  1211. source: `./plugins/${PLUGIN_LIFECYCLE_NAME}`,
  1212. },
  1213. ...extras,
  1214. ],
  1215. });
  1216. }
  1217. function buildDependencyFreeMcpServer(version: string, withUi = false): string {
  1218. const html =
  1219. '<!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>';
  1220. return `#!/usr/bin/env node
  1221. import readline from "node:readline";
  1222. const version = process.argv[2] || ${JSON.stringify(version)};
  1223. const input = readline.createInterface({ input: process.stdin });
  1224. function send(message) { process.stdout.write(JSON.stringify(message) + "\\n"); }
  1225. input.on("line", (line) => {
  1226. let request;
  1227. try { request = JSON.parse(line); } catch { return; }
  1228. if (request.method === "initialize") {
  1229. send({ jsonrpc: "2.0", id: request.id, result: { protocolVersion: "2024-11-05", capabilities: { tools: {}, ${withUi ? "resources: {}," : ""} }, serverInfo: { name: "e2e-plugin-lifecycle", version } } });
  1230. return;
  1231. }
  1232. if (request.method === "tools/list") {
  1233. send({ jsonrpc: "2.0", id: request.id, result: { tools: [{ name: "version_marker", description: "Return the deterministic lifecycle version marker", inputSchema: { type: "object", properties: {} } }] } });
  1234. return;
  1235. }
  1236. if (request.method === "tools/call") {
  1237. send({ jsonrpc: "2.0", id: request.id, result: { content: [{ type: "text", text: ${JSON.stringify(PLUGIN_LIFECYCLE_RUNTIME_MARKER)} + "_" + version }] } });
  1238. return;
  1239. }
  1240. ${
  1241. withUi
  1242. ? `if (request.method === "resources/list") {
  1243. send({ jsonrpc: "2.0", id: request.id, result: { resources: [{ uri: "ui://lifecycle/panel.html", name: "Lifecycle Panel", mimeType: "text/html;profile=mcp-app" }] } }); return;
  1244. }
  1245. if (request.method === "resources/read") {
  1246. send({ jsonrpc: "2.0", id: request.id, result: { contents: [{ uri: request.params.uri, mimeType: "text/html;profile=mcp-app", text: ${JSON.stringify(html)} }] } }); return;
  1247. }`
  1248. : ""
  1249. }
  1250. if (request.id !== undefined) send({ jsonrpc: "2.0", id: request.id, result: {} });
  1251. });
  1252. `;
  1253. }
  1254. async function readJsonRecord(path: string): Promise<Record<string, unknown>> {
  1255. try {
  1256. const parsed = JSON.parse(await readFile(path, "utf-8")) as unknown;
  1257. return isRecord(parsed) ? parsed : {};
  1258. } catch (error) {
  1259. if (
  1260. typeof error === "object" &&
  1261. error !== null &&
  1262. "code" in error &&
  1263. (error as { code?: unknown }).code === "ENOENT"
  1264. ) {
  1265. return {};
  1266. }
  1267. throw error;
  1268. }
  1269. }
  1270. async function writeJson(path: string, value: unknown): Promise<void> {
  1271. await writeText(path, `${JSON.stringify(value, null, 2)}\n`);
  1272. }
  1273. async function writeText(path: string, value: string): Promise<void> {
  1274. await mkdir(dirname(path), { recursive: true });
  1275. await writeFile(path, value, "utf-8");
  1276. }
  1277. function isRecord(value: unknown): value is Record<string, unknown> {
  1278. return typeof value === "object" && value !== null && !Array.isArray(value);
  1279. }