elicitationDialog.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 clickable localized final-minute timer before question navigation", () => {
  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. expect(zhHtml.indexOf(">59秒</button>")).toBeLessThan(zhHtml.indexOf('title="上一题"'));
  131. const enHtml = render("en-US");
  132. expect(enHtml).toContain(">59s</button>");
  133. expect(enHtml).toContain('aria-label="Stop timer"');
  134. } finally {
  135. nowSpy.mockRestore();
  136. }
  137. });
  138. it("shows a subagent source tag for delegated elicitation requests only", () => {
  139. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  140. const request = createMultiQuestionRequest();
  141. const mainHtml = renderToStaticMarkup(
  142. createElement(
  143. ZCodeIntlProvider,
  144. { initialLocale: "zh-CN" },
  145. createElement(Dialog, {
  146. request,
  147. onRespond: () => {},
  148. }),
  149. ),
  150. );
  151. const subagentHtml = renderToStaticMarkup(
  152. createElement(
  153. ZCodeIntlProvider,
  154. { initialLocale: "zh-CN" },
  155. createElement(Dialog, {
  156. request: {
  157. ...request,
  158. origin: SUBAGENT_ORIGIN,
  159. },
  160. onRespond: () => {},
  161. }),
  162. ),
  163. );
  164. expect(mainHtml).not.toContain('data-interaction-origin-badge="subagent"');
  165. expect(subagentHtml).toContain('data-interaction-origin-badge="subagent"');
  166. expect(subagentHtml).toContain("子智能体");
  167. expect(subagentHtml).toContain("来自子智能体:general-purpose");
  168. });
  169. it("renders the custom answer as an auto-wrapping textarea", () => {
  170. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  171. const html = renderToStaticMarkup(
  172. createElement(
  173. ZCodeIntlProvider,
  174. { initialLocale: "zh-CN" },
  175. createElement(Dialog, {
  176. request: createMultiQuestionRequest(),
  177. onRespond: () => {},
  178. }),
  179. ),
  180. );
  181. expect(html).toContain("<textarea");
  182. expect(html).toContain('wrap="soft"');
  183. expect(html).toContain("field-sizing-content");
  184. expect(html).toContain("min-h-5");
  185. expect(html).toContain("focus-visible:ring-0");
  186. });
  187. it("submits after the final question and includes the final selected option", () => {
  188. const request = createMultiQuestionRequest();
  189. const questions = normalizeElicitationQuestions(request);
  190. const initialDrafts = createInitialElicitationDrafts(questions, request);
  191. const firstDrafts = updateElicitationDraftsForOption(initialDrafts, questions[0]!, "fast");
  192. const finalDrafts = updateElicitationDraftsForOption(firstDrafts, questions[1]!, "tests");
  193. expect(getElicitationQuestionAdvanceKind(questions, 0)).toBe("next");
  194. expect(getElicitationQuestionAdvanceKind(questions, 1)).toBe("submit");
  195. expect(buildElicitationResponseContent(questions, finalDrafts)).toEqual({
  196. answers: {
  197. 请选择方案: "fast",
  198. 请选择保障项: "tests",
  199. },
  200. answer_0: "fast",
  201. answer_1: "tests",
  202. });
  203. });
  204. it("允许只提交部分问题的答案且不伪造未回答项", () => {
  205. const request = createMultiQuestionRequest();
  206. const questions = normalizeElicitationQuestions(request);
  207. const initialDrafts = createInitialElicitationDrafts(questions, request);
  208. const finalDrafts = updateElicitationDraftsForOption(initialDrafts, questions[1]!, "tests");
  209. expect(buildElicitationResponseContent(questions, finalDrafts)).toEqual({
  210. answers: { 请选择保障项: "tests" },
  211. answer_1: "tests",
  212. });
  213. });
  214. it("允许提交零回答", () => {
  215. const request = createMultiQuestionRequest();
  216. const questions = normalizeElicitationQuestions(request);
  217. const drafts = createInitialElicitationDrafts(questions, request);
  218. expect(buildElicitationResponseContent(questions, drafts)).toEqual({ answers: {} });
  219. });
  220. it("不再承载聊天底部主列宽度和 summary 偏移", () => {
  221. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  222. const html = renderToStaticMarkup(
  223. createElement(
  224. ZCodeIntlProvider,
  225. { initialLocale: "zh-CN" },
  226. createElement(Dialog, {
  227. request: createMultiQuestionRequest(),
  228. onRespond: () => {},
  229. }),
  230. ),
  231. );
  232. expect(html).not.toContain("translate-x");
  233. expect(html).not.toContain("max-w-3xl");
  234. expect(html).not.toContain("max-w-2xl");
  235. });
  236. it("为截断的问题标题保留完整 hover title", () => {
  237. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  238. const longQuestion =
  239. "The PRD spans 4 native codebases plus shared contract and tokens. How should I sequence implementation?";
  240. const request = createMultiQuestionRequest();
  241. request.questions![0] = {
  242. ...request.questions![0]!,
  243. question: longQuestion,
  244. };
  245. const html = renderToStaticMarkup(
  246. createElement(
  247. ZCodeIntlProvider,
  248. { initialLocale: "zh-CN" },
  249. createElement(Dialog, {
  250. request,
  251. onRespond: () => {},
  252. }),
  253. ),
  254. );
  255. expect(html).toContain(`title="${longQuestion}"`);
  256. });
  257. it("长问题跟在 tag 后完整展示,不只依赖 hover title", () => {
  258. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  259. const longQuestion =
  260. "The PRD spans 4 native codebases plus shared contract and tokens. How should I sequence implementation without hiding the decision text on mobile?";
  261. const request = createMultiQuestionRequest();
  262. request.questions![0] = {
  263. ...request.questions![0]!,
  264. question: longQuestion,
  265. };
  266. const html = renderToStaticMarkup(
  267. createElement(
  268. ZCodeIntlProvider,
  269. { initialLocale: "zh-CN" },
  270. createElement(Dialog, {
  271. request,
  272. onRespond: () => {},
  273. }),
  274. ),
  275. );
  276. const tagIndex = html.indexOf(">方案</span>");
  277. const questionIndex = html.indexOf(`>${longQuestion}</span>`);
  278. expect(html).toContain(`title="${longQuestion}"`);
  279. expect(tagIndex).toBeGreaterThanOrEqual(0);
  280. expect(questionIndex).toBeGreaterThan(tagIndex);
  281. expect(html).toContain("whitespace-pre-wrap");
  282. expect(html).not.toContain(
  283. `truncate text-ui-base font-medium leading-5 text-foreground">${longQuestion}`,
  284. );
  285. });
  286. it("手机端长问题弹窗保留高度上限、内部滚动和折叠入口", () => {
  287. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  288. const longQuestion =
  289. "假设你正在设计一个面向全球用户的下一代分布式实时协作平台,该平台需要支持百万级并发用户同时在线编辑文档、画板、表格和低代码应用,并且要求在离线状态下仍然可以正常编辑并在恢复网络后自动合并冲突。请在数据同步协议层面说明选择。";
  290. const request = createMultiQuestionRequest();
  291. request.questions![0] = {
  292. question: longQuestion,
  293. header: "数据同步协议",
  294. options: [
  295. {
  296. value: "crdt",
  297. label: "CRDT (Conflict-free Replicated Data Types)",
  298. description: "基于无冲突复制数据类型,天然支持去中心化同步和 P2P 场景。",
  299. },
  300. {
  301. value: "ot",
  302. label: "OT (Operational Transform)",
  303. description: "基于操作变换算法,依赖中央服务器对操作进行排序和转换。",
  304. },
  305. {
  306. value: "hybrid",
  307. label: "混合 CRDT + OT",
  308. description: "客户端处理本地变更和离线缓冲,服务端处理最终排序。",
  309. },
  310. ],
  311. };
  312. const html = renderToStaticMarkup(
  313. createElement(
  314. ZCodeIntlProvider,
  315. { initialLocale: "zh-CN" },
  316. createElement(Dialog, {
  317. request,
  318. onRespond: () => {},
  319. }),
  320. ),
  321. );
  322. expect(html).toContain("max-h-[min(72dvh,42rem)]");
  323. expect(html).toContain("overflow-y-auto");
  324. expect(html).toContain("overscroll-contain");
  325. expect(html).toContain("max-md:line-clamp-4");
  326. expect(html).toContain('aria-label="展开问题"');
  327. expect(html).toContain("flex shrink-0 items-center justify-between");
  328. });
  329. it("手机端阻塞弹窗提供整卡折叠入口并标记可隐藏内容", () => {
  330. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  331. const html = renderToStaticMarkup(
  332. createElement(
  333. ZCodeIntlProvider,
  334. { initialLocale: "zh-CN" },
  335. createElement(Dialog, {
  336. request: createMultiQuestionRequest(),
  337. onRespond: () => {},
  338. }),
  339. ),
  340. );
  341. expect(html).toContain('aria-label="折叠问题弹窗"');
  342. expect(html).toContain('aria-expanded="true"');
  343. expect(html).toContain("max-md:inline-flex");
  344. expect(html).toContain('data-elicitation-dialog-body="true"');
  345. expect(html).toContain('data-elicitation-dialog-footer="true"');
  346. });
  347. it("选项文案按标题在前、描述紧随其后的顺序展示,并随界面字号增长", () => {
  348. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  349. const request = createMultiQuestionRequest();
  350. request.questions![0]!.options[0] = {
  351. value: "fast",
  352. label: "快速",
  353. description: "先处理核心路径",
  354. };
  355. const html = renderToStaticMarkup(
  356. createElement(
  357. ZCodeIntlProvider,
  358. { initialLocale: "zh-CN" },
  359. createElement(Dialog, {
  360. request,
  361. onRespond: () => {},
  362. }),
  363. ),
  364. );
  365. expect(html).toContain(
  366. '<span class="text-ui-base font-medium leading-normal text-foreground">快速</span><span class="ml-2 text-ui-base leading-normal text-foreground-subtle">先处理核心路径</span>',
  367. );
  368. expect(html).toContain("min-w-0 flex-1 text-ui-base leading-normal");
  369. expect(html).toContain("h-auto !min-h-5");
  370. expect(html).not.toContain("file:text-ui-base h-5 rounded-none");
  371. });
  372. it("plan approval title follows permission copy and approve option keeps approval copy in both locales", () => {
  373. const Dialog = ElicitationDialog as ComponentType<Record<string, unknown>>;
  374. const request = createPlanApprovalRequest();
  375. const render = (locale: "en-US" | "zh-CN") =>
  376. renderToStaticMarkup(
  377. createElement(
  378. ZCodeIntlProvider,
  379. { initialLocale: locale },
  380. createElement(Dialog, {
  381. request,
  382. onRespond: () => {},
  383. }),
  384. ),
  385. );
  386. const enHtml = render("en-US");
  387. expect(enHtml).toContain("Permission required");
  388. expect(enHtml).toContain("Implementation plan");
  389. expect(enHtml).toContain(">Approve</span>");
  390. expect(enHtml).toContain("Exit plan mode and start implementation.");
  391. expect(enHtml).toContain(">1.</span>");
  392. expect(enHtml).toContain(">2.</span>");
  393. expect(enHtml).not.toContain(">Allow</span>");
  394. expect(enHtml).not.toContain("Allow only this time");
  395. const zhHtml = render("zh-CN");
  396. expect(zhHtml).toContain("需要权限");
  397. expect(zhHtml).toContain("实施计划");
  398. expect(zhHtml).toContain(">批准</span>");
  399. expect(zhHtml).toContain("退出计划模式并开始实施。");
  400. expect(zhHtml).toContain(">1.</span>");
  401. expect(zhHtml).toContain(">2.</span>");
  402. expect(zhHtml).not.toContain(">允许</span>");
  403. expect(zhHtml).not.toContain(">Approve</span>");
  404. expect(zhHtml).not.toContain("Exit plan mode and start implementation.");
  405. });
  406. it("自定义回答输入框 Enter 遵循当前题目和计划审批语义,并避开输入法组词态", () => {
  407. expect(
  408. resolveElicitationCustomInputKeyAction({
  409. key: "Enter",
  410. advanceKind: "next",
  411. }),
  412. ).toBe("advance");
  413. expect(
  414. resolveElicitationCustomInputKeyAction({
  415. key: "Enter",
  416. advanceKind: "submit",
  417. }),
  418. ).toBe("submit");
  419. expect(resolveElicitationCustomInputKeyAction({ key: "Enter" })).toBe("advance");
  420. expect(resolveElicitationCustomInputKeyAction({ key: "Enter", ctrlKey: true })).toBe("submit");
  421. expect(resolveElicitationCustomInputKeyAction({ key: "Enter", metaKey: true })).toBe("submit");
  422. expect(
  423. resolveElicitationCustomInputKeyAction({
  424. key: "Enter",
  425. nativeEvent: { isComposing: true },
  426. }),
  427. ).toBeNull();
  428. expect(
  429. resolveElicitationCustomInputKeyAction({
  430. key: "Enter",
  431. compositionActive: true,
  432. }),
  433. ).toBeNull();
  434. expect(resolveElicitationCustomInputKeyAction({ key: "Escape" })).toBe("dismiss");
  435. expect(
  436. resolveElicitationCustomInputKeyAction({
  437. key: "Escape",
  438. hasPreviousQuestion: true,
  439. }),
  440. ).toBe("previous");
  441. });
  442. it("ExitPlanMode 自定义反馈输入框裸 Enter 提交", () => {
  443. expect(
  444. resolveElicitationCustomInputKeyAction({
  445. key: "Enter",
  446. isPlanApproval: true,
  447. }),
  448. ).toBe("submit");
  449. expect(
  450. resolveElicitationCustomInputKeyAction({
  451. key: "Escape",
  452. hasPreviousQuestion: true,
  453. isPlanApproval: true,
  454. }),
  455. ).toBe("dismiss");
  456. });
  457. });