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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { join, resolve } from "node:path";
  3. import { clearAppData, DEFAULT_WORKSPACE } from "../helpers/desktop-app.js";
  4. import {
  5. E2E_REPLY_TOKEN,
  6. prepareV4ConversationE2E,
  7. sendV4Prompt,
  8. waitForV4AssistantMessageContaining,
  9. waitForV4ConversationState,
  10. waitForV4ComposerText,
  11. waitForV4UserMessageContaining,
  12. } from "#e2e/helpers/v4-conversation";
  13. import {
  14. getLatestUpstreamToolResultByToolCallId,
  15. waitForUpstreamRequest,
  16. } from "#e2e/helpers/conversation-session-network";
  17. import { waitForToolCallBlockByToolName } from "#e2e/helpers/conversation-session-tool";
  18. const PROMPT_MARKER = "E2E_PLAN_MODE_MCP_PERMISSION";
  19. const LOOKUP_QUERY = "E2E_PLAN_MCP_LOOKUP_QUERY";
  20. const LOOKUP_RESULT = `E2E_PLAN_MCP_LOOKUP_RESULT:${LOOKUP_QUERY}`;
  21. const DESTRUCTIVE_MARKER = "E2E_PLAN_MCP_DESTRUCTIVE_ATTEMPT";
  22. const RESET_RESULT = "E2E_PLAN_MCP_RESET_SHOULD_NOT_RUN";
  23. const DENIAL_TEXT = "Plan mode only allows read-only, non-destructive tools";
  24. const ENTER_TOOL_CALL_ID = "toolu_e2e_plan_mcp_enter_plan";
  25. const LOOKUP_TOOL_CALL_ID = "toolu_e2e_plan_mcp_lookup";
  26. const RESET_TOOL_CALL_ID = "toolu_e2e_plan_mcp_reset";
  27. const LOOKUP_TOOL_NAME = "mcp__plan_mode_e2e__lookup";
  28. const RESET_TOOL_NAME = "mcp__plan_mode_e2e__reset";
  29. const CASE_ROOT = join(DEFAULT_WORKSPACE, "plan-mode-mcp-permission-e2e");
  30. const MCP_CONFIG_DIR = join(DEFAULT_WORKSPACE, ".zcode");
  31. const MCP_CONFIG_FILE = join(MCP_CONFIG_DIR, "config.json");
  32. const MCP_CALL_LOG = join(CASE_ROOT, "mcp-calls.ndjson");
  33. const MCP_SERVER_SCRIPT = resolve(
  34. process.cwd(),
  35. "test/e2e/fixtures/mcp/plan-mode-mcp-permission-server.mjs",
  36. );
  37. describe("会话区 Plan mode MCP 权限边界 E2E", () => {
  38. afterEach(async () => {
  39. await cleanupPlanModeMcpFixture();
  40. });
  41. after(async () => {
  42. await browser.electron.restoreAllMocks();
  43. await cleanupPlanModeMcpFixture();
  44. await clearAppData();
  45. });
  46. it("Y01/Y02: Plan mode 允许非 destructive MCP,但拒绝 destructive MCP", async function () {
  47. this.timeout(180000);
  48. await prepareV4ConversationE2E();
  49. await writePlanModeMcpConfig();
  50. const prompt = [
  51. `${PROMPT_MARKER}: Enter plan mode first.`,
  52. `Then call ${LOOKUP_TOOL_NAME} with query ${LOOKUP_QUERY}.`,
  53. `After lookup, call ${RESET_TOOL_NAME} with marker ${DESTRUCTIVE_MARKER}.`,
  54. `Do not call ExitPlanMode. Finish only after the MCP boundary is handled.`,
  55. ].join(" ");
  56. await sendV4Prompt(prompt);
  57. await waitForV4ComposerText("", "Plan mode MCP 首发后输入框没有清空");
  58. await waitForV4UserMessageContaining(PROMPT_MARKER);
  59. await waitForUpstreamRequest(
  60. {
  61. includes: [PROMPT_MARKER, LOOKUP_TOOL_NAME, RESET_TOOL_NAME],
  62. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  63. },
  64. "首轮请求没有暴露 Plan mode MCP E2E 工具 schema",
  65. 60000,
  66. );
  67. // 原因:V4 不展示内部 EnterPlanMode 行;检查真实工具结果,保留模式切换断言。
  68. await browser.waitUntil(
  69. async () =>
  70. (await getLatestUpstreamToolResultByToolCallId(ENTER_TOOL_CALL_ID))?.isError === false,
  71. { timeout: 60_000, timeoutMsg: "EnterPlanMode 没有产生成功的真实工具结果" },
  72. );
  73. await waitForUpstreamRequest(
  74. {
  75. includes: [PROMPT_MARKER, ENTER_TOOL_CALL_ID],
  76. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  77. },
  78. "EnterPlanMode 结果没有进入 lookup 前的 provider continuation",
  79. 60000,
  80. );
  81. await waitForToolCallBlockByToolName(LOOKUP_TOOL_NAME, 90000);
  82. await waitForMcpCall("lookup", 60000);
  83. await waitForUpstreamRequest(
  84. {
  85. includes: [PROMPT_MARKER, LOOKUP_TOOL_CALL_ID, LOOKUP_RESULT],
  86. excludes: [DENIAL_TEXT, "Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  87. },
  88. "非 destructive MCP lookup 没有真实执行并进入 provider continuation",
  89. 60000,
  90. );
  91. await waitForToolCallBlockByToolName(RESET_TOOL_NAME, 60000);
  92. await waitForUpstreamRequest(
  93. {
  94. includes: [PROMPT_MARKER, RESET_TOOL_CALL_ID, DENIAL_TEXT],
  95. excludes: [RESET_RESULT, "Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  96. },
  97. "destructive MCP reset 没有在调用 server 前被 Plan mode 拒绝",
  98. 60000,
  99. );
  100. const resetBlock = await waitForToolCallBlockStatus(
  101. RESET_TOOL_NAME,
  102. // V4 权限拒绝投影为 cancelled/stopped;保留上游拒绝原因和 server 零调用断言。
  103. "stopped",
  104. 60000,
  105. );
  106. expect(resetBlock.text).not.toContain("Running");
  107. await waitForV4AssistantMessageContaining(E2E_REPLY_TOKEN);
  108. await waitForV4ConversationState(
  109. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  110. "Plan mode MCP 权限边界 case 完成后没有回到 idle",
  111. 60000,
  112. );
  113. const calls = await readMcpCalls();
  114. expect(calls.some((call) => call.tool === "lookup")).toBe(true);
  115. expect(calls.some((call) => call.tool === "reset")).toBe(false);
  116. });
  117. });
  118. async function writePlanModeMcpConfig() {
  119. await mkdir(CASE_ROOT, { recursive: true });
  120. await mkdir(MCP_CONFIG_DIR, { recursive: true });
  121. await writeFile(
  122. MCP_CONFIG_FILE,
  123. `${JSON.stringify(
  124. {
  125. mcp: {
  126. servers: {
  127. plan_mode_e2e: {
  128. type: "stdio",
  129. command: process.execPath,
  130. args: [MCP_SERVER_SCRIPT],
  131. env: {
  132. E2E_PLAN_MCP_CALL_LOG: MCP_CALL_LOG,
  133. },
  134. timeoutMs: 30000,
  135. },
  136. },
  137. },
  138. },
  139. null,
  140. 2,
  141. )}\n`,
  142. "utf-8",
  143. );
  144. }
  145. async function cleanupPlanModeMcpFixture() {
  146. await rm(CASE_ROOT, { recursive: true, force: true });
  147. await rm(MCP_CONFIG_FILE, { force: true });
  148. }
  149. interface McpCallLogEntry {
  150. tool?: string;
  151. }
  152. async function waitForMcpCall(tool: string, timeoutMs: number) {
  153. let latest: McpCallLogEntry[] = [];
  154. await browser.waitUntil(
  155. async () => {
  156. latest = await readMcpCalls();
  157. return latest.some((call) => call.tool === tool);
  158. },
  159. {
  160. timeout: timeoutMs,
  161. timeoutMsg: `没有等到 MCP server 调用 ${tool}; latest=${JSON.stringify(latest)}`,
  162. },
  163. );
  164. }
  165. async function waitForToolCallBlockStatus(toolName: string, status: string, timeoutMs: number) {
  166. let latest = await waitForToolCallBlockByToolName(toolName, timeoutMs);
  167. await browser.waitUntil(
  168. async () => {
  169. latest = await waitForToolCallBlockByToolName(toolName, timeoutMs);
  170. return latest.status === status;
  171. },
  172. {
  173. timeout: timeoutMs,
  174. timeoutMsg: `tool block ${toolName} 没有进入 ${status}; latest=${JSON.stringify(latest)}`,
  175. },
  176. );
  177. return latest;
  178. }
  179. async function readMcpCalls(): Promise<McpCallLogEntry[]> {
  180. try {
  181. const raw = await readFile(MCP_CALL_LOG, "utf-8");
  182. return raw
  183. .split("\n")
  184. .map((line) => line.trim())
  185. .filter(Boolean)
  186. .map((line) => JSON.parse(line) as McpCallLogEntry);
  187. } catch (error) {
  188. if (error instanceof Error && "code" in error && error.code === "ENOENT") {
  189. return [];
  190. }
  191. throw error;
  192. }
  193. }