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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. import {
  2. TID_PROMPT_SUGGESTION_OPTION,
  3. TID_PROMPT_SUGGESTION_PANEL,
  4. TID_V4_COMPOSER_INPUT,
  5. testId,
  6. } from "@zcode/shared";
  7. import {
  8. clearAppData,
  9. setInputValueByTestIdDom,
  10. waitForDefaultWorkspaceReady,
  11. } from "./helpers/desktop-app.js";
  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>(
  149. `[data-testid="${inputTestId}"]`,
  150. );
  151. return input?.__zcodeLexicalInputE2E?.getText() ?? "";
  152. }, TID_V4_COMPOSER_INPUT);
  153. }
  154. async function setChatInputFileMentionState() {
  155. await browser.waitUntil(
  156. async () =>
  157. browser.execute((inputTestId) => {
  158. const input = document.querySelector<LexicalInputE2EElement>(
  159. `[data-testid="${inputTestId}"]`,
  160. );
  161. return Boolean(input?.__zcodeLexicalInputE2E);
  162. }, TID_V4_COMPOSER_INPUT),
  163. {
  164. timeout: 15000,
  165. timeoutMsg: "chat input lexical e2e bridge was not attached",
  166. },
  167. );
  168. const result = (await browser.execute(
  169. (inputTestId) => {
  170. try {
  171. const fileMentionPath = "src/option-right-repro.ts";
  172. const fileMentionMarkdown =
  173. "[option-right-repro.ts](src/option-right-repro.ts)";
  174. const stateJson = JSON.stringify({
  175. root: {
  176. children: [
  177. {
  178. children: [
  179. {
  180. category: "files",
  181. data: {
  182. kind: "file",
  183. path: fileMentionPath,
  184. relativePath: fileMentionPath,
  185. scope: "workspace",
  186. },
  187. description: "",
  188. detail: 0,
  189. format: 0,
  190. mentionId: "e2e-option-right-file",
  191. mode: "token",
  192. markdown: fileMentionMarkdown,
  193. style: "",
  194. text: "option-right-repro.ts",
  195. type: "prompt-mention",
  196. value: fileMentionPath,
  197. version: 1,
  198. },
  199. {
  200. detail: 0,
  201. format: 0,
  202. mode: "normal",
  203. style: "",
  204. text: " ",
  205. type: "text",
  206. version: 1,
  207. },
  208. ],
  209. direction: null,
  210. format: "",
  211. indent: 0,
  212. type: "paragraph",
  213. version: 1,
  214. },
  215. ],
  216. direction: null,
  217. format: "",
  218. indent: 0,
  219. type: "root",
  220. version: 1,
  221. },
  222. });
  223. const input = document.querySelector<LexicalInputE2EElement>(
  224. `[data-testid="${inputTestId}"]`,
  225. );
  226. const bridge = input?.__zcodeLexicalInputE2E;
  227. if (!input || !bridge) {
  228. return { ok: false, reason: "bridge-missing" };
  229. }
  230. bridge.setEditorStateJson(stateJson);
  231. bridge.focus();
  232. return {
  233. mentionCount: input.querySelectorAll("[data-mention-id]").length,
  234. ok: bridge.getText().includes(fileMentionMarkdown),
  235. text: bridge.getText(),
  236. };
  237. } catch (error) {
  238. return {
  239. ok: false,
  240. reason: error instanceof Error ? error.message : String(error),
  241. };
  242. }
  243. },
  244. TID_V4_COMPOSER_INPUT,
  245. )) as { mentionCount?: number; ok: boolean; reason?: string; text?: string };
  246. if (!result.ok || result.mentionCount !== 1) {
  247. throw new Error(`failed to seed file mention: ${JSON.stringify(result)}`);
  248. }
  249. }
  250. async function placeSelectionBeforeFileMention() {
  251. const result = (await browser.execute(
  252. (inputTestId) => {
  253. const input = document.querySelector<HTMLElement>(
  254. `[data-testid="${inputTestId}"]`,
  255. );
  256. const mention = input?.querySelector<HTMLElement>(
  257. `[data-mention-id="e2e-option-right-file"]`,
  258. );
  259. if (!input || !mention) {
  260. return { ok: false, reason: "mention-missing" };
  261. }
  262. input.focus();
  263. const range = document.createRange();
  264. range.setStartBefore(mention);
  265. range.collapse(true);
  266. const selection = window.getSelection();
  267. selection?.removeAllRanges();
  268. selection?.addRange(range);
  269. return { ok: true };
  270. },
  271. TID_V4_COMPOSER_INPUT,
  272. )) as { ok: boolean; reason?: string };
  273. if (!result.ok) {
  274. throw new Error(
  275. `failed to place selection before mention: ${JSON.stringify(result)}`,
  276. );
  277. }
  278. }
  279. async function pressOptionArrowRight() {
  280. await browser.performActions([
  281. {
  282. id: "keyboard",
  283. type: "key",
  284. actions: [
  285. { type: "keyDown", value: "\uE00A" },
  286. { type: "keyDown", value: "\uE014" },
  287. { type: "keyUp", value: "\uE014" },
  288. { type: "keyUp", value: "\uE00A" },
  289. ],
  290. },
  291. ]);
  292. await browser.releaseActions();
  293. }
  294. function getMentionNavigationSnapshot() {
  295. return browser.execute((inputTestId) => {
  296. // 修复原因:v4 硬切后 Lexical bridge 挂在 composer v4 testid 上,
  297. // 继续查 legacy chat-input 会把“节点不存在”误报成键盘导航回归。
  298. const input = document.querySelector<LexicalInputE2EElement>(
  299. `[data-testid="${inputTestId}"]`,
  300. );
  301. const selection = window.getSelection();
  302. return {
  303. bridgeText: input?.__zcodeLexicalInputE2E?.getText() ?? "",
  304. domText: input?.innerText ?? input?.textContent ?? "",
  305. mentionCount: input?.querySelectorAll("[data-mention-id]").length ?? 0,
  306. selection: {
  307. anchorNodeName: selection?.anchorNode?.nodeName ?? null,
  308. anchorOffset: selection?.anchorOffset ?? null,
  309. },
  310. };
  311. }, TID_V4_COMPOSER_INPUT);
  312. }