conversation-session-v4-permission.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. // M4 门禁:v4 前向命令 resolveInteraction 收口反向权限请求(catalog Q 组 / permission)。
  2. // 证据层 L3:Write 工具在默认模式触发权限弹窗 → V4InteractionDialogs 渲染 →
  3. // 批准 → resolveInteraction 命令经 v4-bridge → interaction-broker race deferred 收口 →
  4. // 工具执行 → tool_result 回灌 → 终态文本。证明反向 RPC 与前向命令的汇合点打通。
  5. import { access, mkdir, rm } from "node:fs/promises";
  6. import { clearAppData } from "#e2e/helpers/desktop-app";
  7. import { resolveE2ERuntimePath, resolveE2EToolPath } from "#e2e/helpers/e2e-runtime-paths";
  8. import { selectTaskById } from "#e2e/helpers/conversation-session";
  9. import {
  10. approveV4Permission,
  11. denyV4PermissionWithFeedback,
  12. getV4PaneSnapshot,
  13. prepareV4ConversationE2E,
  14. startNewV4Draft,
  15. sendV4Prompt,
  16. waitForV4PermissionDialogInComposerDock,
  17. waitForV4TimelineContaining,
  18. } from "#e2e/helpers/v4-conversation";
  19. import { getLatestUpstreamToolResultByToolCallId } from "#e2e/helpers/conversation-session-network";
  20. import {
  21. beginConversationTelemetryCapture,
  22. readAllEventReportRequests,
  23. type ConversationTelemetryCaptureHandle,
  24. type ConversationTelemetryReport,
  25. } from "#e2e/helpers/conversation-telemetry-parity-capture";
  26. const V4_PERMISSION_CASE = "conversation-session-v4-permission";
  27. const V4_PERMISSION_DIR = resolveE2ERuntimePath(V4_PERMISSION_CASE);
  28. const V4_PERMISSION_OUTPUT_PATH = resolveE2EToolPath(V4_PERMISSION_CASE, "write-output.txt");
  29. const V4_PERMISSION_ALLOW_FEEDBACK_OUTPUT_PATH = resolveE2EToolPath(
  30. V4_PERMISSION_CASE,
  31. "allow-feedback-output.txt",
  32. );
  33. const V4_PERMISSION_DENY_OUTPUT_PATH = resolveE2EToolPath(V4_PERMISSION_CASE, "deny-output.txt");
  34. const V4_PERMISSION_DENY_BLANK_OUTPUT_PATH = resolveE2EToolPath(
  35. V4_PERMISSION_CASE,
  36. "deny-blank-output.txt",
  37. );
  38. const V4_PERMISSION_ALLOW_FEEDBACK = "This note must be ignored when allowing the tool.";
  39. const V4_PERMISSION_DENY_FEEDBACK =
  40. "Do not write the file; explain that the requested change needs clarification first. " +
  41. "Additional context: " +
  42. "x".repeat(600);
  43. const V4_PERMISSION_DENY_BASE_CONTENT =
  44. "The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed.";
  45. describe("v4 M4 门禁:resolveInteraction 收口权限请求", () => {
  46. before(async () => {
  47. await rm(V4_PERMISSION_DIR, { recursive: true, force: true });
  48. await mkdir(V4_PERMISSION_DIR, { recursive: true });
  49. });
  50. after(async () => {
  51. await browser.electron.restoreAllMocks();
  52. await clearAppData();
  53. await rm(V4_PERMISSION_DIR, { recursive: true, force: true });
  54. });
  55. it("默认模式 Write 工具触发权限弹窗,批准后工具执行并出终态文本", async () => {
  56. await prepareV4ConversationE2E();
  57. await ensurePermissionTelemetryCapture();
  58. const baseline = await countPermissionResults("toolu_v4_permission_write");
  59. await sendV4Prompt(`E2E_V4_PERMISSION_WRITE 请写入文件 ${V4_PERMISSION_OUTPUT_PATH}`);
  60. // 反向权限请求 → V4InteractionDialogs 渲染 PermissionDialog。
  61. // Bugfix: v4 权限等待态是 bottom dock 阻塞交互,不应退回 SessionPane 外层全宽底部卡片。
  62. const dockState = await waitForV4PermissionDialogInComposerDock();
  63. // 待处理权限只在底部卡片展示,顶部不再重复提示。
  64. await expect($('[data-testid="v4-pending-interaction-top-notice"]')).not.toExist();
  65. expect(dockState.inDock).toBe(true);
  66. expect(dockState.composerHidden).toBe(true);
  67. expect(dockState.interactionBeforeComposer).toBe(true);
  68. expect(await readPermissionFeedbackTextareaSemantics()).toEqual({
  69. tagName: "TEXTAREA",
  70. rows: "1",
  71. autoSizing: true,
  72. maxRows: true,
  73. index: "5.",
  74. indexCenteredOnFirstLine: true,
  75. rowGaps: [4, 4, 4, 4],
  76. });
  77. // 前向 resolveInteraction 命令收口
  78. const dismissed = await approveV4Permission();
  79. expect(dismissed).toBe(true);
  80. // 批准后工具执行 → tool_result 回灌 → 终态文本
  81. await waitForV4TimelineContaining("V4_PERMISSION_DONE", 60000);
  82. // 用户在弹窗上的选择上报一次,message_id 指向本轮发送。
  83. const { result, reports } = await waitForPermissionResult(
  84. "toolu_v4_permission_write",
  85. baseline,
  86. );
  87. expect(detailOf(result)).toMatchObject({
  88. option: "allow_once",
  89. has_feedback: "0",
  90. tool_name: "Write",
  91. tool_call_id: "toolu_v4_permission_write",
  92. from_subagent: "0",
  93. ack: "accepted",
  94. });
  95. expect(Number(detailOf(result).wait_ms)).toBeGreaterThanOrEqual(0);
  96. expect(result.message_id).toBeTruthy();
  97. expect(
  98. reports.some((r) => r.element_name === "send_btn" && r.message_id === result.message_id),
  99. ).toBe(true);
  100. });
  101. it("批准时填写的反馈被忽略,工具仍按 Allow once 执行", async () => {
  102. await prepareV4ConversationE2E();
  103. await ensurePermissionTelemetryCapture();
  104. const baseline = await countPermissionResults("toolu_v4_permission_allow_feedback");
  105. await sendV4Prompt(
  106. `E2E_V4_PERMISSION_ALLOW_FEEDBACK 请写入文件 ${V4_PERMISSION_ALLOW_FEEDBACK_OUTPUT_PATH}`,
  107. );
  108. await waitForV4PermissionDialogInComposerDock();
  109. expect(await approveV4Permission(V4_PERMISSION_ALLOW_FEEDBACK)).toBe(true);
  110. await waitForV4TimelineContaining("V4_PERMISSION_ALLOW_FEEDBACK_DONE", 60000);
  111. // 批准时填写的反馈会被忽略,不算写了理由。
  112. const { result } = await waitForPermissionResult(
  113. "toolu_v4_permission_allow_feedback",
  114. baseline,
  115. );
  116. expect(detailOf(result)).toMatchObject({ option: "allow_once", has_feedback: "0" });
  117. const allowedResult = await getLatestUpstreamToolResultByToolCallId(
  118. "toolu_v4_permission_allow_feedback",
  119. );
  120. expect(allowedResult?.isError).toBe(false);
  121. expect(allowedResult?.content).not.toContain(V4_PERMISSION_ALLOW_FEEDBACK);
  122. await expectFileExists(V4_PERMISSION_ALLOW_FEEDBACK_OUTPUT_PATH);
  123. });
  124. for (const submitWithEnter of [true, false]) {
  125. it(`第 5 行填写反馈并${submitWithEnter ? "回车" : "确认"},反馈进入同一个 provider-visible tool_result 且工具不执行`, async () => {
  126. await prepareV4ConversationE2E();
  127. await ensurePermissionTelemetryCapture();
  128. const baseline = await countPermissionResults("toolu_v4_permission_deny_feedback");
  129. await sendV4Prompt(
  130. `E2E_V4_PERMISSION_DENY_FEEDBACK 请写入文件 ${V4_PERMISSION_DENY_OUTPUT_PATH}`,
  131. );
  132. await waitForV4PermissionDialogInComposerDock();
  133. const input = await $(
  134. 'textarea[aria-label="Optional feedback for the model when denying"],textarea[aria-label="拒绝时给模型的可选反馈"]',
  135. );
  136. const allow = await $('[data-permission-option-kind="allowOnce"]');
  137. const deny = await $('[data-permission-option-kind^="reject"]');
  138. await expect(allow).toBeFocused();
  139. await browser.keys("ArrowUp");
  140. await expect(input).toBeFocused();
  141. expect((await readPermissionFeedbackTextareaSemantics()).index).toBe("5.");
  142. expect(await deny.getAttribute("aria-selected")).toBe("false");
  143. await browser.keys("ArrowUp");
  144. await expect(deny).toBeFocused();
  145. expect(
  146. await browser.execute(() =>
  147. document
  148. .querySelector(
  149. 'textarea[aria-label="Optional feedback for the model when denying"],textarea[aria-label="拒绝时给模型的可选反馈"]',
  150. )
  151. ?.parentElement?.classList.contains("bg-selected"),
  152. ),
  153. ).toBe(false);
  154. await browser.keys("Tab");
  155. await expect(input).toBeFocused();
  156. await browser.keys(["Shift", "Tab"]);
  157. await expect(deny).toBeFocused();
  158. await browser.keys("ArrowDown");
  159. await expect(input).toBeFocused();
  160. expect(await denyV4PermissionWithFeedback(V4_PERMISSION_DENY_FEEDBACK, submitWithEnter)).toBe(
  161. true,
  162. );
  163. await waitForV4TimelineContaining("V4_PERMISSION_DENY_DONE", 60000);
  164. // 两个参数化用例共用同一 tool_call_id,按本用例开始前的条数取增量。
  165. const { result } = await waitForPermissionResult(
  166. "toolu_v4_permission_deny_feedback",
  167. baseline,
  168. );
  169. expect(detailOf(result)).toMatchObject({
  170. option: "deny",
  171. has_feedback: "1",
  172. ack: "accepted",
  173. });
  174. expect(JSON.stringify(result)).not.toContain("Additional context");
  175. const deniedResult = await getLatestUpstreamToolResultByToolCallId(
  176. "toolu_v4_permission_deny_feedback",
  177. );
  178. expect(deniedResult?.isError).toBe(true);
  179. expect(deniedResult?.content).toBe(
  180. V4_PERMISSION_DENY_BASE_CONTENT +
  181. " To tell you how to proceed, the user said:\n" +
  182. V4_PERMISSION_DENY_FEEDBACK,
  183. );
  184. await expectFileMissing(V4_PERMISSION_DENY_OUTPUT_PATH);
  185. });
  186. }
  187. it("拒绝时只有空白反馈,provider-visible tool_result 保持基础 Deny 文案", async () => {
  188. await prepareV4ConversationE2E();
  189. await ensurePermissionTelemetryCapture();
  190. const baseline = await countPermissionResults("toolu_v4_permission_deny_blank");
  191. await sendV4Prompt(
  192. `E2E_V4_PERMISSION_DENY_BLANK 请写入文件 ${V4_PERMISSION_DENY_BLANK_OUTPUT_PATH}`,
  193. );
  194. await waitForV4PermissionDialogInComposerDock();
  195. // 弹窗挂起时切到别的任务再回来:wait_ms 从首次出现算,不因会话切换、面板重挂载重置。
  196. const sessionId = (await getV4PaneSnapshot()).sessionId!;
  197. await startNewV4Draft();
  198. await browser.pause(PERMISSION_AWAY_MS);
  199. await selectTaskById(sessionId);
  200. await waitForV4PermissionDialogInComposerDock();
  201. expect(await denyV4PermissionWithFeedback(" ")).toBe(true);
  202. await waitForV4TimelineContaining("V4_PERMISSION_DENY_BLANK_DONE", 60000);
  203. const { result } = await waitForPermissionResult("toolu_v4_permission_deny_blank", baseline);
  204. expect(detailOf(result)).toMatchObject({ option: "deny", has_feedback: "0", ack: "accepted" });
  205. expect(Number(detailOf(result).wait_ms)).toBeGreaterThanOrEqual(PERMISSION_AWAY_MS);
  206. const deniedResult = await getLatestUpstreamToolResultByToolCallId(
  207. "toolu_v4_permission_deny_blank",
  208. );
  209. expect(deniedResult?.isError).toBe(true);
  210. expect(deniedResult?.content).toBe(V4_PERMISSION_DENY_BASE_CONTENT);
  211. expect(deniedResult?.content).not.toContain("To tell you how to proceed");
  212. await expectFileMissing(V4_PERMISSION_DENY_BLANK_OUTPUT_PATH);
  213. });
  214. });
  215. async function expectFileExists(path: string) {
  216. const exists = await access(path)
  217. .then(() => true)
  218. .catch(() => false);
  219. expect(exists).toBe(true);
  220. }
  221. async function expectFileMissing(path: string) {
  222. const exists = await access(path)
  223. .then(() => true)
  224. .catch(() => false);
  225. expect(exists).toBe(false);
  226. }
  227. async function readPermissionFeedbackTextareaSemantics() {
  228. return browser.execute(() => {
  229. const textarea = document.querySelector<HTMLTextAreaElement>(
  230. 'textarea[aria-label="Optional feedback for the model when denying"],textarea[aria-label="拒绝时给模型的可选反馈"]',
  231. );
  232. const style = textarea ? getComputedStyle(textarea) : null;
  233. const indexRect = textarea?.previousElementSibling?.getBoundingClientRect();
  234. // 原因:反馈行曾落在外层 12px 分组间距中;校验实际位置,避免只匹配样式名。
  235. const feedbackRow = textarea?.parentElement;
  236. // 原因:切换模式行由按钮和其下方的模式提示组成;按按钮量会把提示文字算进行间距(得到 26)。
  237. // 量 listbox 的直接子元素,即用户看到的整行,仍校验行与行之间的 4px 分组。
  238. const rowRects = [
  239. ...Array.from(feedbackRow?.previousElementSibling?.children ?? []),
  240. ...(feedbackRow ? [feedbackRow] : []),
  241. ].map((row) => row.getBoundingClientRect());
  242. return {
  243. tagName: textarea?.tagName ?? null,
  244. rows: textarea?.getAttribute("rows") ?? null,
  245. autoSizing: textarea?.classList.contains("field-sizing-content") ?? false,
  246. maxRows: textarea?.classList.contains("max-h-[5lh]") ?? false,
  247. index: textarea?.previousElementSibling?.textContent ?? null,
  248. rowGaps: rowRects.slice(1).map((rect, index) => rect.top - rowRects[index]!.bottom),
  249. indexCenteredOnFirstLine: Boolean(
  250. textarea &&
  251. style &&
  252. indexRect &&
  253. Math.abs(
  254. indexRect.top +
  255. indexRect.height / 2 -
  256. (textarea.getBoundingClientRect().top +
  257. parseFloat(style.borderTopWidth) +
  258. parseFloat(style.paddingTop) +
  259. parseFloat(style.lineHeight) / 2),
  260. ) <= 0.5,
  261. ),
  262. };
  263. });
  264. }
  265. let permissionTelemetryCapture: ConversationTelemetryCaptureHandle | undefined;
  266. /** 整个 spec 共用一次 /event/report 抓取;各用例按 tool_call_id 取自己的上报。 */
  267. async function ensurePermissionTelemetryCapture() {
  268. permissionTelemetryCapture ??= await beginConversationTelemetryCapture();
  269. }
  270. function detailOf(report: ConversationTelemetryReport): Record<string, string> {
  271. return (report.event_extra_detail ?? {}) as Record<string, string>;
  272. }
  273. const PERMISSION_AWAY_MS = 3000;
  274. function permissionResultsOf(reports: ConversationTelemetryReport[], toolCallId: string) {
  275. return reports.filter(
  276. (r) => r.element_name === "permission_prompt_result" && detailOf(r).tool_call_id === toolCallId,
  277. );
  278. }
  279. /** 用例开始前的已有条数;断言只看本用例的增量,不依赖其它用例是否先跑。 */
  280. async function countPermissionResults(toolCallId: string) {
  281. if (!permissionTelemetryCapture) throw new Error("权限埋点抓取未启动");
  282. const reports = await readAllEventReportRequests(permissionTelemetryCapture);
  283. return permissionResultsOf(reports, toolCallId).length;
  284. }
  285. /** 等本用例恰好新增一条上报,返回这一条。 */
  286. async function waitForPermissionResult(toolCallId: string, baseline: number) {
  287. if (!permissionTelemetryCapture) throw new Error("权限埋点抓取未启动");
  288. const capture = permissionTelemetryCapture;
  289. let reports: ConversationTelemetryReport[] = [];
  290. await browser.waitUntil(
  291. async () => {
  292. reports = await readAllEventReportRequests(capture);
  293. return permissionResultsOf(reports, toolCallId).length > baseline;
  294. },
  295. { timeout: 30000, timeoutMsg: `${toolCallId} 的 permission_prompt_result 没有新增上报` },
  296. );
  297. const matches = permissionResultsOf(reports, toolCallId);
  298. expect(matches).toHaveLength(baseline + 1);
  299. return { result: matches[baseline]!, reports };
  300. }