plugin-management-ui-market.test.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. import {
  2. startDraftFromProject,
  3. selectNativeProjectDirectories,
  4. } from "#e2e/helpers/project-sidebar";
  5. import { selectUpstreamModel } from "#e2e/helpers/upstream-provider";
  6. import { mkdir, writeFile } from "node:fs/promises";
  7. import { join } from "node:path";
  8. import { DatabaseSync } from "node:sqlite";
  9. import {
  10. TID_SIDE_PANE_TOGGLE,
  11. TID_SIDE_PANE_FULL_VIEW_TOGGLE,
  12. TID_SIDE_PANE_FULL_VIEW_HOST,
  13. } from "@zcode/shared/test-ids";
  14. import { clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  15. import {
  16. getV4PaneSnapshot,
  17. waitForV4Pane,
  18. approveV4Permission,
  19. denyV4PermissionWithFeedback,
  20. waitForV4PermissionDialog,
  21. getV4ConfigProjection,
  22. setV4ComposerText,
  23. getV4ComposerText,
  24. prepareV4ConversationE2E,
  25. selectV4TaskById,
  26. sendV4Prompt,
  27. waitForV4AssistantMessageContaining,
  28. } from "#e2e/helpers/v4-conversation";
  29. import {
  30. PLUGIN_LIFECYCLE_ID,
  31. addLifecycleMarketplaceThroughUi,
  32. capturePluginManualReview,
  33. clickPluginControl,
  34. createPluginLifecycleFixture,
  35. getPluginList,
  36. getPluginOverview,
  37. installPluginThroughUi,
  38. openManageView,
  39. openPluginSettings,
  40. requirePluginManualReview,
  41. removeLifecyclePluginPayload,
  42. setPluginEnabledThroughUi,
  43. uninstallPluginThroughUi,
  44. waitForPluginControl,
  45. } from "#e2e/helpers/plugin-management-lifecycle";
  46. import {
  47. isElectronRecordingEncoderAvailable,
  48. startElectronWindowRecording,
  49. } from "#e2e/helpers/electron-window-recorder";
  50. const ARTIFACT_DIR = join(process.cwd(), ".e2e-artifacts", "plugin-management", "plm-ui-001");
  51. // 每个评审步骤截图后停留,录像里能看清稳定态;同时记录时间点供生成字幕。
  52. const STEP_HOLD_MS = 1500;
  53. type DraftUiWindow = Window & {
  54. __zcodeSessionStoreE2E?: {
  55. getState(): {
  56. getWorkspaceState(workspacePath: string): {
  57. pluginUiOpenRequest: unknown;
  58. };
  59. };
  60. };
  61. };
  62. declare global {
  63. interface Window {
  64. __draftPluginUiCreateGate?: { count: number; restore(): void };
  65. }
  66. }
  67. describe("PLM-UI-001 UI 插件市场与项目配置", () => {
  68. after(async () => {
  69. await browser.execute(() => window.__draftPluginUiCreateGate?.restore());
  70. await browser.electron.restoreAllMocks();
  71. await clearAppData();
  72. });
  73. it("在真实 MCP 沙箱打开界面,关闭不卸载,项目暂停不影响全局和其他项目", async function () {
  74. // 修复原因:该用例串行走 17 个评审步骤(每步截图后停留 STEP_HOLD_MS),Windows 上冷启动与
  75. // 安装/卸载本身就接近 240s,实测在第 12 步后被 mocha 超时截断而非卡死;放宽到 480s。
  76. this.timeout(480000);
  77. requirePluginManualReview();
  78. const fixture = await createPluginLifecycleFixture("1.0.0", true);
  79. await mkdir(ARTIFACT_DIR, { recursive: true });
  80. // 修复原因:录屏只是人工复核证据;Windows runner 没有 ffmpeg 时 stop() 编码报
  81. // spawn ffmpeg ENOENT,把证据通道失败记成行为失败。编码器不可用时不录屏。
  82. const recording = (await isElectronRecordingEncoderAvailable())
  83. ? await startElectronWindowRecording({
  84. frameIntervalMs: 200,
  85. outputPath: join(ARTIFACT_DIR, "plm-ui-001.webm"),
  86. })
  87. : null;
  88. const recordingStartedAt = Date.now();
  89. const chapters: Array<{ label: string; atMs: number }> = [];
  90. const step = async (label: string) => {
  91. await capturePluginManualReview("PLM-UI-001", label);
  92. chapters.push({ label, atMs: Date.now() - recordingStartedAt });
  93. await browser.pause(STEP_HOLD_MS);
  94. };
  95. try {
  96. await openPluginSettings();
  97. await waitForPluginControl("plugin-store-list");
  98. await browser.$('[data-testid="plugin-store-card"]').waitForDisplayed({ timeout: 60000 });
  99. // 截图按 PRD 章节编号,便于逐项对照(PRD:插件市场 & Side Pane 交互调整)。
  100. await step("01-market-header-public");
  101. await addLifecycleMarketplaceThroughUi(fixture);
  102. await clickPluginControl("plugin-store-segment-community");
  103. await step("02-market-community");
  104. await clickPluginControl("plugin-store-segment-personal");
  105. await waitForPluginControl("plugin-store-ui-section");
  106. await step("03-market-personal-ui-section");
  107. // 缺失源包必须保留可重试错误,不能伪装成已安装或打开 UI。
  108. await removeLifecyclePluginPayload(fixture);
  109. try {
  110. await clickPluginControl("plugin-store-install", { pluginId: PLUGIN_LIFECYCLE_ID });
  111. await waitForPluginControl("plugin-store-error");
  112. expect(
  113. (await getPluginList()).plugins.some((plugin) => plugin.id === PLUGIN_LIFECYCLE_ID),
  114. ).toBe(false);
  115. await step("04-install-failure-before-retry");
  116. } finally {
  117. await createPluginLifecycleFixture("1.0.0", true);
  118. }
  119. await installPluginThroughUi(PLUGIN_LIFECYCLE_ID);
  120. await step("05-installed-ui-card");
  121. await startDraftFromProject(getE2EAppDataPaths().workspace);
  122. await prepareV4ConversationE2E();
  123. await startDraftFromProject(getE2EAppDataPaths().workspace);
  124. await selectUpstreamModel();
  125. expect((await getV4PaneSnapshot()).sessionId).toBe("draft");
  126. let sessionId: string | undefined;
  127. // 主导航市场进入根草稿,右侧市场使用所属 pane。
  128. const openSidePaneMarket = async (stepLabel?: string) => {
  129. if (sessionId) await selectV4TaskById(sessionId);
  130. const addTab = browser.$("[data-side-pane-add-tab-trigger]");
  131. if (await addTab.isDisplayed().catch(() => false)) {
  132. await addTab.click();
  133. await browser.$('[data-state="active"] [data-testid="side-pane-plugin-market"]').click();
  134. } else {
  135. // 多工作区会保留隐藏 pane;只点击当前可见按钮,避免切换旧 pane 后误判布局溢出。
  136. await clickPluginControl(TID_SIDE_PANE_TOGGLE);
  137. await waitForPluginControl("side-pane-ui-recommendations");
  138. // 启动页内容必须完整落在窗口内:「查看所有插件」右边缘不能被面板裁切。
  139. await browser.waitUntil(
  140. async () =>
  141. browser.execute(() => {
  142. const button = Array.from(
  143. document.querySelectorAll<HTMLElement>('[data-testid="side-pane-plugin-market"]'),
  144. ).find((element) => element.checkVisibility());
  145. const rect = button?.getBoundingClientRect();
  146. return Boolean(rect && rect.width > 0 && rect.right <= window.innerWidth);
  147. }),
  148. { timeout: 10000, timeoutMsg: "Side Pane 启动页内容超出窗口" },
  149. );
  150. if (stepLabel) await step(stepLabel);
  151. await clickPluginControl("side-pane-plugin-market");
  152. }
  153. await waitForPluginControl("plugin-store-root");
  154. await clickPluginControl("plugin-store-segment-personal");
  155. await waitForPluginControl("plugin-store-open-ui", { pluginId: PLUGIN_LIFECYCLE_ID });
  156. };
  157. const selectMainWorkspaceScope = async () => {
  158. await browser.$('[data-testid="plugin-settings-scope-trigger"]').click();
  159. // 项目已移入设备子菜单;先展开本机项目,仍按原工作区身份选择。
  160. const projects = browser.$(
  161. '[data-scope-projects-trigger="true"][data-scope-device="local"]',
  162. );
  163. await projects.waitForDisplayed();
  164. await projects.click();
  165. await browser.$('[data-testid^="plugin-settings-scope-option"]').waitForDisplayed();
  166. await browser.execute((workspacePath) => {
  167. const option = Array.from(
  168. document.querySelectorAll<HTMLElement>('[data-testid^="plugin-settings-scope-option"]'),
  169. ).find((item) => item.dataset.pluginScopeKey === workspacePath);
  170. if (!option) throw new Error("项目管理缺少原工作区");
  171. option.click();
  172. }, getE2EAppDataPaths().workspace);
  173. await browser.waitUntil(
  174. async () =>
  175. (await browser.$('[data-testid="plugin-settings-scope-trigger"]').getText()).includes(
  176. "ZCodeProject",
  177. ),
  178. { timeout: 10000 },
  179. );
  180. };
  181. const openCardDetail = async () => {
  182. await clickPluginControl("plugin-store-card", { pluginId: PLUGIN_LIFECYCLE_ID });
  183. await waitForPluginControl("plugin-store-detail");
  184. };
  185. const waitForSandboxReady = () =>
  186. browser.waitUntil(
  187. async () =>
  188. (await browser.electron.execute(async (electron) => {
  189. const guests = electron.webContents
  190. .getAllWebContents()
  191. .filter((guest) => guest.getURL().startsWith("zcode-sandbox://"));
  192. for (const guest of guests) {
  193. for (const frame of guest.mainFrame.frames) {
  194. const ready = await frame
  195. .executeJavaScript('document.getElementById("market-ui-ready")?.textContent')
  196. .catch(() => null);
  197. if (ready === "PLUGIN_MARKET_UI_READY") return true;
  198. }
  199. }
  200. return false;
  201. })) === true,
  202. { timeout: 60000, timeoutMsg: "真实插件沙箱没有完成握手" },
  203. );
  204. // 不发送首轮消息,直接从主导航打开插件,保留原输入。
  205. await setV4ComposerText("unsent draft text");
  206. await openPluginSettings();
  207. await clickPluginControl("plugin-store-segment-personal");
  208. await waitForPluginControl("plugin-store-open-ui", { pluginId: PLUGIN_LIFECYCLE_ID });
  209. await clickPluginControl("plugin-store-open-ui", { pluginId: PLUGIN_LIFECYCLE_ID });
  210. await waitForSandboxReady();
  211. await waitForV4Pane((snapshot) => snapshot.sessionId === "draft", "市场没有返回根草稿");
  212. const guestId = await browser.electron.execute(async (electron) => {
  213. for (const guest of electron.webContents.getAllWebContents()) {
  214. if (!guest.getURL().startsWith("zcode-sandbox://")) continue;
  215. for (const frame of guest.mainFrame.frames) {
  216. const ready = await frame
  217. .executeJavaScript('document.getElementById("market-ui-ready")?.textContent')
  218. .catch(() => null);
  219. if (ready !== "PLUGIN_MARKET_UI_READY") continue;
  220. await frame.executeJavaScript(
  221. 'void window.zcode.callTool("version_marker", {}).then(result => { window.__draftToolResult = result; }, error => { window.__draftToolResult = {error:String(error)}; })',
  222. );
  223. await frame.executeJavaScript('window.__draftUiMarker = "unsaved"');
  224. return guest.id;
  225. }
  226. }
  227. throw new Error("缺少插件 guest");
  228. });
  229. expect(await approveV4Permission()).toBe(true);
  230. const evaluateGuest = (script: string) =>
  231. browser.electron.execute(
  232. async (electron, id, code) => {
  233. const guest = electron.webContents.fromId(id);
  234. const frame = guest?.mainFrame.frames.find((item) =>
  235. item.url.startsWith("zcode-sandbox://plugin-"),
  236. );
  237. if (!frame) throw new Error("原插件 frame 已释放");
  238. return frame.executeJavaScript(code);
  239. },
  240. guestId,
  241. script,
  242. );
  243. await browser.waitUntil(
  244. async () =>
  245. String(await evaluateGuest("JSON.stringify(window.__draftToolResult)")).includes("1.0.0"),
  246. { timeout: 15000, timeoutMsg: "批准后未收到工具结果" },
  247. );
  248. await evaluateGuest(
  249. 'void window.zcode.callTool("version_marker", {}).then(result => { window.__draftDeniedResult = result; }, error => { window.__draftDeniedResult = {error:String(error)}; })',
  250. );
  251. await denyV4PermissionWithFeedback("deny draft test");
  252. await browser.waitUntil(
  253. async () =>
  254. Boolean(
  255. await evaluateGuest(
  256. "window.__draftDeniedResult?.error || window.__draftDeniedResult?.isError",
  257. ),
  258. ),
  259. { timeout: 15000, timeoutMsg: "拒绝没有回传给原插件" },
  260. );
  261. // 真实草稿没有 session 父行;完全访问不能为绕过外键提前创建正式任务。
  262. const draftTabId = await browser
  263. .$('[data-side-pane-tab-id^="plugin-ui:"]')
  264. .getAttribute("data-side-pane-tab-id");
  265. if (!draftTabId) throw new Error("缺少草稿插件标签身份");
  266. const draftSessionId = decodeURIComponent(draftTabId.split(":")[2]!);
  267. const readDraftRows = () => {
  268. const db = new DatabaseSync(
  269. join(getE2EAppDataPaths().storageRoot, "cli", "db", "db.sqlite"),
  270. { readOnly: true },
  271. );
  272. try {
  273. return {
  274. sessions: db
  275. .prepare("select count(*) as n from session where id = ?")
  276. .get(draftSessionId)!.n,
  277. entries: db
  278. .prepare("select count(*) as n from session_entry where session_id = ?")
  279. .get(draftSessionId)!.n,
  280. };
  281. } finally {
  282. db.close();
  283. }
  284. };
  285. await evaluateGuest(
  286. 'void window.zcode.callTool("version_marker", {}).then(result => { window.__draftFullAccessResult = result; }, error => { window.__draftFullAccessResult = {error:String(error)}; })',
  287. );
  288. await waitForV4PermissionDialog();
  289. // 新审批默认切换为 guarded;先显式选择完全访问,再验证风险确认和草稿不落盘。
  290. await browser.$('[data-testid="permission-target-picker"]').click();
  291. await browser.$('[data-testid="permission-target-yolo"]').click();
  292. const fullAccess = browser.$('[data-testid="permission-allow-switch"]');
  293. await fullAccess.click();
  294. const confirmation = browser.$('[data-testid="yolo-confirmation-dialog"]');
  295. await confirmation.waitForDisplayed({ timeout: 15000 });
  296. const confirmGrant = browser.$('[data-testid="yolo-confirmation-confirm"]');
  297. expect(await confirmGrant.isEnabled()).toBe(false);
  298. expect((await getV4ConfigProjection()).mode).not.toBe("yolo");
  299. await browser.$('[data-testid="yolo-confirmation-risk"]').click();
  300. await confirmGrant.waitForClickable();
  301. await confirmGrant.click();
  302. await confirmation.waitForDisplayed({ reverse: true });
  303. await browser.waitUntil(
  304. async () =>
  305. String(await evaluateGuest("JSON.stringify(window.__draftFullAccessResult)")).includes(
  306. "1.0.0",
  307. ),
  308. { timeout: 15000, timeoutMsg: "草稿完全访问审批失败" },
  309. );
  310. await browser.waitUntil(async () => (await getV4ConfigProjection()).mode === "yolo", {
  311. timeout: 10000,
  312. timeoutMsg: "草稿输入框未同步完全访问",
  313. });
  314. expect(readDraftRows()).toEqual({ sessions: 0, entries: 0 });
  315. await evaluateGuest(
  316. 'void window.zcode.callTool("version_marker", {}).then(result => { window.__draftAfterGrantResult = result; })',
  317. );
  318. await browser.waitUntil(
  319. async () =>
  320. String(await evaluateGuest("JSON.stringify(window.__draftAfterGrantResult)")).includes(
  321. "1.0.0",
  322. ),
  323. { timeout: 15000, timeoutMsg: "授权后再次调用仍被审批阻塞" },
  324. );
  325. await step("06a-draft-full-access-without-task");
  326. await evaluateGuest(
  327. 'window.zcode.updateModelContext({content:[{type:"text",text:"draft-plugin-context"}]})',
  328. );
  329. expect((await getV4PaneSnapshot()).sessionId).toBe("draft");
  330. expect((await getV4PaneSnapshot()).rowCount).toBe(0);
  331. expect(await getV4ComposerText()).toBe("unsent draft text");
  332. await step("06-main-nav-opens-draft-ui");
  333. // 草稿右侧市场复用同一页面;关闭可见标签不释放 guest。
  334. await browser.$('[data-side-pane-tab-id^="plugin-ui:"] button').click();
  335. await openSidePaneMarket();
  336. await clickPluginControl("plugin-store-open-ui", { pluginId: PLUGIN_LIFECYCLE_ID });
  337. await browser.$('[data-side-pane-tab-id^="plugin-ui:"]').waitForDisplayed();
  338. expect(await evaluateGuest("window.__draftUiMarker")).toBe("unsaved");
  339. await browser.execute(() =>
  340. document
  341. .querySelector<HTMLButtonElement>('[data-side-pane-tab-id="plugin-market"] button')
  342. ?.click(),
  343. );
  344. // 完整视图只改变布局,不能重建草稿插件或丢失未发送输入。
  345. for (const mode of ["floating", "normal"]) {
  346. await browser.$(`[data-testid="${TID_SIDE_PANE_FULL_VIEW_TOGGLE}"]`).click();
  347. await browser.waitUntil(
  348. async () =>
  349. (await browser
  350. .$(`[data-testid="${TID_SIDE_PANE_FULL_VIEW_HOST}"]`)
  351. .getAttribute("data-side-pane-full-view-host")) === mode,
  352. { timeout: 5_000, timeoutMsg: `完整视图未切换到 ${mode}` },
  353. );
  354. expect(await evaluateGuest("window.__draftUiMarker")).toBe("unsaved");
  355. }
  356. expect(await getV4ComposerText()).toBe("unsent draft text");
  357. expect((await getV4PaneSnapshot()).rowCount).toBe(0);
  358. await step("06b-full-view-preserves-draft-ui");
  359. // 真正切换工作区,使原 pane 卸载后再返回。
  360. const draftOther = join(getE2EAppDataPaths().homeDir, "fixtures", "draft-other");
  361. await mkdir(draftOther, { recursive: true });
  362. await browser.$('[data-testid="project-section"]').moveTo();
  363. await browser.$('[data-testid="virtual-project-add"]').click();
  364. await browser.$('[data-testid="virtual-project-name"]').waitForDisplayed();
  365. await browser.$('[data-testid="virtual-project-name"]').setValue("draft-other");
  366. await selectNativeProjectDirectories([draftOther]);
  367. await browser.$('[data-testid="virtual-project-save"]').click();
  368. await browser.$('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  369. await browser.$('[data-testid="project-folder-trust-confirm"]').click();
  370. await startDraftFromProject(draftOther);
  371. await startDraftFromProject(getE2EAppDataPaths().workspace);
  372. await waitForV4Pane((snapshot) => snapshot.sessionId === "draft", "没有回到原工作区草稿");
  373. expect(await evaluateGuest("window.__draftUiMarker")).toBe("unsaved");
  374. expect(await getV4ComposerText()).toBe("unsent draft text");
  375. await browser.$('[data-testid="plugin-ui-model-context-chip"]').waitForDisplayed();
  376. // 离开再回到草稿不应创建新 guest;首发提升继续使用原页面。
  377. await openPluginSettings();
  378. await clickPluginControl("plugin-store-segment-personal");
  379. await clickPluginControl("plugin-store-open-ui", { pluginId: PLUGIN_LIFECYCLE_ID });
  380. await waitForSandboxReady();
  381. await waitForV4Pane((snapshot) => snapshot.sessionId === "draft", "市场没有返回根草稿");
  382. expect(await getV4ComposerText()).toBe("unsent draft text");
  383. await sendV4Prompt("E2E_PLUGIN_MARKET_SESSION_READY");
  384. await waitForV4AssistantMessageContaining("plugin-market-session-ready");
  385. sessionId = (await getV4PaneSnapshot()).sessionId ?? "draft";
  386. if (!sessionId || sessionId === "draft") throw new Error("草稿没有提升为正式会话");
  387. expect(sessionId).toBe(draftSessionId);
  388. expect((await getV4ConfigProjection()).mode).toBe("yolo");
  389. expect(readDraftRows().sessions).toBe(1);
  390. await evaluateGuest(
  391. 'void window.zcode.callTool("version_marker", {}).then(result => { window.__promotedToolResult = result; })',
  392. );
  393. await browser.waitUntil(
  394. async () =>
  395. String(await evaluateGuest("JSON.stringify(window.__promotedToolResult)")).includes(
  396. "1.0.0",
  397. ),
  398. { timeout: 15000, timeoutMsg: "首发后权限回退或原插件失效" },
  399. );
  400. expect(
  401. await browser.electron.execute(async (electron, id) => {
  402. const guest = electron.webContents.fromId(id);
  403. if (!guest) return false;
  404. for (const frame of guest.mainFrame.frames) {
  405. if (
  406. await frame
  407. .executeJavaScript('window.__draftUiMarker === "unsaved"')
  408. .catch(() => false)
  409. )
  410. return true;
  411. }
  412. return false;
  413. }, guestId),
  414. ).toBe(true);
  415. await step("07-draft-promoted-with-same-guest");
  416. // 暂停真实预热 RPC,再用真实导航离开;旧请求不能落到下一份同项目草稿。
  417. for (const [boundary, navigateAway] of [
  418. ["task", () => selectV4TaskById(sessionId!)],
  419. ["workspace", () => startDraftFromProject(draftOther)],
  420. ] as const) {
  421. await selectV4TaskById(sessionId);
  422. await browser.execute(() => {
  423. const original = MessagePort.prototype.postMessage;
  424. const held: Array<() => void> = [];
  425. const gate = {
  426. count: 0,
  427. restore() {
  428. MessagePort.prototype.postMessage = original;
  429. held.splice(0).forEach((send) => send());
  430. delete window.__draftPluginUiCreateGate;
  431. },
  432. };
  433. MessagePort.prototype.postMessage = function (
  434. this: MessagePort,
  435. ...args: [unknown, (Transferable[] | StructuredSerializeOptions)?]
  436. ) {
  437. const forward = () => Reflect.apply(original, this, args);
  438. const data = args[0];
  439. const bytes =
  440. data instanceof ArrayBuffer
  441. ? new Uint8Array(data)
  442. : ArrayBuffer.isView(data)
  443. ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
  444. : null;
  445. const wire = bytes ? new TextDecoder().decode(bytes) : "";
  446. if (
  447. wire.includes("sendConversationCommandV4") &&
  448. wire.includes('"type":"createSession"')
  449. ) {
  450. gate.count++;
  451. held.push(forward);
  452. } else forward();
  453. };
  454. window.__draftPluginUiCreateGate = gate;
  455. });
  456. try {
  457. await openPluginSettings();
  458. await clickPluginControl("plugin-store-segment-personal");
  459. await clickPluginControl("plugin-store-open-ui", { pluginId: PLUGIN_LIFECYCLE_ID });
  460. await browser.waitUntil(
  461. () => browser.execute(() => Boolean(window.__draftPluginUiCreateGate?.count)),
  462. { timeout: 15000, timeoutMsg: "未拦住草稿预热" },
  463. );
  464. expect(
  465. await browser.execute(
  466. (workspacePath) =>
  467. Boolean(
  468. (window as DraftUiWindow)
  469. .__zcodeSessionStoreE2E!.getState()
  470. .getWorkspaceState(workspacePath).pluginUiOpenRequest,
  471. ),
  472. getE2EAppDataPaths().workspace,
  473. ),
  474. ).toBe(true);
  475. await navigateAway();
  476. expect(
  477. await browser.execute(
  478. (workspacePath) =>
  479. (window as DraftUiWindow)
  480. .__zcodeSessionStoreE2E!.getState()
  481. .getWorkspaceState(workspacePath).pluginUiOpenRequest,
  482. getE2EAppDataPaths().workspace,
  483. ),
  484. ).toBeNull();
  485. } finally {
  486. await browser.execute(() => window.__draftPluginUiCreateGate?.restore());
  487. }
  488. await startDraftFromProject(getE2EAppDataPaths().workspace);
  489. await waitForV4Pane((snapshot) => snapshot.sessionId === "draft", "未返回新草稿");
  490. // 启动页推荐区由有效插件 session 控制;旧 draftRuntime 不代表 V4 预热就绪。
  491. if (
  492. !(await browser
  493. .$("[data-side-pane-add-tab-trigger]")
  494. .isDisplayed()
  495. .catch(() => false))
  496. )
  497. await clickPluginControl(TID_SIDE_PANE_TOGGLE);
  498. await waitForPluginControl("side-pane-ui-recommendations");
  499. expect(
  500. await browser
  501. .$('[data-side-pane-tab-id^="plugin-ui:"]')
  502. .isDisplayed()
  503. .catch(() => false),
  504. ).toBe(false);
  505. expect(await evaluateGuest("window.__draftUiMarker")).toBe("unsaved");
  506. await step(`07b-stale-open-cancelled-on-${boundary}`);
  507. }
  508. // 会话右侧市场:卡片多一个「打开」,在当前会话的右侧标签打开 UI。
  509. await openSidePaneMarket("08-side-pane-launcher");
  510. await step("09-side-pane-market-open-button");
  511. await clickPluginControl("plugin-store-open-ui", { pluginId: PLUGIN_LIFECYCLE_ID });
  512. await browser.$('[data-side-pane-tab-id^="plugin-ui:"]').waitForDisplayed({ timeout: 30000 });
  513. await waitForSandboxReady();
  514. await step("10-ui-opened-in-session");
  515. await browser.execute(() => {
  516. const tab = document.querySelector<HTMLElement>('[data-side-pane-tab-id^="plugin-ui:"]');
  517. const close = tab?.querySelector<HTMLButtonElement>("button");
  518. if (!close) throw new Error("UI 面板缺少关闭按钮");
  519. close.click();
  520. });
  521. expect(
  522. (await getPluginOverview()).installedPlugins.some(
  523. (plugin) => plugin.id === PLUGIN_LIFECYCLE_ID,
  524. ),
  525. ).toBe(true);
  526. await browser.$('[data-side-pane-tab-id="plugin-market"]').click();
  527. await openManageView();
  528. expect(await browser.$$('[role="tab"][id$="-trigger-mcps"]')).toHaveLength(0);
  529. // 管理列表异步加载:等「打开」出现在插件行内,避免截到「加载中」。
  530. await browser
  531. .$(
  532. `[data-testid="plugin-settings-plugin-row"][data-plugin-id="${PLUGIN_LIFECYCLE_ID}"] [data-testid="plugin-store-open-ui"]`,
  533. )
  534. .waitForDisplayed({ timeout: 15000 });
  535. await step("11-side-pane-manage-open-button");
  536. await clickPluginControl("plugin-store-manage-back");
  537. await browser.$('[data-side-pane-tab-id="plugin-market"] button').click();
  538. // 项目内暂停:市场读写 User 层,项目覆盖禁用时仍按 User 显示「打开」;打不开时提示并引导到插件管理,不改写项目覆盖。
  539. await openPluginSettings();
  540. await openManageView();
  541. await selectMainWorkspaceScope();
  542. await waitForPluginControl("plugin-settings-plugin-row", { pluginId: PLUGIN_LIFECYCLE_ID });
  543. await setPluginEnabledThroughUi(PLUGIN_LIFECYCLE_ID, false, "manage");
  544. const { workspace, homeDir } = getE2EAppDataPaths();
  545. const other = join(homeDir, "fixtures", "other-project");
  546. await mkdir(other, { recursive: true });
  547. expect(
  548. (await getPluginList(workspace, undefined, "user")).plugins.find(
  549. (plugin) => plugin.id === PLUGIN_LIFECYCLE_ID,
  550. )?.enabled,
  551. ).toBe(true);
  552. expect(
  553. (await getPluginList(other)).plugins.find((plugin) => plugin.id === PLUGIN_LIFECYCLE_ID)
  554. ?.enabled,
  555. ).toBe(true);
  556. await browser.$('[data-testid="plugin-store-manage-back"]').scrollIntoView();
  557. await step("12-project-override");
  558. await clickPluginControl("plugin-store-manage-back");
  559. await clickPluginControl("plugin-store-segment-personal");
  560. await openCardDetail();
  561. expect(
  562. (await getPluginList()).plugins.find((plugin) => plugin.id === PLUGIN_LIFECYCLE_ID)
  563. ?.enabled,
  564. ).toBe(false);
  565. await waitForPluginControl("plugin-store-open-ui", { pluginId: PLUGIN_LIFECYCLE_ID });
  566. await step("13-paused-main-nav-detail");
  567. await openSidePaneMarket();
  568. await step("14-side-pane-project-disabled-open-button");
  569. await clickPluginControl("plugin-store-open-ui", { pluginId: PLUGIN_LIFECYCLE_ID });
  570. const manageAction = browser.$(
  571. '//*[@id="zcode-toast-host"]//button[normalize-space(.)="插件管理" or normalize-space(.)="Manage plugins"]',
  572. );
  573. await manageAction.waitForDisplayed({ timeout: 15000 });
  574. expect(await browser.$("#zcode-toast-host").getText()).toMatch(
  575. /当前项目已禁用|disabled in this project/,
  576. );
  577. expect(
  578. (await getPluginList()).plugins.find((plugin) => plugin.id === PLUGIN_LIFECYCLE_ID)
  579. ?.enabled,
  580. ).toBe(false);
  581. expect(
  582. (await getPluginList(workspace, undefined, "user")).plugins.find(
  583. (plugin) => plugin.id === PLUGIN_LIFECYCLE_ID,
  584. )?.enabled,
  585. ).toBe(true);
  586. expect(await browser.$$('[data-side-pane-tab-id^="plugin-ui:"]')).toHaveLength(0);
  587. await step("15-project-disabled-guidance");
  588. await manageAction.click();
  589. await waitForPluginControl("plugin-settings-plugin-row", { pluginId: PLUGIN_LIFECYCLE_ID });
  590. await browser.waitUntil(
  591. async () =>
  592. (await browser.$('[data-testid="plugin-settings-scope-trigger"]').getText()).includes(
  593. "ZCodeProject",
  594. ),
  595. { timeout: 10000, timeoutMsg: "引导进入的插件管理没有定位到当前项目" },
  596. );
  597. await step("15b-guided-to-project-manage");
  598. const findLifecycle = (list: Awaited<ReturnType<typeof getPluginList>>) =>
  599. list.plugins.find((plugin) => plugin.id === PLUGIN_LIFECYCLE_ID);
  600. // 有项目覆盖时市场开关不改变生效视图,只能按 User 视图确认写入完成。
  601. const setUserEnabledThroughSidePaneMarket = async (enabled: boolean) => {
  602. await clickPluginControl("plugin-store-manage-back");
  603. await clickPluginControl("plugin-store-segment-personal");
  604. await clickPluginControl("plugin-store-enabled-switch", { pluginId: PLUGIN_LIFECYCLE_ID });
  605. await browser.waitUntil(
  606. async () =>
  607. findLifecycle(await getPluginList(workspace, undefined, "user"))?.enabled === enabled,
  608. { timeout: 30000, timeoutMsg: `市场开关没有把 User 写成 ${enabled}` },
  609. );
  610. };
  611. const visibleOpenUiLabel = () =>
  612. browser.execute((pluginId) => {
  613. const button = Array.from(
  614. document.querySelectorAll<HTMLElement>(
  615. `[data-testid="plugin-store-open-ui"][data-plugin-id="${pluginId}"]`,
  616. ),
  617. ).find((element) => element.checkVisibility());
  618. return button?.textContent?.trim() ?? "";
  619. }, PLUGIN_LIFECYCLE_ID);
  620. // User 关 × 项目关:「启用」与开关同层先写 User,面板仍被项目覆盖挡住,再提示并引导。
  621. await setUserEnabledThroughSidePaneMarket(false);
  622. expect(await visibleOpenUiLabel()).toMatch(/启用|Enable/);
  623. await clickPluginControl("plugin-store-open-ui", { pluginId: PLUGIN_LIFECYCLE_ID });
  624. await manageAction.waitForDisplayed({ timeout: 15000 });
  625. expect(findLifecycle(await getPluginList(workspace, undefined, "user"))?.enabled).toBe(true);
  626. expect(findLifecycle(await getPluginList())).toMatchObject({
  627. enabled: false,
  628. enabledSource: "workspace",
  629. });
  630. expect(await browser.$$('[data-side-pane-tab-id^="plugin-ui:"]')).toHaveLength(0);
  631. await step("15c-enable-writes-user-then-guides");
  632. // 回归:按钮按 User 显示「启用」,曾用生效状态决定是否写 User,项目覆盖为启用时跳过写入。
  633. // User 关 × 项目开:点击必须写 User,项目覆盖保持启用,并打开面板。
  634. // 不等沙箱握手:step 10 的页面留在后台,step 12 禁用时被撤销并停在 error 态,重开同一面板不会自动重建。
  635. // 这是已有问题,另见 docs/issues/plugin-ui-page-lifecycle/01-disabled-page-stays-error-after-reenable.md。
  636. await manageAction.click();
  637. await waitForPluginControl("plugin-settings-plugin-row", { pluginId: PLUGIN_LIFECYCLE_ID });
  638. await setPluginEnabledThroughUi(PLUGIN_LIFECYCLE_ID, true, "manage");
  639. await setUserEnabledThroughSidePaneMarket(false);
  640. expect(await visibleOpenUiLabel()).toMatch(/启用|Enable/);
  641. await clickPluginControl("plugin-store-open-ui", { pluginId: PLUGIN_LIFECYCLE_ID });
  642. await browser.$('[data-side-pane-tab-id^="plugin-ui:"]').waitForDisplayed({ timeout: 30000 });
  643. expect(findLifecycle(await getPluginList(workspace, undefined, "user"))?.enabled).toBe(true);
  644. expect(findLifecycle(await getPluginList())).toMatchObject({
  645. enabled: true,
  646. enabledSource: "workspace",
  647. });
  648. await step("15d-enable-user-with-project-enabled-opens-ui");
  649. await browser.execute(() => {
  650. const tab = document.querySelector<HTMLElement>('[data-side-pane-tab-id^="plugin-ui:"]');
  651. const close = tab?.querySelector<HTMLButtonElement>("button");
  652. if (!close) throw new Error("UI 面板缺少关闭按钮");
  653. close.click();
  654. });
  655. await browser.$('[data-side-pane-tab-id="plugin-market"]').click();
  656. await browser.waitUntil(async () => /打开|Open/.test(await visibleOpenUiLabel()), {
  657. timeout: 10000,
  658. timeoutMsg: "写入 User 后市场按钮没有变为「打开」",
  659. });
  660. // 关掉右侧市场标签:会话视图在主导航后台保持挂载,两份市场同时存在会让按 testid 取到隐藏的那份。
  661. // 非激活标签的关闭按钮被遮挡,走 DOM 点击。
  662. await browser.execute(() => {
  663. const close = document.querySelector<HTMLButtonElement>(
  664. '[data-side-pane-tab-id="plugin-market"] button',
  665. );
  666. if (!close) throw new Error("右侧市场标签缺少关闭按钮");
  667. close.click();
  668. });
  669. await browser
  670. .$('[data-side-pane-tab-id="plugin-market"]')
  671. .waitForExist({ reverse: true, timeout: 10000 });
  672. // 管理页的行同样整行进入详情,再从详情恢复继承与卸载。
  673. await openPluginSettings();
  674. await openManageView();
  675. await selectMainWorkspaceScope();
  676. expect(await browser.$$('[data-testid="plugin-settings-ui-details"]')).toHaveLength(0);
  677. await waitForPluginControl("plugin-store-open-ui", { pluginId: PLUGIN_LIFECYCLE_ID });
  678. // 切换作用域后列表会重新加载,等插件行出现再点。
  679. await waitForPluginControl("plugin-settings-plugin-row", { pluginId: PLUGIN_LIFECYCLE_ID });
  680. await browser.execute((pluginId) => {
  681. const row = document.querySelector(
  682. `[data-testid="plugin-settings-plugin-row"][data-plugin-id="${pluginId}"] [data-testid="plugin-store-card"]`,
  683. );
  684. if (!(row instanceof HTMLElement)) throw new Error("管理页缺少插件行");
  685. row.click();
  686. }, PLUGIN_LIFECYCLE_ID);
  687. await waitForPluginControl("plugin-store-detail");
  688. await clickPluginControl("plugin-store-reset-config");
  689. await browser.waitUntil(
  690. async () => {
  691. const plugin = (await getPluginList()).plugins.find(
  692. (item) => item.id === PLUGIN_LIFECYCLE_ID,
  693. );
  694. return plugin?.enabled === true && plugin.enabledSource === "user";
  695. },
  696. { timeout: 30000, timeoutMsg: "项目配置没有恢复继承全局" },
  697. );
  698. await clickPluginControl("plugin-store-item-menu", { pluginId: PLUGIN_LIFECYCLE_ID });
  699. await step("16-more-menu");
  700. await browser.keys(["Escape"]);
  701. // 菜单关闭完成后再走卸载 helper,否则 helper 的点击会把仍在关闭的菜单切回关闭态。
  702. await browser
  703. .$('[data-testid="plugin-store-menu-uninstall"]')
  704. .waitForDisplayed({ reverse: true, timeout: 10000 });
  705. await uninstallPluginThroughUi(PLUGIN_LIFECYCLE_ID, false);
  706. await uninstallPluginThroughUi(PLUGIN_LIFECYCLE_ID, true);
  707. } finally {
  708. if (recording) {
  709. const result = await recording.stop({ tailDurationMs: 500 });
  710. await writeFile(
  711. join(ARTIFACT_DIR, "plm-ui-001.chapters.json"),
  712. JSON.stringify(
  713. { videoPath: result.videoPath, frameCount: result.frameCount, chapters },
  714. null,
  715. 2,
  716. ),
  717. );
  718. }
  719. }
  720. });
  721. });