conversation-session-plan-mode-mcp-permission.test.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { dirname, join, resolve } from "node:path";
  3. import { clearAppData, DEFAULT_WORKSPACE } from "../helpers/desktop-app.js";
  4. import {
  5. E2E_REPLY_TOKEN,
  6. approveV4Permission,
  7. prepareV4ConversationE2E,
  8. sendV4Prompt,
  9. waitForV4AssistantMessageContaining,
  10. waitForV4ConversationState,
  11. waitForV4ComposerText,
  12. waitForV4PermissionDialog,
  13. waitForV4UserMessageContaining,
  14. } from "#e2e/helpers/v4-conversation";
  15. import {
  16. getLatestUpstreamToolResultByToolCallId,
  17. waitForUpstreamRequest,
  18. } from "#e2e/helpers/conversation-session-network";
  19. import { waitForToolCallBlockByToolName } from "#e2e/helpers/conversation-session-tool";
  20. const PROMPT_MARKER = "E2E_PLAN_MODE_MCP_PERMISSION";
  21. const LOOKUP_QUERY = "E2E_PLAN_MCP_LOOKUP_QUERY";
  22. const LOOKUP_RESULT = `E2E_PLAN_MCP_LOOKUP_RESULT:${LOOKUP_QUERY}`;
  23. const DESTRUCTIVE_MARKER = "E2E_PLAN_MCP_DESTRUCTIVE_ATTEMPT";
  24. const RESET_RESULT = "E2E_PLAN_MCP_RESET_SHOULD_NOT_RUN";
  25. const DENIAL_TEXT = "Plan mode only allows read-only, non-destructive tools";
  26. const ENTER_TOOL_CALL_ID = "toolu_e2e_plan_mcp_enter_plan";
  27. const LOOKUP_TOOL_CALL_ID = "toolu_e2e_plan_mcp_lookup";
  28. const RESET_TOOL_CALL_ID = "toolu_e2e_plan_mcp_reset";
  29. const LOOKUP_TOOL_NAME = "mcp__plan_mode_e2e__lookup";
  30. const RESET_TOOL_NAME = "mcp__plan_mode_e2e__reset";
  31. const CASE_ROOT = join(DEFAULT_WORKSPACE, "plan-mode-mcp-permission-e2e");
  32. // 修复原因:工作区 MCP 自 2026-10-23 起需逐条信任才会连接,写在工作区 `.zcode/config.json`
  33. // 的 fixture server 停在 untrusted,lookup 报“工具未注册”,走不到 Plan 权限判定。
  34. // 本例只验证 Plan 权限边界,改用隔离 E2E HOME 下的用户级配置注入 server,结束时还原。
  35. const MCP_CONFIG_DIR = join(dirname(DEFAULT_WORKSPACE), ".zcode", "cli");
  36. const MCP_CONFIG_FILE = join(MCP_CONFIG_DIR, "config.json");
  37. // undefined 表示本例尚未写入用户配置;null 表示写入前没有用户配置。
  38. let originalUserConfig: string | null | undefined;
  39. const MCP_CALL_LOG = join(CASE_ROOT, "mcp-calls.ndjson");
  40. const MCP_SERVER_SCRIPT = resolve(
  41. process.cwd(),
  42. "test/e2e/fixtures/mcp/plan-mode-mcp-permission-server.mjs",
  43. );
  44. describe("会话区 Plan mode MCP 权限边界 E2E", () => {
  45. afterEach(async () => {
  46. await cleanupPlanModeMcpFixture();
  47. });
  48. after(async () => {
  49. await browser.electron.restoreAllMocks();
  50. await cleanupPlanModeMcpFixture();
  51. await clearAppData();
  52. });
  53. it("Y01/Y02: Plan mode 对非 destructive MCP 单次询问,并拒绝 destructive MCP", async function () {
  54. this.timeout(180000);
  55. await prepareV4ConversationE2E();
  56. await writePlanModeMcpConfig();
  57. const prompt = [
  58. `${PROMPT_MARKER}: Enter plan mode first.`,
  59. `Then call ${LOOKUP_TOOL_NAME} with query ${LOOKUP_QUERY}.`,
  60. `After lookup, call ${RESET_TOOL_NAME} with marker ${DESTRUCTIVE_MARKER}.`,
  61. `Do not call ExitPlanMode. Finish only after the MCP boundary is handled.`,
  62. ].join(" ");
  63. await sendV4Prompt(prompt);
  64. await waitForV4ComposerText("", "Plan mode MCP 首发后输入框没有清空");
  65. await waitForV4UserMessageContaining(PROMPT_MARKER);
  66. await waitForUpstreamRequest(
  67. {
  68. includes: [PROMPT_MARKER, LOOKUP_TOOL_NAME, RESET_TOOL_NAME],
  69. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  70. },
  71. "首轮请求没有暴露 Plan mode MCP E2E 工具 schema",
  72. 60000,
  73. );
  74. // 原因:V4 不展示内部 EnterPlanMode 行;检查真实工具结果,保留模式切换断言。
  75. await browser.waitUntil(
  76. async () =>
  77. (await getLatestUpstreamToolResultByToolCallId(ENTER_TOOL_CALL_ID))?.isError === false,
  78. { timeout: 60_000, timeoutMsg: "EnterPlanMode 没有产生成功的真实工具结果" },
  79. );
  80. await waitForUpstreamRequest(
  81. {
  82. includes: [PROMPT_MARKER, ENTER_TOOL_CALL_ID],
  83. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  84. },
  85. "EnterPlanMode 结果没有进入 lookup 前的 provider continuation",
  86. 60000,
  87. );
  88. await waitForToolCallBlockByToolName(LOOKUP_TOOL_NAME, 90000);
  89. // 原因:Plan 只在原模式(build)之上收紧,非只读 MCP 必须先经用户确认;
  90. // 在 Plan 下记住的规则不会生效,所以弹窗不提供"始终允许"。
  91. await waitForV4PermissionDialog(60000);
  92. expect((await readMcpCalls()).some((call) => call.tool === "lookup")).toBe(false);
  93. expect(
  94. await browser.execute(
  95. () => document.querySelectorAll('[data-permission-option-kind="allowAlways"]').length,
  96. ),
  97. ).toBe(0);
  98. expect(await approveV4Permission()).toBe(true);
  99. await waitForMcpCall("lookup", 60000);
  100. await waitForUpstreamRequest(
  101. {
  102. includes: [PROMPT_MARKER, LOOKUP_TOOL_CALL_ID, LOOKUP_RESULT],
  103. excludes: [DENIAL_TEXT, "Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  104. },
  105. "非 destructive MCP lookup 允许一次后没有真实执行并进入 provider continuation",
  106. 60000,
  107. );
  108. await waitForToolCallBlockByToolName(RESET_TOOL_NAME, 60000);
  109. await waitForUpstreamRequest(
  110. {
  111. includes: [PROMPT_MARKER, RESET_TOOL_CALL_ID, DENIAL_TEXT],
  112. excludes: [RESET_RESULT, "Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  113. },
  114. "destructive MCP reset 没有在调用 server 前被 Plan mode 拒绝",
  115. 60000,
  116. );
  117. const resetBlock = await waitForToolCallBlockStatus(
  118. RESET_TOOL_NAME,
  119. // V4 权限拒绝投影为 cancelled/stopped;保留上游拒绝原因和 server 零调用断言。
  120. "stopped",
  121. 60000,
  122. );
  123. expect(resetBlock.text).not.toContain("Running");
  124. await waitForV4AssistantMessageContaining(E2E_REPLY_TOKEN);
  125. await waitForV4ConversationState(
  126. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  127. "Plan mode MCP 权限边界 case 完成后没有回到 idle",
  128. 60000,
  129. );
  130. const calls = await readMcpCalls();
  131. expect(calls.some((call) => call.tool === "lookup")).toBe(true);
  132. expect(calls.some((call) => call.tool === "reset")).toBe(false);
  133. });
  134. });
  135. async function writePlanModeMcpConfig() {
  136. await mkdir(CASE_ROOT, { recursive: true });
  137. await mkdir(MCP_CONFIG_DIR, { recursive: true });
  138. originalUserConfig = await readFile(MCP_CONFIG_FILE, "utf-8").catch((error: unknown) => {
  139. if (error instanceof Error && "code" in error && error.code === "ENOENT") return null;
  140. throw error;
  141. });
  142. const existing = originalUserConfig
  143. ? (JSON.parse(originalUserConfig) as Record<string, unknown>)
  144. : {};
  145. await writeFile(
  146. MCP_CONFIG_FILE,
  147. `${JSON.stringify(
  148. {
  149. ...existing,
  150. mcp: {
  151. servers: {
  152. plan_mode_e2e: {
  153. type: "stdio",
  154. command: process.execPath,
  155. args: [MCP_SERVER_SCRIPT],
  156. env: {
  157. E2E_PLAN_MCP_CALL_LOG: MCP_CALL_LOG,
  158. },
  159. timeoutMs: 30000,
  160. },
  161. },
  162. },
  163. },
  164. null,
  165. 2,
  166. )}\n`,
  167. "utf-8",
  168. );
  169. }
  170. async function cleanupPlanModeMcpFixture() {
  171. await rm(CASE_ROOT, { recursive: true, force: true });
  172. if (originalUserConfig === undefined) return;
  173. if (originalUserConfig === null) {
  174. await rm(MCP_CONFIG_FILE, { force: true });
  175. } else {
  176. await writeFile(MCP_CONFIG_FILE, originalUserConfig, "utf-8");
  177. }
  178. originalUserConfig = undefined;
  179. }
  180. interface McpCallLogEntry {
  181. tool?: string;
  182. }
  183. async function waitForMcpCall(tool: string, timeoutMs: number) {
  184. let latest: McpCallLogEntry[] = [];
  185. await browser.waitUntil(
  186. async () => {
  187. latest = await readMcpCalls();
  188. return latest.some((call) => call.tool === tool);
  189. },
  190. {
  191. timeout: timeoutMs,
  192. timeoutMsg: `没有等到 MCP server 调用 ${tool}; latest=${JSON.stringify(latest)}`,
  193. },
  194. );
  195. }
  196. async function waitForToolCallBlockStatus(toolName: string, status: string, timeoutMs: number) {
  197. let latest = await waitForToolCallBlockByToolName(toolName, timeoutMs);
  198. await browser.waitUntil(
  199. async () => {
  200. latest = await waitForToolCallBlockByToolName(toolName, timeoutMs);
  201. return latest.status === status;
  202. },
  203. {
  204. timeout: timeoutMs,
  205. timeoutMsg: `tool block ${toolName} 没有进入 ${status}; latest=${JSON.stringify(latest)}`,
  206. },
  207. );
  208. return latest;
  209. }
  210. async function readMcpCalls(): Promise<McpCallLogEntry[]> {
  211. try {
  212. const raw = await readFile(MCP_CALL_LOG, "utf-8");
  213. return raw
  214. .split("\n")
  215. .map((line) => line.trim())
  216. .filter(Boolean)
  217. .map((line) => JSON.parse(line) as McpCallLogEntry);
  218. } catch (error) {
  219. if (error instanceof Error && "code" in error && error.code === "ENOENT") {
  220. return [];
  221. }
  222. throw error;
  223. }
  224. }