elicitationDialogRequestIdentity.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. import type { ZCodeElicitationRequest } from "@zcode/shared";
  2. import { act, createElement, forwardRef, type ReactNode } from "react";
  3. import { createRoot, type Root } from "react-dom/client";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import { ElicitationDialog } from "../src/ElicitationDialog.js";
  6. type TestEvent = {
  7. bubbles?: boolean;
  8. button?: number;
  9. currentTarget?: TestElement;
  10. defaultPrevented?: boolean;
  11. preventDefault?: () => void;
  12. stopPropagation?: () => void;
  13. target?: TestElement;
  14. type: string;
  15. };
  16. type TestEventHandler = (event: TestEvent) => void;
  17. type TestElement = Element & {
  18. __attrs: Map<string, string>;
  19. __listeners: Map<string, TestEventHandler[]>;
  20. childNodes: TestElement[];
  21. dispatchEvent: (event: TestEvent) => boolean;
  22. parentNode: TestElement | null;
  23. };
  24. vi.mock("lucide-react", () => {
  25. const Icon = (props: Record<string, unknown>) => createElement("svg", props);
  26. return {
  27. CheckIcon: Icon,
  28. ChevronDown: Icon,
  29. ChevronLeft: Icon,
  30. ChevronRight: Icon,
  31. ChevronUp: Icon,
  32. Info: Icon,
  33. };
  34. });
  35. vi.mock("@/components/ui/badge.js", () => ({
  36. Badge: ({ children }: { children?: ReactNode }) => createElement("span", null, children),
  37. }));
  38. vi.mock("@/components/ui/button.js", () => ({
  39. Button: ({ children, ...props }: { children?: ReactNode }) =>
  40. createElement("button", props, children),
  41. }));
  42. vi.mock("@/components/ui/input.js", () => ({
  43. Input: forwardRef<HTMLInputElement, Record<string, unknown>>((props, ref) =>
  44. createElement("input", { ...props, ref }),
  45. ),
  46. }));
  47. vi.mock("@/InteractionRequestOriginBadge.js", () => ({
  48. InteractionRequestOriginBadge: () => null,
  49. }));
  50. vi.mock("@/i18n/IntlProvider.js", () => ({
  51. useZCodeIntl: () => ({
  52. intl: {
  53. formatMessage: ({ id }: { id: string }) => id,
  54. },
  55. }),
  56. }));
  57. function createRequest(requestId: string): ZCodeElicitationRequest {
  58. return {
  59. type: "elicitation_request",
  60. taskId: "task-1",
  61. traceId: "trace-1",
  62. requestId,
  63. message: "请选择方案",
  64. options: [],
  65. questions: [
  66. {
  67. question: "请选择方案",
  68. header: "方案",
  69. options: [
  70. { value: "fast", label: "快速" },
  71. { value: "safe", label: "稳妥" },
  72. ],
  73. },
  74. {
  75. question: "请选择保障项",
  76. header: "保障项",
  77. options: [
  78. { value: "tests", label: "测试" },
  79. { value: "docs", label: "文档" },
  80. ],
  81. },
  82. ],
  83. };
  84. }
  85. function createSingleQuestionRequest(requestId: string): ZCodeElicitationRequest {
  86. return {
  87. type: "elicitation_request",
  88. taskId: "task-1",
  89. traceId: "trace-1",
  90. requestId,
  91. message: "请选择方案",
  92. options: [{ value: "fast", label: "快速" }],
  93. questions: [
  94. {
  95. question: "请选择方案",
  96. header: "方案",
  97. options: [{ value: "fast", label: "快速" }],
  98. },
  99. ],
  100. };
  101. }
  102. function createPlanApprovalRequest(requestId: string): ZCodeElicitationRequest {
  103. return {
  104. type: "elicitation_request",
  105. taskId: "task-1",
  106. traceId: "trace-1",
  107. requestId,
  108. message: "Review this implementation plan.",
  109. header: "Plan",
  110. options: [
  111. {
  112. value: "approve",
  113. label: "Approve",
  114. description: "Exit plan mode and start implementation.",
  115. },
  116. ],
  117. questions: [
  118. {
  119. question: "Review this implementation plan.",
  120. header: "Plan",
  121. options: [
  122. {
  123. value: "approve",
  124. label: "Approve",
  125. description: "Exit plan mode and start implementation.",
  126. },
  127. ],
  128. },
  129. ],
  130. schema: { interaction: "plan_approval", toolName: "ExitPlanMode" },
  131. };
  132. }
  133. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  134. const element = {
  135. __attrs: new Map<string, string>(),
  136. __listeners: new Map<string, TestEventHandler[]>(),
  137. addEventListener: (type: string, handler: TestEventHandler) => {
  138. const handlers = element.__listeners.get(type) ?? [];
  139. handlers.push(handler);
  140. element.__listeners.set(type, handlers);
  141. },
  142. appendChild: (child: TestElement) => {
  143. child.parentNode = element as unknown as TestElement;
  144. element.childNodes.push(child);
  145. return child;
  146. },
  147. childNodes: [] as TestElement[],
  148. dispatchEvent: (event: TestEvent) => {
  149. event.target ??= element as unknown as TestElement;
  150. event.preventDefault ??= () => {
  151. event.defaultPrevented = true;
  152. };
  153. event.stopPropagation ??= () => {};
  154. let current: TestElement | null = element as unknown as TestElement;
  155. while (current) {
  156. event.currentTarget = current;
  157. for (const handler of current.__listeners.get(event.type) ?? []) {
  158. handler(event);
  159. }
  160. if (!event.bubbles) break;
  161. current = current.parentNode;
  162. }
  163. return !event.defaultPrevented;
  164. },
  165. focus: () => {},
  166. getAttribute: (name: string) => element.__attrs.get(name) ?? null,
  167. insertBefore: (child: TestElement, beforeChild?: TestElement | null) => {
  168. child.parentNode = element as unknown as TestElement;
  169. const beforeIndex = beforeChild ? element.childNodes.indexOf(beforeChild) : -1;
  170. if (beforeIndex >= 0) {
  171. element.childNodes.splice(beforeIndex, 0, child);
  172. } else {
  173. element.childNodes.push(child);
  174. }
  175. return child;
  176. },
  177. nodeName: tagName.toUpperCase(),
  178. nodeType: 1,
  179. ownerDocument,
  180. parentNode: null as TestElement | null,
  181. removeAttribute: (name: string) => {
  182. element.__attrs.delete(name);
  183. },
  184. removeChild: (child: TestElement) => {
  185. element.childNodes = element.childNodes.filter((item) => item !== child);
  186. child.parentNode = null;
  187. return child;
  188. },
  189. removeEventListener: (type: string, handler: TestEventHandler) => {
  190. element.__listeners.set(
  191. type,
  192. (element.__listeners.get(type) ?? []).filter((item) => item !== handler),
  193. );
  194. },
  195. setAttribute: (name: string, value: string) => {
  196. element.__attrs.set(name, String(value));
  197. },
  198. style: {},
  199. tagName: tagName.toUpperCase(),
  200. value: "",
  201. };
  202. return element as unknown as TestElement;
  203. }
  204. function installMinimalDom() {
  205. const documentMock = {
  206. addEventListener: () => {},
  207. createElement: (tagName: string) =>
  208. createMinimalElement(documentMock as unknown as Document, tagName),
  209. createElementNS: (_namespace: string, tagName: string) =>
  210. createMinimalElement(documentMock as unknown as Document, tagName),
  211. createTextNode: (nodeValue: string) => ({
  212. nodeType: 3,
  213. nodeValue,
  214. ownerDocument: documentMock,
  215. parentNode: null,
  216. }),
  217. nodeType: 9,
  218. removeEventListener: () => {},
  219. } as unknown as Document;
  220. const requestAnimationFrame = (callback: FrameRequestCallback) => {
  221. callback(0);
  222. return 1;
  223. };
  224. const windowMock = {
  225. addEventListener: () => {},
  226. cancelAnimationFrame: () => {},
  227. clearTimeout,
  228. document: documentMock,
  229. HTMLIFrameElement: function HTMLIFrameElement() {},
  230. HTMLElement: function HTMLElement() {},
  231. Node: function Node() {},
  232. removeEventListener: () => {},
  233. requestAnimationFrame,
  234. setTimeout,
  235. };
  236. Object.assign(globalThis, {
  237. cancelAnimationFrame: () => {},
  238. document: documentMock,
  239. HTMLElement: windowMock.HTMLElement,
  240. HTMLIFrameElement: windowMock.HTMLIFrameElement,
  241. IS_REACT_ACT_ENVIRONMENT: true,
  242. Node: windowMock.Node,
  243. requestAnimationFrame,
  244. window: windowMock,
  245. });
  246. return createMinimalElement(documentMock);
  247. }
  248. function findOptions(node: unknown): TestElement[] {
  249. if (typeof node !== "object" || node === null) return [];
  250. const treeNode = node as {
  251. childNodes?: unknown[];
  252. getAttribute?: (name: string) => string | null;
  253. };
  254. const matches = treeNode.getAttribute?.("role") === "option" ? [node as TestElement] : [];
  255. return [...matches, ...(treeNode.childNodes ?? []).flatMap((child) => findOptions(child))];
  256. }
  257. function findByAttribute(node: unknown, name: string, value: string): TestElement | undefined {
  258. if (typeof node !== "object" || node === null) return undefined;
  259. const treeNode = node as {
  260. childNodes?: unknown[];
  261. getAttribute?: (attributeName: string) => string | null;
  262. };
  263. if (treeNode.getAttribute?.(name) === value) return node as TestElement;
  264. for (const child of treeNode.childNodes ?? []) {
  265. const match = findByAttribute(child, name, value);
  266. if (match) return match;
  267. }
  268. return undefined;
  269. }
  270. function findByTagName(node: unknown, tagName: string): TestElement[] {
  271. if (typeof node !== "object" || node === null) return [];
  272. const treeNode = node as {
  273. childNodes?: unknown[];
  274. tagName?: string;
  275. };
  276. const matches = treeNode.tagName === tagName.toUpperCase() ? [node as TestElement] : [];
  277. return [
  278. ...matches,
  279. ...(treeNode.childNodes ?? []).flatMap((child) => findByTagName(child, tagName)),
  280. ];
  281. }
  282. function clickFirstOption(container: TestElement) {
  283. const option = findOptions(container)[0];
  284. expect(option).toBeDefined();
  285. option?.dispatchEvent({ bubbles: true, button: 0, type: "click" });
  286. }
  287. function clickPrimaryAction(container: TestElement) {
  288. const footer = findByAttribute(container, "data-elicitation-dialog-footer", "true");
  289. const buttons = findByTagName(footer, "button");
  290. const primaryAction = buttons.at(-1);
  291. expect(primaryAction).toBeDefined();
  292. primaryAction?.dispatchEvent({ bubbles: true, button: 0, type: "click" });
  293. }
  294. function changeCustomAnswer(container: TestElement, value: string) {
  295. const input = findByAttribute(
  296. container,
  297. "placeholder",
  298. "chat.elicitation.customAnswer.placeholder",
  299. );
  300. expect(input).toBeDefined();
  301. const inputRecord = input as unknown as Record<string, unknown>;
  302. const reactPropsKey = Object.keys(inputRecord).find((key) => key.startsWith("__reactProps$"));
  303. const reactProps = reactPropsKey
  304. ? (inputRecord[reactPropsKey] as { onChange?: (event: { target: { value: string } }) => void })
  305. : undefined;
  306. expect(reactProps?.onChange).toBeTypeOf("function");
  307. reactProps?.onChange?.({ target: { value } });
  308. }
  309. let mountedRoot: Root | null = null;
  310. afterEach(() => {
  311. if (mountedRoot) {
  312. act(() => mountedRoot?.unmount());
  313. mountedRoot = null;
  314. }
  315. for (const key of [
  316. "cancelAnimationFrame",
  317. "document",
  318. "HTMLElement",
  319. "HTMLIFrameElement",
  320. "IS_REACT_ACT_ENVIRONMENT",
  321. "Node",
  322. "requestAnimationFrame",
  323. "window",
  324. ]) {
  325. Reflect.deleteProperty(globalThis, key);
  326. }
  327. });
  328. describe("ElicitationDialog request identity", () => {
  329. it("计划审批空反馈点击主提交等同批准,普通单选题无交互点提交保持空答案", () => {
  330. const container = installMinimalDom();
  331. mountedRoot = createRoot(container);
  332. const onRespond = vi.fn();
  333. act(() => {
  334. mountedRoot?.render(
  335. createElement(ElicitationDialog, {
  336. request: createPlanApprovalRequest("plan-primary-submit"),
  337. onRespond,
  338. }),
  339. );
  340. });
  341. act(() => clickPrimaryAction(container));
  342. expect(onRespond).toHaveBeenLastCalledWith("plan-primary-submit", "accept", {
  343. answers: { "Review this implementation plan.": "approve" },
  344. answer_0: "approve",
  345. answer: "approve",
  346. });
  347. act(() => {
  348. mountedRoot?.render(
  349. createElement(ElicitationDialog, {
  350. request: createSingleQuestionRequest("ask-primary-submit"),
  351. onRespond,
  352. }),
  353. );
  354. });
  355. act(() => clickPrimaryAction(container));
  356. // 修复原因:不预选任何选项(activeOptionIndex 初始 -1),用户未按键导航时
  357. // 点 Submit 提交空答案,表示明确跳过该问题。
  358. expect(onRespond).toHaveBeenLastCalledWith("ask-primary-submit", "accept", {
  359. answers: {},
  360. });
  361. });
  362. it("计划审批主提交保留自定义反馈而不改写成批准", () => {
  363. const container = installMinimalDom();
  364. mountedRoot = createRoot(container);
  365. const onRespond = vi.fn();
  366. act(() => {
  367. mountedRoot?.render(
  368. createElement(ElicitationDialog, {
  369. request: createPlanApprovalRequest("plan-feedback-submit"),
  370. onRespond,
  371. }),
  372. );
  373. });
  374. act(() => changeCustomAnswer(container, "先补测试再实施"));
  375. act(() => clickPrimaryAction(container));
  376. expect(onRespond).toHaveBeenCalledWith("plan-feedback-submit", "accept", {
  377. answers: { "Review this implementation plan.": "先补测试再实施" },
  378. answer_0: "先补测试再实施",
  379. answer: "先补测试再实施",
  380. });
  381. });
  382. it("does not snooze on mount or auto focus, but snoozes once when the panel is hovered", () => {
  383. const container = installMinimalDom();
  384. mountedRoot = createRoot(container);
  385. const onFirstInteraction = vi.fn(() => true);
  386. act(() => {
  387. mountedRoot?.render(
  388. createElement(ElicitationDialog, {
  389. request: createRequest("request-hover"),
  390. onFirstInteraction,
  391. onRespond: vi.fn(),
  392. }),
  393. );
  394. });
  395. expect(onFirstInteraction).not.toHaveBeenCalled();
  396. const card = findByAttribute(container, "data-elicitation-dialog-card", "true");
  397. expect(card).toBeDefined();
  398. act(() => {
  399. card?.dispatchEvent({ bubbles: true, type: "mouseover" });
  400. card?.dispatchEvent({ bubbles: true, type: "mouseover" });
  401. });
  402. act(() => clickFirstOption(container));
  403. expect(onFirstInteraction).toHaveBeenCalledTimes(1);
  404. expect(onFirstInteraction).toHaveBeenCalledWith("panelHover");
  405. });
  406. it("clicking the final-minute seconds snoozes without submitting an answer", () => {
  407. const nowSpy = vi.spyOn(Date, "now").mockReturnValue(940_001);
  408. const container = installMinimalDom();
  409. mountedRoot = createRoot(container);
  410. const onFirstInteraction = vi.fn(() => true);
  411. const onRespond = vi.fn();
  412. try {
  413. act(() => {
  414. mountedRoot?.render(
  415. createElement(ElicitationDialog, {
  416. request: createRequest("request-countdown"),
  417. autoResolution: {
  418. state: "visibleCountdown",
  419. startedAt: 700_000,
  420. visibleAt: 760_000,
  421. deadlineAt: 1_000_000,
  422. },
  423. onFirstInteraction,
  424. onRespond,
  425. }),
  426. );
  427. });
  428. const countdown = findByAttribute(container, "data-elicitation-countdown-seconds", "59");
  429. expect(countdown).toBeDefined();
  430. act(() => countdown?.dispatchEvent({ bubbles: true, button: 0, type: "click" }));
  431. expect(onFirstInteraction).toHaveBeenCalledTimes(1);
  432. expect(onFirstInteraction).toHaveBeenCalledWith("countdown");
  433. expect(onRespond).not.toHaveBeenCalled();
  434. } finally {
  435. nowSpy.mockRestore();
  436. }
  437. });
  438. it("reports an option selection as an answer interaction", () => {
  439. const container = installMinimalDom();
  440. mountedRoot = createRoot(container);
  441. const onFirstInteraction = vi.fn(() => true);
  442. act(() => {
  443. mountedRoot?.render(
  444. createElement(ElicitationDialog, {
  445. request: createRequest("request-answer"),
  446. onFirstInteraction,
  447. onRespond: vi.fn(),
  448. }),
  449. );
  450. });
  451. act(() => clickFirstOption(container));
  452. expect(onFirstInteraction).toHaveBeenCalledTimes(1);
  453. expect(onFirstInteraction).toHaveBeenCalledWith("answer");
  454. });
  455. it("reports question paging as a navigation interaction", () => {
  456. const container = installMinimalDom();
  457. mountedRoot = createRoot(container);
  458. const onFirstInteraction = vi.fn(() => true);
  459. act(() => {
  460. mountedRoot?.render(
  461. createElement(ElicitationDialog, {
  462. request: createRequest("request-navigation"),
  463. onFirstInteraction,
  464. onRespond: vi.fn(),
  465. }),
  466. );
  467. });
  468. const next = findByAttribute(container, "aria-label", "chat.elicitation.nextQuestion");
  469. expect(next).toBeDefined();
  470. act(() => next?.dispatchEvent({ bubbles: true, button: 0, type: "click" }));
  471. expect(onFirstInteraction).toHaveBeenCalledTimes(1);
  472. expect(onFirstInteraction).toHaveBeenCalledWith("navigation");
  473. });
  474. it("reports custom input changes as an answer interaction", () => {
  475. const container = installMinimalDom();
  476. mountedRoot = createRoot(container);
  477. const onFirstInteraction = vi.fn(() => true);
  478. act(() => {
  479. mountedRoot?.render(
  480. createElement(ElicitationDialog, {
  481. request: createRequest("request-custom-answer"),
  482. onFirstInteraction,
  483. onRespond: vi.fn(),
  484. }),
  485. );
  486. });
  487. act(() => changeCustomAnswer(container, "自定义方案"));
  488. expect(onFirstInteraction).toHaveBeenCalledTimes(1);
  489. expect(onFirstInteraction).toHaveBeenCalledWith("answer");
  490. });
  491. it("allows a later interaction to retry when the snooze command fails", async () => {
  492. const container = installMinimalDom();
  493. mountedRoot = createRoot(container);
  494. const onFirstInteraction = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true);
  495. act(() => {
  496. mountedRoot?.render(
  497. createElement(ElicitationDialog, {
  498. request: createRequest("request-retry"),
  499. onFirstInteraction,
  500. onRespond: vi.fn(),
  501. }),
  502. );
  503. });
  504. await act(async () => {
  505. clickFirstOption(container);
  506. await Promise.resolve();
  507. });
  508. act(() => clickFirstOption(container));
  509. expect(onFirstInteraction).toHaveBeenCalledTimes(2);
  510. expect(onFirstInteraction).toHaveBeenNthCalledWith(1, "answer");
  511. expect(onFirstInteraction).toHaveBeenNthCalledWith(2, "answer");
  512. });
  513. it("keeps the current question and drafts when the same request is reprojected", () => {
  514. const container = installMinimalDom();
  515. mountedRoot = createRoot(container);
  516. const onRespond = vi.fn();
  517. const request = createRequest("request-1");
  518. act(() => {
  519. mountedRoot?.render(createElement(ElicitationDialog, { request, onRespond }));
  520. });
  521. act(() => clickFirstOption(container));
  522. // 模拟 autoResolution hiddenGrace -> snoozed 后,同一 interaction 被投影成新对象。
  523. act(() => {
  524. mountedRoot?.render(
  525. createElement(ElicitationDialog, {
  526. request: { ...request },
  527. onRespond,
  528. }),
  529. );
  530. });
  531. act(() => clickFirstOption(container));
  532. expect(onRespond).toHaveBeenCalledWith("request-1", "accept", {
  533. answers: {
  534. 请选择保障项: "tests",
  535. 请选择方案: "fast",
  536. },
  537. answer_0: "fast",
  538. answer_1: "tests",
  539. });
  540. });
  541. it("creates a fresh local form when requestId changes", () => {
  542. const container = installMinimalDom();
  543. mountedRoot = createRoot(container);
  544. const onRespond = vi.fn();
  545. act(() => {
  546. mountedRoot?.render(
  547. createElement(ElicitationDialog, {
  548. request: createRequest("request-1"),
  549. onRespond,
  550. }),
  551. );
  552. });
  553. act(() => clickFirstOption(container));
  554. act(() => {
  555. mountedRoot?.render(
  556. createElement(ElicitationDialog, {
  557. request: createRequest("request-2"),
  558. onRespond,
  559. }),
  560. );
  561. });
  562. act(() => clickFirstOption(container));
  563. expect(onRespond).not.toHaveBeenCalled();
  564. });
  565. it("restores the current question and answers after the dialog is remounted", () => {
  566. const container = installMinimalDom();
  567. mountedRoot = createRoot(container);
  568. const onRespond = vi.fn();
  569. const request = createRequest("request-restored");
  570. const initialFormDraft = {
  571. questionIndex: 1,
  572. drafts: {
  573. "0:请选择方案": { selectedValues: ["fast"], customAnswer: "" },
  574. "1:请选择保障项": { selectedValues: [], customAnswer: "" },
  575. },
  576. };
  577. act(() => {
  578. mountedRoot?.render(
  579. createElement(ElicitationDialog, { request, initialFormDraft, onRespond }),
  580. );
  581. });
  582. act(() => clickFirstOption(container));
  583. expect(onRespond).toHaveBeenCalledWith("request-restored", "accept", {
  584. answers: {
  585. 请选择保障项: "tests",
  586. 请选择方案: "fast",
  587. },
  588. answer_0: "fast",
  589. answer_1: "tests",
  590. });
  591. });
  592. });