plugin-management-lifecycle.ts 40 KB

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