conversation-session-markdown-preview-selection.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. import { getUpstreamRequestEvidence } from "../helpers/conversation-session-network.js";
  2. import { mkdir, rm, writeFile } from "node:fs/promises";
  3. import { dirname, join } from "node:path";
  4. import {
  5. TID_WORKSPACE_FILE_TREE_BUTTON,
  6. TID_WORKSPACE_ITEM,
  7. TID_WORKSPACE_FILE_TREE_ROW,
  8. TID_V4_COMPOSER_INPUT,
  9. TID_V4_SESSION_PANE,
  10. testId,
  11. } from "@zcode/shared";
  12. import { clearAppData, clickTestIdByDom, DEFAULT_WORKSPACE } from "../helpers/desktop-app.js";
  13. import { resolveE2ERuntimePath } from "../helpers/e2e-runtime-paths.js";
  14. import {
  15. prepareV4ConversationE2E,
  16. sendV4Prompt,
  17. waitForV4TimelineContaining,
  18. } from "../helpers/v4-conversation.js";
  19. const filePath = resolveE2ERuntimePath("markdown-preview-selection", "selection.md");
  20. const marker = "E2E_MARKDOWN_PREVIEW_SELECTED_PARAGRAPH";
  21. describe("Markdown preview selection", () => {
  22. after(async () => {
  23. await rm(dirname(filePath), { recursive: true, force: true });
  24. await clearAppData();
  25. });
  26. it("MPS01/02/06/08/09: 预览选区加入草稿,去重、移除且不自动发送", async function () {
  27. this.timeout(120000);
  28. await prepareV4ConversationE2E();
  29. await mkdir(dirname(filePath), { recursive: true });
  30. await writeFile(filePath, `# Preview\n\n${marker}\n`, "utf8");
  31. // 工作区行的操作按真实 hover 挂载;外层容器不保证可 focus,不能用 DOM focus 代替手势。
  32. const workspaceRow = await $(
  33. `[data-testid="${testId(TID_WORKSPACE_ITEM, DEFAULT_WORKSPACE)}"]`,
  34. );
  35. await workspaceRow.waitForDisplayed({ timeout: 15000 });
  36. await workspaceRow.moveTo();
  37. await browser
  38. .waitUntil(
  39. async () =>
  40. browser.execute(
  41. (actionId) => {
  42. return Boolean(document.querySelector(`[data-testid="${actionId}"]`));
  43. },
  44. testId(TID_WORKSPACE_FILE_TREE_BUTTON, DEFAULT_WORKSPACE),
  45. ),
  46. { timeout: 5000, timeoutMsg: "Workspace file tree action did not mount after hover" },
  47. )
  48. .catch(async (error) => {
  49. if (process.env.ZCODE_E2E_ARTIFACT_DIR) {
  50. await browser.saveScreenshot(
  51. join(process.env.ZCODE_E2E_ARTIFACT_DIR, "markdown-file-tree-unavailable.png"),
  52. );
  53. }
  54. console.log(
  55. "[MPS workspace entry]",
  56. await browser.execute(() =>
  57. Array.from(document.querySelectorAll<HTMLElement>("[data-testid]"))
  58. .filter((element) =>
  59. /workspace|file-tree|sidebar|project/.test(element.dataset.testid ?? ""),
  60. )
  61. .map((element) => ({
  62. id: element.dataset.testid,
  63. text: element.innerText.slice(0, 100),
  64. })),
  65. ),
  66. );
  67. throw error;
  68. });
  69. await clickTestIdByDom(testId(TID_WORKSPACE_FILE_TREE_BUTTON, DEFAULT_WORKSPACE));
  70. // 文件树会将单子目录链压缩为一行,入口使用压缩后的最深目录。
  71. for (const path of [dirname(filePath), filePath]) {
  72. const row = await $(`[data-testid="${testId(TID_WORKSPACE_FILE_TREE_ROW, path)}"]`);
  73. await row.waitForDisplayed({ timeout: 15000 });
  74. await row.click();
  75. }
  76. const preview = await $("[data-markdown-preview]");
  77. await preview.waitForDisplayed({ timeout: 15000 });
  78. const paneId = testId(TID_V4_SESSION_PANE, "workspace-main");
  79. await browser.execute(
  80. (paneTestId, inputTestId) => {
  81. const input = document.querySelector(
  82. `[data-testid="${paneTestId}"] [data-testid="${inputTestId}"]`,
  83. ) as HTMLElement & { __zcodeLexicalInputE2E?: { setText: (text: string) => void } };
  84. if (!input?.__zcodeLexicalInputE2E) throw new Error("Composer bridge missing");
  85. input.__zcodeLexicalInputE2E.setText("E2E_MARKDOWN_DRAFT_KEEP");
  86. },
  87. paneId,
  88. TID_V4_COMPOSER_INPUT,
  89. );
  90. for (let i = 0; i < 2; i++) {
  91. await browser.execute((text) => {
  92. const root = document.querySelector("[data-markdown-preview]")!;
  93. const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
  94. let node: Node | null;
  95. while ((node = walker.nextNode())) {
  96. if (!node.textContent?.includes(text)) continue;
  97. const range = document.createRange();
  98. range.selectNodeContents(node);
  99. const selection = window.getSelection()!;
  100. selection.removeAllRanges();
  101. selection.addRange(range);
  102. node.parentElement!.dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));
  103. return;
  104. }
  105. throw new Error("Preview text missing");
  106. }, marker);
  107. const action = await $('[data-conversation-selection-action="add-to-task"]');
  108. await action.waitForDisplayed({ timeout: 5000 });
  109. const layout = await browser.execute(() => {
  110. const menu = document.querySelector<HTMLElement>("[data-conversation-selection-tooltip]")!;
  111. const [add, side] = Array.from(menu.querySelectorAll("button")).map((button) =>
  112. button.getBoundingClientRect(),
  113. );
  114. if (!add || !side) throw new Error("Selection actions missing");
  115. const rect = menu.getBoundingClientRect();
  116. return {
  117. horizontal: Math.abs(add.top - side.top) < 1 && side.left >= add.right,
  118. adaptive: menu.style.width === "max-content",
  119. inside: rect.left >= 11 && rect.right <= innerWidth - 11,
  120. };
  121. });
  122. expect(layout).toEqual({ horizontal: true, adaptive: true, inside: true });
  123. if (i === 0 && process.env.ZCODE_E2E_ARTIFACT_DIR) {
  124. await browser.saveScreenshot(
  125. join(process.env.ZCODE_E2E_ARTIFACT_DIR, "markdown-selection-tooltip.png"),
  126. );
  127. }
  128. await action.click();
  129. }
  130. const chip = await $(
  131. `[data-testid="${paneId}"] [data-conversation-selection-reference-count="1"]`,
  132. );
  133. await chip.waitForDisplayed();
  134. expect(await chip.getText()).toContain("selection.md");
  135. if (process.env.ZCODE_E2E_ARTIFACT_DIR) {
  136. await browser.saveScreenshot(
  137. join(process.env.ZCODE_E2E_ARTIFACT_DIR, "markdown-selection-composer.png"),
  138. );
  139. }
  140. const state = await browser.execute(
  141. (paneTestId, inputTestId) => {
  142. const pane = document.querySelector(`[data-testid="${paneTestId}"]`)!;
  143. const input = pane.querySelector(`[data-testid="${inputTestId}"]`) as HTMLElement & {
  144. __zcodeLexicalInputE2E?: { getText: () => string };
  145. };
  146. return {
  147. session: pane.getAttribute("data-session-id"),
  148. text: input.__zcodeLexicalInputE2E?.getText(),
  149. };
  150. },
  151. paneId,
  152. TID_V4_COMPOSER_INPUT,
  153. );
  154. expect(state).toEqual({ session: "draft", text: "E2E_MARKDOWN_DRAFT_KEEP" });
  155. const remove = await $(
  156. `[data-testid="${paneId}"] button[aria-label="移除对话引用"], [data-testid="${paneId}"] button[aria-label="Remove conversation selection"]`,
  157. );
  158. await remove.click();
  159. await chip.waitForExist({ reverse: true });
  160. // 移除后重新通过预览添加,验证实际发送与历史消息保留来源。
  161. await browser.execute(() => {
  162. const paragraph = document.querySelector("[data-markdown-preview] p")!;
  163. const range = document.createRange();
  164. range.selectNodeContents(paragraph);
  165. const selection = window.getSelection()!;
  166. selection.removeAllRanges();
  167. selection.addRange(range);
  168. paragraph.dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));
  169. });
  170. const addAgain = await $('[data-conversation-selection-action="add-to-task"]');
  171. await addAgain.waitForDisplayed();
  172. await addAgain.click();
  173. await sendV4Prompt("E2E_MARKDOWN_SIDE_PARENT Reply with a short acknowledgment.");
  174. await waitForV4TimelineContaining("E2E_MARKDOWN_SIDE_READY", 30000);
  175. const evidence = await getUpstreamRequestEvidence({
  176. lastUserMessageIncludes: ["E2E_MARKDOWN_SIDE_PARENT", "# userselect:"],
  177. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  178. });
  179. // 仅搜索文件名会被其他上下文误满足;精确检查实际 userselect 发送合同。
  180. expect(evidence.length).toBeGreaterThan(0);
  181. for (const record of evidence) {
  182. const { messages } = record.requestJson as {
  183. messages: Array<{ role: string; content: string | Array<{ type: string; text?: string }> }>;
  184. };
  185. const selections = messages
  186. .filter((message) => message.role === "user")
  187. .flatMap((message) =>
  188. typeof message.content === "string"
  189. ? [message.content]
  190. : message.content
  191. .filter((block) => block.type === "text")
  192. .map((block) => block.text ?? ""),
  193. )
  194. .filter((text) => text.includes("E2E_MARKDOWN_SIDE_PARENT"))
  195. .flatMap((text) =>
  196. Array.from(
  197. text.matchAll(/# userselect:\n```userselect\n([^]*?)\n```/g),
  198. (match) => JSON.parse(match[1]!) as unknown,
  199. ),
  200. );
  201. expect(selections).toEqual([[{ path: filePath, text: marker }]]);
  202. }
  203. const historyChip = await $(
  204. `[data-testid="${paneId}"] [data-conversation-selection-reference-count="1"]`,
  205. );
  206. await historyChip.waitForDisplayed();
  207. expect(await historyChip.getText()).toContain("selection.md");
  208. // 草稿提升为任务会切换 task-owned 侧栏,重新打开该文件后再选区。
  209. await $(`[data-testid="${testId(TID_WORKSPACE_FILE_TREE_ROW, filePath)}"]`).click();
  210. await preview.waitForDisplayed({ timeout: 15000 });
  211. await browser.execute(
  212. (paneTestId, inputTestId) => {
  213. const input = document.querySelector(
  214. `[data-testid="${paneTestId}"] [data-testid="${inputTestId}"]`,
  215. ) as HTMLElement & { __zcodeLexicalInputE2E: { setText: (text: string) => void } };
  216. input.__zcodeLexicalInputE2E.setText("E2E_MARKDOWN_MAIN_KEEP");
  217. },
  218. paneId,
  219. TID_V4_COMPOSER_INPUT,
  220. );
  221. // Lexical 提交草稿时会更新原生 Selection;等编辑器提交完成再创建预览选区。
  222. await browser.executeAsync((done) =>
  223. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  224. );
  225. await browser.execute(() => {
  226. const paragraph = document.querySelector("[data-markdown-preview] p")!;
  227. const range = document.createRange();
  228. range.selectNodeContents(paragraph);
  229. const selection = window.getSelection()!;
  230. selection.removeAllRanges();
  231. selection.addRange(range);
  232. paragraph.dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));
  233. });
  234. const sideAction = await $('[data-conversation-selection-action="ask-in-side-chat"]');
  235. await sideAction.waitForEnabled({ timeout: 15000 });
  236. await sideAction.click();
  237. const sideChip = await $(
  238. '[data-testid^="v4-session-pane-selection-side-chat:"] [data-conversation-selection-reference-count="1"]',
  239. );
  240. await sideChip.waitForDisplayed({ timeout: 30000 });
  241. expect(await sideChip.getText()).toContain("selection.md");
  242. const sideState = await browser.execute((inputTestId) => {
  243. const pane = document.querySelector('[data-testid^="v4-session-pane-selection-side-chat:"]')!;
  244. const input = pane.querySelector(`[data-testid="${inputTestId}"]`) as HTMLElement & {
  245. __zcodeLexicalInputE2E?: { getText: () => string };
  246. };
  247. const main = document.querySelector('[data-testid="v4-session-pane-workspace-main"]')!;
  248. const mainInput = main.querySelector(`[data-testid="${inputTestId}"]`) as typeof input;
  249. return {
  250. sideText: input.__zcodeLexicalInputE2E?.getText(),
  251. mainText: mainInput.__zcodeLexicalInputE2E?.getText(),
  252. distinct: pane.getAttribute("data-session-id") !== main.getAttribute("data-session-id"),
  253. };
  254. }, TID_V4_COMPOSER_INPUT);
  255. expect(sideState).toEqual({ sideText: "", mainText: "E2E_MARKDOWN_MAIN_KEEP", distinct: true });
  256. if (process.env.ZCODE_E2E_ARTIFACT_DIR)
  257. await browser.saveScreenshot(
  258. join(process.env.ZCODE_E2E_ARTIFACT_DIR, "markdown-side-conversation.png"),
  259. );
  260. });
  261. });