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

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