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

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