mcp-failure-guidance.test.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { chromium } from "playwright-core";
  4. import {
  5. TID_MCP_SERVER_ROW,
  6. TID_PLUGIN_MCP_SERVER_ROW,
  7. TID_TASK_SETTINGS_BUTTON,
  8. TID_SETTINGS_BACK_BUTTON,
  9. TID_SETTINGS_SECTION_NAV,
  10. testId,
  11. } from "@zcode/shared/test-ids";
  12. import {
  13. clearAppData,
  14. clickTestIdByDom,
  15. getE2EAppDataPaths,
  16. waitForTestIdByDom,
  17. } from "#e2e/helpers/desktop-app";
  18. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  19. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  20. import { obtainUnreadPairingUrl } from "#e2e/helpers/web-remote-unread";
  21. import {
  22. MCP_DIAGNOSTIC_PYTHON,
  23. MCP_DIAGNOSTIC_NODE,
  24. MCP_DIAGNOSTIC_COMMAND,
  25. } from "#e2e/helpers/mcp-failure-guidance-fixture";
  26. const paths = getE2EAppDataPaths();
  27. const artifactDir =
  28. process.env.ZCODE_E2E_ARTIFACT_DIR ?? join(paths.homeDir, "mcp-diagnostic-artifacts");
  29. const pythonRow = testId(TID_MCP_SERVER_ROW, MCP_DIAGNOSTIC_PYTHON);
  30. const nodeRow = testId(TID_PLUGIN_MCP_SERVER_ROW, MCP_DIAGNOSTIC_NODE);
  31. const commandRow = testId(TID_MCP_SERVER_ROW, MCP_DIAGNOSTIC_COMMAND);
  32. const activePopover = '[data-testid="mcp-failure-popover"][data-state="open"]';
  33. type PresentationWindow = Window & {
  34. __testActions?: {
  35. setLocale(locale: "zh-CN" | "en-US"): void;
  36. setTheme(theme: "zai-light" | "zai-dark"): void;
  37. };
  38. };
  39. async function openSettings() {
  40. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  41. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "mcp"));
  42. await waitForTestIdByDom(pythonRow);
  43. await browser.waitUntil(
  44. () =>
  45. browser.execute(
  46. (id) =>
  47. document.querySelector(`[data-testid="${id}"]`)?.getAttribute("data-mcp-status") ===
  48. "error",
  49. pythonRow,
  50. ),
  51. { timeout: 30_000 },
  52. );
  53. }
  54. function expectSafeDetails(text: string, cause: string) {
  55. expect(text).toContain(cause);
  56. expect(text).not.toContain("\u001b");
  57. expect(text).not.toContain("secret");
  58. for (const secret of ["fixture-sensitive", "fixture-bearer", "fixture-pass", "fixture-key"])
  59. expect(text).not.toContain(secret);
  60. }
  61. describe("MCP 启动失败处理建议(候选)", () => {
  62. after(async () => {
  63. await browser.electron.restoreAllMocks();
  64. await clearAppData();
  65. });
  66. it("MCP-DIAG-01: 真实进程失败在详情展示处理建议与脱敏原因", async function () {
  67. this.timeout(180_000);
  68. await mkdir(artifactDir, { recursive: true });
  69. await prepareV4ConversationE2E({ skipProvider: true });
  70. await openSettings();
  71. for (const [id, cause] of [
  72. [pythonRow, "No module named 'mcp'"],
  73. [nodeRow, "Cannot find package 'example-mcp'"],
  74. [commandRow, "ENOENT"],
  75. ] as const) {
  76. const row = await browser.$(`[data-testid="${id}"]`);
  77. await row.scrollIntoView({ block: "center" });
  78. await row.$('button[aria-label="详情"]').click();
  79. // 关闭动画期间旧 Popover 仍挂在 DOM;只读取当前 open 实例,不能取同名第一个节点。
  80. await browser.waitUntil(() => browser.$(activePopover).isExisting(), { timeout: 10_000 });
  81. await writeFile(
  82. join(artifactDir, `MCP-DIAG-01-open-${id.replaceAll(":", "-")}.json`),
  83. JSON.stringify(
  84. await browser.execute(() =>
  85. Array.from(
  86. document.querySelectorAll<HTMLElement>('[data-testid="mcp-failure-popover"]'),
  87. ).map((popover) => ({
  88. state: popover.dataset.state,
  89. opacity: getComputedStyle(popover).opacity,
  90. advice: popover.querySelector('[data-testid="mcp-failure-advice"]')?.textContent,
  91. error: popover.querySelector('[data-testid="mcp-failure-error"]')?.textContent,
  92. })),
  93. ),
  94. null,
  95. 2,
  96. ),
  97. );
  98. await browser.$(`${activePopover} [data-testid="mcp-failure-advice"]`).waitForDisplayed();
  99. expect(
  100. await browser.$(`${activePopover} [data-testid="mcp-failure-advice"]`).getText(),
  101. ).toContain("Python");
  102. expectSafeDetails(
  103. await browser.$(`${activePopover} [data-testid="mcp-failure-error"]`).getText(),
  104. cause!,
  105. );
  106. await browser.saveScreenshot(join(artifactDir, `MCP-DIAG-01-${id.replaceAll(":", "-")}.png`));
  107. await browser.keys("Escape");
  108. }
  109. for (const [locale, theme] of [
  110. ["zh-CN", "zai-dark"],
  111. ["en-US", "zai-light"],
  112. ] as const) {
  113. await browser.execute(
  114. ({ locale, theme }) => {
  115. (window as PresentationWindow).__testActions!.setLocale(locale);
  116. (window as PresentationWindow).__testActions!.setTheme(theme);
  117. },
  118. { locale, theme },
  119. );
  120. const row = await browser.$(`[data-testid="${pythonRow}"]`);
  121. await row.scrollIntoView({ block: "center" });
  122. await row.$(`button[aria-label="${locale === "zh-CN" ? "详情" : "Details"}"]`).click();
  123. // 关闭动画期间旧 Popover 仍挂在 DOM;只读取当前 open 实例,不能取同名第一个节点。
  124. await browser.waitUntil(() => browser.$(activePopover).isExisting(), { timeout: 10_000 });
  125. await browser.$(`${activePopover} [data-testid="mcp-failure-advice"]`).waitForDisplayed();
  126. expect(
  127. await browser.$(`${activePopover} [data-testid="mcp-failure-advice"]`).getText(),
  128. ).toContain(locale === "zh-CN" ? "运行" : "device");
  129. await browser.saveScreenshot(join(artifactDir, `MCP-DIAG-01-${locale}-${theme}.png`));
  130. await browser.keys("Escape");
  131. }
  132. });
  133. it("MCP-DIAG-02: 手机窄屏可读,恢复后刷新清除旧错误", async function () {
  134. this.timeout(180_000);
  135. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  136. const url = await obtainUnreadPairingUrl(
  137. new URL(process.env.ZCODE_WEB_REMOTE_CONTROL_URL!).origin,
  138. );
  139. const mobile = await chromium.launch({ channel: "chrome", headless: true });
  140. const context = await mobile.newContext({ viewport: { width: 390, height: 844 } });
  141. await seedMobileFixtureLogin(context);
  142. const page = await context.newPage();
  143. try {
  144. await openMobilePairingPage(page, url, {
  145. artifactDir,
  146. caseMarker: "MCP-DIAG-02",
  147. phase: "mobile",
  148. readySelector: `[data-testid="${TID_TASK_SETTINGS_BUTTON}"]`,
  149. });
  150. await page.getByTestId(TID_TASK_SETTINGS_BUTTON).click();
  151. await page.getByTestId(testId(TID_SETTINGS_SECTION_NAV, "mcp")).click();
  152. for (const [locale, theme] of [
  153. ["zh-CN", "zai-light"],
  154. ["en-US", "zai-dark"],
  155. ] as const) {
  156. await page.evaluate(
  157. ({ locale, theme }) => {
  158. (window as PresentationWindow).__testActions!.setLocale(locale);
  159. (window as PresentationWindow).__testActions!.setTheme(theme);
  160. },
  161. { locale, theme },
  162. );
  163. await page
  164. .getByTestId(pythonRow)
  165. .getByRole("button", { name: locale === "zh-CN" ? "详情" : "Details", exact: true })
  166. .click();
  167. const popover = page.locator(activePopover);
  168. const advice = popover.getByTestId("mcp-failure-advice");
  169. await advice.waitFor();
  170. expectSafeDetails(
  171. await popover.getByTestId("mcp-failure-error").innerText(),
  172. "No module named 'mcp'",
  173. );
  174. const bounds = await popover.boundingBox();
  175. expect(bounds!.x).toBeGreaterThanOrEqual(0);
  176. expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(390);
  177. await page.screenshot({ path: join(artifactDir, `MCP-DIAG-02-${locale}-${theme}.png`) });
  178. await page.keyboard.press("Escape");
  179. }
  180. } finally {
  181. await context.close();
  182. await mobile.close();
  183. }
  184. await openSettings();
  185. await writeFile(join(paths.storageRoot, "mcp-diagnostic-recovered"), "ready");
  186. await clickTestIdByDom("mcp-settings-refresh");
  187. await browser.waitUntil(
  188. () =>
  189. browser.execute(
  190. (id) =>
  191. document.querySelector(`[data-testid="${id}"]`)?.getAttribute("data-mcp-status") ===
  192. "connected",
  193. pythonRow,
  194. ),
  195. { timeout: 30_000 },
  196. );
  197. expect(
  198. await browser
  199. .$(`[data-testid="${pythonRow}"]`)
  200. .$$('button[aria-label="Details"], button[aria-label="详情"]'),
  201. ).toHaveLength(0);
  202. await browser.saveScreenshot(join(artifactDir, "MCP-DIAG-02-recovered.png"));
  203. });
  204. });