permissionDialogFocus.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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.previousElementSibling).toBe(options[0]!.parentElement);
  174. expect(input!.closest('[role="listbox"]')).toBeNull();
  175. const key = (key: string, shiftKey = false) => {
  176. fireEvent.keyDown(document.activeElement!, { key, shiftKey });
  177. flush();
  178. };
  179. expect(document.activeElement).toBe(options[0]);
  180. expect(input!.previousElementSibling?.textContent).toBe("4.");
  181. key("ArrowUp");
  182. expect(document.activeElement).toBe(input);
  183. expect(feedbackRow.classList.contains("bg-selected")).toBe(true);
  184. expect(options.every((option) => option.getAttribute("aria-selected") === "false")).toBe(true);
  185. expect(confirm.disabled).toBe(true);
  186. key("Enter");
  187. expect(onRespond).not.toHaveBeenCalled();
  188. fireEvent.change(input!, { target: { value: " 保留反馈 " } });
  189. key("ArrowUp");
  190. expect(document.activeElement).toBe(options[2]);
  191. expect(options[2]!.getAttribute("aria-selected")).toBe("true");
  192. expect(feedbackRow.classList.contains("bg-selected")).toBe(false);
  193. key("Tab");
  194. expect(document.activeElement).toBe(input);
  195. key("Tab", true);
  196. expect(document.activeElement).toBe(options[2]);
  197. key("ArrowDown");
  198. expect(document.activeElement).toBe(input);
  199. key("ArrowDown");
  200. expect(document.activeElement).toBe(options[0]);
  201. key("4");
  202. expect(document.activeElement).toBe(input);
  203. key("Tab");
  204. expect(document.activeElement).toBe(options[0]);
  205. key("Tab", true);
  206. expect(document.activeElement).toBe(input);
  207. expect(input!.value).toBe(" 保留反馈 ");
  208. expect(onRespond).not.toHaveBeenCalled();
  209. });
  210. it.each(["Enter", "confirm"])(
  211. "submits feedback as Deny via %s without selecting the Deny row",
  212. (method) => {
  213. const { input, options, flush, confirm, onRespond } = renderPermission();
  214. act(() => input!.focus());
  215. fireEvent.change(input!, { target: { value: " 请先解释\n然后再修改 " } });
  216. flush();
  217. expect(options[2]!.getAttribute("aria-selected")).toBe("false");
  218. expect(confirm.disabled).toBe(false);
  219. if (method === "Enter") fireEvent.keyDown(input!, { key: "Enter" });
  220. else fireEvent.click(confirm);
  221. expect(onRespond).toHaveBeenCalledExactlyOnceWith(
  222. request.requestId,
  223. request.options[2],
  224. "请先解释\n然后再修改",
  225. );
  226. },
  227. );
  228. it("keeps IME navigation and Escape local to feedback, and ignores the draft when allowing", () => {
  229. const { input, options, flush, confirm, onRespond } = renderPermission();
  230. act(() => input!.focus());
  231. fireEvent.change(input!, { target: { value: "请先解释" } });
  232. for (const key of ["ArrowUp", "ArrowDown", "Enter"]) {
  233. fireEvent.keyDown(input!, { key, isComposing: true });
  234. flush();
  235. expect(document.activeElement).toBe(input);
  236. }
  237. fireEvent.compositionStart(input!);
  238. fireEvent.keyDown(input!, { key: "ArrowUp" });
  239. flush();
  240. expect(document.activeElement).toBe(input);
  241. fireEvent.compositionEnd(input!);
  242. fireEvent.keyDown(input!, { key: "Escape" });
  243. expect(document.activeElement).not.toBe(input);
  244. expect(onRespond).not.toHaveBeenCalled();
  245. act(() => options[0]!.focus());
  246. fireEvent.click(confirm);
  247. expect(onRespond).toHaveBeenCalledExactlyOnceWith(
  248. request.requestId,
  249. request.options[0],
  250. undefined,
  251. );
  252. });
  253. it("preserves three-option navigation and plain Deny without feedback capability", () => {
  254. const { input, options, flush, confirm, onRespond } = renderPermission(false);
  255. expect(input).toBeNull();
  256. fireEvent.keyDown(options[0]!, { key: "ArrowUp" });
  257. flush();
  258. expect(document.activeElement).toBe(options[2]);
  259. fireEvent.click(confirm);
  260. expect(onRespond).toHaveBeenCalledExactlyOnceWith(
  261. request.requestId,
  262. request.options[2],
  263. undefined,
  264. );
  265. });
  266. it("does not steal feedback input focus from a queued option focus frame", () => {
  267. const animationFrame = installAnimationFrameController();
  268. render(
  269. createElement(
  270. ZCodeIntlProvider,
  271. { initialLocale: "zh-CN" },
  272. createElement(PermissionDialog, {
  273. request: {
  274. type: "permission_request",
  275. taskId: "task-focus",
  276. traceId: "trace-focus",
  277. requestId: "request-focus",
  278. description: "Run ls",
  279. kind: "Bash",
  280. freeText: true,
  281. options: [
  282. {
  283. optionId: "allow_once",
  284. kind: "allow_once",
  285. name: "Allow once",
  286. response: { decision: "allow" },
  287. },
  288. {
  289. optionId: "deny",
  290. kind: "deny",
  291. name: "Deny",
  292. response: { decision: "deny" },
  293. },
  294. ],
  295. raw: { command: "ls" },
  296. },
  297. onRespond: () => {},
  298. workspacePath: "/tmp/workspace",
  299. }),
  300. ),
  301. );
  302. const feedbackInput = document.querySelector<HTMLTextAreaElement>(
  303. 'textarea[aria-label="拒绝时给模型的可选反馈"]',
  304. );
  305. expect(feedbackInput).not.toBeNull();
  306. act(() => {
  307. feedbackInput?.focus();
  308. animationFrame.flush();
  309. });
  310. expect(document.activeElement).toBe(feedbackInput);
  311. });
  312. it("remounts the dialog when the pending permission changes", () => {
  313. installAnimationFrameController();
  314. const renderDialog = (interactionId: string) =>
  315. createElement(
  316. ZCodeIntlProvider,
  317. { initialLocale: "zh-CN" },
  318. createElement(V4InteractionDialogs, {
  319. sessionId: "task-focus",
  320. workspacePath: "/tmp/workspace",
  321. snapshot: permissionSnapshot(interactionId),
  322. }),
  323. );
  324. const view = render(renderDialog("permission-a"));
  325. const firstInput = document.querySelector<HTMLTextAreaElement>(
  326. 'textarea[aria-label="拒绝时给模型的可选反馈"]',
  327. );
  328. expect(firstInput).not.toBeNull();
  329. act(() => firstInput?.focus());
  330. view.rerender(renderDialog("permission-b"));
  331. const secondInput = document.querySelector<HTMLTextAreaElement>(
  332. 'textarea[aria-label="拒绝时给模型的可选反馈"]',
  333. );
  334. expect(secondInput).not.toBe(firstInput);
  335. });
  336. });