conversation-session-ask-user-question-keyboard-navigation.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import { clearAppData } from "#e2e/helpers/desktop-app";
  2. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  3. import { waitForToolCallBlockByToolName } from "#e2e/helpers/conversation-session-tool";
  4. import {
  5. prepareV4ConversationE2E,
  6. sendV4Prompt,
  7. waitForV4TimelineContaining,
  8. } from "#e2e/helpers/v4-conversation";
  9. const PROMPT_MARKER = "E2E_ASK_USER_QUESTION_KEYBOARD_NAV";
  10. const TOOL_MARKER = "E2E_ASK_USER_QUESTION_KEYBOARD_NAV_TOOL";
  11. const CUSTOM_ANSWER_MARKER = "E2E_ASK_USER_QUESTION_KEYBOARD_CUSTOM";
  12. const QUESTION_ONE = "E2E_AQK_Q1_CUSTOM_ENTER";
  13. const QUESTION_TWO = "E2E_AQK_Q2_OPTION_SPACE";
  14. const QUESTION_THREE = "E2E_AQK_Q3_OPTION_ENTER";
  15. const Q1_OPTION_A = "E2E_AQK_Q1_OPTION_A";
  16. const Q1_OPTION_B = "E2E_AQK_Q1_OPTION_B";
  17. const Q2_OPTION_A = "E2E_AQK_Q2_OPTION_A";
  18. const Q2_OPTION_B = "E2E_AQK_Q2_OPTION_B";
  19. const Q3_OPTION_A = "E2E_AQK_Q3_OPTION_A";
  20. const Q3_OPTION_B = "E2E_AQK_Q3_OPTION_B";
  21. describe("会话区 AskUserQuestion 键盘导航 E2E", () => {
  22. after(async () => {
  23. await browser.electron.restoreAllMocks();
  24. await clearAppData();
  25. });
  26. it("自定义 Enter、Esc 返回、上下预选和空格/Enter 选中应符合多题问答键盘语义", async function () {
  27. this.timeout(180000);
  28. // Bug 根因:已转正用例仍经由 legacy helper 定位消息,
  29. // 与 formal 目录的 V4 pane 证据合同不一致。
  30. await prepareV4ConversationE2E();
  31. const runId = Date.now();
  32. const customAnswer = `${CUSTOM_ANSWER_MARKER}_${runId}`;
  33. const prompt = [
  34. `${PROMPT_MARKER}_${runId}: Trigger the AskUserQuestion tool exactly once.`,
  35. `${TOOL_MARKER}: ask exactly three questions in one AskUserQuestion call.`,
  36. `Question 1 text must be ${QUESTION_ONE} and should allow a custom answer.`,
  37. `Question 2 text must be ${QUESTION_TWO} with options ${Q2_OPTION_A} and ${Q2_OPTION_B}.`,
  38. `Question 3 text must be ${QUESTION_THREE} with options ${Q3_OPTION_A} and ${Q3_OPTION_B}.`,
  39. "Do not answer the questions yourself. After the user responds, continue briefly.",
  40. ].join(" ");
  41. await sendV4Prompt(prompt);
  42. await waitForV4TimelineContaining(`${PROMPT_MARKER}_${runId}`);
  43. await waitForToolCallBlockByToolName("AskUserQuestion", 60000);
  44. await waitForElicitationPage("1 / 3", QUESTION_ONE);
  45. expect(await readCustomInputSemantics()).toEqual({
  46. tagName: "TEXTAREA",
  47. rows: "1",
  48. autoSizing: true,
  49. });
  50. await browser.waitUntil(
  51. () =>
  52. browser.execute(
  53. () => document.activeElement?.getAttribute("data-elicitation-dialog-card") === "true",
  54. ),
  55. { timeout: 10000, timeoutMsg: "普通问答初始焦点应在卡片,不能自动进入自定义输入框" },
  56. );
  57. await browser.keys("ArrowUp");
  58. await expectCustomInputFocused();
  59. const input = await $('[data-elicitation-dialog-body="true"] textarea');
  60. // 长答案必须真的换行并在五行内滚动;仅断言 CSS class 无法发现布局失效。
  61. // 修复原因:原先重复 240 次(约 6700 字符),Windows chromedriver 逐键输入超过
  62. // WebDriver 单请求 30 秒上限而中断;24 次已远超五行高度,足以覆盖换行与滚动断言。
  63. await input.setValue("自动换行的自定义回答 wrapped answer ".repeat(24));
  64. const layout = await browser.execute(() => {
  65. const textarea = document.querySelector<HTMLTextAreaElement>(
  66. '[data-elicitation-dialog-body="true"] textarea',
  67. )!;
  68. const style = getComputedStyle(textarea);
  69. const markerRect = textarea.previousElementSibling!.getBoundingClientRect();
  70. return {
  71. height: textarea.getBoundingClientRect().height,
  72. lineHeight: parseFloat(style.lineHeight),
  73. scrollHeight: textarea.scrollHeight,
  74. clientHeight: textarea.clientHeight,
  75. marker: textarea.previousElementSibling?.textContent,
  76. markerFirstLineCenterGap: Math.abs(
  77. markerRect.top +
  78. markerRect.height / 2 -
  79. (textarea.getBoundingClientRect().top +
  80. parseFloat(style.borderTopWidth) +
  81. parseFloat(style.paddingTop) +
  82. parseFloat(style.lineHeight) / 2),
  83. ),
  84. };
  85. });
  86. expect(layout.height).toBeGreaterThan(layout.lineHeight * 4);
  87. expect(layout.height).toBeLessThanOrEqual(layout.lineHeight * 5 + 1);
  88. expect(layout.scrollHeight).toBeGreaterThan(layout.clientHeight);
  89. expect(layout.marker).toBe("3.");
  90. expect(layout.markerFirstLineCenterGap).toBeLessThanOrEqual(0.5);
  91. await focusCustomInputAndSetValue(customAnswer);
  92. await browser.keys("ArrowUp");
  93. await expectActiveOption(Q1_OPTION_B);
  94. await browser.keys("ArrowDown");
  95. await expectCustomInputFocused();
  96. await browser.keys("ArrowDown");
  97. await expectActiveOption(Q1_OPTION_A);
  98. await browser.keys("ArrowUp");
  99. await expectCustomInputFocused();
  100. await expectCustomInputValue(customAnswer);
  101. await browser.keys("Enter");
  102. await waitForElicitationPage("2 / 3", QUESTION_TWO);
  103. await browser.keys("Escape");
  104. await waitForElicitationPage("1 / 3", QUESTION_ONE);
  105. await expectCustomInputValue(customAnswer);
  106. await browser.keys("Enter");
  107. await waitForElicitationPage("2 / 3", QUESTION_TWO);
  108. await browser.keys("Tab");
  109. await expectActiveOption(Q2_OPTION_A);
  110. await browser.keys("ArrowDown");
  111. await expectActiveOption(Q2_OPTION_B);
  112. await browser.keys(" ");
  113. await waitForElicitationPage("3 / 3", QUESTION_THREE);
  114. await browser.keys("Tab");
  115. await expectActiveOption(Q3_OPTION_A);
  116. await browser.keys("ArrowDown");
  117. await expectActiveOption(Q3_OPTION_B);
  118. await browser.keys("ArrowUp");
  119. await expectActiveOption(Q3_OPTION_A);
  120. await browser.keys("Enter");
  121. await waitForUpstreamRequest(
  122. {
  123. includes: [customAnswer, Q2_OPTION_B, Q3_OPTION_A, TOOL_MARKER],
  124. },
  125. "AskUserQuestion 键盘选择结果没有进入下一次模型请求",
  126. 60000,
  127. );
  128. });
  129. });
  130. interface ElicitationKeyboardSnapshot {
  131. activeText: string;
  132. bodyText: string;
  133. customInputValue: string;
  134. focusedTag: string;
  135. pageText: string | null;
  136. selectedTexts: string[];
  137. visible: boolean;
  138. }
  139. async function waitForElicitationPage(pageText: string, questionText: string) {
  140. let latest: ElicitationKeyboardSnapshot | null = null;
  141. try {
  142. await browser.waitUntil(
  143. async () => {
  144. latest = await getElicitationKeyboardSnapshot();
  145. return (
  146. latest.visible && latest.pageText === pageText && latest.bodyText.includes(questionText)
  147. );
  148. },
  149. {
  150. timeout: 60000,
  151. timeoutMsg: `AskUserQuestion 没有进入目标题目 ${pageText} ${questionText}`,
  152. },
  153. );
  154. } catch (error) {
  155. latest = await getElicitationKeyboardSnapshot();
  156. throw new Error(
  157. `AskUserQuestion 没有进入目标题目; expected=${pageText}/${questionText}; snapshot=${JSON.stringify(latest)}`,
  158. { cause: error },
  159. );
  160. }
  161. }
  162. async function focusCustomInputAndSetValue(value: string) {
  163. const input = await $('[data-elicitation-dialog-body="true"] textarea');
  164. await input.waitForDisplayed({
  165. timeout: 30000,
  166. timeoutMsg: "AskUserQuestion 自定义回答输入框没有出现",
  167. });
  168. await input.click();
  169. await input.setValue(value);
  170. await expectCustomInputValue(value);
  171. }
  172. async function expectCustomInputValue(value: string) {
  173. let latest: ElicitationKeyboardSnapshot | null = null;
  174. try {
  175. await browser.waitUntil(
  176. async () => {
  177. latest = await getElicitationKeyboardSnapshot();
  178. return latest.customInputValue === value;
  179. },
  180. {
  181. timeout: 10000,
  182. timeoutMsg: "AskUserQuestion 自定义回答输入框内容不符合预期",
  183. },
  184. );
  185. } catch (error) {
  186. latest = await getElicitationKeyboardSnapshot();
  187. throw new Error(
  188. `AskUserQuestion 自定义回答输入框内容不符合预期; expected=${value}; snapshot=${JSON.stringify(latest)}`,
  189. { cause: error },
  190. );
  191. }
  192. }
  193. async function expectCustomInputFocused() {
  194. await browser.waitUntil(
  195. () =>
  196. browser.execute(
  197. () =>
  198. document.activeElement ===
  199. document.querySelector('[data-elicitation-dialog-body="true"] textarea'),
  200. ),
  201. { timeout: 10000, timeoutMsg: "上下键没有把真实焦点移到自定义输入框" },
  202. );
  203. }
  204. function readCustomInputSemantics() {
  205. return browser.execute(() => {
  206. const textarea = document.querySelector<HTMLTextAreaElement>(
  207. '[data-elicitation-dialog-body="true"] textarea',
  208. );
  209. return {
  210. tagName: textarea?.tagName ?? null,
  211. rows: textarea?.getAttribute("rows") ?? null,
  212. autoSizing: textarea?.classList.contains("field-sizing-content") ?? false,
  213. };
  214. });
  215. }
  216. async function expectActiveOption(optionText: string) {
  217. let latest: ElicitationKeyboardSnapshot | null = null;
  218. try {
  219. await browser.waitUntil(
  220. async () => {
  221. latest = await getElicitationKeyboardSnapshot();
  222. return latest.activeText.includes(optionText);
  223. },
  224. {
  225. timeout: 10000,
  226. timeoutMsg: `AskUserQuestion 当前预选项不是 ${optionText}`,
  227. },
  228. );
  229. } catch (error) {
  230. latest = await getElicitationKeyboardSnapshot();
  231. throw new Error(
  232. `AskUserQuestion 当前预选项不是 ${optionText}; snapshot=${JSON.stringify(latest)}`,
  233. { cause: error },
  234. );
  235. }
  236. }
  237. function getElicitationKeyboardSnapshot(): Promise<ElicitationKeyboardSnapshot> {
  238. return browser.execute(() => {
  239. const normalizeText = (value: string | null | undefined) =>
  240. (value ?? "").replace(/\u00a0/g, " ").trim();
  241. const body = document.querySelector<HTMLElement>('[data-elicitation-dialog-body="true"]');
  242. const focused = document.activeElement as HTMLElement | null;
  243. // 修复原因:普通问答切题后卡片本身获得焦点,第一项仅作为 roving
  244. // tabindex 入口保留 tabindex=0,不能把它误判为真实焦点。
  245. const activeOption = focused?.closest<HTMLElement>('button[role="option"],[role="checkbox"]');
  246. const pageText =
  247. normalizeText(body?.innerText)
  248. .match(/\b\d+\s*\/\s*\d+\b/)?.[0]
  249. ?.replace(/\s+/g, " ") ?? null;
  250. const selectedTexts = Array.from(
  251. body?.querySelectorAll<HTMLElement>(
  252. 'button[role="option"][aria-selected="true"],[role="checkbox"][aria-checked="true"]',
  253. ) ?? [],
  254. ).map((element) => normalizeText(element.innerText));
  255. const input = body?.querySelector<HTMLTextAreaElement>("textarea") ?? null;
  256. return {
  257. activeText: normalizeText(activeOption?.innerText),
  258. bodyText: normalizeText(body?.innerText),
  259. customInputValue: input?.value ?? "",
  260. focusedTag: focused?.tagName ?? "",
  261. pageText,
  262. selectedTexts,
  263. visible: Boolean(body),
  264. };
  265. });
  266. }