conversation-session-chat-find-refocus.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. import { execFile } from "node:child_process";
  2. import { promisify } from "node:util";
  3. import { mkdir, rm, writeFile } from "node:fs/promises";
  4. import { join, resolve } from "node:path";
  5. import { TID_V4_TIMELINE, TID_GIT_PANE } from "@zcode/shared/test-ids";
  6. import { Key } from "webdriverio";
  7. import { DEFAULT_WORKSPACE, clearAppData } from "#e2e/helpers/desktop-app";
  8. import {
  9. prepareV4ConversationE2E,
  10. sendV4Prompt,
  11. waitForV4TimelineContaining,
  12. waitForV4Pane,
  13. } from "#e2e/helpers/v4-conversation";
  14. const runGit = promisify(execFile);
  15. const FIND_MARKER = "E2E_CHAT_FIND_REFOCUS_NEEDLE";
  16. const FILE_CHANGE_FIND_MARKER = "E2E_FILE_CHANGE_FIND_REFOCUS_NEEDLE";
  17. const FILE_CHANGE_FIXTURE_NAME = "chat-find-refocus.txt";
  18. const FILE_CHANGE_FIXTURE_PATH = join(DEFAULT_WORKSPACE, FILE_CHANGE_FIXTURE_NAME);
  19. const GIT_BINARY = process.env.ZCODE_GIT_BINARY?.trim() || "git";
  20. const CONVERSATION_FIND_PLACEHOLDERS = ["Search messages...", "搜索消息..."];
  21. const FILE_CHANGE_FIND_PLACEHOLDERS = ["Search file changes...", "搜索文件变更..."];
  22. const FIND_PLACEHOLDERS = [...CONVERSATION_FIND_PLACEHOLDERS, ...FILE_CHANGE_FIND_PLACEHOLDERS];
  23. const PREVIOUS_LABELS = ["Previous result", "上一个结果"];
  24. const NEXT_LABELS = ["Next result", "下一个结果"];
  25. const FILE_CHANGE_SCOPE_LABELS = ["Search file changes", "搜索文件变更"];
  26. const REFRESH_LABELS = ["Refresh", "刷新"];
  27. let createdFixtureRepository = false;
  28. describe("会话区单命中重复查找重新聚焦 E2E", () => {
  29. after(async () => {
  30. await browser.electron.restoreAllMocks();
  31. await clearAppData();
  32. await cleanupFileChangeFindFixture();
  33. });
  34. it("会话和文件变更滚走后,重复导航仍把同一个命中重新居中", async function () {
  35. this.timeout(120000);
  36. await prepareFileChangeFindFixture();
  37. await prepareV4ConversationE2E();
  38. await prepareLongCompletedConversation();
  39. await openConversationFind();
  40. await setFindQuery(CONVERSATION_FIND_PLACEHOLDERS, FIND_MARKER);
  41. await waitForFindCentered("首次搜索没有把唯一命中居中");
  42. for (const action of ["next", "previous", "enter", "shift-enter"] as const) {
  43. await scrollFindMatchAway();
  44. await triggerFindNavigation(action);
  45. await waitForFindCentered(`${action} 没有把唯一命中重新居中`);
  46. }
  47. await switchFindScopeToFileChanges();
  48. await setFindQuery(FILE_CHANGE_FIND_PLACEHOLDERS, FILE_CHANGE_FIND_MARKER);
  49. await waitForFileChangeFindCentered("文件变更首次搜索没有把唯一命中居中");
  50. for (const action of ["next", "previous", "enter", "shift-enter"] as const) {
  51. await scrollFileChangeFindMatchAway();
  52. await triggerFindNavigation(action);
  53. await waitForFileChangeFindCentered(`文件变更 ${action} 没有把唯一命中重新居中`);
  54. }
  55. });
  56. });
  57. async function prepareFileChangeFindFixture() {
  58. await mkdir(DEFAULT_WORKSPACE, { recursive: true });
  59. let repositoryRoot = "";
  60. try {
  61. repositoryRoot = (
  62. await runGit(GIT_BINARY, ["rev-parse", "--show-toplevel"], {
  63. cwd: DEFAULT_WORKSPACE,
  64. encoding: "utf8",
  65. })
  66. ).stdout.trim();
  67. } catch {
  68. repositoryRoot = "";
  69. }
  70. if (resolve(repositoryRoot) !== resolve(DEFAULT_WORKSPACE)) {
  71. await runGit(GIT_BINARY, ["init"], {
  72. cwd: DEFAULT_WORKSPACE,
  73. });
  74. createdFixtureRepository = true;
  75. }
  76. await runGit(GIT_BINARY, ["config", "user.name", "ZCode E2E"], {
  77. cwd: DEFAULT_WORKSPACE,
  78. });
  79. await runGit(GIT_BINARY, ["config", "user.email", "zcode-e2e@example.com"], {
  80. cwd: DEFAULT_WORKSPACE,
  81. });
  82. await writeFile(FILE_CHANGE_FIXTURE_PATH, "", "utf8");
  83. await runGit(GIT_BINARY, ["add", "--", FILE_CHANGE_FIXTURE_NAME], {
  84. cwd: DEFAULT_WORKSPACE,
  85. });
  86. await runGit(
  87. GIT_BINARY,
  88. ["-c", "commit.gpgsign=false", "commit", "-m", "test: seed chat find fixture"],
  89. {
  90. cwd: DEFAULT_WORKSPACE,
  91. },
  92. );
  93. const changedLines = Array.from({ length: 1_300 }, (_, index) =>
  94. index === 79
  95. ? FILE_CHANGE_FIND_MARKER
  96. : `文件变更查找回归行 ${index + 1}:用于撑开 Review 滚动区域。`,
  97. );
  98. await writeFile(FILE_CHANGE_FIXTURE_PATH, `${changedLines.join("\n")}\n`, "utf8");
  99. }
  100. async function cleanupFileChangeFindFixture() {
  101. await rm(FILE_CHANGE_FIXTURE_PATH, { force: true });
  102. if (createdFixtureRepository) {
  103. await rm(join(DEFAULT_WORKSPACE, ".git"), { force: true, recursive: true });
  104. }
  105. }
  106. async function prepareLongCompletedConversation() {
  107. // 旧 setter 已随 V4 状态归属收口移除;通过真实发送建立可查找的长消息。
  108. await sendV4Prompt("E2E_CHAT_FIND_REFOCUS_SETUP 请返回查找回归长正文。");
  109. await waitForV4TimelineContaining(FIND_MARKER);
  110. await waitForV4Pane((state) => Boolean(state.sessionId) && !state.canStop, "长正文未完成");
  111. }
  112. async function openConversationFind() {
  113. await browser.execute(() => {
  114. const isApple = /Mac|iPhone|iPad|iPod/.test(`${navigator.platform} ${navigator.userAgent}`);
  115. window.dispatchEvent(
  116. new KeyboardEvent("keydown", {
  117. bubbles: true,
  118. cancelable: true,
  119. code: "KeyF",
  120. key: "f",
  121. metaKey: isApple,
  122. ctrlKey: !isApple,
  123. }),
  124. );
  125. });
  126. await browser.waitUntil(
  127. () =>
  128. browser.execute(
  129. (placeholders) =>
  130. Array.from(document.querySelectorAll<HTMLInputElement>("input")).some((input) =>
  131. placeholders.includes(input.placeholder),
  132. ),
  133. FIND_PLACEHOLDERS,
  134. ),
  135. {
  136. timeout: 10000,
  137. timeoutMsg: "Cmd/Ctrl+F 没有打开会话查找框",
  138. },
  139. );
  140. }
  141. async function setFindQuery(placeholders: readonly string[], query: string) {
  142. const updated = await browser.execute(
  143. (placeholders, nextQuery) => {
  144. const input = Array.from(document.querySelectorAll<HTMLInputElement>("input")).find(
  145. (candidate) => placeholders.includes(candidate.placeholder),
  146. );
  147. if (!input) {
  148. return false;
  149. }
  150. const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
  151. input.focus();
  152. valueSetter?.call(input, nextQuery);
  153. input.dispatchEvent(
  154. new InputEvent("input", {
  155. bubbles: true,
  156. data: nextQuery,
  157. inputType: "insertText",
  158. }),
  159. );
  160. return true;
  161. },
  162. placeholders,
  163. query,
  164. );
  165. expect(updated).toBe(true);
  166. }
  167. async function switchFindScopeToFileChanges() {
  168. const switched = await browser.execute((labels) => {
  169. const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  170. (candidate) => labels.includes(candidate.getAttribute("aria-label") ?? ""),
  171. );
  172. button?.click();
  173. return Boolean(button);
  174. }, FILE_CHANGE_SCOPE_LABELS);
  175. expect(switched).toBe(true);
  176. await browser.waitUntil(
  177. () =>
  178. browser.execute(
  179. (gitPaneTestId) => Boolean(document.querySelector(`[data-testid="${gitPaneTestId}"]`)),
  180. TID_GIT_PANE,
  181. ),
  182. {
  183. timeout: 10000,
  184. timeoutMsg: "切换文件变更范围后没有打开 Git 面板",
  185. },
  186. );
  187. await browser.waitUntil(
  188. () =>
  189. browser.execute(
  190. (gitPaneTestId, refreshLabels) => {
  191. const pane = document.querySelector<HTMLElement>(`[data-testid="${gitPaneTestId}"]`);
  192. const refreshButton = Array.from(
  193. pane?.querySelectorAll<HTMLButtonElement>("button") ?? [],
  194. ).find((button) => refreshLabels.includes(button.textContent?.trim() ?? ""));
  195. if (!refreshButton || refreshButton.disabled) {
  196. return false;
  197. }
  198. refreshButton.click();
  199. return true;
  200. },
  201. TID_GIT_PANE,
  202. REFRESH_LABELS,
  203. ),
  204. {
  205. timeout: 15000,
  206. timeoutMsg: "Git 面板刷新按钮没有进入可用状态",
  207. },
  208. );
  209. try {
  210. await browser.waitUntil(
  211. () =>
  212. browser.execute(
  213. (gitPaneTestId, fixtureName) =>
  214. document
  215. .querySelector<HTMLElement>(`[data-testid="${gitPaneTestId}"]`)
  216. ?.innerText.includes(fixtureName) === true,
  217. TID_GIT_PANE,
  218. FILE_CHANGE_FIXTURE_NAME,
  219. ),
  220. {
  221. timeout: 15000,
  222. timeoutMsg: "Git 面板没有加载 case-local 文件变更",
  223. },
  224. );
  225. } catch (error) {
  226. const diagnostics = await getGitPaneDiagnostics();
  227. throw new Error(
  228. `Git 面板没有加载 case-local 文件变更; diagnostics=${JSON.stringify(diagnostics)}`,
  229. { cause: error },
  230. );
  231. }
  232. }
  233. function getGitPaneDiagnostics() {
  234. return browser.execute((gitPaneTestId) => {
  235. const pane = document.querySelector<HTMLElement>(`[data-testid="${gitPaneTestId}"]`);
  236. return {
  237. buttons: Array.from(pane?.querySelectorAll<HTMLButtonElement>("button") ?? []).map(
  238. (button) => ({
  239. disabled: button.disabled,
  240. expanded: button.getAttribute("aria-expanded"),
  241. text: button.textContent?.trim() ?? "",
  242. }),
  243. ),
  244. rowCount: pane?.querySelectorAll("[data-git-pane-change-virtual-row]").length ?? 0,
  245. text: pane?.innerText ?? "",
  246. };
  247. }, TID_GIT_PANE);
  248. }
  249. async function scrollFindMatchAway() {
  250. const scrolled = await browser.execute((messagesTestId) => {
  251. const root = document.querySelector<HTMLElement>(`[data-testid="${messagesTestId}"]`);
  252. const viewport = root;
  253. if (!viewport) {
  254. return false;
  255. }
  256. viewport.scrollTop = 0;
  257. viewport.dispatchEvent(new Event("scroll", { bubbles: true }));
  258. return true;
  259. }, TID_V4_TIMELINE);
  260. expect(scrolled).toBe(true);
  261. await browser.waitUntil(
  262. async () => {
  263. const snapshot = await getFindSnapshot();
  264. return snapshot.markerDistanceFromCenter > snapshot.viewportHeight / 2;
  265. },
  266. {
  267. timeout: 10000,
  268. timeoutMsg: "没有把唯一命中滚出视口",
  269. },
  270. );
  271. }
  272. async function triggerFindNavigation(action: "next" | "previous" | "enter" | "shift-enter") {
  273. if (action === "next" || action === "previous") {
  274. const labels = action === "previous" ? PREVIOUS_LABELS : NEXT_LABELS;
  275. for (const label of labels) {
  276. const button = await $(`button[aria-label="${label}"]`);
  277. if (!(await button.isExisting())) {
  278. continue;
  279. }
  280. await button.click();
  281. return;
  282. }
  283. throw new Error(`${action} 导航按钮不存在`);
  284. }
  285. for (const placeholder of FIND_PLACEHOLDERS) {
  286. const input = await $(`input[placeholder="${placeholder}"]`);
  287. if (!(await input.isExisting())) {
  288. continue;
  289. }
  290. await input.click();
  291. if (action === "shift-enter") {
  292. // 评审收口:显式使用 W3C key action,确保 Enter 触发时 Shift 仍保持按下。
  293. // 不改用 DOM dispatchEvent,因为非 trusted 事件无法代表真实用户键盘链路。
  294. await browser
  295. .action("key")
  296. .down(Key.Shift)
  297. .down(Key.Enter)
  298. .up(Key.Enter)
  299. .up(Key.Shift)
  300. .perform();
  301. } else {
  302. await browser.keys("Enter");
  303. }
  304. return;
  305. }
  306. throw new Error(`${action} 导航输入框不存在`);
  307. }
  308. async function waitForFindCentered(timeoutMsg: string) {
  309. let latest: FindSnapshot | null = null;
  310. try {
  311. await browser.waitUntil(
  312. async () => {
  313. latest = await getFindSnapshot();
  314. return (
  315. latest.counter.includes("1/1") &&
  316. latest.scrollTop > 0 &&
  317. latest.markerDistanceFromCenter <= Math.max(120, latest.viewportHeight * 0.3)
  318. );
  319. },
  320. {
  321. timeout: 15000,
  322. timeoutMsg,
  323. },
  324. );
  325. } catch (error) {
  326. latest = await getFindSnapshot().catch(() => latest);
  327. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(latest)}`, {
  328. cause: error,
  329. });
  330. }
  331. }
  332. async function scrollFileChangeFindMatchAway() {
  333. const scrolled = await browser.execute(
  334. (gitPaneTestId, fixtureName) => {
  335. const pane = document.querySelector<HTMLElement>(`[data-testid="${gitPaneTestId}"]`);
  336. const row = Array.from(
  337. pane?.querySelectorAll<HTMLElement>("[data-git-pane-change-virtual-row]") ?? [],
  338. ).find((candidate) => candidate.innerText.includes(fixtureName));
  339. const viewport = row?.parentElement?.parentElement;
  340. if (!(viewport instanceof HTMLElement)) {
  341. return false;
  342. }
  343. viewport.scrollTop = 0;
  344. viewport.dispatchEvent(new Event("scroll", { bubbles: true }));
  345. return true;
  346. },
  347. TID_GIT_PANE,
  348. FILE_CHANGE_FIXTURE_NAME,
  349. );
  350. expect(scrolled).toBe(true);
  351. await browser.waitUntil(
  352. async () => {
  353. const snapshot = await getFileChangeFindSnapshot();
  354. return snapshot.markerDistanceFromCenter > snapshot.viewportHeight / 2;
  355. },
  356. {
  357. timeout: 10000,
  358. timeoutMsg: "没有把文件变更唯一命中滚出视口",
  359. },
  360. );
  361. }
  362. async function waitForFileChangeFindCentered(timeoutMsg: string) {
  363. let latest: FileChangeFindSnapshot | null = null;
  364. try {
  365. await browser.waitUntil(
  366. async () => {
  367. latest = await getFileChangeFindSnapshot();
  368. return (
  369. latest.counter.includes("1/1") &&
  370. latest.expanded &&
  371. latest.scrollTop > 0 &&
  372. latest.markerDistanceFromCenter <= Math.max(120, latest.viewportHeight * 0.3)
  373. );
  374. },
  375. {
  376. timeout: 20000,
  377. timeoutMsg,
  378. },
  379. );
  380. } catch (error) {
  381. latest = await getFileChangeFindSnapshot().catch(() => latest);
  382. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(latest)}`, {
  383. cause: error,
  384. });
  385. }
  386. }
  387. interface FindSnapshot {
  388. counter: string;
  389. markerDistanceFromCenter: number;
  390. scrollTop: number;
  391. viewportHeight: number;
  392. }
  393. interface FileChangeFindSnapshot extends FindSnapshot {
  394. expanded: boolean;
  395. }
  396. function getFileChangeFindSnapshot(): Promise<FileChangeFindSnapshot> {
  397. return browser.execute(
  398. (gitPaneTestId, placeholders, fixtureName, marker) => {
  399. const pane = document.querySelector<HTMLElement>(`[data-testid="${gitPaneTestId}"]`);
  400. const input = Array.from(document.querySelectorAll<HTMLInputElement>("input")).find(
  401. (candidate) => placeholders.includes(candidate.placeholder),
  402. );
  403. const row = Array.from(
  404. pane?.querySelectorAll<HTMLElement>("[data-git-pane-change-virtual-row]") ?? [],
  405. ).find((candidate) => candidate.innerText.includes(fixtureName));
  406. const viewport = row?.parentElement?.parentElement;
  407. if (!input || !(viewport instanceof HTMLElement) || !row) {
  408. return {
  409. counter: input?.parentElement?.textContent ?? "",
  410. expanded: false,
  411. markerDistanceFromCenter: Number.POSITIVE_INFINITY,
  412. scrollTop: viewport instanceof HTMLElement ? viewport.scrollTop : 0,
  413. viewportHeight: viewport instanceof HTMLElement ? viewport.clientHeight : 0,
  414. };
  415. }
  416. const walker = document.createTreeWalker(row, NodeFilter.SHOW_TEXT);
  417. let textNode = walker.nextNode();
  418. let markerRect: DOMRect | null = null;
  419. while (textNode) {
  420. const markerIndex = textNode.textContent?.indexOf(marker) ?? -1;
  421. if (markerIndex >= 0) {
  422. const range = document.createRange();
  423. range.setStart(textNode, markerIndex);
  424. range.setEnd(textNode, markerIndex + marker.length);
  425. markerRect = range.getBoundingClientRect();
  426. break;
  427. }
  428. textNode = walker.nextNode();
  429. }
  430. const viewportRect = viewport.getBoundingClientRect();
  431. const viewportCenter = viewportRect.top + viewportRect.height / 2;
  432. const markerCenter = markerRect
  433. ? markerRect.top + markerRect.height / 2
  434. : Number.POSITIVE_INFINITY;
  435. return {
  436. counter: input.parentElement?.textContent ?? "",
  437. expanded: Boolean(row.querySelector('button[aria-expanded="true"]')),
  438. markerDistanceFromCenter: Math.abs(markerCenter - viewportCenter),
  439. scrollTop: viewport.scrollTop,
  440. viewportHeight: viewport.clientHeight,
  441. };
  442. },
  443. TID_GIT_PANE,
  444. FILE_CHANGE_FIND_PLACEHOLDERS,
  445. FILE_CHANGE_FIXTURE_NAME,
  446. FILE_CHANGE_FIND_MARKER,
  447. );
  448. }
  449. function getFindSnapshot(): Promise<FindSnapshot> {
  450. return browser.execute(
  451. (messagesTestId, placeholders, marker) => {
  452. const root = document.querySelector<HTMLElement>(`[data-testid="${messagesTestId}"]`);
  453. const input = Array.from(document.querySelectorAll<HTMLInputElement>("input")).find(
  454. (candidate) => placeholders.includes(candidate.placeholder),
  455. );
  456. const viewport = root;
  457. if (!input || !viewport || !root) {
  458. return {
  459. counter: "",
  460. markerDistanceFromCenter: Number.POSITIVE_INFINITY,
  461. scrollTop: viewport?.scrollTop ?? 0,
  462. viewportHeight: viewport?.clientHeight ?? 0,
  463. };
  464. }
  465. const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
  466. let textNode = walker.nextNode();
  467. let markerRect: DOMRect | null = null;
  468. while (textNode) {
  469. const markerIndex = textNode.textContent?.indexOf(marker) ?? -1;
  470. if (markerIndex >= 0) {
  471. const range = document.createRange();
  472. range.setStart(textNode, markerIndex);
  473. range.setEnd(textNode, markerIndex + marker.length);
  474. markerRect = range.getBoundingClientRect();
  475. break;
  476. }
  477. textNode = walker.nextNode();
  478. }
  479. const viewportRect = viewport.getBoundingClientRect();
  480. const viewportCenter = viewportRect.top + viewportRect.height / 2;
  481. const markerCenter = markerRect
  482. ? markerRect.top + markerRect.height / 2
  483. : Number.POSITIVE_INFINITY;
  484. return {
  485. counter: input.parentElement?.textContent ?? "",
  486. markerDistanceFromCenter: Math.abs(markerCenter - viewportCenter),
  487. scrollTop: viewport.scrollTop,
  488. viewportHeight: viewport.clientHeight,
  489. };
  490. },
  491. TID_V4_TIMELINE,
  492. FIND_PLACEHOLDERS,
  493. FIND_MARKER,
  494. );
  495. }