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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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 "../helpers/desktop-app.js";
  7. import { resolveE2ERuntimePath, resolveE2EToolPath } from "../helpers/e2e-runtime-paths.js";
  8. import {
  9. approveV4Permission,
  10. denyV4PermissionWithFeedback,
  11. prepareV4ConversationE2E,
  12. sendV4Prompt,
  13. waitForV4PermissionDialogInComposerDock,
  14. waitForV4TimelineContaining,
  15. } from "../helpers/v4-conversation.js";
  16. import { getLatestUpstreamToolResultByToolCallId } from "../helpers/conversation-session-network.js";
  17. const V4_PERMISSION_CASE = "conversation-session-v4-permission";
  18. const V4_PERMISSION_DIR = resolveE2ERuntimePath(V4_PERMISSION_CASE);
  19. const V4_PERMISSION_OUTPUT_PATH = resolveE2EToolPath(V4_PERMISSION_CASE, "write-output.txt");
  20. const V4_PERMISSION_ALLOW_FEEDBACK_OUTPUT_PATH = resolveE2EToolPath(
  21. V4_PERMISSION_CASE,
  22. "allow-feedback-output.txt",
  23. );
  24. const V4_PERMISSION_DENY_OUTPUT_PATH = resolveE2EToolPath(V4_PERMISSION_CASE, "deny-output.txt");
  25. const V4_PERMISSION_DENY_BLANK_OUTPUT_PATH = resolveE2EToolPath(
  26. V4_PERMISSION_CASE,
  27. "deny-blank-output.txt",
  28. );
  29. const V4_PERMISSION_ALLOW_FEEDBACK = "This note must be ignored when allowing the tool.";
  30. const V4_PERMISSION_DENY_FEEDBACK =
  31. "Do not write the file; explain that the requested change needs clarification first. " +
  32. "Additional context: " +
  33. "x".repeat(600);
  34. const V4_PERMISSION_DENY_BASE_CONTENT =
  35. "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.";
  36. describe("v4 M4 门禁:resolveInteraction 收口权限请求", () => {
  37. before(async () => {
  38. await rm(V4_PERMISSION_DIR, { recursive: true, force: true });
  39. await mkdir(V4_PERMISSION_DIR, { recursive: true });
  40. });
  41. after(async () => {
  42. await browser.electron.restoreAllMocks();
  43. await clearAppData();
  44. await rm(V4_PERMISSION_DIR, { recursive: true, force: true });
  45. });
  46. it("默认模式 Write 工具触发权限弹窗,批准后工具执行并出终态文本", async () => {
  47. await prepareV4ConversationE2E();
  48. await sendV4Prompt(`E2E_V4_PERMISSION_WRITE 请写入文件 ${V4_PERMISSION_OUTPUT_PATH}`);
  49. // 反向权限请求 → V4InteractionDialogs 渲染 PermissionDialog。
  50. // Bugfix: v4 权限等待态是 bottom dock 阻塞交互,不应退回 SessionPane 外层全宽底部卡片。
  51. const dockState = await waitForV4PermissionDialogInComposerDock();
  52. // 待处理权限只在底部卡片展示,顶部不再重复提示。
  53. await expect($('[data-testid="v4-pending-interaction-top-notice"]')).not.toExist();
  54. expect(dockState.inDock).toBe(true);
  55. expect(dockState.composerHidden).toBe(true);
  56. expect(dockState.interactionBeforeComposer).toBe(true);
  57. expect(await readPermissionFeedbackTextareaSemantics()).toEqual({
  58. tagName: "TEXTAREA",
  59. rows: "1",
  60. autoSizing: true,
  61. maxRows: true,
  62. index: "5.",
  63. indexCenteredOnFirstLine: true,
  64. rowGaps: [4, 4, 4, 4],
  65. });
  66. // 前向 resolveInteraction 命令收口
  67. const dismissed = await approveV4Permission();
  68. expect(dismissed).toBe(true);
  69. // 批准后工具执行 → tool_result 回灌 → 终态文本
  70. await waitForV4TimelineContaining("V4_PERMISSION_DONE", 60000);
  71. });
  72. it("批准时填写的反馈被忽略,工具仍按 Allow once 执行", async () => {
  73. await prepareV4ConversationE2E();
  74. await sendV4Prompt(
  75. `E2E_V4_PERMISSION_ALLOW_FEEDBACK 请写入文件 ${V4_PERMISSION_ALLOW_FEEDBACK_OUTPUT_PATH}`,
  76. );
  77. await waitForV4PermissionDialogInComposerDock();
  78. expect(await approveV4Permission(V4_PERMISSION_ALLOW_FEEDBACK)).toBe(true);
  79. await waitForV4TimelineContaining("V4_PERMISSION_ALLOW_FEEDBACK_DONE", 60000);
  80. const allowedResult = await getLatestUpstreamToolResultByToolCallId(
  81. "toolu_v4_permission_allow_feedback",
  82. );
  83. expect(allowedResult?.isError).toBe(false);
  84. expect(allowedResult?.content).not.toContain(V4_PERMISSION_ALLOW_FEEDBACK);
  85. await expectFileExists(V4_PERMISSION_ALLOW_FEEDBACK_OUTPUT_PATH);
  86. });
  87. for (const submitWithEnter of [true, false]) {
  88. it(`第 5 行填写反馈并${submitWithEnter ? "回车" : "确认"},反馈进入同一个 provider-visible tool_result 且工具不执行`, async () => {
  89. await prepareV4ConversationE2E();
  90. await sendV4Prompt(
  91. `E2E_V4_PERMISSION_DENY_FEEDBACK 请写入文件 ${V4_PERMISSION_DENY_OUTPUT_PATH}`,
  92. );
  93. await waitForV4PermissionDialogInComposerDock();
  94. const input = await $(
  95. 'textarea[aria-label="Optional feedback for the model when denying"],textarea[aria-label="拒绝时给模型的可选反馈"]',
  96. );
  97. const allow = await $('[data-permission-option-kind="allowOnce"]');
  98. const deny = await $('[data-permission-option-kind^="reject"]');
  99. await expect(allow).toBeFocused();
  100. await browser.keys("ArrowUp");
  101. await expect(input).toBeFocused();
  102. expect((await readPermissionFeedbackTextareaSemantics()).index).toBe("5.");
  103. expect(await deny.getAttribute("aria-selected")).toBe("false");
  104. await browser.keys("ArrowUp");
  105. await expect(deny).toBeFocused();
  106. expect(
  107. await browser.execute(() =>
  108. document
  109. .querySelector(
  110. 'textarea[aria-label="Optional feedback for the model when denying"],textarea[aria-label="拒绝时给模型的可选反馈"]',
  111. )
  112. ?.parentElement?.classList.contains("bg-selected"),
  113. ),
  114. ).toBe(false);
  115. await browser.keys("Tab");
  116. await expect(input).toBeFocused();
  117. await browser.keys(["Shift", "Tab"]);
  118. await expect(deny).toBeFocused();
  119. await browser.keys("ArrowDown");
  120. await expect(input).toBeFocused();
  121. expect(await denyV4PermissionWithFeedback(V4_PERMISSION_DENY_FEEDBACK, submitWithEnter)).toBe(
  122. true,
  123. );
  124. await waitForV4TimelineContaining("V4_PERMISSION_DENY_DONE", 60000);
  125. const deniedResult = await getLatestUpstreamToolResultByToolCallId(
  126. "toolu_v4_permission_deny_feedback",
  127. );
  128. expect(deniedResult?.isError).toBe(true);
  129. expect(deniedResult?.content).toBe(
  130. V4_PERMISSION_DENY_BASE_CONTENT +
  131. " To tell you how to proceed, the user said:\n" +
  132. V4_PERMISSION_DENY_FEEDBACK,
  133. );
  134. await expectFileMissing(V4_PERMISSION_DENY_OUTPUT_PATH);
  135. });
  136. }
  137. it("拒绝时只有空白反馈,provider-visible tool_result 保持基础 Deny 文案", async () => {
  138. await prepareV4ConversationE2E();
  139. await sendV4Prompt(
  140. `E2E_V4_PERMISSION_DENY_BLANK 请写入文件 ${V4_PERMISSION_DENY_BLANK_OUTPUT_PATH}`,
  141. );
  142. await waitForV4PermissionDialogInComposerDock();
  143. expect(await denyV4PermissionWithFeedback(" ")).toBe(true);
  144. await waitForV4TimelineContaining("V4_PERMISSION_DENY_BLANK_DONE", 60000);
  145. const deniedResult = await getLatestUpstreamToolResultByToolCallId(
  146. "toolu_v4_permission_deny_blank",
  147. );
  148. expect(deniedResult?.isError).toBe(true);
  149. expect(deniedResult?.content).toBe(V4_PERMISSION_DENY_BASE_CONTENT);
  150. expect(deniedResult?.content).not.toContain("To tell you how to proceed");
  151. await expectFileMissing(V4_PERMISSION_DENY_BLANK_OUTPUT_PATH);
  152. });
  153. });
  154. async function expectFileExists(path: string) {
  155. const exists = await access(path)
  156. .then(() => true)
  157. .catch(() => false);
  158. expect(exists).toBe(true);
  159. }
  160. async function expectFileMissing(path: string) {
  161. const exists = await access(path)
  162. .then(() => true)
  163. .catch(() => false);
  164. expect(exists).toBe(false);
  165. }
  166. async function readPermissionFeedbackTextareaSemantics() {
  167. return browser.execute(() => {
  168. const textarea = document.querySelector<HTMLTextAreaElement>(
  169. 'textarea[aria-label="Optional feedback for the model when denying"],textarea[aria-label="拒绝时给模型的可选反馈"]',
  170. );
  171. const style = textarea ? getComputedStyle(textarea) : null;
  172. const indexRect = textarea?.previousElementSibling?.getBoundingClientRect();
  173. // 原因:反馈行曾落在外层 12px 分组间距中;校验实际位置,避免只匹配样式名。
  174. const feedbackRow = textarea?.parentElement;
  175. const rowRects = [
  176. ...Array.from(
  177. feedbackRow?.previousElementSibling?.querySelectorAll("[data-permission-option-kind]") ??
  178. [],
  179. ),
  180. ...(feedbackRow ? [feedbackRow] : []),
  181. ].map((row) => row.getBoundingClientRect());
  182. return {
  183. tagName: textarea?.tagName ?? null,
  184. rows: textarea?.getAttribute("rows") ?? null,
  185. autoSizing: textarea?.classList.contains("field-sizing-content") ?? false,
  186. maxRows: textarea?.classList.contains("max-h-[5lh]") ?? false,
  187. index: textarea?.previousElementSibling?.textContent ?? null,
  188. rowGaps: rowRects.slice(1).map((rect, index) => rect.top - rowRects[index]!.bottom),
  189. indexCenteredOnFirstLine: Boolean(
  190. textarea &&
  191. style &&
  192. indexRect &&
  193. Math.abs(
  194. indexRect.top +
  195. indexRect.height / 2 -
  196. (textarea.getBoundingClientRect().top +
  197. parseFloat(style.borderTopWidth) +
  198. parseFloat(style.paddingTop) +
  199. parseFloat(style.lineHeight) / 2),
  200. ) <= 0.5,
  201. ),
  202. };
  203. });
  204. }