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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import { clearAppData } from "../helpers/desktop-app.js";
  2. import { waitForUpstreamRequest } from "../helpers/conversation-session-network.js";
  3. import { waitForToolCallBlockByToolName } from "../helpers/conversation-session-tool.js";
  4. import {
  5. prepareV4ConversationE2E,
  6. sendV4Prompt,
  7. waitForV4TimelineContaining,
  8. } from "../helpers/v4-conversation.js";
  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. await input.setValue("自动换行的自定义回答 wrapped answer ".repeat(240));
  62. const layout = await browser.execute(() => {
  63. const textarea = document.querySelector<HTMLTextAreaElement>(
  64. '[data-elicitation-dialog-body="true"] textarea',
  65. )!;
  66. const style = getComputedStyle(textarea);
  67. const markerRect = textarea.previousElementSibling!.getBoundingClientRect();
  68. return {
  69. height: textarea.getBoundingClientRect().height,
  70. lineHeight: parseFloat(style.lineHeight),
  71. scrollHeight: textarea.scrollHeight,
  72. clientHeight: textarea.clientHeight,
  73. marker: textarea.previousElementSibling?.textContent,
  74. markerFirstLineCenterGap: Math.abs(
  75. markerRect.top +
  76. markerRect.height / 2 -
  77. (textarea.getBoundingClientRect().top +
  78. parseFloat(style.borderTopWidth) +
  79. parseFloat(style.paddingTop) +
  80. parseFloat(style.lineHeight) / 2),
  81. ),
  82. };
  83. });
  84. expect(layout.height).toBeGreaterThan(layout.lineHeight * 4);
  85. expect(layout.height).toBeLessThanOrEqual(layout.lineHeight * 5 + 1);
  86. expect(layout.scrollHeight).toBeGreaterThan(layout.clientHeight);
  87. expect(layout.marker).toBe("3.");
  88. expect(layout.markerFirstLineCenterGap).toBeLessThanOrEqual(0.5);
  89. await focusCustomInputAndSetValue(customAnswer);
  90. await browser.keys("ArrowUp");
  91. await expectActiveOption(Q1_OPTION_B);
  92. await browser.keys("ArrowDown");
  93. await expectCustomInputFocused();
  94. await browser.keys("ArrowDown");
  95. await expectActiveOption(Q1_OPTION_A);
  96. await browser.keys("ArrowUp");
  97. await expectCustomInputFocused();
  98. await expectCustomInputValue(customAnswer);
  99. await browser.keys("Enter");
  100. await waitForElicitationPage("2 / 3", QUESTION_TWO);
  101. await browser.keys("Escape");
  102. await waitForElicitationPage("1 / 3", QUESTION_ONE);
  103. await expectCustomInputValue(customAnswer);
  104. await browser.keys("Enter");
  105. await waitForElicitationPage("2 / 3", QUESTION_TWO);
  106. await browser.keys("Tab");
  107. await expectActiveOption(Q2_OPTION_A);
  108. await browser.keys("ArrowDown");
  109. await expectActiveOption(Q2_OPTION_B);
  110. await browser.keys(" ");
  111. await waitForElicitationPage("3 / 3", QUESTION_THREE);
  112. await browser.keys("Tab");
  113. await expectActiveOption(Q3_OPTION_A);
  114. await browser.keys("ArrowDown");
  115. await expectActiveOption(Q3_OPTION_B);
  116. await browser.keys("ArrowUp");
  117. await expectActiveOption(Q3_OPTION_A);
  118. await browser.keys("Enter");
  119. await waitForUpstreamRequest(
  120. {
  121. includes: [customAnswer, Q2_OPTION_B, Q3_OPTION_A, TOOL_MARKER],
  122. },
  123. "AskUserQuestion 键盘选择结果没有进入下一次模型请求",
  124. 60000,
  125. );
  126. });
  127. });
  128. interface ElicitationKeyboardSnapshot {
  129. activeText: string;
  130. bodyText: string;
  131. customInputValue: string;
  132. focusedTag: string;
  133. pageText: string | null;
  134. selectedTexts: string[];
  135. visible: boolean;
  136. }
  137. async function waitForElicitationPage(pageText: string, questionText: string) {
  138. let latest: ElicitationKeyboardSnapshot | null = null;
  139. try {
  140. await browser.waitUntil(
  141. async () => {
  142. latest = await getElicitationKeyboardSnapshot();
  143. return (
  144. latest.visible && latest.pageText === pageText && latest.bodyText.includes(questionText)
  145. );
  146. },
  147. {
  148. timeout: 60000,
  149. timeoutMsg: `AskUserQuestion 没有进入目标题目 ${pageText} ${questionText}`,
  150. },
  151. );
  152. } catch (error) {
  153. latest = await getElicitationKeyboardSnapshot();
  154. throw new Error(
  155. `AskUserQuestion 没有进入目标题目; expected=${pageText}/${questionText}; snapshot=${JSON.stringify(latest)}`,
  156. { cause: error },
  157. );
  158. }
  159. }
  160. async function focusCustomInputAndSetValue(value: string) {
  161. const input = await $('[data-elicitation-dialog-body="true"] textarea');
  162. await input.waitForDisplayed({
  163. timeout: 30000,
  164. timeoutMsg: "AskUserQuestion 自定义回答输入框没有出现",
  165. });
  166. await input.click();
  167. await input.setValue(value);
  168. await expectCustomInputValue(value);
  169. }
  170. async function expectCustomInputValue(value: string) {
  171. let latest: ElicitationKeyboardSnapshot | null = null;
  172. try {
  173. await browser.waitUntil(
  174. async () => {
  175. latest = await getElicitationKeyboardSnapshot();
  176. return latest.customInputValue === value;
  177. },
  178. {
  179. timeout: 10000,
  180. timeoutMsg: "AskUserQuestion 自定义回答输入框内容不符合预期",
  181. },
  182. );
  183. } catch (error) {
  184. latest = await getElicitationKeyboardSnapshot();
  185. throw new Error(
  186. `AskUserQuestion 自定义回答输入框内容不符合预期; expected=${value}; snapshot=${JSON.stringify(latest)}`,
  187. { cause: error },
  188. );
  189. }
  190. }
  191. async function expectCustomInputFocused() {
  192. await browser.waitUntil(
  193. () =>
  194. browser.execute(
  195. () =>
  196. document.activeElement ===
  197. document.querySelector('[data-elicitation-dialog-body="true"] textarea'),
  198. ),
  199. { timeout: 10000, timeoutMsg: "上下键没有把真实焦点移到自定义输入框" },
  200. );
  201. }
  202. function readCustomInputSemantics() {
  203. return browser.execute(() => {
  204. const textarea = document.querySelector<HTMLTextAreaElement>(
  205. '[data-elicitation-dialog-body="true"] textarea',
  206. );
  207. return {
  208. tagName: textarea?.tagName ?? null,
  209. rows: textarea?.getAttribute("rows") ?? null,
  210. autoSizing: textarea?.classList.contains("field-sizing-content") ?? false,
  211. };
  212. });
  213. }
  214. async function expectActiveOption(optionText: string) {
  215. let latest: ElicitationKeyboardSnapshot | null = null;
  216. try {
  217. await browser.waitUntil(
  218. async () => {
  219. latest = await getElicitationKeyboardSnapshot();
  220. return latest.activeText.includes(optionText);
  221. },
  222. {
  223. timeout: 10000,
  224. timeoutMsg: `AskUserQuestion 当前预选项不是 ${optionText}`,
  225. },
  226. );
  227. } catch (error) {
  228. latest = await getElicitationKeyboardSnapshot();
  229. throw new Error(
  230. `AskUserQuestion 当前预选项不是 ${optionText}; snapshot=${JSON.stringify(latest)}`,
  231. { cause: error },
  232. );
  233. }
  234. }
  235. function getElicitationKeyboardSnapshot(): Promise<ElicitationKeyboardSnapshot> {
  236. return browser.execute(() => {
  237. const normalizeText = (value: string | null | undefined) =>
  238. (value ?? "").replace(/\u00a0/g, " ").trim();
  239. const body = document.querySelector<HTMLElement>('[data-elicitation-dialog-body="true"]');
  240. const focused = document.activeElement as HTMLElement | null;
  241. // 修复原因:普通问答切题后卡片本身获得焦点,第一项仅作为 roving
  242. // tabindex 入口保留 tabindex=0,不能把它误判为真实焦点。
  243. const activeOption = focused?.closest<HTMLElement>('button[role="option"],[role="checkbox"]');
  244. const pageText =
  245. normalizeText(body?.innerText)
  246. .match(/\b\d+\s*\/\s*\d+\b/)?.[0]
  247. ?.replace(/\s+/g, " ") ?? null;
  248. const selectedTexts = Array.from(
  249. body?.querySelectorAll<HTMLElement>(
  250. 'button[role="option"][aria-selected="true"],[role="checkbox"][aria-checked="true"]',
  251. ) ?? [],
  252. ).map((element) => normalizeText(element.innerText));
  253. const input = body?.querySelector<HTMLTextAreaElement>("textarea") ?? null;
  254. return {
  255. activeText: normalizeText(activeOption?.innerText),
  256. bodyText: normalizeText(body?.innerText),
  257. customInputValue: input?.value ?? "",
  258. focusedTag: focused?.tagName ?? "",
  259. pageText,
  260. selectedTexts,
  261. visible: Boolean(body),
  262. };
  263. });
  264. }