conversation-session-workspace-mcp-trust.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. import { clickOpenScopeMenuOption } from "#e2e/helpers/settings-scope-menu";
  2. import { chromium, type BrowserContext, type Page } from "playwright-core";
  3. import { setTimeout as pause } from "node:timers/promises";
  4. import {
  5. startElectronWindowRecording,
  6. ELECTRON_WINDOW_RECORDING_CAPTURE_MODE,
  7. } from "#e2e/helpers/electron-window-recorder";
  8. import { openMobilePairingPage } from "#e2e/helpers/mobile-pairing";
  9. import { obtainUnreadPairingUrl } from "#e2e/helpers/web-remote-unread";
  10. import { WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS } from "#e2e/helpers/web-remote-control-session-events-fixture";
  11. import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
  12. import { dirname, join, resolve } from "node:path";
  13. import {
  14. TID_CONFIRM_DIALOG_CONFIRM,
  15. TID_MCP_SERVER_ROW,
  16. TID_SETTINGS_BACK_BUTTON,
  17. TID_SETTINGS_PAGE,
  18. TID_SETTINGS_SECTION_NAV,
  19. TID_TASK_SETTINGS_BUTTON,
  20. TID_TASK_ITEM,
  21. testId,
  22. } from "@zcode/shared/test-ids";
  23. import {
  24. clearAppData,
  25. clickTestIdByDom,
  26. getE2EAppDataPaths,
  27. waitForTestIdByDom,
  28. } from "#e2e/helpers/desktop-app";
  29. import {
  30. getV4ConversationState,
  31. prepareV4ConversationE2E,
  32. sendV4Prompt,
  33. } from "#e2e/helpers/v4-conversation";
  34. import { setPluginPresentation } from "#e2e/helpers/plugin-management-lifecycle";
  35. const paths = getE2EAppDataPaths();
  36. const name = "e2e_workspace_mcp_trust";
  37. const marker = join(paths.workspace, ".mcp-trust-wire.ndjson");
  38. const configPath = join(paths.workspace, ".zcode", "config.json");
  39. const trustPath = join(paths.storageRoot, "security", "workspace-mcp-trust-v1.json");
  40. const rowId = testId(TID_MCP_SERVER_ROW, name);
  41. const pendingTriggerId = "v4-workspace-mcp-pending-trigger";
  42. const pendingPopoverId = "v4-workspace-mcp-pending-popover";
  43. const pendingUnreadId = "v4-workspace-mcp-pending-unread";
  44. const pendingReviewId = "v4-workspace-mcp-pending-review";
  45. const pendingDismissId = "v4-workspace-mcp-pending-dismiss";
  46. let original: string | undefined;
  47. const fallbackPath = join(paths.workspace, ".agents", "mcp.json");
  48. let fallbackOriginal: string | undefined;
  49. let fallbackWritten = false;
  50. // 仅为人工评审保留可读画面;状态就绪仍由下面的断言等待。
  51. const REVIEW_PAUSE_MS = 1_200;
  52. async function exists(path: string) {
  53. try {
  54. await access(path);
  55. return true;
  56. } catch {
  57. return false;
  58. }
  59. }
  60. async function waitTrusted(trusted: boolean, targetRowId = rowId) {
  61. await browser.waitUntil(
  62. async () =>
  63. browser.execute(
  64. (id, expected) => {
  65. const row = document.querySelector(`[data-testid="${id}"]`);
  66. return (
  67. row?.querySelector("[data-mcp-trusted]")?.getAttribute("data-mcp-trusted") ===
  68. String(expected)
  69. );
  70. },
  71. targetRowId,
  72. trusted,
  73. ),
  74. { timeout: 30_000, timeoutMsg: "MCP trust projection did not update" },
  75. );
  76. }
  77. // 验证实际高亮后的代码内容与边界;穿过现有 CodeViewer 的 Shadow DOM。
  78. function readTrustCodePresentation() {
  79. const dialog = document.querySelector<HTMLElement>('[data-confirm-intent="workspace-mcp-trust"]');
  80. const block = dialog?.querySelector<HTMLElement>('[data-testid="confirm-dialog-code"]');
  81. if (!dialog || !block) return null;
  82. const roots: ParentNode[] = [block];
  83. let code: HTMLElement | null = null;
  84. while (roots.length && !code) {
  85. const root = roots.shift()!;
  86. code = root.querySelector<HTMLElement>("[data-code] [data-content]");
  87. for (const element of root.querySelectorAll("*")) {
  88. if (element.shadowRoot) roots.push(element.shadowRoot);
  89. }
  90. }
  91. if (!code) return null;
  92. const descriptionId = dialog.getAttribute("aria-describedby");
  93. const description = descriptionId ? document.getElementById(descriptionId) : null;
  94. let descriptionFits = false;
  95. const descriptionText = description?.firstChild;
  96. if (description && descriptionText?.nodeType === Node.TEXT_NODE) {
  97. // 来源路径允许滚动;首段风险和生效说明必须无需滚动即可完整看到。
  98. const explanation = document.createRange();
  99. explanation.selectNodeContents(descriptionText);
  100. const separator = descriptionText.textContent?.indexOf("\n\n") ?? -1;
  101. if (separator >= 0) explanation.setEnd(descriptionText, separator);
  102. descriptionFits =
  103. explanation.getBoundingClientRect().bottom <= description.getBoundingClientRect().bottom + 1;
  104. }
  105. const bounds = dialog.getBoundingClientRect();
  106. const confirm = dialog
  107. .querySelector<HTMLElement>('[data-testid="confirm-dialog-confirm"]')
  108. ?.getBoundingClientRect();
  109. return {
  110. text: Array.from(
  111. code.querySelectorAll("[data-line]"),
  112. (line) => line.textContent?.trimEnd() ?? "",
  113. ).join("\n"),
  114. highlighted: code.querySelectorAll("span[style]").length > 0,
  115. fits:
  116. bounds.left >= 0 &&
  117. bounds.right <= innerWidth + 1 &&
  118. bounds.top >= 0 &&
  119. bounds.bottom <= innerHeight + 1 &&
  120. dialog.scrollWidth <= dialog.clientWidth + 1,
  121. confirmVisible: Boolean(confirm && confirm.top >= 0 && confirm.bottom <= innerHeight),
  122. descriptionFits,
  123. };
  124. }
  125. async function openMcpPendingPopover(page?: Page) {
  126. if (page) {
  127. await page.getByTestId(pendingTriggerId).click();
  128. await page.getByTestId(pendingPopoverId).waitFor({ state: "visible" });
  129. } else {
  130. await browser.$(`[data-testid="${pendingTriggerId}"]`).click();
  131. await browser.$(`[data-testid="${pendingPopoverId}"]`).waitForDisplayed();
  132. }
  133. }
  134. async function reviewTrustCode(page?: Page) {
  135. const read = () =>
  136. page ? page.evaluate(readTrustCodePresentation) : browser.execute(readTrustCodePresentation);
  137. await browser.waitUntil(async () => Boolean((await read())?.highlighted), {
  138. timeout: 15_000,
  139. timeoutMsg: "Trust JSON syntax highlighting did not render",
  140. });
  141. const view = (await read())!;
  142. expect(JSON.parse(view.text).command).toBe(
  143. `${process.execPath} ${resolve(process.cwd(), "test/e2e/fixtures/mcp/dual-era-version-server.mjs")}`,
  144. );
  145. expect(view.text).toContain('\n "command"');
  146. expect(view.fits).toBe(true);
  147. expect(view.confirmVisible).toBe(true);
  148. expect(view.descriptionFits).toBe(true);
  149. }
  150. describe("WMT-01 workspace MCP manual trust", () => {
  151. afterEach(async function () {
  152. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR;
  153. if (artifactDir && this.currentTest?.state === "failed") {
  154. const caseMarker = this.currentTest.title.match(/^WMT-\d+/u)?.[0] ?? "WMT-01";
  155. await browser.saveScreenshot(join(artifactDir, `${caseMarker}-desktop-failure.png`));
  156. await writeFile(
  157. join(artifactDir, `${caseMarker}-desktop-dom.txt`),
  158. await browser.execute(() => document.body.innerText),
  159. );
  160. }
  161. });
  162. after(async () => {
  163. if (original !== undefined) await writeFile(configPath, original);
  164. else await rm(configPath, { force: true });
  165. if (fallbackWritten) {
  166. if (fallbackOriginal !== undefined) await writeFile(fallbackPath, fallbackOriginal);
  167. else await rm(fallbackPath, { force: true });
  168. }
  169. await browser.electron.restoreAllMocks();
  170. await clearAppData();
  171. });
  172. it("WMT-01/04: session guidance, exact trust and revoke preserve MCP admission", async function () {
  173. this.timeout(180_000);
  174. await prepareV4ConversationE2E();
  175. if (await exists(configPath)) original = await readFile(configPath, "utf8");
  176. await mkdir(dirname(configPath), { recursive: true });
  177. await rm(marker, { force: true });
  178. const config = original ? JSON.parse(original) : {};
  179. config.mcp = {
  180. ...config.mcp,
  181. servers: {
  182. ...config.mcp?.servers,
  183. [name]: {
  184. type: "stdio",
  185. command: process.execPath,
  186. args: [resolve(process.cwd(), "test/e2e/fixtures/mcp/dual-era-version-server.mjs")],
  187. protocolVersion: "legacy",
  188. env: { E2E_MCP_VERSION_MODE: "legacy", E2E_MCP_VERSION_WIRE_LOG: marker },
  189. },
  190. },
  191. };
  192. await writeFile(configPath, JSON.stringify(config));
  193. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR;
  194. if (!artifactDir) throw new Error("isolated artifact directory required");
  195. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1280, height: 660 });
  196. const recording = await startElectronWindowRecording({
  197. outputPath: join(artifactDir, "WMT-01-desktop-full-flow.mp4"),
  198. frameIntervalMs: 200,
  199. preRollDurationMs: 1_000,
  200. });
  201. try {
  202. await sendV4Prompt("E2E_MCP_TRUST_GUIDANCE first: reply with ok");
  203. await browser.waitUntil(
  204. async () =>
  205. browser.execute(() => document.body.innerText.includes("MCP guidance first ready")),
  206. { timeout: 30_000 },
  207. );
  208. await waitForTestIdByDom(pendingTriggerId);
  209. await waitForTestIdByDom(pendingUnreadId);
  210. expect(await browser.$(`[data-testid="${pendingPopoverId}"]`).isExisting()).toBe(false);
  211. await openMcpPendingPopover();
  212. expect(await browser.$(`[data-testid="${pendingUnreadId}"]`).isExisting()).toBe(false);
  213. expect(await browser.$(`[data-testid="${pendingPopoverId}"]`).getText()).toContain(
  214. "信任变更在新建或重启会话时生效",
  215. );
  216. expect(await exists(marker)).toBe(false);
  217. await browser.saveScreenshot(join(artifactDir, "WMT-04-session-pending.png"));
  218. await pause(REVIEW_PAUSE_MS);
  219. await browser.keys("Escape");
  220. await browser.$(`[data-testid="${pendingPopoverId}"]`).waitForExist({ reverse: true });
  221. expect(await browser.$(`[data-testid="${pendingTriggerId}"]`).isExisting()).toBe(true);
  222. expect(await browser.$(`[data-testid="${pendingTriggerId}"]`).isFocused()).toBe(true);
  223. await openMcpPendingPopover();
  224. await clickTestIdByDom(pendingDismissId);
  225. await browser.$(`[data-testid="${pendingTriggerId}"]`).waitForExist({ reverse: true });
  226. // 声明变化由下一条用户输入触发重读;普通模型续步不再承担提示刷新。
  227. config.mcp.servers[name].env.E2E_MCP_GUIDANCE_REVISION = "2";
  228. await writeFile(configPath, JSON.stringify(config));
  229. expect(await browser.$(`[data-testid="${pendingTriggerId}"]`).isExisting()).toBe(false);
  230. await sendV4Prompt("E2E_MCP_TRUST_GUIDANCE changed: reply with ok");
  231. await browser.waitUntil(
  232. async () =>
  233. browser.execute(() => document.body.innerText.includes("MCP guidance changed ready")),
  234. { timeout: 30_000 },
  235. );
  236. await waitForTestIdByDom(pendingTriggerId);
  237. await waitForTestIdByDom(pendingUnreadId);
  238. await openMcpPendingPopover();
  239. await clickTestIdByDom(pendingReviewId);
  240. await waitForTestIdByDom(TID_SETTINGS_PAGE);
  241. await waitForTestIdByDom(rowId);
  242. await waitTrusted(false);
  243. // 设置页已有「用户」选择时,审核意图仍须回到这条会话的工作区。
  244. await browser.$('[data-testid="plugin-settings-scope-trigger"]').click();
  245. await clickOpenScopeMenuOption("user");
  246. await browser.$(`[data-testid="${rowId}"]`).waitForExist({ reverse: true });
  247. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  248. await openMcpPendingPopover();
  249. await clickTestIdByDom(pendingReviewId);
  250. await waitForTestIdByDom(rowId);
  251. await waitTrusted(false);
  252. expect(await exists(marker)).toBe(false);
  253. await pause(REVIEW_PAUSE_MS);
  254. for (const [locale, theme] of [
  255. ["zh-CN", "zai-dark"],
  256. ["en-US", "zai-light"],
  257. ] as const) {
  258. await setPluginPresentation({ locale, theme, width: 1280, height: 660 });
  259. await waitTrusted(false);
  260. await browser.saveScreenshot(join(artifactDir, `WMT-01-${locale}-${theme}.png`));
  261. await pause(REVIEW_PAUSE_MS);
  262. }
  263. await setPluginPresentation({
  264. locale: "zh-CN",
  265. theme: "zai-light",
  266. width: 1280,
  267. height: 660,
  268. });
  269. await clickTestIdByDom(testId("mcp-workspace-trust", name));
  270. await pause(REVIEW_PAUSE_MS);
  271. await reviewTrustCode();
  272. const copyButton = browser.$('[data-testid="confirm-dialog-code"] button');
  273. await copyButton.click();
  274. await reviewTrustCode();
  275. await browser.execute(() =>
  276. document
  277. .querySelector<HTMLButtonElement>('[data-testid="confirm-dialog-code"] button')
  278. ?.focus(),
  279. );
  280. await browser.keys("Enter");
  281. await reviewTrustCode();
  282. await waitTrusted(false);
  283. for (const theme of ["zai-dark", "zai-light"] as const) {
  284. await setPluginPresentation({ locale: "zh-CN", theme, width: 1280, height: 660 });
  285. await reviewTrustCode();
  286. await browser.saveScreenshot(join(artifactDir, `WMT-01-json-${theme}.png`));
  287. await pause(REVIEW_PAUSE_MS);
  288. }
  289. await pause(REVIEW_PAUSE_MS);
  290. await browser.saveScreenshot(join(artifactDir, "WMT-01-review.png"));
  291. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM);
  292. await waitTrusted(true);
  293. const store = JSON.parse(await readFile(trustPath, "utf8"));
  294. expect(
  295. store.records.some((record: { serverName: string }) => record.serverName === name),
  296. ).toBe(true);
  297. expect(await exists(marker)).toBe(false);
  298. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  299. await browser.$(`[data-testid="${pendingTriggerId}"]`).waitForExist({ reverse: true });
  300. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  301. await browser.$('[data-testid="plugin-settings-scope-trigger"]').click();
  302. await clickOpenScopeMenuOption(paths.workspace);
  303. await waitForTestIdByDom(rowId);
  304. await pause(REVIEW_PAUSE_MS);
  305. await clickTestIdByDom("mcp-settings-refresh");
  306. await browser.waitUntil(
  307. async () =>
  308. (await exists(marker)) &&
  309. (await readFile(marker, "utf8")).includes('"method":"tools/list"'),
  310. { timeout: 30_000, timeoutMsg: "Trusted MCP did not handshake" },
  311. );
  312. await browser.waitUntil(
  313. async () =>
  314. (await browser.$(`[data-testid="${rowId}"]`).getAttribute("data-mcp-status")) ===
  315. "connected",
  316. { timeout: 30_000, timeoutMsg: "Connected MCP status did not reach the UI" },
  317. );
  318. await pause(REVIEW_PAUSE_MS);
  319. await clickTestIdByDom(testId("mcp-workspace-trust", name));
  320. await pause(REVIEW_PAUSE_MS);
  321. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM);
  322. await waitTrusted(false);
  323. const revoked = JSON.parse(await readFile(trustPath, "utf8"));
  324. expect(
  325. revoked.records.some((record: { serverName: string }) => record.serverName === name),
  326. ).toBe(false);
  327. await pause(REVIEW_PAUSE_MS);
  328. } finally {
  329. const video = await recording.stop({ tailDurationMs: 1_000 });
  330. await writeFile(
  331. join(artifactDir, "WMT-01-video.json"),
  332. JSON.stringify(
  333. {
  334. video_capture_mode: ELECTRON_WINDOW_RECORDING_CAPTURE_MODE,
  335. frameCount: video.frameCount,
  336. captureError: video.captureError,
  337. file: "WMT-01-desktop-full-flow.mp4",
  338. },
  339. null,
  340. 2,
  341. ),
  342. );
  343. expect(video.captureError).toBeUndefined();
  344. }
  345. });
  346. it("WMT-02/05: mobile session guidance and settings share the Host trust state", async function () {
  347. this.timeout(180_000);
  348. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR;
  349. if (!artifactDir) throw new Error("isolated artifact directory required");
  350. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  351. await waitForTestIdByDom(pendingTriggerId);
  352. const { taskId } = await getV4ConversationState();
  353. expect(taskId).toBeTruthy();
  354. const pairingUrl = await obtainUnreadPairingUrl();
  355. const executablePath =
  356. process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE || process.env.R3_MOBILE_CHROME;
  357. const chrome = await chromium.launch({
  358. ...(executablePath ? { executablePath } : { channel: "chrome" }),
  359. headless: true,
  360. });
  361. let page: Page | undefined;
  362. let context: BrowserContext | undefined;
  363. let recording: Awaited<ReturnType<typeof startElectronWindowRecording>> | undefined;
  364. try {
  365. context = await chrome.newContext({
  366. viewport: { width: 390, height: 844 },
  367. isMobile: true,
  368. hasTouch: true,
  369. locale: "zh-CN",
  370. });
  371. await context.addInitScript((credentials) => {
  372. if (sessionStorage.getItem("mcp-trust-seeded")) return;
  373. sessionStorage.setItem("mcp-trust-seeded", "1");
  374. for (const [key, value] of Object.entries(credentials)) localStorage.setItem(key, value);
  375. }, WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS);
  376. page = await context.newPage();
  377. await openMobilePairingPage(page, pairingUrl, {
  378. artifactDir,
  379. caseMarker: "WMT-02",
  380. phase: "mobile",
  381. readySelector: '[data-testid="sidebar"]',
  382. });
  383. // Chrome 原生 screencast 会裁掉模拟手机视口底部;复用连续采帧器读取完整视口。
  384. recording = await startElectronWindowRecording({
  385. captureFrame: () => page!.screenshot({ type: "png", timeout: 5_000 }),
  386. outputPath: join(artifactDir, "WMT-02-mobile-full-flow.mp4"),
  387. frameIntervalMs: 200,
  388. });
  389. await page.getByTestId(testId(TID_TASK_ITEM, taskId!)).click();
  390. await page.getByTestId(pendingTriggerId).waitFor({ state: "visible" });
  391. await page.getByTestId(pendingUnreadId).waitFor({ state: "visible" });
  392. await openMcpPendingPopover(page);
  393. expect(await page.getByTestId(pendingUnreadId).count()).toBe(0);
  394. const pendingBounds = await page.getByTestId(pendingPopoverId).boundingBox();
  395. expect(pendingBounds).not.toBeNull();
  396. expect(pendingBounds!.x).toBeGreaterThanOrEqual(0);
  397. expect(pendingBounds!.x + pendingBounds!.width).toBeLessThanOrEqual(390);
  398. expect(await page.getByTestId(pendingPopoverId).innerText()).toContain(
  399. "信任变更在新建或重启会话时生效",
  400. );
  401. await page.screenshot({ path: join(artifactDir, "WMT-05-mobile-session-pending.png") });
  402. await page.getByTestId(pendingReviewId).click();
  403. await page.getByTestId(rowId).waitFor({ state: "visible" });
  404. const wireBeforeTrust = await readFile(marker, "utf8");
  405. await pause(REVIEW_PAUSE_MS);
  406. await page.getByTestId(testId("mcp-workspace-trust", name)).click();
  407. await pause(REVIEW_PAUSE_MS);
  408. await reviewTrustCode(page);
  409. for (const theme of ["zai-dark", "zai-light"] as const) {
  410. await page.evaluate((theme) => {
  411. (
  412. window as typeof window & { __testActions: { setTheme(theme: string): void } }
  413. ).__testActions.setTheme(theme);
  414. }, theme);
  415. await reviewTrustCode(page);
  416. await page.screenshot({ path: join(artifactDir, `WMT-02-json-${theme}.png`) });
  417. await pause(REVIEW_PAUSE_MS);
  418. }
  419. await pause(REVIEW_PAUSE_MS);
  420. await page.getByTestId(TID_CONFIRM_DIALOG_CONFIRM).click();
  421. await page.waitForFunction(
  422. (id) =>
  423. document
  424. .querySelector(`[data-testid="${id}"] [data-mcp-trusted]`)
  425. ?.getAttribute("data-mcp-trusted") === "true",
  426. rowId,
  427. );
  428. const store = JSON.parse(await readFile(trustPath, "utf8"));
  429. expect(
  430. store.records.filter((record: { serverName: string }) => record.serverName === name),
  431. ).toHaveLength(1);
  432. expect(
  433. store.records.find((record: { serverName: string }) => record.serverName === name)
  434. .workspaceIdentity,
  435. ).toBe(paths.workspace);
  436. expect(await readFile(marker, "utf8")).toBe(wireBeforeTrust);
  437. await page.getByTestId(TID_SETTINGS_BACK_BUTTON).click();
  438. await page.getByTestId(pendingTriggerId).waitFor({ state: "hidden" });
  439. await page.getByRole("button", { name: "返回任务首页" }).click();
  440. await page.getByTestId(TID_TASK_SETTINGS_BUTTON).click();
  441. await page.getByTestId("plugin-settings-scope-trigger").click();
  442. await page.locator('[data-scope-projects-trigger="true"][data-scope-device="local"]').click();
  443. await page.locator(`[data-plugin-scope-key="${paths.workspace}"]`).click();
  444. await page.getByTestId(rowId).waitFor({ state: "visible" });
  445. for (const [locale, theme] of [
  446. ["zh-CN", "zai-dark"],
  447. ["en-US", "zai-light"],
  448. ] as const) {
  449. await page.evaluate(
  450. ({ locale, theme }) => {
  451. const actions = (
  452. window as typeof window & {
  453. __testActions?: { setLocale(value: string): void; setTheme(value: string): void };
  454. }
  455. ).__testActions;
  456. if (!actions) throw new Error("missing presentation test actions");
  457. actions.setLocale(locale);
  458. actions.setTheme(theme);
  459. },
  460. { locale, theme },
  461. );
  462. const row = page.getByTestId(rowId);
  463. await row.waitFor();
  464. const box = await row.boundingBox();
  465. expect(box).not.toBeNull();
  466. expect(box!.x).toBeGreaterThanOrEqual(0);
  467. expect(box!.x + box!.width).toBeLessThanOrEqual(390);
  468. const trustText = await row.locator("[data-mcp-trusted]").boundingBox();
  469. expect(trustText!.width).toBeGreaterThanOrEqual(120);
  470. await page.screenshot({ path: join(artifactDir, `WMT-02-${locale}-${theme}.png`) });
  471. await pause(REVIEW_PAUSE_MS);
  472. }
  473. await page.getByTestId(testId("mcp-workspace-trust", name)).click();
  474. await pause(REVIEW_PAUSE_MS);
  475. await reviewTrustCode(page);
  476. await pause(REVIEW_PAUSE_MS);
  477. await page.getByTestId(TID_CONFIRM_DIALOG_CONFIRM).click();
  478. await page.waitForFunction(
  479. (id) =>
  480. document
  481. .querySelector(`[data-testid="${id}"] [data-mcp-trusted]`)
  482. ?.getAttribute("data-mcp-trusted") === "false",
  483. rowId,
  484. );
  485. await pause(REVIEW_PAUSE_MS);
  486. } catch (error) {
  487. if (page && !page.isClosed()) {
  488. await page.screenshot({ path: join(artifactDir, "WMT-02-mobile-failure.png") });
  489. await writeFile(
  490. join(artifactDir, "WMT-02-mobile-dom.txt"),
  491. await page.locator("body").innerText(),
  492. );
  493. }
  494. throw error;
  495. } finally {
  496. try {
  497. if (recording) {
  498. const video = await recording.stop({ tailDurationMs: 1_000 });
  499. await writeFile(
  500. join(artifactDir, "WMT-02-video.json"),
  501. JSON.stringify({
  502. video_capture_mode: "playwright_viewport_capture",
  503. frameCount: video.frameCount,
  504. captureError: video.captureError,
  505. }),
  506. );
  507. expect(video.captureError).toBeUndefined();
  508. }
  509. } finally {
  510. await context?.close();
  511. await chrome.close();
  512. }
  513. }
  514. });
  515. it("WMT-03: deleting the final project entry exposes a trustable fallback beside invalid config", async function () {
  516. this.timeout(180_000);
  517. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR;
  518. if (!artifactDir) throw new Error("isolated artifact directory required");
  519. const fallbackName = "e2e_workspace_mcp_fallback";
  520. const fallbackRowId = testId(TID_MCP_SERVER_ROW, fallbackName);
  521. const fallbackMarker = join(paths.workspace, ".mcp-fallback-wire.ndjson");
  522. const invalidMarker = join(paths.workspace, ".mcp-invalid-wire.ndjson");
  523. if (await exists(fallbackPath)) fallbackOriginal = await readFile(fallbackPath, "utf8");
  524. await mkdir(dirname(fallbackPath), { recursive: true });
  525. await rm(fallbackMarker, { force: true });
  526. await rm(invalidMarker, { force: true });
  527. await writeFile(
  528. fallbackPath,
  529. JSON.stringify({
  530. mcpServers: {
  531. [fallbackName]: {
  532. type: "stdio",
  533. command: process.execPath,
  534. args: [resolve(process.cwd(), "test/e2e/fixtures/mcp/dual-era-version-server.mjs")],
  535. protocolVersion: "legacy",
  536. isolation: "session",
  537. environment: {
  538. E2E_MCP_VERSION_MODE: "legacy",
  539. E2E_MCP_VERSION_WIRE_LOG: fallbackMarker,
  540. },
  541. },
  542. e2e_invalid_neighbor: {
  543. type: "stdio",
  544. command: process.execPath,
  545. args: [resolve(process.cwd(), "test/e2e/fixtures/mcp/dual-era-version-server.mjs")],
  546. env: { E2E_MCP_VERSION_MODE: "legacy", E2E_MCP_VERSION_WIRE_LOG: invalidMarker },
  547. description: "unsupported metadata",
  548. },
  549. },
  550. }),
  551. );
  552. fallbackWritten = true;
  553. const recording = await startElectronWindowRecording({
  554. outputPath: join(artifactDir, "WMT-03-fallback-full-flow.mp4"),
  555. frameIntervalMs: 200,
  556. });
  557. try {
  558. await setPluginPresentation({
  559. locale: "zh-CN",
  560. theme: "zai-light",
  561. width: 1280,
  562. height: 660,
  563. });
  564. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  565. await waitForTestIdByDom(TID_SETTINGS_PAGE);
  566. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "mcp"));
  567. await browser.$('[data-testid="plugin-settings-scope-trigger"]').click();
  568. await clickOpenScopeMenuOption(paths.workspace);
  569. await waitForTestIdByDom(rowId);
  570. expect(Object.keys(JSON.parse(await readFile(configPath, "utf8")).mcp.servers)).toEqual([
  571. name,
  572. ]);
  573. await clickTestIdByDom(rowId);
  574. await browser.$("button=删除").click();
  575. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM);
  576. await browser.waitUntil(
  577. async () =>
  578. Object.keys(JSON.parse(await readFile(configPath, "utf8")).mcp.servers).length === 0,
  579. { timeout: 15_000 },
  580. );
  581. // 删除只移除当前缓存行;通过真实刷新入口重读目录,发现 fallback 配置。
  582. await clickTestIdByDom("mcp-settings-refresh");
  583. await waitForTestIdByDom(fallbackRowId);
  584. await waitTrusted(false, fallbackRowId);
  585. expect(await exists(fallbackMarker)).toBe(false);
  586. await pause(REVIEW_PAUSE_MS);
  587. await browser.saveScreenshot(join(artifactDir, "WMT-03-fallback-pending.png"));
  588. await clickTestIdByDom(testId("mcp-workspace-trust", fallbackName));
  589. await reviewTrustCode();
  590. await pause(REVIEW_PAUSE_MS);
  591. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM);
  592. await waitTrusted(true, fallbackRowId);
  593. expect(await exists(fallbackMarker)).toBe(false);
  594. await clickTestIdByDom("mcp-settings-refresh");
  595. await browser.waitUntil(
  596. async () =>
  597. (await exists(fallbackMarker)) &&
  598. (await readFile(fallbackMarker, "utf8")).includes('"method":"tools/list"'),
  599. {
  600. timeout: 30_000,
  601. timeoutMsg: "Fallback MCP environment did not reach the real handshake",
  602. },
  603. );
  604. await browser.waitUntil(
  605. async () =>
  606. (await browser.$(`[data-testid="${fallbackRowId}"]`).getAttribute("data-mcp-status")) ===
  607. "connected",
  608. { timeout: 30_000 },
  609. );
  610. // 无效声明没有审核摘要;验证无法批准和零启动,不把 UI 的 unknown 投影当成准入状态。
  611. expect(
  612. await browser
  613. .$(`[data-testid="${testId("mcp-workspace-trust", "e2e_invalid_neighbor")}"]`)
  614. .isEnabled(),
  615. ).toBe(false);
  616. const invalidRow = browser.$(
  617. `[data-testid="${testId(TID_MCP_SERVER_ROW, "e2e_invalid_neighbor")}"]`,
  618. );
  619. expect(await invalidRow.getAttribute("data-mcp-status")).toBe("untrusted");
  620. expect(await invalidRow.getText()).toContain("当前声明待信任");
  621. expect(await invalidRow.getText()).not.toContain("重启 Agent");
  622. expect(await exists(invalidMarker)).toBe(false);
  623. await pause(REVIEW_PAUSE_MS);
  624. await browser.saveScreenshot(join(artifactDir, "WMT-03-fallback-connected.png"));
  625. } finally {
  626. const video = await recording.stop({ tailDurationMs: 1_000 });
  627. expect(video.captureError).toBeUndefined();
  628. }
  629. });
  630. });