chat-input-mention-navigation.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. import { mkdir, rm, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { ServiceChannels } from "@zcode/shared";
  4. import {
  5. TID_PROMPT_SUGGESTION_OPTION,
  6. TID_PROMPT_SUGGESTION_PANEL,
  7. TID_PROMPT_SUGGESTION_SECTION,
  8. TID_V4_COMPOSER_INPUT,
  9. testId,
  10. } from "@zcode/shared/test-ids";
  11. import {
  12. clearAppData,
  13. DEFAULT_WORKSPACE,
  14. setInputValueByTestIdDom,
  15. waitForDefaultWorkspaceReady,
  16. } from "#e2e/helpers/desktop-app";
  17. import { callHandoffHost, installHandoffRpcProbe } from "#e2e/helpers/remote-project-handoff-probe";
  18. type LexicalInputE2EBridge = {
  19. focus: () => void;
  20. getText: () => string;
  21. setEditorStateJson: (editorStateJson: string) => void;
  22. };
  23. type LexicalInputE2EElement = HTMLElement & {
  24. __zcodeLexicalInputE2E?: LexicalInputE2EBridge;
  25. };
  26. const FILE_MENTION_LABEL = "option-right-repro.ts";
  27. const FILE_MENTION_PATH = "src/option-right-repro.ts";
  28. const FILE_MENTION_MARKDOWN = `[${FILE_MENTION_LABEL}](${FILE_MENTION_PATH})`;
  29. const TYPED_AFTER_MENTION = "继续输入";
  30. const PLUGIN_NAME = "skill-creator";
  31. const PLUGIN_STABLE_ID = "skill-creator@zcode-plugins-official";
  32. const PLUGIN_OPTION_ID = `plugin:${PLUGIN_STABLE_ID}`;
  33. const SCROLL_ANCHOR_PREFIX = "e2e-scroll-anchor";
  34. const SCROLL_ANCHOR_DIR = join(DEFAULT_WORKSPACE, SCROLL_ANCHOR_PREFIX);
  35. const SCROLL_ANCHOR_FILE_COUNT = 40;
  36. const ZCODEIGNORE_PATH = join(DEFAULT_WORKSPACE, ".zcodeignore");
  37. const OPTION_ROW_HEIGHT = 34;
  38. const LISTBOX_SELECTOR = `[data-testid="${TID_PROMPT_SUGGESTION_PANEL}"] [role="listbox"]`;
  39. describe("chat input mention navigation", () => {
  40. after(async () => {
  41. await browser.electron.restoreAllMocks();
  42. await clearAppData();
  43. });
  44. it("keeps a file mention when typing after Option+ArrowRight moves across it", async () => {
  45. await waitForDefaultWorkspaceReady(30000);
  46. await setChatInputFileMentionState();
  47. await placeSelectionBeforeFileMention();
  48. await pressOptionArrowRight();
  49. const afterMove = await getMentionNavigationSnapshot();
  50. expect(afterMove.mentionCount).toBe(1);
  51. await browser.keys(TYPED_AFTER_MENTION);
  52. const afterTyping = await getMentionNavigationSnapshot();
  53. expect(afterTyping.mentionCount).toBe(1);
  54. expect(afterTyping.bridgeText).toContain(FILE_MENTION_MARKDOWN);
  55. expect(afterTyping.bridgeText).toContain(TYPED_AFTER_MENTION);
  56. });
  57. it("keeps the Plugin candidates stable while ArrowLeft/ArrowRight moves inside the active token", async () => {
  58. await waitForDefaultWorkspaceReady(30000);
  59. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, `@${PLUGIN_NAME}`, {
  60. stabilizeLexicalCaretAtEnd: true,
  61. timeout: 15000,
  62. });
  63. await waitForPluginOption();
  64. await startPluginOptionStabilityProbe();
  65. await browser.keys("ArrowLeft");
  66. await waitForPluginOption();
  67. await browser.keys("ArrowRight");
  68. await waitForPluginOption();
  69. await browser.keys("ArrowLeft");
  70. await waitForPluginOption();
  71. expect(await finishPluginOptionStabilityProbe()).toEqual({
  72. optionDisconnected: false,
  73. panelDisconnected: false,
  74. });
  75. await browser.keys("Enter");
  76. await browser.waitUntil(
  77. async () => (await getComposerText()) === `[@${PLUGIN_NAME}](plugin://${PLUGIN_STABLE_ID}) `,
  78. {
  79. timeout: 10000,
  80. timeoutMsg: "ArrowLeft 后选择 Plugin 没有替换完整 token,或残留了重复后缀",
  81. },
  82. );
  83. });
  84. // 反馈 ZCT-2122356778527907840(3.18.2):长列表用滚轮翻到中段后,后台任务状态变化触发候选刷新,
  85. // 列表被拉回开头。这里用真实 wheel 滚动,再走与后台任务变化相同的 state:projects 广播刷新候选。
  86. it("keeps the wheel scroll position when candidates refresh, and ArrowDown scrolls the selection into view", async () => {
  87. await waitForDefaultWorkspaceReady(30000);
  88. await mkdir(SCROLL_ANCHOR_DIR, { recursive: true });
  89. try {
  90. for (let index = 0; index < SCROLL_ANCHOR_FILE_COUNT; index += 1) {
  91. await writeFile(
  92. join(SCROLL_ANCHOR_DIR, `${SCROLL_ANCHOR_PREFIX}-${String(index).padStart(2, "0")}.ts`),
  93. `export const value = ${index};\n`,
  94. );
  95. }
  96. await installHandoffRpcProbe();
  97. await installFileSearchResponseProbe();
  98. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, `@${SCROLL_ANCHOR_PREFIX}`, {
  99. stabilizeLexicalCaretAtEnd: true,
  100. timeout: 15000,
  101. });
  102. await browser.waitUntil(
  103. async () =>
  104. ((await getListboxSnapshot())?.optionRowEstimate ?? 0) >= SCROLL_ANCHOR_FILE_COUNT,
  105. { timeout: 30000, timeoutMsg: "长列表文件候选没有全部出现" },
  106. );
  107. const initial = await getListboxSnapshot();
  108. expect(initial!.scrollHeight).toBeGreaterThan(initial!.clientHeight * 3);
  109. await browser
  110. .action("wheel")
  111. .scroll({ origin: await $(LISTBOX_SELECTOR), deltaY: 520, duration: 0 })
  112. .perform();
  113. await browser.waitUntil(async () => ((await getListboxSnapshot())?.scrollTop ?? 0) > 200, {
  114. timeout: 5000,
  115. timeoutMsg: "真实 wheel 没有把候选列表滚到中段",
  116. });
  117. const beforeRefresh = await getListboxSnapshot();
  118. // 刷新结果要和刷新前有可见差异,才能证明新结果真的替换上去了:用 .zcodeignore 去掉最后一个文件
  119. // (远离视口,不影响当前滚动位置)。.zcodeignore 的修改时间与大小属于 Host 文件列表缓存签名,
  120. // 这次重新查询不会命中旧缓存。
  121. await writeFile(
  122. ZCODEIGNORE_PATH,
  123. `${SCROLL_ANCHOR_PREFIX}/${SCROLL_ANCHOR_PREFIX}-${String(SCROLL_ANCHOR_FILE_COUNT - 1).padStart(2, "0")}.ts\n`,
  124. );
  125. // 等候选刷新的 Host 响应真正回到渲染层,再判定位置,避免刷新未发生时用例空过。
  126. const responsesBefore = await readFileSearchResponseCount();
  127. await callHandoffHost(ServiceChannels.Broadcast, "send", [
  128. { channel: "state:projects", payload: {} },
  129. ]);
  130. await browser.waitUntil(async () => (await readFileSearchResponseCount()) > responsesBefore, {
  131. timeout: 15000,
  132. timeoutMsg: "state:projects 广播后文件候选没有重新查询",
  133. });
  134. await browser.waitUntil(
  135. async () =>
  136. (await getListboxSnapshot())?.optionRowEstimate === beforeRefresh!.optionRowEstimate - 1,
  137. { timeout: 10000, timeoutMsg: "刷新结果没有替换到候选列表(被忽略的文件仍在)" },
  138. );
  139. await waitForAnimationFrames(3);
  140. const afterRefresh = await getListboxSnapshot();
  141. expect(afterRefresh!.loadingCount).toBe(0);
  142. expect(Math.abs(afterRefresh!.scrollTop - beforeRefresh!.scrollTop)).toBeLessThanOrEqual(2);
  143. for (let step = 0; step < 15; step += 1) {
  144. await browser.keys("ArrowDown");
  145. await browser.waitUntil(
  146. async () => (await getListboxSnapshot())?.selectedIndex === step + 1,
  147. { timeout: 5000, timeoutMsg: `ArrowDown 第 ${step + 1} 次没有移动选中项` },
  148. );
  149. await waitForAnimationFrames(2);
  150. const snapshot = await getListboxSnapshot();
  151. expect(snapshot!.selectedVisible).toBe(true);
  152. }
  153. // 重新输入关键字:选中项回到首项,列表回到开头。
  154. await browser
  155. .action("wheel")
  156. .scroll({ origin: await $(LISTBOX_SELECTOR), deltaY: 520, duration: 0 })
  157. .perform();
  158. await browser.keys(["-", "1"]);
  159. await browser.waitUntil(
  160. async () => {
  161. const snapshot = await getListboxSnapshot();
  162. return (
  163. snapshot?.scrollTop === 0 && snapshot.selectedIndex === 0 && snapshot.selectedVisible
  164. );
  165. },
  166. { timeout: 10000, timeoutMsg: "重新输入关键字后候选列表没有回到开头" },
  167. );
  168. // 多分组面板:各分组加载完成后,首个分组标题和首项都在视口内。
  169. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "@", {
  170. stabilizeLexicalCaretAtEnd: true,
  171. timeout: 15000,
  172. });
  173. await browser.waitUntil(
  174. async () => {
  175. const snapshot = await getListboxSnapshot();
  176. return (
  177. snapshot !== null &&
  178. snapshot.loadingCount === 0 &&
  179. snapshot.firstSectionVisible &&
  180. snapshot.selectedIndex === 0 &&
  181. snapshot.selectedVisible &&
  182. snapshot.scrollTop === 0
  183. );
  184. },
  185. { timeout: 30000, timeoutMsg: "分组加载完成后首个分组标题或首项不在视口内" },
  186. );
  187. } finally {
  188. await browser.keys("Escape");
  189. await rm(SCROLL_ANCHOR_DIR, { recursive: true, force: true });
  190. await rm(ZCODEIGNORE_PATH, { force: true });
  191. }
  192. });
  193. });
  194. type ListboxSnapshot = {
  195. clientHeight: number;
  196. firstSectionVisible: boolean;
  197. loadingCount: number;
  198. optionRowEstimate: number;
  199. scrollHeight: number;
  200. scrollTop: number;
  201. selectedIndex: number | null;
  202. selectedVisible: boolean;
  203. };
  204. async function getListboxSnapshot(): Promise<ListboxSnapshot | null> {
  205. return browser.execute(
  206. (listboxSelector, optionRowHeight, sectionTestId) => {
  207. const listbox = document.querySelector<HTMLElement>(listboxSelector);
  208. if (!listbox) return null;
  209. const selected = listbox.querySelector<HTMLElement>('[data-selected="true"]');
  210. const listboxRect = listbox.getBoundingClientRect();
  211. const selectedRect = selected?.getBoundingClientRect();
  212. const firstSectionRect = listbox
  213. .querySelector<HTMLElement>(`[data-testid^="${sectionTestId}"]`)
  214. ?.getBoundingClientRect();
  215. return {
  216. // 虚拟列表只渲染视口附近的行;单分组无标题时,总高度 / 行高 = 候选条数。
  217. optionRowEstimate: Math.floor(listbox.scrollHeight / optionRowHeight),
  218. clientHeight: listbox.clientHeight,
  219. firstSectionVisible: Boolean(
  220. firstSectionRect && firstSectionRect.top >= listbox.getBoundingClientRect().top - 4,
  221. ),
  222. loadingCount: listbox.querySelectorAll('[data-status="loading"]').length,
  223. scrollHeight: listbox.scrollHeight,
  224. scrollTop: listbox.scrollTop,
  225. selectedIndex: selected ? Number(selected.dataset.optionIndex) : null,
  226. // 虚拟列表按行定位,不计列表 3px 上下内边距,选中行可压进内边距;容差取内边距大小。
  227. selectedVisible: Boolean(
  228. selectedRect &&
  229. selectedRect.top >= listboxRect.top - 4 &&
  230. selectedRect.bottom <= listboxRect.bottom + 4,
  231. ),
  232. };
  233. },
  234. LISTBOX_SELECTOR,
  235. OPTION_ROW_HEIGHT,
  236. TID_PROMPT_SUGGESTION_SECTION,
  237. );
  238. }
  239. /** 统计渲染层收到的、包含长列表文件名的 Host 响应,用来确认候选刷新确实发生。 */
  240. async function installFileSearchResponseProbe() {
  241. await browser.execute((marker) => {
  242. const probeWindow = window as Window & { __zcodeMentionScrollProbe?: { responses: number } };
  243. const probe = { responses: 0 };
  244. const ports = new WeakSet<MessagePort>();
  245. const original = MessagePort.prototype.postMessage;
  246. MessagePort.prototype.postMessage = function (message: unknown, options?: unknown) {
  247. if (message instanceof Uint8Array && !ports.has(this)) {
  248. ports.add(this);
  249. this.addEventListener("message", (event: MessageEvent) => {
  250. if (
  251. event.data instanceof Uint8Array &&
  252. new TextDecoder().decode(event.data).includes(marker)
  253. )
  254. probe.responses += 1;
  255. });
  256. }
  257. Reflect.apply(original, this, options === undefined ? [message] : [message, options]);
  258. };
  259. probeWindow.__zcodeMentionScrollProbe = probe;
  260. }, `${SCROLL_ANCHOR_PREFIX}-00`);
  261. }
  262. async function readFileSearchResponseCount(): Promise<number> {
  263. return browser.execute(
  264. () =>
  265. (window as Window & { __zcodeMentionScrollProbe?: { responses: number } })
  266. .__zcodeMentionScrollProbe?.responses ?? 0,
  267. );
  268. }
  269. async function waitForAnimationFrames(count: number) {
  270. await browser.execute(
  271. (frames) =>
  272. new Promise<void>((resolve) => {
  273. const step = (left: number) =>
  274. left <= 0 ? resolve() : requestAnimationFrame(() => step(left - 1));
  275. step(frames);
  276. }),
  277. count,
  278. );
  279. }
  280. async function waitForPluginOption() {
  281. await browser.waitUntil(
  282. async () =>
  283. browser.execute(
  284. (panelTestId, optionTestId) =>
  285. Boolean(
  286. document.querySelector(`[data-testid="${panelTestId}"]`) &&
  287. document.querySelector(`[data-testid="${optionTestId}"]`),
  288. ),
  289. TID_PROMPT_SUGGESTION_PANEL,
  290. testId(TID_PROMPT_SUGGESTION_OPTION, PLUGIN_OPTION_ID),
  291. ),
  292. {
  293. timeout: 30000,
  294. timeoutMsg: "Plugin mention candidate did not become visible",
  295. },
  296. );
  297. }
  298. async function startPluginOptionStabilityProbe() {
  299. const started = await browser.execute(
  300. (panelTestId, optionTestId) => {
  301. type StabilityProbe = {
  302. observer: MutationObserver;
  303. option: Element;
  304. optionDisconnected: boolean;
  305. panel: Element;
  306. panelDisconnected: boolean;
  307. };
  308. const probeWindow = window as Window & {
  309. __zcodeMentionStabilityProbe?: StabilityProbe;
  310. };
  311. const panel = document.querySelector(`[data-testid="${panelTestId}"]`);
  312. const option = document.querySelector(`[data-testid="${optionTestId}"]`);
  313. if (!panel || !option) {
  314. return false;
  315. }
  316. const probe: StabilityProbe = {
  317. observer: new MutationObserver(() => {
  318. probe.optionDisconnected ||= !document.contains(probe.option);
  319. probe.panelDisconnected ||= !document.contains(probe.panel);
  320. }),
  321. option,
  322. optionDisconnected: false,
  323. panel,
  324. panelDisconnected: false,
  325. };
  326. probe.observer.observe(document.body, { childList: true, subtree: true });
  327. probeWindow.__zcodeMentionStabilityProbe = probe;
  328. return true;
  329. },
  330. TID_PROMPT_SUGGESTION_PANEL,
  331. testId(TID_PROMPT_SUGGESTION_OPTION, PLUGIN_OPTION_ID),
  332. );
  333. expect(started).toBe(true);
  334. }
  335. async function finishPluginOptionStabilityProbe() {
  336. return browser.execute(() => {
  337. const probeWindow = window as Window & {
  338. __zcodeMentionStabilityProbe?: {
  339. observer: MutationObserver;
  340. optionDisconnected: boolean;
  341. panelDisconnected: boolean;
  342. };
  343. };
  344. const probe = probeWindow.__zcodeMentionStabilityProbe;
  345. probe?.observer.disconnect();
  346. delete probeWindow.__zcodeMentionStabilityProbe;
  347. return {
  348. optionDisconnected: probe?.optionDisconnected ?? true,
  349. panelDisconnected: probe?.panelDisconnected ?? true,
  350. };
  351. });
  352. }
  353. function getComposerText() {
  354. return browser.execute((inputTestId) => {
  355. const input = document.querySelector<LexicalInputE2EElement>(`[data-testid="${inputTestId}"]`);
  356. return input?.__zcodeLexicalInputE2E?.getText() ?? "";
  357. }, TID_V4_COMPOSER_INPUT);
  358. }
  359. async function setChatInputFileMentionState() {
  360. await browser.waitUntil(
  361. async () =>
  362. browser.execute((inputTestId) => {
  363. const input = document.querySelector<LexicalInputE2EElement>(
  364. `[data-testid="${inputTestId}"]`,
  365. );
  366. return Boolean(input?.__zcodeLexicalInputE2E);
  367. }, TID_V4_COMPOSER_INPUT),
  368. {
  369. timeout: 15000,
  370. timeoutMsg: "chat input lexical e2e bridge was not attached",
  371. },
  372. );
  373. const result = (await browser.execute((inputTestId) => {
  374. try {
  375. const fileMentionPath = "src/option-right-repro.ts";
  376. const fileMentionMarkdown = "[option-right-repro.ts](src/option-right-repro.ts)";
  377. const stateJson = JSON.stringify({
  378. root: {
  379. children: [
  380. {
  381. children: [
  382. {
  383. category: "files",
  384. data: {
  385. kind: "file",
  386. path: fileMentionPath,
  387. relativePath: fileMentionPath,
  388. scope: "workspace",
  389. },
  390. description: "",
  391. detail: 0,
  392. format: 0,
  393. mentionId: "e2e-option-right-file",
  394. mode: "token",
  395. markdown: fileMentionMarkdown,
  396. style: "",
  397. text: "option-right-repro.ts",
  398. type: "prompt-mention",
  399. value: fileMentionPath,
  400. version: 1,
  401. },
  402. {
  403. detail: 0,
  404. format: 0,
  405. mode: "normal",
  406. style: "",
  407. text: " ",
  408. type: "text",
  409. version: 1,
  410. },
  411. ],
  412. direction: null,
  413. format: "",
  414. indent: 0,
  415. type: "paragraph",
  416. version: 1,
  417. },
  418. ],
  419. direction: null,
  420. format: "",
  421. indent: 0,
  422. type: "root",
  423. version: 1,
  424. },
  425. });
  426. const input = document.querySelector<LexicalInputE2EElement>(
  427. `[data-testid="${inputTestId}"]`,
  428. );
  429. const bridge = input?.__zcodeLexicalInputE2E;
  430. if (!input || !bridge) {
  431. return { ok: false, reason: "bridge-missing" };
  432. }
  433. bridge.setEditorStateJson(stateJson);
  434. bridge.focus();
  435. return {
  436. mentionCount: input.querySelectorAll("[data-mention-id]").length,
  437. ok: bridge.getText().includes(fileMentionMarkdown),
  438. text: bridge.getText(),
  439. };
  440. } catch (error) {
  441. return {
  442. ok: false,
  443. reason: error instanceof Error ? error.message : String(error),
  444. };
  445. }
  446. }, TID_V4_COMPOSER_INPUT)) as {
  447. mentionCount?: number;
  448. ok: boolean;
  449. reason?: string;
  450. text?: string;
  451. };
  452. if (!result.ok || result.mentionCount !== 1) {
  453. throw new Error(`failed to seed file mention: ${JSON.stringify(result)}`);
  454. }
  455. }
  456. async function placeSelectionBeforeFileMention() {
  457. const result = (await browser.execute((inputTestId) => {
  458. const input = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  459. const mention = input?.querySelector<HTMLElement>(`[data-mention-id="e2e-option-right-file"]`);
  460. if (!input || !mention) {
  461. return { ok: false, reason: "mention-missing" };
  462. }
  463. input.focus();
  464. const range = document.createRange();
  465. range.setStartBefore(mention);
  466. range.collapse(true);
  467. const selection = window.getSelection();
  468. selection?.removeAllRanges();
  469. selection?.addRange(range);
  470. return { ok: true };
  471. }, TID_V4_COMPOSER_INPUT)) as { ok: boolean; reason?: string };
  472. if (!result.ok) {
  473. throw new Error(`failed to place selection before mention: ${JSON.stringify(result)}`);
  474. }
  475. }
  476. async function pressOptionArrowRight() {
  477. await browser.performActions([
  478. {
  479. id: "keyboard",
  480. type: "key",
  481. actions: [
  482. { type: "keyDown", value: "\uE00A" },
  483. { type: "keyDown", value: "\uE014" },
  484. { type: "keyUp", value: "\uE014" },
  485. { type: "keyUp", value: "\uE00A" },
  486. ],
  487. },
  488. ]);
  489. await browser.releaseActions();
  490. }
  491. function getMentionNavigationSnapshot() {
  492. return browser.execute((inputTestId) => {
  493. // 修复原因:v4 硬切后 Lexical bridge 挂在 composer v4 testid 上,
  494. // 继续查 legacy chat-input 会把“节点不存在”误报成键盘导航回归。
  495. const input = document.querySelector<LexicalInputE2EElement>(`[data-testid="${inputTestId}"]`);
  496. const selection = window.getSelection();
  497. return {
  498. bridgeText: input?.__zcodeLexicalInputE2E?.getText() ?? "",
  499. domText: input?.innerText ?? input?.textContent ?? "",
  500. mentionCount: input?.querySelectorAll("[data-mention-id]").length ?? 0,
  501. selection: {
  502. anchorNodeName: selection?.anchorNode?.nodeName ?? null,
  503. anchorOffset: selection?.anchorOffset ?? null,
  504. },
  505. };
  506. }, TID_V4_COMPOSER_INPUT);
  507. }