conversation-session-selection-side-chat.test.ts 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  1. import { writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { startDraftFromProject } from "#e2e/helpers/project-sidebar";
  4. import {
  5. clickSelectionAction,
  6. typeSelectionComment,
  7. } from "#e2e/helpers/conversation-selection-comment";
  8. import {
  9. TID_PROMPT_SUGGESTION_PANEL,
  10. TID_SIDE_PANE_TOGGLE,
  11. TID_V4_COMPOSER_INPUT,
  12. TID_V4_COMPOSER_SEND,
  13. TID_V4_SESSION_PANE,
  14. testId,
  15. } from "@zcode/shared/test-ids";
  16. import { clearAppData, DEFAULT_WORKSPACE, pinE2ELocale } from "#e2e/helpers/desktop-app";
  17. import {
  18. getV4PaneSnapshot,
  19. prepareV4ConversationE2E,
  20. sendV4Prompt,
  21. waitForV4Pane,
  22. waitForV4ConversationState,
  23. waitForV4AssistantMessageContaining,
  24. } from "#e2e/helpers/v4-conversation";
  25. const PARENT_MARKER = "E2E_SSC_PARENT_SELECTION_MARKER";
  26. const MAIN_DRAFT = "E2E_SSC_MAIN_DRAFT_KEEP";
  27. const SIDE_DRAFT = "E2E_SSC_SIDE_DRAFT_KEEP";
  28. const SIDE_COMMENT_SEED = "Reply with exactly E2E_SSC_SIDE_COMMENT_SEED";
  29. const SIDE_COMMENT_TARGET = "E2E_SSC_SIDE_COMMENT_TARGET";
  30. const SIDE_COMMENT_RUNNING = "E2E_SSC_SIDE_COMMENT_RUNNING";
  31. const SIDE_LIVE_PARA = "E2E_SSC_SIDE_LIVE_PARA";
  32. const SIDE_COMMENT_NOTE = "E2E side note";
  33. const SIDE_COMMENT_DISCARD = "E2E discard me";
  34. describe("框选文字副屏会话 manual review", () => {
  35. after(async () => {
  36. await browser.electron.restoreAllMocks();
  37. await clearAppData();
  38. });
  39. it("SSC01/02/08/14/15/17/19/25/26/27/28/29/30/31: 隐藏历史、多开、关闭隔离、active 路由与 /side 命令", async function () {
  40. this.timeout(180000);
  41. await prepareV4ConversationE2E();
  42. // 用例断言中文辅助 tab 标题;首帧跟随系统语言,必须先固定语言再创建 child。
  43. await pinE2ELocale("zh-CN");
  44. await sendV4Prompt(`Reply with exactly ${PARENT_MARKER}`);
  45. await waitForSelectableMainTimelineText(PARENT_MARKER, 60000);
  46. const parent = await waitForV4Pane(
  47. (snapshot) => Boolean(snapshot.sessionId && snapshot.sessionId !== "draft"),
  48. "SSC parent session 没有建立",
  49. );
  50. await setComposerText(testId(TID_V4_SESSION_PANE, "workspace-main"), MAIN_DRAFT);
  51. await selectMainTimelineText(PARENT_MARKER);
  52. // 当前 CLI 已把旧“添加到当前任务”合并到注释;留空保存仍只加原文,不覆盖主草稿。
  53. await clickSelectionAction("comment");
  54. const commentInput = $("[data-conversation-selection-comment-input]");
  55. await commentInput.waitForDisplayed({ timeout: 5000 });
  56. expect(await commentInput.getValue()).toBe("");
  57. await $("[data-conversation-selection-comment-save]").click();
  58. await $("[data-conversation-selection-comment-editor]").waitForDisplayed({ reverse: true });
  59. await expectComposerState(testId(TID_V4_SESSION_PANE, "workspace-main"), MAIN_DRAFT, 1);
  60. await selectMainTimelineText(PARENT_MARKER);
  61. await clickSelectionAction("ask-in-side-chat");
  62. const firstSide = await waitForSelectionSidePane();
  63. expect(firstSide.childSessionId).not.toBe(parent.sessionId);
  64. await expectComposerState(firstSide.paneTestId, "", 1);
  65. const inheritedHistoryVisible = await browser.execute(
  66. (paneTestId, marker) => {
  67. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  68. return pane?.innerText.includes(marker) ?? false;
  69. },
  70. firstSide.paneTestId,
  71. PARENT_MARKER,
  72. );
  73. expect(inheritedHistoryVisible).toBe(false);
  74. await setComposerText(firstSide.paneTestId, SIDE_DRAFT);
  75. await selectMainTimelineText("E2E_SSC_PARENT");
  76. await clickSelectionAction("ask-in-side-chat");
  77. const reusedSide = await waitForSelectionSidePane();
  78. expect(reusedSide.childSessionId).toBe(firstSide.childSessionId);
  79. await expectComposerState(reusedSide.paneTestId, SIDE_DRAFT, 2);
  80. await clickComposerSend(testId(TID_V4_SESSION_PANE, "workspace-main"));
  81. // 修复原因:timeline 容器也含 Composer,旧草稿会在请求发出前满足“完成”检查。
  82. // 先等本轮独有回答,再关闭副屏划词,避免新消息投影在拖选时移动文本。
  83. await waitForV4AssistantMessageContaining("E2E_SSC_MAIN_DRAFT_DONE", 30000);
  84. await waitForV4ConversationState(
  85. (state) => state.state === "idle" && state.activeInputId === null,
  86. "父会话追加输入没有完成",
  87. );
  88. const afterParentAdvance = await waitForSelectionSidePane();
  89. expect(afterParentAdvance.childSessionId).toBe(firstSide.childSessionId);
  90. await expectComposerState(afterParentAdvance.paneTestId, SIDE_DRAFT, 2);
  91. await closeSelectionSideTab();
  92. await browser.waitUntil(
  93. async () =>
  94. browser.execute(
  95. () => !document.querySelector('[data-side-pane-tab-id^="selection-side-chat:"]'),
  96. ),
  97. { timeout: 30000, timeoutMsg: "关闭后 selection side tab 仍存在" },
  98. );
  99. // 关闭最后一个标签会收起右侧面板;宽度动画持续触发时间线 scroll,scroll 会关闭选区浮层。
  100. // 等实际面板收至零宽后再划词,不能把 tab DOM 消失当作布局已稳定。
  101. await browser.waitUntil(
  102. () =>
  103. browser.execute(() => {
  104. const panel = document.querySelector('[data-workspace-side-frame="true"]')?.parentElement;
  105. return !panel || panel.getBoundingClientRect().width === 0;
  106. }),
  107. { timeout: 10000, timeoutMsg: "关闭最后一个辅助 tab 后面板没有收起" },
  108. );
  109. await selectMainTimelineText(PARENT_MARKER);
  110. await clickSelectionAction("ask-in-side-chat");
  111. const recreatedSide = await waitForSelectionSidePane();
  112. expect(recreatedSide.childSessionId).not.toBe(firstSide.childSessionId);
  113. await clickAddSelectionSideConversation();
  114. await waitForSelectionSidePanes(2);
  115. await clickAddSelectionSideConversation();
  116. const threeSides = await waitForSelectionSidePanes(3);
  117. expect(new Set(threeSides.map((side) => side.childSessionId)).size).toBe(3);
  118. expect(threeSides.map((side) => side.title)).toEqual([
  119. "辅助对话 1",
  120. "辅助对话 2",
  121. "辅助对话 3",
  122. ]);
  123. await activateSidePaneTab(recreatedSide.tabId);
  124. await selectMainTimelineText("E2E_SSC_PARENT");
  125. await clickSelectionAction("ask-in-side-chat");
  126. await expectComposerState(recreatedSide.paneTestId, "", 2);
  127. for (const side of threeSides.filter(
  128. (candidate) => candidate.childSessionId !== recreatedSide.childSessionId,
  129. )) {
  130. await expectNoSelectionReferences(side.paneTestId);
  131. }
  132. const siblingSides = threeSides.filter(
  133. (candidate) => candidate.childSessionId !== recreatedSide.childSessionId,
  134. );
  135. const sideToClose = siblingSides[0];
  136. const survivingSibling = siblingSides[1];
  137. if (!sideToClose || !survivingSibling) {
  138. throw new Error("multi-open sibling side panes missing");
  139. }
  140. // 隐藏 tab 的输入框不可交互;先走真实切换,再验证关闭另一个 tab 不丢草稿。
  141. await activateSidePaneTab(survivingSibling.tabId);
  142. await setComposerText(survivingSibling.paneTestId, "E2E_SSC_SIBLING_DRAFT");
  143. await closeSelectionSideTab(sideToClose.tabId);
  144. const remainingSides = await waitForSelectionSidePanes(2);
  145. expect(
  146. remainingSides.some((candidate) => candidate.childSessionId === sideToClose.childSessionId),
  147. ).toBe(false);
  148. await expectComposerText(survivingSibling.paneTestId, "E2E_SSC_SIBLING_DRAFT");
  149. await expectNoSelectionReferences(survivingSibling.paneTestId);
  150. await clickAddSidePaneItem("terminal");
  151. await waitForActiveSidePaneTab("terminal:");
  152. await selectMainTimelineText(PARENT_MARKER);
  153. await clickSelectionAction("ask-in-side-chat");
  154. const afterNoActiveAuxiliary = await waitForSelectionSidePanes(3);
  155. const remainingChildIds = new Set(remainingSides.map((side) => side.childSessionId));
  156. const createdForSelection = afterNoActiveAuxiliary.find(
  157. (side) => !remainingChildIds.has(side.childSessionId),
  158. );
  159. expect(createdForSelection).toBeDefined();
  160. if (!createdForSelection) {
  161. throw new Error("selection did not create a new auxiliary child");
  162. }
  163. await expectComposerState(createdForSelection.paneTestId, "", 1);
  164. // SSC28:/side 与 /btw App 层命令选中即开新辅助 tab,并移除输入中的命令 token。
  165. const mainPaneTestId = testId(TID_V4_SESSION_PANE, "workspace-main");
  166. const sidesBeforeSlashCommand = await waitForSelectionSidePanes(3);
  167. const knownChildIds = new Set(sidesBeforeSlashCommand.map((side) => side.childSessionId));
  168. await typeIntoComposerByKeyboard(mainPaneTestId, "/side");
  169. await clickSlashSuggestionOption("app-slash:side");
  170. const afterSideCommand = await waitForSelectionSidePanes(4);
  171. const sideCommandChild = afterSideCommand.find(
  172. (side) => !knownChildIds.has(side.childSessionId),
  173. );
  174. expect(sideCommandChild).toBeDefined();
  175. await expectComposerPlainText(mainPaneTestId, "");
  176. await typeIntoComposerByKeyboard(mainPaneTestId, "/btw");
  177. await clickSlashSuggestionOption("app-slash:btw");
  178. await waitForSelectionSidePanes(5);
  179. await expectComposerPlainText(mainPaneTestId, "");
  180. // SSC30:带参数的 `/side` 直接创建 child,并把参数作为首条普通输入提交。
  181. const childrenBeforeArgument = await waitForSelectionSidePanes(5);
  182. const childrenBeforeArgumentIds = new Set(
  183. childrenBeforeArgument.map((side) => side.childSessionId),
  184. );
  185. await setComposerText(mainPaneTestId, "/side E2E_SSC_SIDE_ARGUMENT_IDLE");
  186. await clickComposerSend(mainPaneTestId);
  187. const idleArgumentChildren = await waitForSelectionSidePanes(6);
  188. const idleArgumentChild = idleArgumentChildren.find(
  189. (side) => !childrenBeforeArgumentIds.has(side.childSessionId),
  190. );
  191. expect(idleArgumentChild).toBeDefined();
  192. if (!idleArgumentChild) throw new Error("带参数 /side 没有创建 child");
  193. await waitForSelectionSidePaneContaining(
  194. idleArgumentChild.paneTestId,
  195. "E2E_SSC_SIDE_ARGUMENT_IDLE",
  196. );
  197. await expectComposerPlainText(mainPaneTestId, "");
  198. // SSC31:父会话启动新 turn 后立即发送 `/btw <text>`,参数命令只启动 child,
  199. // 不把父会话当前 turn 改成 queue/guide。
  200. await setComposerText(mainPaneTestId, "Reply with exactly E2E_SSC_RUNNING_PARENT");
  201. await clickComposerSend(mainPaneTestId);
  202. await waitForV4ConversationState(
  203. // V4 运行态来自可见 Stop projection,不依赖旧 store 的 activeInputId 镜像。
  204. (state) => state.state === "streaming",
  205. "SSC31 父轮没有实际运行",
  206. );
  207. const childrenBeforeRunningArgument = await waitForSelectionSidePanes(6);
  208. const childrenBeforeRunningArgumentIds = new Set(
  209. childrenBeforeRunningArgument.map((side) => side.childSessionId),
  210. );
  211. await setComposerText(mainPaneTestId, "/btw E2E_SSC_SIDE_ARGUMENT_RUNNING");
  212. await clickComposerSend(mainPaneTestId);
  213. const runningArgumentChildren = await waitForSelectionSidePanes(7);
  214. const runningArgumentChild = runningArgumentChildren.find(
  215. (side) => !childrenBeforeRunningArgumentIds.has(side.childSessionId),
  216. );
  217. expect(runningArgumentChild).toBeDefined();
  218. if (!runningArgumentChild) throw new Error("运行中带参数 /btw 没有创建 child");
  219. await waitForSelectionSidePaneContaining(
  220. runningArgumentChild.paneTestId,
  221. "E2E_SSC_SIDE_ARGUMENT_RUNNING",
  222. );
  223. await expectComposerPlainText(mainPaneTestId, "");
  224. // SSC29:辅助对话自身 composer 的 `/` 面板不提供 /side、/btw,CLI 命令展示不受影响。
  225. const activeSideAfterBtw = await waitForActiveSelectionSidePane();
  226. await typeIntoComposerByKeyboard(activeSideAfterBtw.paneTestId, "/");
  227. await expectSlashPanelWithoutSideCommands();
  228. await dismissSlashPanel(activeSideAfterBtw.paneTestId);
  229. // SSC29:草稿态(未创建 session)不提供 /side、/btw。
  230. await openNewTaskDraft();
  231. await typeIntoComposerByKeyboard(mainPaneTestId, "/");
  232. await expectSlashPanelWithoutSideCommands();
  233. await dismissSlashPanel(mainPaneTestId);
  234. });
  235. it("SSC37/38/39/40/41/42: 辅助对话时间线复用主对话选区注释,写入辅助 composer", async function () {
  236. this.timeout(240000);
  237. await prepareV4ConversationE2E({ resetDraftBeforeProvider: true });
  238. await pinE2ELocale("zh-CN");
  239. const mainPaneTestId = testId(TID_V4_SESSION_PANE, "workspace-main");
  240. // 上一个用例留下的辅助 composer 仍挂载;单点 Lexical bridge 可能不在主输入框上,改用真实键盘输入。
  241. await setComposerText(mainPaneTestId, `Reply with exactly ${PARENT_MARKER}`);
  242. await clickComposerSend(mainPaneTestId);
  243. await waitForSelectableMainTimelineText(PARENT_MARKER, 60000);
  244. await waitForV4ConversationState(
  245. (state) => state.state === "idle" && state.activeInputId === null,
  246. "SSC37 父会话没有完成",
  247. );
  248. const sideA = await openBareSideChat(mainPaneTestId);
  249. await setComposerText(sideA.paneTestId, SIDE_COMMENT_SEED);
  250. await clickComposerSend(sideA.paneTestId);
  251. await waitForSelectableMainTimelineText(SIDE_COMMENT_TARGET, 60000, sideA.paneTestId);
  252. await waitForV4Pane((pane) => !pane.canStop, "SSC37 辅助对话没有完成", 30000, sideA.tabId);
  253. // SSC37:辅助时间线框选 → 浮层只有“注释” → 保存后只进辅助 composer,辅助正文画编号。
  254. await selectMainTimelineText(SIDE_COMMENT_TARGET, sideA.paneTestId);
  255. expect(await readSelectionMenuActions()).toEqual(["comment"]);
  256. await clickSelectionAction("comment");
  257. await typeSelectionComment(SIDE_COMMENT_NOTE);
  258. await $("[data-conversation-selection-comment-save]").click();
  259. await $("[data-conversation-selection-comment-editor]").waitForDisplayed({ reverse: true });
  260. await waitForPaneAnnotations(sideA.paneTestId, 1);
  261. expect(await readPaneComposerReferenceCount(mainPaneTestId)).toBeNull();
  262. expect(await readPaneAnnotationMarkCount(mainPaneTestId)).toBe(0);
  263. // SSC42 + SSC39:收起再展开侧栏,焦点不自动回辅助输入框;已保存注释与编号仍在。
  264. await toggleSidePane(sideA.paneTestId, "collapse");
  265. await toggleSidePane(sideA.paneTestId, "expand");
  266. expect(await isFocusInsideComposer(sideA.paneTestId)).toBe(false);
  267. await waitForPaneAnnotations(sideA.paneTestId, 1);
  268. // SSC38:注释输入中收起侧栏 → 输入丢弃;展开后不重弹。
  269. await selectMainTimelineText(SIDE_COMMENT_TARGET, sideA.paneTestId);
  270. await clickSelectionAction("comment");
  271. await typeSelectionComment(SIDE_COMMENT_DISCARD);
  272. await toggleSidePane(sideA.paneTestId, "collapse");
  273. await expectNoSelectionOverlay();
  274. await toggleSidePane(sideA.paneTestId, "expand");
  275. await expectNoSelectionOverlayStays();
  276. await waitForPaneAnnotations(sideA.paneTestId, 1);
  277. // SSC39:另一个辅助 tab 的 composer 没有这条注释。
  278. const sideB = await openBareSideChat(mainPaneTestId);
  279. expect(await readPaneComposerReferenceCount(sideB.paneTestId)).toBeNull();
  280. expect(await readPaneAnnotationMarkCount(sideB.paneTestId)).toBe(0);
  281. // SSC38:输入中切到另一辅助 tab → 原 tab 输入丢弃;切回不重弹。SSC39:切回后注释仍在。
  282. await activateSidePaneTab(sideA.tabId);
  283. await waitForActiveSidePaneTab(sideA.tabId);
  284. await selectMainTimelineText(SIDE_COMMENT_TARGET, sideA.paneTestId);
  285. await clickSelectionAction("comment");
  286. await typeSelectionComment(SIDE_COMMENT_DISCARD);
  287. await activateSidePaneTab(sideB.tabId);
  288. await waitForActiveSidePaneTab(sideB.tabId);
  289. await expectNoSelectionOverlay();
  290. await activateSidePaneTab(sideA.tabId);
  291. await waitForActiveSidePaneTab(sideA.tabId);
  292. await expectNoSelectionOverlayStays();
  293. await waitForPaneAnnotations(sideA.paneTestId, 1);
  294. expect(await readPaneComposerReferenceCount(sideB.paneTestId)).toBeNull();
  295. // SSC40:辅助输入中点主对话 → 输入丢弃;主对话“在辅助对话中提问”照常进当前辅助 tab。
  296. await selectMainTimelineText(SIDE_COMMENT_TARGET, sideA.paneTestId);
  297. await clickSelectionAction("comment");
  298. await typeSelectionComment(SIDE_COMMENT_DISCARD);
  299. await $(`[data-testid="${mainPaneTestId}"] [data-testid="${TID_V4_COMPOSER_INPUT}"]`).click();
  300. await expectNoSelectionOverlay();
  301. await selectMainTimelineText(PARENT_MARKER);
  302. expect(await readSelectionMenuActions()).toContain("ask-in-side-chat");
  303. await clickSelectionAction("ask-in-side-chat");
  304. await waitForPaneComposerReferenceCount(sideA.paneTestId, 2);
  305. expect(await readPaneComposerReferenceCount(sideB.paneTestId)).toBeNull();
  306. expect(await readPaneComposerReferenceCount(mainPaneTestId)).toBeNull();
  307. // SSC41:辅助对话输出中框选;Esc 只关浮层,不停止辅助对话;输出中可保存注释。
  308. await setComposerText(sideA.paneTestId, SIDE_COMMENT_RUNNING);
  309. await clickComposerSend(sideA.paneTestId);
  310. await waitForV4Pane(
  311. (pane) => pane.canStop && pane.timelineText.includes("ssc-side-live-2"),
  312. "SSC41 辅助对话没有开始流式输出",
  313. 30000,
  314. sideA.tabId,
  315. );
  316. // 正在输出的段落逐词渐显,文字节点不稳定;框选已输出完的第一段(第二段已出现)。
  317. await waitForSelectableMainTimelineText(SIDE_LIVE_PARA, 30000, sideA.paneTestId);
  318. await selectMainTimelineText(SIDE_LIVE_PARA, sideA.paneTestId);
  319. expect(await readSelectionMenuActions()).toEqual(["comment"]);
  320. await browser.keys("Escape");
  321. await expectNoSelectionOverlay();
  322. const beforeEscape = (await getV4PaneSnapshot(sideA.tabId)).timelineText.length;
  323. // stop 命令异步生效:先跨过两个增量间隔,再确认仍可停止且正文继续增长,排除“已发 stop 但尚未落地”。
  324. await browser.pause(3200);
  325. const afterEscape = await getV4PaneSnapshot(sideA.tabId);
  326. expect(afterEscape.canStop).toBe(true);
  327. expect(afterEscape.timelineText.length).toBeGreaterThan(beforeEscape + 10);
  328. await selectMainTimelineText(SIDE_LIVE_PARA, sideA.paneTestId);
  329. await clickSelectionAction("comment");
  330. await typeSelectionComment(SIDE_COMMENT_NOTE);
  331. await $("[data-conversation-selection-comment-save]").click();
  332. await $("[data-conversation-selection-comment-editor]").waitForDisplayed({ reverse: true });
  333. await waitForPaneComposerReferenceCount(sideA.paneTestId, 1);
  334. // composer 有待发送注释时停止按钮会换成发送按钮,canStop 不再代表运行态;改看正文是否继续输出。
  335. const afterSave = (await getV4PaneSnapshot(sideA.tabId)).timelineText.length;
  336. await waitForV4Pane(
  337. (pane) => pane.timelineText.length > afterSave + 10,
  338. "SSC41 保存注释后辅助对话没有继续输出",
  339. 15000,
  340. sideA.tabId,
  341. );
  342. // SSC38:菜单已出时关闭 tab,浮层随 tab 消失。
  343. await selectMainTimelineText(SIDE_LIVE_PARA, sideA.paneTestId);
  344. await closeSelectionSideTab(sideA.tabId);
  345. await expectNoSelectionOverlay();
  346. });
  347. });
  348. async function selectMainTimelineText(
  349. text: string,
  350. paneTestId = testId(TID_V4_SESSION_PANE, "workspace-main"),
  351. ): Promise<void> {
  352. await browser.execute(() => {
  353. const state = window as Window & { __selectionTrace?: { events: unknown[]; stop(): void } };
  354. state.__selectionTrace?.stop();
  355. const events: unknown[] = [];
  356. const types = ["mousedown", "mouseup", "selectionchange", "scroll", "resize", "focusin"];
  357. const listener = (event: Event) => {
  358. const selection = window.getSelection();
  359. events.push({
  360. type: event.type,
  361. time: performance.now(),
  362. text: selection?.toString(),
  363. target: (event.target as Element)?.getAttribute?.("data-testid"),
  364. anchor: selection?.anchorNode?.parentElement
  365. ?.closest("[data-row-id]")
  366. ?.getAttribute("data-row-id"),
  367. focused: document.activeElement?.getAttribute("data-testid"),
  368. tooltip: Boolean(document.querySelector("[data-conversation-selection-tooltip]")),
  369. });
  370. };
  371. for (const type of types) window.addEventListener(type, listener, true);
  372. state.__selectionTrace = {
  373. events,
  374. stop: () => {
  375. for (const type of types) window.removeEventListener(type, listener, true);
  376. },
  377. };
  378. });
  379. // 上一次引用动作可能保留选区;在旧选区上拖动会变成 HTML 拖放,而不是重新划词。
  380. await browser.execute(() => window.getSelection()?.removeAllRanges());
  381. // 旧 helper 直接改 DOM Range,再重试 mouseup;它绕过了原生选区与 pane 焦点更新。
  382. // 这里只读取文本坐标,交互由真实 pointer drag 完成;滚动先于 pointerdown。
  383. const locator = (id: string, targetText: string, scroll: boolean) => {
  384. const pane = document.querySelector<HTMLElement>(`[data-testid="${id}"]`);
  385. if (!pane) throw new Error("缺少主 pane");
  386. const walker = document.createTreeWalker(pane, NodeFilter.SHOW_TEXT);
  387. let found: { node: Node; offset: number } | null = null;
  388. for (let node = walker.nextNode(); node; node = walker.nextNode()) {
  389. const value = node.textContent ?? "";
  390. const offset = value.indexOf(targetText);
  391. if (offset < 0 || !node.parentElement?.closest("[data-row-id]")) continue;
  392. found ??= { node, offset };
  393. if (value.trim() === targetText) {
  394. found = { node, offset };
  395. break;
  396. }
  397. }
  398. if (!found) throw new Error(`主时间线缺少选区文本: ${targetText}`);
  399. if (scroll) found.node.parentElement?.scrollIntoView({ block: "center", behavior: "instant" });
  400. const range = document.createRange();
  401. range.setStart(found.node, found.offset);
  402. range.setEnd(found.node, found.offset + 1);
  403. const first = range.getBoundingClientRect();
  404. range.setStart(found.node, found.offset + targetText.length - 1);
  405. range.setEnd(found.node, found.offset + targetText.length);
  406. const last = range.getBoundingClientRect();
  407. return {
  408. x1: Math.ceil(first.left),
  409. y1: Math.round(first.top + first.height / 2),
  410. x2: Math.floor(last.right),
  411. y2: Math.round(last.top + last.height / 2),
  412. };
  413. };
  414. const readLayoutTransitions = (id: string): string[] => {
  415. const pane = document.querySelector<HTMLElement>(`[data-testid="${id}"]`);
  416. if (!pane) return ["missing-pane"];
  417. return document.getAnimations().flatMap((animation) => {
  418. if (!(animation instanceof CSSTransition) || animation.playState !== "running") return [];
  419. if (!["width", "max-width", "height", "transform"].includes(animation.transitionProperty))
  420. return [];
  421. const target = (animation.effect as KeyframeEffect | null)?.target;
  422. return target instanceof Element && (pane.contains(target) || target.contains(pane))
  423. ? [animation.transitionProperty]
  424. : [];
  425. });
  426. };
  427. // 辅助面板收起后,主列还会跨断点做宽度过渡;动态测高会把文字再滚动 59px。
  428. // 等实际布局过渡结束后才取坐标,避免用旧坐标拖选相邻行。
  429. await browser.waitUntil(
  430. async () => (await browser.execute(readLayoutTransitions, paneTestId)).length === 0,
  431. { timeout: 10000, timeoutMsg: "主时间线布局过渡未结束,不能开始原生划词" },
  432. );
  433. await browser.execute(locator, paneTestId, text, true);
  434. const position = await browser.execute(locator, paneTestId, text, false);
  435. expect(await browser.execute(readLayoutTransitions, paneTestId)).toEqual([]);
  436. await browser.performActions([
  437. {
  438. type: "pointer",
  439. id: "selection-drag",
  440. parameters: { pointerType: "mouse" },
  441. actions: [
  442. { type: "pointerMove", x: position.x1, y: position.y1, duration: 0 },
  443. { type: "pointerDown", button: 0 },
  444. { type: "pointerMove", x: position.x2, y: position.y2, duration: 200 },
  445. { type: "pointerUp", button: 0 },
  446. ],
  447. },
  448. ]);
  449. await browser.releaseActions();
  450. try {
  451. await browser.waitUntil(
  452. () => browser.execute((expected) => window.getSelection()?.toString() === expected, text),
  453. { timeout: 5000, timeoutMsg: `真实拖选未选中目标文本: ${text}` },
  454. );
  455. await $("[data-conversation-selection-tooltip]").waitForDisplayed({ timeout: 5000 });
  456. } catch (error) {
  457. const events = await browser.execute(
  458. () =>
  459. (window as Window & { __selectionTrace?: { events: unknown[] } }).__selectionTrace?.events,
  460. );
  461. await writeFile(
  462. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "selection-events.json"),
  463. JSON.stringify(
  464. {
  465. text,
  466. position,
  467. currentPosition: await browser.execute(locator, paneTestId, text, false),
  468. events,
  469. },
  470. null,
  471. 2,
  472. ),
  473. );
  474. throw error;
  475. } finally {
  476. await browser.execute(() =>
  477. (window as Window & { __selectionTrace?: { stop(): void } }).__selectionTrace?.stop(),
  478. );
  479. }
  480. }
  481. async function waitForSelectableMainTimelineText(
  482. text: string,
  483. timeout: number,
  484. paneTestId = testId(TID_V4_SESSION_PANE, "workspace-main"),
  485. ): Promise<void> {
  486. await browser.waitUntil(
  487. async () =>
  488. browser.execute(
  489. (paneTestId, targetText) => {
  490. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  491. if (!pane) return false;
  492. const walker = document.createTreeWalker(pane, NodeFilter.SHOW_TEXT);
  493. let node = walker.nextNode();
  494. while (node) {
  495. if (
  496. node.textContent?.trim() === targetText &&
  497. node.parentElement?.closest("[data-row-id]")
  498. ) {
  499. return true;
  500. }
  501. node = walker.nextNode();
  502. }
  503. return false;
  504. },
  505. paneTestId,
  506. text,
  507. ),
  508. {
  509. timeout,
  510. timeoutMsg: `时间线没有出现可选文本: ${text}`,
  511. },
  512. );
  513. }
  514. async function waitForSelectionSidePane(): Promise<{
  515. childSessionId: string;
  516. paneTestId: string;
  517. tabId: string;
  518. }> {
  519. let result: { childSessionId: string; paneTestId: string; tabId: string } | null = null;
  520. await browser.waitUntil(
  521. async () => {
  522. result = await browser.execute((panePrefix) => {
  523. const tab = document.querySelector<HTMLElement>(
  524. '[data-side-pane-tab-id^="selection-side-chat:"]',
  525. );
  526. const tabId = tab?.dataset.sidePaneTabId;
  527. if (!tabId) return null;
  528. const paneTestId = `${panePrefix}-${tabId}`;
  529. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  530. const childSessionId = pane?.dataset.sessionId;
  531. return childSessionId ? { childSessionId, paneTestId, tabId } : null;
  532. }, TID_V4_SESSION_PANE);
  533. return result !== null;
  534. },
  535. { timeout: 30000, timeoutMsg: "selection side pane 没有打开" },
  536. );
  537. if (!result) throw new Error("selection side pane result missing");
  538. return result;
  539. }
  540. async function waitForSelectionSidePanes(expectedCount: number): Promise<
  541. Array<{
  542. childSessionId: string;
  543. paneTestId: string;
  544. tabId: string;
  545. title: string;
  546. }>
  547. > {
  548. let result: Array<{
  549. childSessionId: string;
  550. paneTestId: string;
  551. tabId: string;
  552. title: string;
  553. }> = [];
  554. await browser.waitUntil(
  555. async () => {
  556. result = await browser.execute(
  557. (panePrefix) =>
  558. Array.from(
  559. document.querySelectorAll<HTMLElement>(
  560. '[data-side-pane-tab-id^="selection-side-chat:"]',
  561. ),
  562. ).flatMap((tab) => {
  563. const tabId = tab.dataset.sidePaneTabId;
  564. if (!tabId) return [];
  565. const paneTestId = `${panePrefix}-${tabId}`;
  566. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  567. const childSessionId = pane?.dataset.sessionId;
  568. return childSessionId
  569. ? [{ childSessionId, paneTestId, tabId, title: tab.innerText.trim() }]
  570. : [];
  571. }),
  572. TID_V4_SESSION_PANE,
  573. );
  574. return result.length === expectedCount;
  575. },
  576. {
  577. timeout: 30000,
  578. timeoutMsg: `selection side pane 数量不是 ${expectedCount}`,
  579. },
  580. );
  581. return result;
  582. }
  583. async function clickAddSelectionSideConversation(): Promise<void> {
  584. await clickAddSidePaneItem("selection-side-conversation");
  585. }
  586. async function clickAddSidePaneItem(
  587. itemId: "selection-side-conversation" | "terminal",
  588. ): Promise<void> {
  589. // 修复原因:Radix DropdownMenu trigger 依赖 pointerdown 手势,element.click()
  590. // 或单独的 WebDriver click 在 Electron 下不稳定;与 e2ecase-regression 同口径,
  591. // 派发完整 pointer/mouse/click 事件序列激活 trigger 与 menu item。
  592. const dispatchActivationScript = (selector: string) => {
  593. const target = document.querySelector<HTMLElement>(selector);
  594. if (!target) return false;
  595. target.scrollIntoView({ block: "center", inline: "nearest" });
  596. target.focus();
  597. for (const type of ["pointerdown", "mousedown", "pointerup", "mouseup", "click"]) {
  598. const event = type.startsWith("pointer")
  599. ? new PointerEvent(type, {
  600. bubbles: true,
  601. cancelable: true,
  602. button: 0,
  603. pointerId: 1,
  604. pointerType: "mouse",
  605. isPrimary: true,
  606. })
  607. : new MouseEvent(type, { bubbles: true, cancelable: true, button: 0 });
  608. target.dispatchEvent(event);
  609. }
  610. return true;
  611. };
  612. await browser.waitUntil(
  613. async () => browser.execute(dispatchActivationScript, "[data-side-pane-add-trigger]"),
  614. { timeout: 15000, timeoutMsg: "Side Pane 新增标签按钮不存在" },
  615. );
  616. const itemSelector = `[data-state="active"] [data-side-pane-open-tab-item="${itemId}"]`;
  617. await browser.waitUntil(
  618. async () =>
  619. browser.execute((selector) => Boolean(document.querySelector(selector)), itemSelector),
  620. { timeout: 15000, timeoutMsg: `${itemId} 新增菜单没有打开` },
  621. );
  622. const clicked = await browser.execute(dispatchActivationScript, itemSelector);
  623. expect(clicked).toBe(true);
  624. }
  625. async function waitForActiveSidePaneTab(idPrefix: string): Promise<void> {
  626. await browser.waitUntil(
  627. async () =>
  628. browser.execute((nextIdPrefix) => {
  629. const activeTab = document.querySelector<HTMLElement>(
  630. '[data-side-pane-tab-id][data-state="active"]',
  631. );
  632. return activeTab?.dataset.sidePaneTabId?.startsWith(nextIdPrefix) ?? false;
  633. }, idPrefix),
  634. {
  635. timeout: 30000,
  636. timeoutMsg: `Side Pane active tab 不是 ${idPrefix}`,
  637. },
  638. );
  639. }
  640. async function activateSidePaneTab(tabId: string): Promise<void> {
  641. const clicked = await browser.execute((targetTabId) => {
  642. const tab = document.querySelector<HTMLElement>(
  643. `[data-side-pane-tab-id="${CSS.escape(targetTabId)}"]`,
  644. );
  645. tab?.click();
  646. return Boolean(tab);
  647. }, tabId);
  648. expect(clicked).toBe(true);
  649. }
  650. async function setComposerText(paneTestId: string, text: string): Promise<void> {
  651. // 多 pane 共用 testid 时单点 Lexical bridge 可能不在目标输入上;通过真实键盘输入。
  652. await clearComposerByKeyboard(paneTestId);
  653. await browser.keys(text.split(""));
  654. await expectComposerPlainText(paneTestId, text);
  655. }
  656. async function expectComposerState(
  657. paneTestId: string,
  658. text: string,
  659. referenceCount: number,
  660. ): Promise<void> {
  661. await browser.waitUntil(
  662. async () =>
  663. browser.execute(
  664. (nextPaneTestId, inputTestId, expectedText, expectedReferenceCount) => {
  665. const pane = document.querySelector<HTMLElement>(`[data-testid="${nextPaneTestId}"]`);
  666. const input = pane?.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  667. return (
  668. (input?.textContent ?? "").trim() === expectedText &&
  669. pane?.querySelector(
  670. `[data-conversation-selection-reference-count="${expectedReferenceCount}"]`,
  671. ) !== null
  672. );
  673. },
  674. paneTestId,
  675. TID_V4_COMPOSER_INPUT,
  676. text,
  677. referenceCount,
  678. ),
  679. {
  680. timeout: 15000,
  681. timeoutMsg: `composer 草稿或引用数量不匹配: ${paneTestId}`,
  682. },
  683. );
  684. }
  685. async function expectNoSelectionReferences(paneTestId: string): Promise<void> {
  686. await browser.waitUntil(
  687. async () =>
  688. browser.execute((nextPaneTestId) => {
  689. const pane = document.querySelector<HTMLElement>(`[data-testid="${nextPaneTestId}"]`);
  690. return (
  691. pane !== null &&
  692. pane.querySelector("[data-conversation-selection-reference-count]") === null
  693. );
  694. }, paneTestId),
  695. {
  696. timeout: 15000,
  697. timeoutMsg: `非目标辅助对话出现了划词引用: ${paneTestId}`,
  698. },
  699. );
  700. }
  701. async function expectComposerText(paneTestId: string, text: string): Promise<void> {
  702. await browser.waitUntil(
  703. async () =>
  704. browser.execute(
  705. (nextPaneTestId, inputTestId, expectedText) => {
  706. const pane = document.querySelector<HTMLElement>(`[data-testid="${nextPaneTestId}"]`);
  707. const input = pane?.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  708. return (
  709. (
  710. input as
  711. | (HTMLElement & {
  712. __zcodeLexicalInputE2E?: { getText: () => string };
  713. })
  714. | undefined
  715. )?.__zcodeLexicalInputE2E?.getText() === expectedText
  716. );
  717. },
  718. paneTestId,
  719. TID_V4_COMPOSER_INPUT,
  720. text,
  721. ),
  722. {
  723. timeout: 15000,
  724. timeoutMsg: `composer 草稿不匹配: ${paneTestId}`,
  725. },
  726. );
  727. }
  728. async function clickComposerSend(paneTestId: string): Promise<void> {
  729. const clicked = await browser.execute(
  730. (nextPaneTestId, sendTestId) => {
  731. const pane = document.querySelector<HTMLElement>(`[data-testid="${nextPaneTestId}"]`);
  732. const button = pane?.querySelector<HTMLButtonElement>(`[data-testid="${sendTestId}"]`);
  733. if (!button || button.disabled) return false;
  734. button.click();
  735. return true;
  736. },
  737. paneTestId,
  738. TID_V4_COMPOSER_SEND,
  739. );
  740. expect(clicked).toBe(true);
  741. }
  742. async function waitForActiveSelectionSidePane(): Promise<{
  743. childSessionId: string;
  744. paneTestId: string;
  745. tabId: string;
  746. }> {
  747. let result: { childSessionId: string; paneTestId: string; tabId: string } | null = null;
  748. await browser.waitUntil(
  749. async () => {
  750. result = await browser.execute((panePrefix) => {
  751. const tab = document.querySelector<HTMLElement>(
  752. '[data-side-pane-tab-id^="selection-side-chat:"][data-state="active"]',
  753. );
  754. const tabId = tab?.dataset.sidePaneTabId;
  755. if (!tabId) return null;
  756. const paneTestId = `${panePrefix}-${tabId}`;
  757. const childSessionId = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`)
  758. ?.dataset.sessionId;
  759. return childSessionId ? { childSessionId, paneTestId, tabId } : null;
  760. }, TID_V4_SESSION_PANE);
  761. return result !== null;
  762. },
  763. { timeout: 30000, timeoutMsg: "没有 active 的 selection side pane" },
  764. );
  765. if (!result) throw new Error("active selection side pane missing");
  766. return result;
  767. }
  768. async function waitForSelectionSidePaneContaining(
  769. paneTestId: string,
  770. marker: string,
  771. ): Promise<void> {
  772. await browser.waitUntil(
  773. async () =>
  774. browser.execute(
  775. (nextPaneTestId, nextMarker) =>
  776. document
  777. .querySelector<HTMLElement>(`[data-testid="${nextPaneTestId}"]`)
  778. ?.innerText.includes(nextMarker) ?? false,
  779. paneTestId,
  780. marker,
  781. ),
  782. { timeout: 60000, timeoutMsg: `selection side pane 没有出现 ${marker}` },
  783. );
  784. }
  785. /** 斜杠面板由真实键盘事件触发,输入一次后等待可见正文收敛。 */
  786. async function typeIntoComposerByKeyboard(paneTestId: string, text: string): Promise<void> {
  787. await setComposerText(paneTestId, text);
  788. }
  789. /** 不依赖 bridge 的清空:全选 + Backspace(真实键序,Lexical 正常处理)。 */
  790. async function clearComposerByKeyboard(paneTestId: string): Promise<void> {
  791. const inputSelector = `[data-testid="${paneTestId}"] [data-testid="${TID_V4_COMPOSER_INPUT}"]`;
  792. const input = $(inputSelector);
  793. await input.waitForClickable({ timeout: 15000 });
  794. await input.click();
  795. const modifier = process.platform === "darwin" ? "Meta" : "Control";
  796. await browser.keys([modifier, "a"]);
  797. await browser.keys("Backspace");
  798. await browser.waitUntil(
  799. async () =>
  800. browser.execute(
  801. (selector) =>
  802. (document.querySelector<HTMLElement>(selector)?.textContent ?? "").trim() === "",
  803. inputSelector,
  804. ),
  805. { timeout: 10000, timeoutMsg: `composer 清空失败: ${paneTestId}` },
  806. );
  807. }
  808. /** 不依赖 bridge 的 composer 文本断言(bridge 在多 composer 场景可能脱落)。 */
  809. async function expectComposerPlainText(paneTestId: string, text: string): Promise<void> {
  810. const inputSelector = `[data-testid="${paneTestId}"] [data-testid="${TID_V4_COMPOSER_INPUT}"]`;
  811. await browser.waitUntil(
  812. async () =>
  813. browser.execute(
  814. (selector, expectedText) =>
  815. (document.querySelector<HTMLElement>(selector)?.textContent ?? "").trim() ===
  816. expectedText,
  817. inputSelector,
  818. text,
  819. ),
  820. { timeout: 15000, timeoutMsg: `composer 文本不匹配: ${paneTestId}` },
  821. );
  822. }
  823. async function clickSlashSuggestionOption(optionId: string): Promise<void> {
  824. // 修复原因:面板可能因编辑器失焦(新辅助 tab autofocus)瞬时关闭;"先查后点"两次
  825. // 往返之间选项会消失。这里把查找与 mousedown 合成单个原子脚本并整体重试。
  826. // MentionPanel 选项在 onMouseDown 触发 onSelect,element.click() 不会命中。
  827. await browser.waitUntil(
  828. async () =>
  829. browser.execute((nextOptionId) => {
  830. const option = document.querySelector<HTMLButtonElement>(
  831. `[data-option-id="${CSS.escape(nextOptionId)}"]`,
  832. );
  833. if (!option) return false;
  834. option.dispatchEvent(
  835. new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }),
  836. );
  837. return true;
  838. }, optionId),
  839. { timeout: 15000, timeoutMsg: `斜杠面板没有出现选项: ${optionId}` },
  840. );
  841. }
  842. async function expectSlashPanelWithoutSideCommands(): Promise<void> {
  843. await browser.waitUntil(
  844. async () =>
  845. browser.execute(
  846. (panelTestId) => Boolean(document.querySelector(`[data-testid="${panelTestId}"]`)),
  847. TID_PROMPT_SUGGESTION_PANEL,
  848. ),
  849. { timeout: 15000, timeoutMsg: "斜杠面板没有打开" },
  850. );
  851. // SSC29 只限制辅助对话入口;/plan 等后续加入的合法 App 命令不在禁止范围。
  852. const appCommands = await browser.execute(() =>
  853. [...document.querySelectorAll('[data-option-id^="app-slash:"]')].map((node) =>
  854. node.getAttribute("data-option-id"),
  855. ),
  856. );
  857. expect(appCommands).not.toContain("app-slash:side");
  858. expect(appCommands).not.toContain("app-slash:btw");
  859. }
  860. async function dismissSlashPanel(paneTestId: string): Promise<void> {
  861. await browser.keys("Escape");
  862. await clearComposerByKeyboard(paneTestId);
  863. }
  864. async function openNewTaskDraft(): Promise<void> {
  865. await startDraftFromProject(DEFAULT_WORKSPACE);
  866. await waitForV4ConversationState(
  867. (state) => state.sessionId === null && state.taskId === null,
  868. "项目没有进入空草稿",
  869. );
  870. }
  871. async function closeSelectionSideTab(tabId?: string): Promise<void> {
  872. const clicked = await browser.execute((targetTabId) => {
  873. const tab = document.querySelector<HTMLElement>(
  874. targetTabId
  875. ? `[data-side-pane-tab-id="${CSS.escape(targetTabId)}"]`
  876. : '[data-side-pane-tab-id^="selection-side-chat:"]',
  877. );
  878. const button = tab?.querySelector<HTMLButtonElement>("button");
  879. button?.click();
  880. return Boolean(button);
  881. }, tabId);
  882. expect(clicked).toBe(true);
  883. }
  884. /** 用裸 `/btw` 新建并激活一个空辅助对话;按 tab id 差集识别新 tab,不受其他父任务的隐藏 tab 影响。 */
  885. async function openBareSideChat(
  886. mainPaneTestId: string,
  887. ): Promise<{ paneTestId: string; tabId: string }> {
  888. const previousTabIds = await readSelectionSideTabIds();
  889. await typeIntoComposerByKeyboard(mainPaneTestId, "/btw");
  890. await clickSlashSuggestionOption("app-slash:btw");
  891. let tabId = "";
  892. await browser.waitUntil(
  893. async () => {
  894. tabId = (await readSelectionSideTabIds()).find((id) => !previousTabIds.includes(id)) ?? "";
  895. return Boolean(tabId);
  896. },
  897. { timeout: 30000, timeoutMsg: "裸 /btw 没有新建辅助 tab" },
  898. );
  899. await waitForV4Pane((pane) => Boolean(pane.sessionId), "辅助对话没有就绪", 30000, tabId);
  900. await waitForActiveSidePaneTab(tabId);
  901. return { paneTestId: testId(TID_V4_SESSION_PANE, tabId), tabId };
  902. }
  903. async function readSelectionSideTabIds(): Promise<string[]> {
  904. return browser.execute(() =>
  905. Array.from(
  906. document.querySelectorAll<HTMLElement>('[data-side-pane-tab-id^="selection-side-chat:"]'),
  907. (tab) => tab.dataset.sidePaneTabId ?? "",
  908. ).filter(Boolean),
  909. );
  910. }
  911. /** 当前选区浮层里的动作按钮,按 DOM 顺序。 */
  912. async function readSelectionMenuActions(): Promise<string[]> {
  913. await $("[data-conversation-selection-tooltip]").waitForDisplayed({ timeout: 5000 });
  914. return browser.execute(() =>
  915. Array.from(
  916. document.querySelectorAll<HTMLElement>(
  917. "[data-conversation-selection-tooltip] [data-conversation-selection-action]",
  918. ),
  919. (button) => button.dataset.conversationSelectionAction ?? "",
  920. ),
  921. );
  922. }
  923. /** composer 里的引用条数;排除时间线历史 user row 上的 chip。 */
  924. async function readPaneComposerReferenceCount(paneTestId: string): Promise<number | null> {
  925. return browser.execute((nextPaneTestId) => {
  926. const pane = document.querySelector<HTMLElement>(`[data-testid="${nextPaneTestId}"]`);
  927. const chip = Array.from(
  928. pane?.querySelectorAll<HTMLElement>("[data-conversation-selection-reference-count]") ?? [],
  929. )
  930. .filter((candidate) => !candidate.closest("[data-row-id]"))
  931. .at(-1);
  932. return chip ? Number(chip.dataset.conversationSelectionReferenceCount) : null;
  933. }, paneTestId);
  934. }
  935. async function waitForPaneComposerReferenceCount(paneTestId: string, count: number): Promise<void> {
  936. await browser.waitUntil(
  937. async () => (await readPaneComposerReferenceCount(paneTestId)) === count,
  938. { timeout: 15000, timeoutMsg: `composer 注释条数不是 ${count}: ${paneTestId}` },
  939. );
  940. }
  941. async function readPaneAnnotationMarkCount(paneTestId: string): Promise<number> {
  942. return browser.execute(
  943. (nextPaneTestId) =>
  944. document
  945. .querySelector<HTMLElement>(`[data-testid="${nextPaneTestId}"]`)
  946. ?.querySelectorAll("[data-conversation-annotation-marks] [data-annotation-number-variant]")
  947. .length ?? 0,
  948. paneTestId,
  949. );
  950. }
  951. /** composer 有 count 条注释,且该 pane 正文画出同样数量的编号标记。 */
  952. async function waitForPaneAnnotations(paneTestId: string, count: number): Promise<void> {
  953. await waitForPaneComposerReferenceCount(paneTestId, count);
  954. await browser.waitUntil(async () => (await readPaneAnnotationMarkCount(paneTestId)) === count, {
  955. timeout: 15000,
  956. timeoutMsg: `正文注释编号数量不是 ${count}: ${paneTestId}`,
  957. });
  958. }
  959. async function expectNoSelectionOverlay(): Promise<void> {
  960. await browser.waitUntil(
  961. () =>
  962. browser.execute(
  963. () =>
  964. !document.querySelector("[data-conversation-selection-tooltip]") &&
  965. !document.querySelector("[data-conversation-selection-comment-editor]"),
  966. ),
  967. { timeout: 5000, timeoutMsg: "选区浮层或注释输入没有关闭" },
  968. );
  969. }
  970. /** 恢复可见后浮层不能重新弹出:先确认关闭,再观察一段时间仍为关闭。 */
  971. async function expectNoSelectionOverlayStays(): Promise<void> {
  972. await expectNoSelectionOverlay();
  973. // 浮层由 rAF 调度重新检查选区;观察窗口覆盖多帧与侧栏展开动画。
  974. await browser.pause(1000);
  975. await expectNoSelectionOverlay();
  976. }
  977. async function toggleSidePane(paneTestId: string, target: "collapse" | "expand"): Promise<void> {
  978. await $(`[data-testid="${TID_SIDE_PANE_TOGGLE}"]`).click();
  979. await $(
  980. `[data-testid="${paneTestId}"] [data-testid="${TID_V4_COMPOSER_INPUT}"]`,
  981. ).waitForDisplayed({ reverse: target === "collapse", timeout: 15000 });
  982. if (target === "collapse") return;
  983. // 侧栏展开宽度由动画驱动(不全是 CSS transition),文字仍在横移时取坐标会拖偏;
  984. // 等 pane 位置连续两次采样一致后再继续划词。
  985. let previous = "";
  986. await browser.waitUntil(
  987. async () => {
  988. const rect = await browser.execute((nextPaneTestId) => {
  989. const box = document
  990. .querySelector<HTMLElement>(`[data-testid="${nextPaneTestId}"]`)
  991. ?.getBoundingClientRect();
  992. return box ? `${box.left}:${box.width}` : "";
  993. }, paneTestId);
  994. const stable = rect !== "" && rect === previous;
  995. previous = rect;
  996. return stable;
  997. },
  998. { timeout: 10000, interval: 200, timeoutMsg: `侧栏展开后布局没有稳定: ${paneTestId}` },
  999. );
  1000. }
  1001. async function isFocusInsideComposer(paneTestId: string): Promise<boolean> {
  1002. return browser.execute(
  1003. (nextPaneTestId, inputTestId) => {
  1004. const input = document.querySelector<HTMLElement>(
  1005. `[data-testid="${nextPaneTestId}"] [data-testid="${inputTestId}"]`,
  1006. );
  1007. return Boolean(input && document.activeElement && input.contains(document.activeElement));
  1008. },
  1009. paneTestId,
  1010. TID_V4_COMPOSER_INPUT,
  1011. );
  1012. }