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

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