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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. import {
  2. TID_PROMPT_SUGGESTION_OPTION,
  3. TID_PROMPT_SUGGESTION_PANEL,
  4. TID_V4_COMPOSER_INPUT,
  5. testId,
  6. } from "@zcode/shared/test-ids";
  7. import {
  8. clearAppData,
  9. setInputValueByTestIdDom,
  10. waitForDefaultWorkspaceReady,
  11. } from "#e2e/helpers/desktop-app";
  12. type LexicalInputE2EBridge = {
  13. focus: () => void;
  14. getText: () => string;
  15. setEditorStateJson: (editorStateJson: string) => void;
  16. };
  17. type LexicalInputE2EElement = HTMLElement & {
  18. __zcodeLexicalInputE2E?: LexicalInputE2EBridge;
  19. };
  20. const FILE_MENTION_LABEL = "option-right-repro.ts";
  21. const FILE_MENTION_PATH = "src/option-right-repro.ts";
  22. const FILE_MENTION_MARKDOWN = `[${FILE_MENTION_LABEL}](${FILE_MENTION_PATH})`;
  23. const TYPED_AFTER_MENTION = "继续输入";
  24. const PLUGIN_NAME = "skill-creator";
  25. const PLUGIN_STABLE_ID = "skill-creator@zcode-plugins-official";
  26. const PLUGIN_OPTION_ID = `plugin:${PLUGIN_STABLE_ID}`;
  27. describe("chat input mention navigation", () => {
  28. after(async () => {
  29. await browser.electron.restoreAllMocks();
  30. await clearAppData();
  31. });
  32. it("keeps a file mention when typing after Option+ArrowRight moves across it", async () => {
  33. await waitForDefaultWorkspaceReady(30000);
  34. await setChatInputFileMentionState();
  35. await placeSelectionBeforeFileMention();
  36. await pressOptionArrowRight();
  37. const afterMove = await getMentionNavigationSnapshot();
  38. expect(afterMove.mentionCount).toBe(1);
  39. await browser.keys(TYPED_AFTER_MENTION);
  40. const afterTyping = await getMentionNavigationSnapshot();
  41. expect(afterTyping.mentionCount).toBe(1);
  42. expect(afterTyping.bridgeText).toContain(FILE_MENTION_MARKDOWN);
  43. expect(afterTyping.bridgeText).toContain(TYPED_AFTER_MENTION);
  44. });
  45. it("keeps the Plugin candidates stable while ArrowLeft/ArrowRight moves inside the active token", async () => {
  46. await waitForDefaultWorkspaceReady(30000);
  47. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, `@${PLUGIN_NAME}`, {
  48. stabilizeLexicalCaretAtEnd: true,
  49. timeout: 15000,
  50. });
  51. await waitForPluginOption();
  52. await startPluginOptionStabilityProbe();
  53. await browser.keys("ArrowLeft");
  54. await waitForPluginOption();
  55. await browser.keys("ArrowRight");
  56. await waitForPluginOption();
  57. await browser.keys("ArrowLeft");
  58. await waitForPluginOption();
  59. expect(await finishPluginOptionStabilityProbe()).toEqual({
  60. optionDisconnected: false,
  61. panelDisconnected: false,
  62. });
  63. await browser.keys("Enter");
  64. await browser.waitUntil(
  65. async () => (await getComposerText()) === `[@${PLUGIN_NAME}](plugin://${PLUGIN_STABLE_ID}) `,
  66. {
  67. timeout: 10000,
  68. timeoutMsg: "ArrowLeft 后选择 Plugin 没有替换完整 token,或残留了重复后缀",
  69. },
  70. );
  71. });
  72. });
  73. async function waitForPluginOption() {
  74. await browser.waitUntil(
  75. async () =>
  76. browser.execute(
  77. (panelTestId, optionTestId) =>
  78. Boolean(
  79. document.querySelector(`[data-testid="${panelTestId}"]`) &&
  80. document.querySelector(`[data-testid="${optionTestId}"]`),
  81. ),
  82. TID_PROMPT_SUGGESTION_PANEL,
  83. testId(TID_PROMPT_SUGGESTION_OPTION, PLUGIN_OPTION_ID),
  84. ),
  85. {
  86. timeout: 30000,
  87. timeoutMsg: "Plugin mention candidate did not become visible",
  88. },
  89. );
  90. }
  91. async function startPluginOptionStabilityProbe() {
  92. const started = await browser.execute(
  93. (panelTestId, optionTestId) => {
  94. type StabilityProbe = {
  95. observer: MutationObserver;
  96. option: Element;
  97. optionDisconnected: boolean;
  98. panel: Element;
  99. panelDisconnected: boolean;
  100. };
  101. const probeWindow = window as Window & {
  102. __zcodeMentionStabilityProbe?: StabilityProbe;
  103. };
  104. const panel = document.querySelector(`[data-testid="${panelTestId}"]`);
  105. const option = document.querySelector(`[data-testid="${optionTestId}"]`);
  106. if (!panel || !option) {
  107. return false;
  108. }
  109. const probe: StabilityProbe = {
  110. observer: new MutationObserver(() => {
  111. probe.optionDisconnected ||= !document.contains(probe.option);
  112. probe.panelDisconnected ||= !document.contains(probe.panel);
  113. }),
  114. option,
  115. optionDisconnected: false,
  116. panel,
  117. panelDisconnected: false,
  118. };
  119. probe.observer.observe(document.body, { childList: true, subtree: true });
  120. probeWindow.__zcodeMentionStabilityProbe = probe;
  121. return true;
  122. },
  123. TID_PROMPT_SUGGESTION_PANEL,
  124. testId(TID_PROMPT_SUGGESTION_OPTION, PLUGIN_OPTION_ID),
  125. );
  126. expect(started).toBe(true);
  127. }
  128. async function finishPluginOptionStabilityProbe() {
  129. return browser.execute(() => {
  130. const probeWindow = window as Window & {
  131. __zcodeMentionStabilityProbe?: {
  132. observer: MutationObserver;
  133. optionDisconnected: boolean;
  134. panelDisconnected: boolean;
  135. };
  136. };
  137. const probe = probeWindow.__zcodeMentionStabilityProbe;
  138. probe?.observer.disconnect();
  139. delete probeWindow.__zcodeMentionStabilityProbe;
  140. return {
  141. optionDisconnected: probe?.optionDisconnected ?? true,
  142. panelDisconnected: probe?.panelDisconnected ?? true,
  143. };
  144. });
  145. }
  146. function getComposerText() {
  147. return browser.execute((inputTestId) => {
  148. const input = document.querySelector<LexicalInputE2EElement>(`[data-testid="${inputTestId}"]`);
  149. return input?.__zcodeLexicalInputE2E?.getText() ?? "";
  150. }, TID_V4_COMPOSER_INPUT);
  151. }
  152. async function setChatInputFileMentionState() {
  153. await browser.waitUntil(
  154. async () =>
  155. browser.execute((inputTestId) => {
  156. const input = document.querySelector<LexicalInputE2EElement>(
  157. `[data-testid="${inputTestId}"]`,
  158. );
  159. return Boolean(input?.__zcodeLexicalInputE2E);
  160. }, TID_V4_COMPOSER_INPUT),
  161. {
  162. timeout: 15000,
  163. timeoutMsg: "chat input lexical e2e bridge was not attached",
  164. },
  165. );
  166. const result = (await browser.execute((inputTestId) => {
  167. try {
  168. const fileMentionPath = "src/option-right-repro.ts";
  169. const fileMentionMarkdown = "[option-right-repro.ts](src/option-right-repro.ts)";
  170. const stateJson = JSON.stringify({
  171. root: {
  172. children: [
  173. {
  174. children: [
  175. {
  176. category: "files",
  177. data: {
  178. kind: "file",
  179. path: fileMentionPath,
  180. relativePath: fileMentionPath,
  181. scope: "workspace",
  182. },
  183. description: "",
  184. detail: 0,
  185. format: 0,
  186. mentionId: "e2e-option-right-file",
  187. mode: "token",
  188. markdown: fileMentionMarkdown,
  189. style: "",
  190. text: "option-right-repro.ts",
  191. type: "prompt-mention",
  192. value: fileMentionPath,
  193. version: 1,
  194. },
  195. {
  196. detail: 0,
  197. format: 0,
  198. mode: "normal",
  199. style: "",
  200. text: " ",
  201. type: "text",
  202. version: 1,
  203. },
  204. ],
  205. direction: null,
  206. format: "",
  207. indent: 0,
  208. type: "paragraph",
  209. version: 1,
  210. },
  211. ],
  212. direction: null,
  213. format: "",
  214. indent: 0,
  215. type: "root",
  216. version: 1,
  217. },
  218. });
  219. const input = document.querySelector<LexicalInputE2EElement>(
  220. `[data-testid="${inputTestId}"]`,
  221. );
  222. const bridge = input?.__zcodeLexicalInputE2E;
  223. if (!input || !bridge) {
  224. return { ok: false, reason: "bridge-missing" };
  225. }
  226. bridge.setEditorStateJson(stateJson);
  227. bridge.focus();
  228. return {
  229. mentionCount: input.querySelectorAll("[data-mention-id]").length,
  230. ok: bridge.getText().includes(fileMentionMarkdown),
  231. text: bridge.getText(),
  232. };
  233. } catch (error) {
  234. return {
  235. ok: false,
  236. reason: error instanceof Error ? error.message : String(error),
  237. };
  238. }
  239. }, TID_V4_COMPOSER_INPUT)) as {
  240. mentionCount?: number;
  241. ok: boolean;
  242. reason?: string;
  243. text?: string;
  244. };
  245. if (!result.ok || result.mentionCount !== 1) {
  246. throw new Error(`failed to seed file mention: ${JSON.stringify(result)}`);
  247. }
  248. }
  249. async function placeSelectionBeforeFileMention() {
  250. const result = (await browser.execute((inputTestId) => {
  251. const input = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  252. const mention = input?.querySelector<HTMLElement>(`[data-mention-id="e2e-option-right-file"]`);
  253. if (!input || !mention) {
  254. return { ok: false, reason: "mention-missing" };
  255. }
  256. input.focus();
  257. const range = document.createRange();
  258. range.setStartBefore(mention);
  259. range.collapse(true);
  260. const selection = window.getSelection();
  261. selection?.removeAllRanges();
  262. selection?.addRange(range);
  263. return { ok: true };
  264. }, TID_V4_COMPOSER_INPUT)) as { ok: boolean; reason?: string };
  265. if (!result.ok) {
  266. throw new Error(`failed to place selection before mention: ${JSON.stringify(result)}`);
  267. }
  268. }
  269. async function pressOptionArrowRight() {
  270. await browser.performActions([
  271. {
  272. id: "keyboard",
  273. type: "key",
  274. actions: [
  275. { type: "keyDown", value: "\uE00A" },
  276. { type: "keyDown", value: "\uE014" },
  277. { type: "keyUp", value: "\uE014" },
  278. { type: "keyUp", value: "\uE00A" },
  279. ],
  280. },
  281. ]);
  282. await browser.releaseActions();
  283. }
  284. function getMentionNavigationSnapshot() {
  285. return browser.execute((inputTestId) => {
  286. // 修复原因:v4 硬切后 Lexical bridge 挂在 composer v4 testid 上,
  287. // 继续查 legacy chat-input 会把“节点不存在”误报成键盘导航回归。
  288. const input = document.querySelector<LexicalInputE2EElement>(`[data-testid="${inputTestId}"]`);
  289. const selection = window.getSelection();
  290. return {
  291. bridgeText: input?.__zcodeLexicalInputE2E?.getText() ?? "",
  292. domText: input?.innerText ?? input?.textContent ?? "",
  293. mentionCount: input?.querySelectorAll("[data-mention-id]").length ?? 0,
  294. selection: {
  295. anchorNodeName: selection?.anchorNode?.nodeName ?? null,
  296. anchorOffset: selection?.anchorOffset ?? null,
  297. },
  298. };
  299. }, TID_V4_COMPOSER_INPUT);
  300. }