conversation-selection-comment.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import { TID_V4_SESSION_PANE, testId } from "@zcode/shared/test-ids";
  2. const MAIN_PANE = testId(TID_V4_SESSION_PANE, "workspace-main");
  3. /** 读取主时间线中目标文字的首尾坐标;表格单元格等整段匹配的文本节点优先。 */
  4. function locateTimelineText(paneTestId: string, targetText: string, scroll: boolean) {
  5. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  6. if (!pane) throw new Error("缺少主 pane");
  7. const walker = document.createTreeWalker(pane, NodeFilter.SHOW_TEXT);
  8. let found: { node: Node; offset: number } | null = null;
  9. for (let node = walker.nextNode(); node; node = walker.nextNode()) {
  10. const value = node.textContent ?? "";
  11. const offset = value.indexOf(targetText);
  12. if (offset < 0 || !node.parentElement?.closest("[data-row-id]")) continue;
  13. found ??= { node, offset };
  14. if (value.trim() === targetText) {
  15. found = { node, offset };
  16. break;
  17. }
  18. }
  19. if (!found) throw new Error(`主时间线缺少选区文本: ${targetText}`);
  20. if (scroll) found.node.parentElement?.scrollIntoView({ block: "center", behavior: "instant" });
  21. const range = document.createRange();
  22. range.setStart(found.node, found.offset);
  23. range.setEnd(found.node, found.offset + 1);
  24. const first = range.getBoundingClientRect();
  25. range.setStart(found.node, found.offset + targetText.length - 1);
  26. range.setEnd(found.node, found.offset + targetText.length);
  27. const last = range.getBoundingClientRect();
  28. return {
  29. x1: Math.ceil(first.left),
  30. y1: Math.round(first.top + first.height / 2),
  31. x2: Math.floor(last.right),
  32. y2: Math.round(last.top + last.height / 2),
  33. };
  34. }
  35. /**
  36. * 真实 pointer 拖选主时间线文字,并等待选区浮层出现。
  37. * scroll=false 时不滚动目标:回答输出过程中滚动会让时间线退出“跟随到底”,改变被测场景。
  38. */
  39. export async function dragSelectMainTimelineText(
  40. text: string,
  41. options: { scroll?: boolean } = {},
  42. ): Promise<void> {
  43. if (options.scroll !== false) await browser.execute(locateTimelineText, MAIN_PANE, text, true);
  44. // 回答输出时时间线会跟随滚动,定位坐标与按下鼠标之间文字可能已经移动;没选中就重新定位再拖。
  45. let actual = "";
  46. let position = { x1: 0, y1: 0, x2: 0, y2: 0 };
  47. for (let attempt = 0; attempt < 5; attempt += 1) {
  48. // 上一次动作可能保留选区;在旧选区上拖动会变成 HTML 拖放,而不是重新划词。
  49. await browser.execute(() => window.getSelection()?.removeAllRanges());
  50. position = await browser.execute(locateTimelineText, MAIN_PANE, text, false);
  51. await browser.performActions([
  52. {
  53. type: "pointer",
  54. id: "selection-comment-drag",
  55. parameters: { pointerType: "mouse" },
  56. actions: [
  57. { type: "pointerMove", x: position.x1, y: position.y1, duration: 0 },
  58. { type: "pointerDown", button: 0 },
  59. { type: "pointerMove", x: position.x2, y: position.y2, duration: 200 },
  60. { type: "pointerUp", button: 0 },
  61. ],
  62. },
  63. ]);
  64. await browser.releaseActions();
  65. actual = await browser.execute(() => window.getSelection()?.toString() ?? "");
  66. if (actual === text) break;
  67. }
  68. if (actual !== text) {
  69. throw new Error(
  70. `真实拖选未选中目标文本: ${text}; 实际选区=${JSON.stringify(actual)} 坐标=${JSON.stringify(position)}`,
  71. );
  72. }
  73. await $("[data-conversation-selection-tooltip]").waitForDisplayed({ timeout: 5000 });
  74. }
  75. /** 真实 pointer 从 startText 的首字拖到 endText 的末字(可跨段落、代码块),并等待选区浮层出现。 */
  76. export async function dragSelectMainTimelineRange(
  77. startText: string,
  78. endText: string,
  79. ): Promise<void> {
  80. await browser.execute(() => window.getSelection()?.removeAllRanges());
  81. await browser.execute(locateTimelineText, MAIN_PANE, startText, true);
  82. const start = await browser.execute(locateTimelineText, MAIN_PANE, startText, false);
  83. const end = await browser.execute(locateTimelineText, MAIN_PANE, endText, false);
  84. await browser.performActions([
  85. {
  86. type: "pointer",
  87. id: "selection-comment-drag",
  88. parameters: { pointerType: "mouse" },
  89. actions: [
  90. { type: "pointerMove", x: start.x1, y: start.y1, duration: 0 },
  91. { type: "pointerDown", button: 0 },
  92. { type: "pointerMove", x: end.x2, y: end.y2, duration: 300 },
  93. { type: "pointerUp", button: 0 },
  94. ],
  95. },
  96. ]);
  97. await browser.releaseActions();
  98. await browser.waitUntil(
  99. () =>
  100. browser.execute(
  101. (first, last) => {
  102. const selected = window.getSelection()?.toString() ?? "";
  103. return selected.startsWith(first) && selected.endsWith(last);
  104. },
  105. startText,
  106. endText,
  107. ),
  108. { timeout: 5000, timeoutMsg: `真实拖选未选中范围: ${startText} → ${endText}` },
  109. );
  110. await $("[data-conversation-selection-tooltip]").waitForDisplayed({ timeout: 5000 });
  111. }
  112. /** 浮层可能在 selectionchange/rAF 中重挂载;检查与点击合成一次原子脚本并整体重试。 */
  113. export async function clickSelectionAction(
  114. action: "comment" | "add-to-task" | "ask-in-side-chat",
  115. ): Promise<void> {
  116. await browser.waitUntil(
  117. async () =>
  118. browser.execute((nextAction) => {
  119. const button = document.querySelector<HTMLButtonElement>(
  120. `[data-conversation-selection-action="${nextAction}"]`,
  121. );
  122. if (!button || button.disabled) return false;
  123. button.click();
  124. return true;
  125. }, action),
  126. { timeout: 30000, timeoutMsg: `划词动作不可用: ${action}` },
  127. );
  128. }
  129. /** 在批注浮层里用真实键盘输入批注。 */
  130. export async function typeSelectionComment(comment: string): Promise<void> {
  131. const input = await $("[data-conversation-selection-comment-input]");
  132. await input.waitForDisplayed({ timeout: 5000 });
  133. await browser.waitUntil(
  134. () =>
  135. browser.execute(
  136. () =>
  137. document.activeElement?.hasAttribute("data-conversation-selection-comment-input") ===
  138. true,
  139. ),
  140. { timeout: 5000, timeoutMsg: "批注输入框没有自动获得焦点" },
  141. );
  142. await browser.keys(comment.split(""));
  143. await browser.waitUntil(async () => (await input.getValue()) === comment, {
  144. timeout: 5000,
  145. timeoutMsg: "批注输入在键入过程中被清空或浮层被关闭",
  146. });
  147. }
  148. /** 主 composer 的引用 chip 状态:引用条数与 aria-label(含批注数)。 */
  149. export async function readMainComposerSelectionChip(): Promise<{
  150. count: number | null;
  151. label: string | null;
  152. }> {
  153. return browser.execute((paneTestId) => {
  154. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  155. const chips = Array.from(
  156. pane?.querySelectorAll<HTMLElement>("[data-conversation-selection-reference-count]") ?? [],
  157. ).filter((chip) => !chip.closest("[data-row-id]"));
  158. const chip = chips.at(-1);
  159. if (!chip) return { count: null, label: null };
  160. return {
  161. count: Number(chip.dataset.conversationSelectionReferenceCount),
  162. label: chip.getAttribute("aria-label"),
  163. };
  164. }, MAIN_PANE);
  165. }
  166. /** 主时间线正文里的注释编号标记(含已发送的灰色标记),按编号排序。 */
  167. export async function readMainTimelineAnnotationMarks(): Promise<
  168. { number: number; variant: string }[]
  169. > {
  170. return browser.execute((paneTestId) => {
  171. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  172. return Array.from(
  173. pane?.querySelectorAll<HTMLElement>(
  174. "[data-conversation-annotation-marks] [data-annotation-number-variant]",
  175. ) ?? [],
  176. )
  177. .map((mark) => ({
  178. number: Number(mark.textContent),
  179. variant: mark.dataset.annotationNumberVariant ?? "",
  180. }))
  181. .sort((a, b) => a.number - b.number || a.variant.localeCompare(b.variant));
  182. }, MAIN_PANE);
  183. }
  184. /** 点正文里第 n 号注释气泡,等待编辑浮层出现。 */
  185. export async function openMainTimelineAnnotation(number: number): Promise<void> {
  186. await browser.waitUntil(
  187. async () =>
  188. browser.execute(
  189. (paneTestId, target) => {
  190. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  191. const button = pane?.querySelector<HTMLButtonElement>(
  192. `[data-annotation-mark-number="${target}"]`,
  193. );
  194. if (!button) return false;
  195. button.click();
  196. return true;
  197. },
  198. MAIN_PANE,
  199. number,
  200. ),
  201. { timeout: 10000, timeoutMsg: `正文里没有第 ${number} 号注释标记` },
  202. );
  203. await $('[data-conversation-selection-comment-mode="edit"]').waitForDisplayed({ timeout: 5000 });
  204. }