permissionDialogFocus.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. // @vitest-environment jsdom
  2. import { act, cleanup, fireEvent, render } from "@testing-library/react";
  3. import { createElement } from "react";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. import type { ZCodePermissionRequest } from "@zcode/shared";
  6. import type { ConversationSnapshot } from "@zcode/shared/zcode-protocol-v4";
  7. import { PermissionDialog } from "@/PermissionDialog.js";
  8. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  9. import { V4InteractionDialogs } from "@/v4/V4InteractionDialogs.js";
  10. vi.mock("@/v4/V4ConversationContext.js", () => ({
  11. useV4Conversation: () => ({ sendCommand: vi.fn() }),
  12. }));
  13. function installAnimationFrameController() {
  14. let nextFrameId = 1;
  15. const callbacks = new Map<number, FrameRequestCallback>();
  16. const requestAnimationFrame = vi.fn((callback: FrameRequestCallback) => {
  17. const frameId = nextFrameId;
  18. nextFrameId += 1;
  19. callbacks.set(frameId, callback);
  20. return frameId;
  21. });
  22. const cancelAnimationFrame = vi.fn((frameId: number) => {
  23. callbacks.delete(frameId);
  24. });
  25. vi.stubGlobal("requestAnimationFrame", requestAnimationFrame);
  26. vi.stubGlobal("cancelAnimationFrame", cancelAnimationFrame);
  27. return {
  28. flush() {
  29. const pendingCallbacks = [...callbacks.values()];
  30. callbacks.clear();
  31. for (const callback of pendingCallbacks) {
  32. callback(performance.now());
  33. }
  34. },
  35. };
  36. }
  37. function permissionSnapshot(interactionId: string): ConversationSnapshot {
  38. return {
  39. sessionId: "task-focus",
  40. pendingInteractions: [
  41. {
  42. interactionId,
  43. kind: "permission",
  44. anchorRowId: null,
  45. createdAt: 1,
  46. payload: {
  47. kind: "permission",
  48. toolCallId: `tool-${interactionId}`,
  49. toolName: "Bash",
  50. summary: "Run ls",
  51. detail: { command: "ls" },
  52. freeText: true,
  53. options: [
  54. { optionId: "allowOnce", kind: "allowOnce", label: "Allow once" },
  55. { optionId: "deny", kind: "deny", label: "Deny" },
  56. ],
  57. },
  58. },
  59. ],
  60. } as ConversationSnapshot;
  61. }
  62. describe("PermissionDialog focus", () => {
  63. beforeEach(() => {
  64. // jsdom 不提供 ResizeObserver;焦点测试不依赖布局,真实命令溢出由 browser E2E 验证。
  65. vi.stubGlobal(
  66. "ResizeObserver",
  67. class {
  68. observe() {}
  69. unobserve() {}
  70. disconnect() {}
  71. },
  72. );
  73. });
  74. afterEach(() => {
  75. cleanup();
  76. vi.unstubAllGlobals();
  77. });
  78. const request: ZCodePermissionRequest = {
  79. type: "permission_request",
  80. taskId: "task-focus",
  81. traceId: "trace-focus",
  82. requestId: "request-focus",
  83. description: "Run ls",
  84. kind: "Bash",
  85. freeText: true,
  86. options: [
  87. {
  88. optionId: "allow_once",
  89. kind: "allow_once",
  90. name: "Allow once",
  91. response: { decision: "allow" },
  92. },
  93. {
  94. optionId: "allow_project",
  95. kind: "allow_project",
  96. name: "Allow project",
  97. response: { decision: "allow" },
  98. },
  99. { optionId: "deny", kind: "deny", name: "Deny", response: { decision: "deny" } },
  100. ],
  101. raw: { command: "ls" },
  102. };
  103. function renderPermission(freeText = true, fullAccess = false) {
  104. const animationFrame = installAnimationFrameController();
  105. const onRespond = vi.fn();
  106. const view = render(
  107. createElement(
  108. ZCodeIntlProvider,
  109. { initialLocale: "zh-CN" },
  110. createElement(PermissionDialog, {
  111. request: {
  112. ...request,
  113. freeText,
  114. options: fullAccess
  115. ? [
  116. request.options[0]!,
  117. {
  118. ...request.options[1]!,
  119. kind: "allow_always",
  120. name: "Always allow in this project",
  121. },
  122. {
  123. optionId: "fullAccess",
  124. kind: "custom",
  125. name: "Full access",
  126. response: { decision: "deny" },
  127. },
  128. request.options[2]!,
  129. ]
  130. : request.options,
  131. },
  132. onRespond,
  133. workspacePath: "/tmp/workspace",
  134. }),
  135. ),
  136. );
  137. const flush = () => act(() => animationFrame.flush());
  138. flush();
  139. return {
  140. ...view,
  141. onRespond,
  142. flush,
  143. options: view.getAllByRole("option"),
  144. input: view.queryByRole("textbox") as HTMLTextAreaElement | null,
  145. confirm: view.getByRole("button", { name: "确认" }) as HTMLButtonElement,
  146. };
  147. }
  148. it("完全访问为第三项,数字 5 只聚焦反馈,第三项按原 optionId 提交", () => {
  149. const { input, options, flush, onRespond, confirm } = renderPermission(true, true);
  150. expect(options).toHaveLength(4);
  151. expect(options[2]!.textContent).toContain("完全访问");
  152. expect(input!.previousElementSibling?.textContent).toBe("5.");
  153. fireEvent.keyDown(options[0]!, { key: "5" });
  154. flush();
  155. expect(document.activeElement).toBe(input);
  156. expect(onRespond).not.toHaveBeenCalled();
  157. fireEvent.keyDown(input!, { key: "ArrowUp" });
  158. flush();
  159. expect(document.activeElement).toBe(options[3]);
  160. fireEvent.keyDown(options[3]!, { key: "ArrowUp" });
  161. flush();
  162. expect(document.activeElement).toBe(options[2]);
  163. fireEvent.click(confirm);
  164. expect(onRespond).toHaveBeenCalledWith(
  165. "request-focus",
  166. expect.objectContaining({ optionId: "fullAccess" }),
  167. undefined,
  168. );
  169. });
  170. it("gives feedback its own numbered row in the arrow and Tab focus cycle", () => {
  171. const { input, options, flush, onRespond, confirm } = renderPermission();
  172. const feedbackRow = input!.parentElement!;
  173. expect(feedbackRow.parentElement?.classList.contains("space-y-1")).toBe(true);
  174. expect(feedbackRow.previousElementSibling).toBe(options[0]!.parentElement);
  175. expect(input!.closest('[role="listbox"]')).toBeNull();
  176. const key = (key: string, shiftKey = false) => {
  177. fireEvent.keyDown(document.activeElement!, { key, shiftKey });
  178. flush();
  179. };
  180. expect(document.activeElement).toBe(options[0]);
  181. expect(input!.previousElementSibling?.textContent).toBe("4.");
  182. expect(input!.previousElementSibling?.classList.contains("self-start")).toBe(true);
  183. expect(input!.previousElementSibling?.classList.contains("mt-px")).toBe(true);
  184. expect(input!.previousElementSibling?.classList.contains("leading-5")).toBe(true);
  185. expect(input!.previousElementSibling?.classList.contains("md:leading-relaxed")).toBe(true);
  186. key("ArrowUp");
  187. expect(document.activeElement).toBe(input);
  188. expect(feedbackRow.classList.contains("bg-selected")).toBe(true);
  189. expect(options.every((option) => option.getAttribute("aria-selected") === "false")).toBe(true);
  190. expect(confirm.disabled).toBe(true);
  191. key("Enter");
  192. expect(onRespond).not.toHaveBeenCalled();
  193. fireEvent.change(input!, { target: { value: " 保留反馈 " } });
  194. key("ArrowUp");
  195. expect(document.activeElement).toBe(options[2]);
  196. expect(options[2]!.getAttribute("aria-selected")).toBe("true");
  197. expect(feedbackRow.classList.contains("bg-selected")).toBe(false);
  198. key("Tab");
  199. expect(document.activeElement).toBe(input);
  200. key("Tab", true);
  201. expect(document.activeElement).toBe(options[2]);
  202. key("ArrowDown");
  203. expect(document.activeElement).toBe(input);
  204. key("ArrowDown");
  205. expect(document.activeElement).toBe(options[0]);
  206. key("4");
  207. expect(document.activeElement).toBe(input);
  208. key("Tab");
  209. expect(document.activeElement).toBe(options[0]);
  210. key("Tab", true);
  211. expect(document.activeElement).toBe(input);
  212. expect(input!.value).toBe(" 保留反馈 ");
  213. expect(onRespond).not.toHaveBeenCalled();
  214. });
  215. it.each(["Enter", "confirm"])(
  216. "submits feedback as Deny via %s without selecting the Deny row",
  217. (method) => {
  218. const { input, options, flush, confirm, onRespond } = renderPermission();
  219. act(() => input!.focus());
  220. fireEvent.change(input!, { target: { value: " 请先解释\n然后再修改 " } });
  221. flush();
  222. expect(options[2]!.getAttribute("aria-selected")).toBe("false");
  223. expect(confirm.disabled).toBe(false);
  224. if (method === "Enter") fireEvent.keyDown(input!, { key: "Enter" });
  225. else fireEvent.click(confirm);
  226. expect(onRespond).toHaveBeenCalledExactlyOnceWith(
  227. request.requestId,
  228. request.options[2],
  229. "请先解释\n然后再修改",
  230. );
  231. },
  232. );
  233. it("keeps IME navigation and Escape local to feedback, and ignores the draft when allowing", () => {
  234. const { input, options, flush, confirm, onRespond } = renderPermission();
  235. act(() => input!.focus());
  236. fireEvent.change(input!, { target: { value: "请先解释" } });
  237. for (const key of ["ArrowUp", "ArrowDown", "Enter"]) {
  238. fireEvent.keyDown(input!, { key, isComposing: true });
  239. flush();
  240. expect(document.activeElement).toBe(input);
  241. }
  242. fireEvent.compositionStart(input!);
  243. fireEvent.keyDown(input!, { key: "ArrowUp" });
  244. flush();
  245. expect(document.activeElement).toBe(input);
  246. fireEvent.compositionEnd(input!);
  247. fireEvent.keyDown(input!, { key: "Escape" });
  248. expect(document.activeElement).not.toBe(input);
  249. expect(onRespond).not.toHaveBeenCalled();
  250. act(() => options[0]!.focus());
  251. fireEvent.click(confirm);
  252. expect(onRespond).toHaveBeenCalledExactlyOnceWith(
  253. request.requestId,
  254. request.options[0],
  255. undefined,
  256. );
  257. });
  258. it("preserves three-option navigation and plain Deny without feedback capability", () => {
  259. const { input, options, flush, confirm, onRespond } = renderPermission(false);
  260. expect(input).toBeNull();
  261. fireEvent.keyDown(options[0]!, { key: "ArrowUp" });
  262. flush();
  263. expect(document.activeElement).toBe(options[2]);
  264. fireEvent.click(confirm);
  265. expect(onRespond).toHaveBeenCalledExactlyOnceWith(
  266. request.requestId,
  267. request.options[2],
  268. undefined,
  269. );
  270. });
  271. it("does not steal feedback input focus from a queued option focus frame", () => {
  272. const animationFrame = installAnimationFrameController();
  273. render(
  274. createElement(
  275. ZCodeIntlProvider,
  276. { initialLocale: "zh-CN" },
  277. createElement(PermissionDialog, {
  278. request: {
  279. type: "permission_request",
  280. taskId: "task-focus",
  281. traceId: "trace-focus",
  282. requestId: "request-focus",
  283. description: "Run ls",
  284. kind: "Bash",
  285. freeText: true,
  286. options: [
  287. {
  288. optionId: "allow_once",
  289. kind: "allow_once",
  290. name: "Allow once",
  291. response: { decision: "allow" },
  292. },
  293. {
  294. optionId: "deny",
  295. kind: "deny",
  296. name: "Deny",
  297. response: { decision: "deny" },
  298. },
  299. ],
  300. raw: { command: "ls" },
  301. },
  302. onRespond: () => {},
  303. workspacePath: "/tmp/workspace",
  304. }),
  305. ),
  306. );
  307. const feedbackInput = document.querySelector<HTMLTextAreaElement>(
  308. 'textarea[aria-label="拒绝时给模型的可选反馈"]',
  309. );
  310. expect(feedbackInput).not.toBeNull();
  311. act(() => {
  312. feedbackInput?.focus();
  313. animationFrame.flush();
  314. });
  315. expect(document.activeElement).toBe(feedbackInput);
  316. });
  317. it("remounts the dialog when the pending permission changes", () => {
  318. installAnimationFrameController();
  319. const renderDialog = (interactionId: string) =>
  320. createElement(
  321. ZCodeIntlProvider,
  322. { initialLocale: "zh-CN" },
  323. createElement(V4InteractionDialogs, {
  324. sessionId: "task-focus",
  325. workspacePath: "/tmp/workspace",
  326. snapshot: permissionSnapshot(interactionId),
  327. }),
  328. );
  329. const view = render(renderDialog("permission-a"));
  330. const firstInput = document.querySelector<HTMLTextAreaElement>(
  331. 'textarea[aria-label="拒绝时给模型的可选反馈"]',
  332. );
  333. expect(firstInput).not.toBeNull();
  334. act(() => firstInput?.focus());
  335. view.rerender(renderDialog("permission-b"));
  336. const secondInput = document.querySelector<HTMLTextAreaElement>(
  337. 'textarea[aria-label="拒绝时给模型的可选反馈"]',
  338. );
  339. expect(secondInput).not.toBe(firstInput);
  340. });
  341. });