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

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