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

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