conversation-session-plugin-store-try-states.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import { cp, mkdir, readFile, writeFile } from "node:fs/promises";
  2. import { dirname, join } from "node:path";
  3. import { TID_V4_COMPOSER_INPUT } from "@zcode/shared/test-ids";
  4. import { clearAppData, setInputValueByTestIdDom } from "#e2e/helpers/desktop-app";
  5. import {
  6. ELECTRON_WINDOW_RECORDING_CAPTURE_MODE,
  7. isElectronRecordingEncoderAvailable,
  8. startElectronWindowRecording,
  9. } from "#e2e/helpers/electron-window-recorder";
  10. import {
  11. getV4ComposerText,
  12. waitForV4MentionOptionPrefix,
  13. waitForV4Pane,
  14. } from "#e2e/helpers/v4-conversation";
  15. import {
  16. PLUGIN_LIFECYCLE_EXAMPLE_PROMPT,
  17. PLUGIN_LIFECYCLE_ID,
  18. PLUGIN_LIFECYCLE_MARKETPLACE_ID,
  19. capturePluginManualReview,
  20. clickPluginControl,
  21. createPluginLifecycleFixture,
  22. openPluginCard,
  23. openPluginSettings,
  24. pluginStoragePath,
  25. requirePluginManualReview,
  26. getPluginList,
  27. waitUntilPluginList,
  28. waitForPluginControl,
  29. } from "#e2e/helpers/plugin-management-lifecycle";
  30. const CASE_TIMEOUT_MS = 300_000;
  31. const CASE_ID = "PLG12-TRY-STATES";
  32. const ARTIFACT_DIR = join(
  33. process.cwd(),
  34. ".e2e-artifacts",
  35. "plugin-management",
  36. CASE_ID.toLowerCase(),
  37. );
  38. const VIDEO_PATH = join(ARTIFACT_DIR, "plugin-store-try-states.webm");
  39. const VIDEO_MANIFEST_PATH = join(ARTIFACT_DIR, "plugin-store-try-states.recording.json");
  40. describe("PLG12 Plugin 商店试用状态视觉验收", () => {
  41. after(async () => {
  42. await browser.electron.restoreAllMocks();
  43. await clearAppData();
  44. });
  45. it("覆盖未安装、enabled、disabled 与保留的 @ Plugin 候选面板", async function () {
  46. this.timeout(CASE_TIMEOUT_MS);
  47. requirePluginManualReview();
  48. const fixture = await createPluginLifecycleFixture("1.0.0");
  49. await seedLifecycleMarketplaceCache(fixture.marketplaceRoot);
  50. await openPluginSettings();
  51. await clickPluginControl("plugin-store-segment-personal");
  52. await openPluginCard(PLUGIN_LIFECYCLE_ID);
  53. await waitForPluginControl("plugin-store-example-prompt", {
  54. pluginId: PLUGIN_LIFECYCLE_ID,
  55. });
  56. // 修复原因:录屏只是视觉复核证据,runner 缺 ffmpeg 时 stop() 编码会报 spawn ENOENT,
  57. // 把证据通道失败记成行为失败。编码器不可用时跳过录屏,行为断言与截图保持不变。
  58. const recording = (await isElectronRecordingEncoderAvailable())
  59. ? await startElectronWindowRecording({
  60. frameIntervalMs: 250,
  61. outputPath: VIDEO_PATH,
  62. preRollDurationMs: 500,
  63. })
  64. : null;
  65. if (!recording) {
  66. console.warn(`[${CASE_ID}] ffmpeg unavailable; skip window recording evidence`);
  67. }
  68. try {
  69. await capturePluginManualReview(CASE_ID, "01-uninstalled-detail");
  70. // 未安装:点击示例提示词只安装并留在详情页,不能提前创建对话草稿。
  71. await clickPluginControl("plugin-store-example-prompt", {
  72. pluginId: PLUGIN_LIFECYCLE_ID,
  73. });
  74. await waitForPluginControl(
  75. "plugin-store-item-menu",
  76. { pluginId: PLUGIN_LIFECYCLE_ID },
  77. 120_000,
  78. );
  79. expect(await isPluginSettingsVisible()).toBe(true);
  80. await waitForEnabledState(true);
  81. await capturePluginManualReview(CASE_ID, "02-installed-stays-detail");
  82. // enabled:再次点击才进入标准新草稿;canonical + prompt 只预填,不发送。
  83. await clickPluginControl("plugin-store-example-prompt", {
  84. pluginId: PLUGIN_LIFECYCLE_ID,
  85. });
  86. await expectTryDraft("enabled");
  87. await capturePluginManualReview(CASE_ID, "03-enabled-try-draft");
  88. expect(await countCapturedRequestsContaining(PLUGIN_LIFECYCLE_EXAMPLE_PROMPT)).toBe(0);
  89. // disabled:仍允许生成同形草稿;disabled_in_session 只在真正发送时由 Agent 判定。
  90. await openPluginSettings();
  91. await clickPluginControl("plugin-store-segment-personal");
  92. await openPluginCard(PLUGIN_LIFECYCLE_ID);
  93. // 详情页启停已进入真实菜单,旧独立开关仅保留在管理页。
  94. await clickPluginControl("plugin-store-item-menu", { pluginId: PLUGIN_LIFECYCLE_ID });
  95. await clickPluginControl("plugin-store-menu-enabled", { pluginId: PLUGIN_LIFECYCLE_ID });
  96. await waitForEnabledSwitchState(false);
  97. await capturePluginManualReview(CASE_ID, "04-disabled-detail");
  98. await clickPluginControl("plugin-store-example-prompt", {
  99. pluginId: PLUGIN_LIFECYCLE_ID,
  100. });
  101. await expectTryDraft("disabled");
  102. await capturePluginManualReview(CASE_ID, "05-disabled-try-draft");
  103. expect(await countCapturedRequestsContaining(PLUGIN_LIFECYCLE_EXAMPLE_PROMPT)).toBe(0);
  104. // 试用入口不能替代或关闭旧能力:返回 composer 后 @ Plugin 候选仍可打开。
  105. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "@", {
  106. timeout: 15_000,
  107. timeoutMsg: "PLG12 visual review could not edit the v4 composer",
  108. });
  109. const optionId = await waitForV4MentionOptionPrefix("plugin:", 30_000);
  110. expect(optionId.startsWith("plugin:")).toBe(true);
  111. await capturePluginManualReview(CASE_ID, "06-at-plugin-picker-retained");
  112. } finally {
  113. // 不能在 finally 里 return:会吞掉 try 中的断言错误。
  114. if (recording) {
  115. const recordingResult = await recording.stop({
  116. tailDurationMs: 1_000,
  117. timeoutMs: 60_000,
  118. });
  119. expect(recordingResult.captureMode).toBe(ELECTRON_WINDOW_RECORDING_CAPTURE_MODE);
  120. expect(recordingResult.frameCount).toBeGreaterThan(1);
  121. expect(recordingResult.captureError).toBeUndefined();
  122. await writeFile(
  123. VIDEO_MANIFEST_PATH,
  124. `${JSON.stringify(
  125. {
  126. caseId: CASE_ID,
  127. frameCount: recordingResult.frameCount,
  128. states: [
  129. "uninstalled-install-only",
  130. "installed-enabled-canonical-draft",
  131. "installed-disabled-canonical-draft",
  132. "composer-at-plugin-picker-retained",
  133. ],
  134. video_capture_mode: recordingResult.captureMode,
  135. videoPath: recordingResult.videoPath,
  136. },
  137. null,
  138. 2,
  139. )}\n`,
  140. "utf-8",
  141. );
  142. }
  143. }
  144. });
  145. });
  146. async function expectTryDraft(pluginState: "enabled" | "disabled"): Promise<void> {
  147. await waitForV4Pane(
  148. (state) => state.sessionId === "draft" && !state.canStop,
  149. `Plugin Store try did not enter an idle draft for ${pluginState} Plugin`,
  150. 30_000,
  151. );
  152. await browser.waitUntil(
  153. async () => {
  154. const composerText = (await getV4ComposerText()) ?? "";
  155. return (
  156. composerText.includes(`plugin://${PLUGIN_LIFECYCLE_ID}`) &&
  157. composerText.endsWith(` ${PLUGIN_LIFECYCLE_EXAMPLE_PROMPT}`)
  158. );
  159. },
  160. {
  161. timeout: 30_000,
  162. timeoutMsg: `Plugin Store try did not prefill canonical Plugin reference and prompt for ${pluginState} Plugin`,
  163. },
  164. );
  165. }
  166. async function isPluginSettingsVisible(): Promise<boolean> {
  167. return browser.execute(() =>
  168. Boolean(document.querySelector('[data-testid="plugin-store-root"]')),
  169. );
  170. }
  171. async function seedLifecycleMarketplaceCache(marketplaceRoot: string): Promise<void> {
  172. const managedMarketplaceRoot = pluginStoragePath("marketplaces", PLUGIN_LIFECYCLE_MARKETPLACE_ID);
  173. await mkdir(dirname(managedMarketplaceRoot), { recursive: true });
  174. await cp(marketplaceRoot, managedMarketplaceRoot, {
  175. force: true,
  176. recursive: true,
  177. });
  178. // 插件运行时读取的是托管缓存根目录的 marketplace.json;fixture 原始目录使用
  179. // Claude marketplace 的 .claude-plugin/marketplace.json 布局,直接复制目录会让
  180. // known record 存在但商店无法加载 manifest,因此这里补齐运行时缓存形态。
  181. await writeFile(
  182. join(managedMarketplaceRoot, "marketplace.json"),
  183. await readFile(join(marketplaceRoot, ".claude-plugin", "marketplace.json"), "utf-8"),
  184. "utf-8",
  185. );
  186. await writeFile(
  187. pluginStoragePath("known_marketplaces.json"),
  188. `${JSON.stringify(
  189. {
  190. version: 1,
  191. marketplaces: [
  192. // Settings 首次进入会按需刷新两个官方市场;若不预置成功时间,Claude
  193. // marketplace 的 git clone 会占用插件协议串行锁 90 秒,令本地 fixture 的
  194. // install/enable 操作看似卡死。该隔离 HOME 只需声明已刷新,PLG12 不验证公网目录。
  195. {
  196. addedAt: "2026-07-31T00:00:00.000Z",
  197. description: "Deterministic offline ZCode marketplace marker",
  198. id: "zcode-plugins-official",
  199. lastUpdated: "2099-01-01T00:00:00.000Z",
  200. name: "zcode-plugins-official",
  201. pluginCount: 1,
  202. source: {
  203. source: "url",
  204. url: "https://cdn-zcode.z.ai/zcode/official-plugin/marketplace.json",
  205. },
  206. },
  207. {
  208. addedAt: "2026-07-31T00:00:00.000Z",
  209. description: "Deterministic offline Claude marketplace marker",
  210. id: "claude-plugins-official",
  211. lastUpdated: "2099-01-01T00:00:00.000Z",
  212. name: "claude-plugins-official",
  213. pluginCount: 1,
  214. source: {
  215. repo: "anthropics/claude-plugins-official",
  216. source: "github",
  217. },
  218. },
  219. {
  220. addedAt: "2026-07-31T00:00:00.000Z",
  221. description: "Deterministic PLG12 visual review marketplace",
  222. id: PLUGIN_LIFECYCLE_MARKETPLACE_ID,
  223. name: PLUGIN_LIFECYCLE_MARKETPLACE_ID,
  224. pluginCount: 8,
  225. source: {
  226. path: marketplaceRoot,
  227. source: "directory",
  228. },
  229. },
  230. ],
  231. },
  232. null,
  233. 2,
  234. )}\n`,
  235. "utf-8",
  236. );
  237. }
  238. async function waitForEnabledState(enabled: boolean): Promise<void> {
  239. await waitUntilPluginList(
  240. (list) =>
  241. list.plugins.some(
  242. (plugin) => plugin.id === PLUGIN_LIFECYCLE_ID && plugin.enabled === enabled,
  243. ),
  244. `Plugin enabled state did not become ${enabled}`,
  245. );
  246. }
  247. async function waitForEnabledSwitchState(enabled: boolean): Promise<void> {
  248. // 试用入口创建未归类草稿,市场启停写入当前 workspace;不能再查询初始项目的覆盖值。
  249. // 商店替换主区域时 workspace badge 不挂载,读取当前 Tab 的只读身份。
  250. const workspacePath = await browser.execute(
  251. () =>
  252. (
  253. window as Window & {
  254. __zcodeTabStoreE2E?: { getState(): { activeWorkspacePath?: string | null } };
  255. }
  256. ).__zcodeTabStoreE2E?.getState().activeWorkspacePath,
  257. );
  258. if (!workspacePath) throw new Error("Plugin 试用没有当前 workspace");
  259. await browser.waitUntil(
  260. async () =>
  261. (await getPluginList(workspacePath)).plugins.some(
  262. (plugin) => plugin.id === PLUGIN_LIFECYCLE_ID && plugin.enabled === enabled,
  263. ),
  264. {
  265. timeout: 30000,
  266. timeoutMsg: `Plugin enabled state did not become ${enabled} in ${workspacePath}`,
  267. },
  268. );
  269. }
  270. async function countCapturedRequestsContaining(marker: string): Promise<number> {
  271. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  272. if (!capturePath) return 0;
  273. try {
  274. const artifact = JSON.parse(await readFile(capturePath, "utf-8")) as {
  275. records?: Array<{ requestJson?: unknown }>;
  276. };
  277. return (artifact.records ?? []).filter((record) =>
  278. JSON.stringify(record.requestJson).includes(marker),
  279. ).length;
  280. } catch {
  281. return 0;
  282. }
  283. }