elicitationDialog.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. import type { ZCodeElicitationRequest } from "@zcode/shared";
  2. import { createElement, type ComponentType } from "react";
  3. import { renderToStaticMarkup } from "react-dom/server";
  4. import { describe, expect, it, vi } from "vitest";
  5. import {
  6. buildElicitationResponseContent,
  7. createInitialElicitationDrafts,
  8. ElicitationDialog,
  9. getElicitationCountdownSeconds,
  10. getElicitationQuestionAdvanceKind,
  11. normalizeElicitationQuestions,
  12. resolveElicitationCustomInputKeyAction,
  13. updateElicitationDraftsForOption,
  14. } from "../src/ElicitationDialog.js";
  15. import { ZCodeIntlProvider } from "../src/i18n/IntlProvider.js";
  16. const SUBAGENT_ORIGIN = {
  17. kind: "subagent" as const,
  18. agentId: "general-purpose",
  19. agentType: "general-purpose",
  20. childSessionId: "sess-child",
  21. parentSessionId: "sess-parent",
  22. parentToolCallId: "tool-parent-agent",
  23. };
  24. function createMultiQuestionRequest(): ZCodeElicitationRequest {
  25. return {
  26. type: "elicitation_request",
  27. taskId: "task-1",
  28. traceId: "run-1",
  29. requestId: "request-1",
  30. message: "请选择方案",
  31. options: [],
  32. questions: [
  33. {
  34. question: "请选择方案",
  35. header: "方案",
  36. options: [
  37. { value: "fast", label: "快速" },
  38. { value: "safe", label: "稳妥" },
  39. ],
  40. },
  41. {
  42. question: "请选择保障项",
  43. header: "保障项",
  44. options: [
  45. { value: "tests", label: "测试" },
  46. { value: "docs", label: "文档" },
  47. ],
  48. },
  49. ],
  50. };
  51. }
  52. function createPlanApprovalRequest(): ZCodeElicitationRequest {
  53. return {
  54. type: "elicitation_request",
  55. taskId: "task-1",
  56. traceId: "run-1",
  57. requestId: "exit-plan-1",
  58. message: "Review this implementation plan.",
  59. header: "Plan",
  60. options: [
  61. {
  62. value: "approve",
  63. label: "Approve",
  64. description: "Exit plan mode and start implementation.",
  65. },
  66. ],
  67. questions: [
  68. {
  69. question: "Review this implementation plan.",
  70. header: "Plan",
  71. options: [
  72. {
  73. value: "approve",
  74. label: "Approve",
  75. description: "Exit plan mode and start implementation.",
  76. },
  77. ],
  78. },
  79. ],
  80. schema: { interaction: "plan_approval", toolName: "ExitPlanMode" },
  81. };
  82. }
  83. describe("ElicitationDialog", () => {
  84. it("only exposes 59s through 1s during the final minute", () => {
  85. const autoResolution = {
  86. state: "visibleCountdown" as const,
  87. startedAt: 700_000,
  88. visibleAt: 760_000,
  89. deadlineAt: 1_000_000,
  90. };
  91. expect(getElicitationCountdownSeconds(autoResolution, 940_000)).toBeNull();
  92. expect(getElicitationCountdownSeconds(autoResolution, 940_001)).toBe(59);
  93. expect(getElicitationCountdownSeconds(autoResolution, 999_000)).toBe(1);
  94. expect(getElicitationCountdownSeconds(autoResolution, 999_999)).toBe(1);
  95. expect(getElicitationCountdownSeconds(autoResolution, 1_000_000)).toBeNull();
  96. expect(
  97. getElicitationCountdownSeconds(
  98. { state: "snoozed", startedAt: 700_000, snoozedAt: 900_000 },
  99. 940_001,
  100. ),
  101. ).toBeNull();
  102. });
  103. it("renders a localized final-minute timer", () => {
  104. const nowSpy = vi.spyOn(Date, "now").mockReturnValue(940_001);
  105. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  106. const autoResolution = {
  107. state: "visibleCountdown" as const,
  108. startedAt: 700_000,
  109. visibleAt: 760_000,
  110. deadlineAt: 1_000_000,
  111. };
  112. const render = (locale: "en-US" | "zh-CN") =>
  113. renderToStaticMarkup(
  114. createElement(
  115. ZCodeIntlProvider,
  116. { initialLocale: locale },
  117. createElement(Dialog, {
  118. request: createMultiQuestionRequest(),
  119. autoResolution,
  120. onFirstInteraction: () => {},
  121. onRespond: () => {},
  122. }),
  123. ),
  124. );
  125. try {
  126. const zhHtml = render("zh-CN");
  127. expect(zhHtml).toContain('data-elicitation-countdown-seconds="59"');
  128. expect(zhHtml).toContain('aria-label="停止计时"');
  129. expect(zhHtml).toContain(">59秒</button>");
  130. const enHtml = render("en-US");
  131. expect(enHtml).toContain(">59s</button>");
  132. expect(enHtml).toContain('aria-label="Stop timer"');
  133. } finally {
  134. nowSpy.mockRestore();
  135. }
  136. });
  137. it("shows a subagent source tag for delegated elicitation requests only", () => {
  138. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  139. const request = createMultiQuestionRequest();
  140. const mainHtml = renderToStaticMarkup(
  141. createElement(
  142. ZCodeIntlProvider,
  143. { initialLocale: "zh-CN" },
  144. createElement(Dialog, {
  145. request,
  146. onRespond: () => {},
  147. }),
  148. ),
  149. );
  150. const subagentHtml = renderToStaticMarkup(
  151. createElement(
  152. ZCodeIntlProvider,
  153. { initialLocale: "zh-CN" },
  154. createElement(Dialog, {
  155. request: {
  156. ...request,
  157. origin: SUBAGENT_ORIGIN,
  158. },
  159. onRespond: () => {},
  160. }),
  161. ),
  162. );
  163. expect(mainHtml).not.toContain('data-interaction-origin-badge="subagent"');
  164. expect(subagentHtml).toContain('data-interaction-origin-badge="subagent"');
  165. expect(subagentHtml).toContain("子智能体");
  166. expect(subagentHtml).toContain("来自子智能体:general-purpose");
  167. });
  168. it("submits after the final question and includes the final selected option", () => {
  169. const request = createMultiQuestionRequest();
  170. const questions = normalizeElicitationQuestions(request);
  171. const initialDrafts = createInitialElicitationDrafts(questions, request);
  172. const firstDrafts = updateElicitationDraftsForOption(initialDrafts, questions[0]!, "fast");
  173. const finalDrafts = updateElicitationDraftsForOption(firstDrafts, questions[1]!, "tests");
  174. expect(getElicitationQuestionAdvanceKind(questions, 0)).toBe("next");
  175. expect(getElicitationQuestionAdvanceKind(questions, 1)).toBe("submit");
  176. expect(buildElicitationResponseContent(questions, finalDrafts)).toEqual({
  177. answers: {
  178. 请选择方案: "fast",
  179. 请选择保障项: "tests",
  180. },
  181. answer_0: "fast",
  182. answer_1: "tests",
  183. });
  184. });
  185. it("允许只提交部分问题的答案且不伪造未回答项", () => {
  186. const request = createMultiQuestionRequest();
  187. const questions = normalizeElicitationQuestions(request);
  188. const initialDrafts = createInitialElicitationDrafts(questions, request);
  189. const finalDrafts = updateElicitationDraftsForOption(initialDrafts, questions[1]!, "tests");
  190. expect(buildElicitationResponseContent(questions, finalDrafts)).toEqual({
  191. answers: { 请选择保障项: "tests" },
  192. answer_1: "tests",
  193. });
  194. });
  195. it("允许提交零回答", () => {
  196. const request = createMultiQuestionRequest();
  197. const questions = normalizeElicitationQuestions(request);
  198. const drafts = createInitialElicitationDrafts(questions, request);
  199. expect(buildElicitationResponseContent(questions, drafts)).toEqual({ answers: {} });
  200. });
  201. it("为截断的问题标题保留完整 hover title", () => {
  202. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  203. const longQuestion =
  204. "The PRD spans 4 native codebases plus shared contract and tokens. How should I sequence implementation?";
  205. const request = createMultiQuestionRequest();
  206. request.questions![0] = {
  207. ...request.questions![0]!,
  208. question: longQuestion,
  209. };
  210. const html = renderToStaticMarkup(
  211. createElement(
  212. ZCodeIntlProvider,
  213. { initialLocale: "zh-CN" },
  214. createElement(Dialog, {
  215. request,
  216. onRespond: () => {},
  217. }),
  218. ),
  219. );
  220. expect(html).toContain(`title="${longQuestion}"`);
  221. });
  222. it("长问题同时保留正文与完整title", () => {
  223. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  224. const longQuestion =
  225. "The PRD spans 4 native codebases plus shared contract and tokens. How should I sequence implementation without hiding the decision text on mobile?";
  226. const request = createMultiQuestionRequest();
  227. request.questions![0] = {
  228. ...request.questions![0]!,
  229. question: longQuestion,
  230. };
  231. const html = renderToStaticMarkup(
  232. createElement(
  233. ZCodeIntlProvider,
  234. { initialLocale: "zh-CN" },
  235. createElement(Dialog, {
  236. request,
  237. onRespond: () => {},
  238. }),
  239. ),
  240. );
  241. expect(html).toContain(`title="${longQuestion}"`);
  242. expect(html).toContain(">方案</span>");
  243. expect(html).toContain(`>${longQuestion}</span>`);
  244. });
  245. it("长问题提供展开入口", () => {
  246. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  247. const longQuestion =
  248. "假设你正在设计一个面向全球用户的下一代分布式实时协作平台,该平台需要支持百万级并发用户同时在线编辑文档、画板、表格和低代码应用,并且要求在离线状态下仍然可以正常编辑并在恢复网络后自动合并冲突。请在数据同步协议层面说明选择。";
  249. const request = createMultiQuestionRequest();
  250. request.questions![0] = {
  251. question: longQuestion,
  252. header: "数据同步协议",
  253. options: [
  254. {
  255. value: "crdt",
  256. label: "CRDT (Conflict-free Replicated Data Types)",
  257. description: "基于无冲突复制数据类型,天然支持去中心化同步和 P2P 场景。",
  258. },
  259. {
  260. value: "ot",
  261. label: "OT (Operational Transform)",
  262. description: "基于操作变换算法,依赖中央服务器对操作进行排序和转换。",
  263. },
  264. {
  265. value: "hybrid",
  266. label: "混合 CRDT + OT",
  267. description: "客户端处理本地变更和离线缓冲,服务端处理最终排序。",
  268. },
  269. ],
  270. };
  271. const html = renderToStaticMarkup(
  272. createElement(
  273. ZCodeIntlProvider,
  274. { initialLocale: "zh-CN" },
  275. createElement(Dialog, {
  276. request,
  277. onRespond: () => {},
  278. }),
  279. ),
  280. );
  281. expect(html).toContain('aria-label="展开问题"');
  282. });
  283. it("手机端阻塞弹窗提供整卡折叠入口并标记可隐藏内容", () => {
  284. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  285. const html = renderToStaticMarkup(
  286. createElement(
  287. ZCodeIntlProvider,
  288. { initialLocale: "zh-CN" },
  289. createElement(Dialog, {
  290. request: createMultiQuestionRequest(),
  291. onRespond: () => {},
  292. }),
  293. ),
  294. );
  295. expect(html).toContain('aria-label="折叠问题弹窗"');
  296. expect(html).toContain('aria-expanded="true"');
  297. expect(html).toContain('data-elicitation-dialog-body="true"');
  298. expect(html).toContain('data-elicitation-dialog-footer="true"');
  299. });
  300. it("选项显示标题与描述", () => {
  301. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  302. const request = createMultiQuestionRequest();
  303. request.questions![0]!.options[0] = {
  304. value: "fast",
  305. label: "快速",
  306. description: "先处理核心路径",
  307. };
  308. const html = renderToStaticMarkup(
  309. createElement(
  310. ZCodeIntlProvider,
  311. { initialLocale: "zh-CN" },
  312. createElement(Dialog, {
  313. request,
  314. onRespond: () => {},
  315. }),
  316. ),
  317. );
  318. expect(html).toContain(">快速</span>");
  319. expect(html).toContain(">先处理核心路径</span>");
  320. });
  321. it("plan approval title follows permission copy and approve option keeps approval copy in both locales", () => {
  322. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  323. const request = createPlanApprovalRequest();
  324. const render = (locale: "en-US" | "zh-CN") =>
  325. renderToStaticMarkup(
  326. createElement(
  327. ZCodeIntlProvider,
  328. { initialLocale: locale },
  329. createElement(Dialog, {
  330. request,
  331. onRespond: () => {},
  332. }),
  333. ),
  334. );
  335. const enHtml = render("en-US");
  336. expect(enHtml).toContain("Permission required");
  337. expect(enHtml).toContain("Implementation plan");
  338. expect(enHtml).toContain(">Approve</span>");
  339. expect(enHtml).toContain("Exit plan mode and start implementation.");
  340. expect(enHtml).toContain(">1.</span>");
  341. expect(enHtml).toContain(">2.</span>");
  342. expect(enHtml).not.toContain(">Allow</span>");
  343. expect(enHtml).not.toContain("Allow only this time");
  344. const zhHtml = render("zh-CN");
  345. expect(zhHtml).toContain("需要权限");
  346. expect(zhHtml).toContain("实施计划");
  347. expect(zhHtml).toContain(">批准</span>");
  348. expect(zhHtml).toContain("退出计划模式并开始实施。");
  349. expect(zhHtml).toContain(">1.</span>");
  350. expect(zhHtml).toContain(">2.</span>");
  351. expect(zhHtml).not.toContain(">允许</span>");
  352. expect(zhHtml).not.toContain(">Approve</span>");
  353. expect(zhHtml).not.toContain("Exit plan mode and start implementation.");
  354. });
  355. it("自定义回答输入框 Enter 遵循当前题目和计划审批语义,并避开输入法组词态", () => {
  356. expect(
  357. resolveElicitationCustomInputKeyAction({
  358. key: "Enter",
  359. advanceKind: "next",
  360. }),
  361. ).toBe("advance");
  362. expect(
  363. resolveElicitationCustomInputKeyAction({
  364. key: "Enter",
  365. advanceKind: "submit",
  366. }),
  367. ).toBe("submit");
  368. expect(resolveElicitationCustomInputKeyAction({ key: "Enter" })).toBe("advance");
  369. expect(resolveElicitationCustomInputKeyAction({ key: "Enter", ctrlKey: true })).toBe("submit");
  370. expect(resolveElicitationCustomInputKeyAction({ key: "Enter", metaKey: true })).toBe("submit");
  371. expect(
  372. resolveElicitationCustomInputKeyAction({
  373. key: "Enter",
  374. nativeEvent: { isComposing: true },
  375. }),
  376. ).toBeNull();
  377. expect(
  378. resolveElicitationCustomInputKeyAction({
  379. key: "Enter",
  380. compositionActive: true,
  381. }),
  382. ).toBeNull();
  383. expect(resolveElicitationCustomInputKeyAction({ key: "Escape" })).toBe("dismiss");
  384. expect(
  385. resolveElicitationCustomInputKeyAction({
  386. key: "Escape",
  387. hasPreviousQuestion: true,
  388. }),
  389. ).toBe("previous");
  390. });
  391. it("ExitPlanMode 自定义反馈输入框裸 Enter 提交", () => {
  392. expect(
  393. resolveElicitationCustomInputKeyAction({
  394. key: "Enter",
  395. isPlanApproval: true,
  396. }),
  397. ).toBe("submit");
  398. expect(
  399. resolveElicitationCustomInputKeyAction({
  400. key: "Escape",
  401. hasPreviousQuestion: true,
  402. isPlanApproval: true,
  403. }),
  404. ).toBe("dismiss");
  405. });
  406. });