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

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