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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. import { writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { startDraftFromProject } from "#e2e/helpers/project-sidebar";
  4. import {
  5. TID_PROMPT_SUGGESTION_PANEL,
  6. TID_V4_COMPOSER_INPUT,
  7. TID_V4_COMPOSER_SEND,
  8. TID_V4_SESSION_PANE,
  9. testId,
  10. } from "@zcode/shared/test-ids";
  11. import { clearAppData, DEFAULT_WORKSPACE } from "../helpers/desktop-app.js";
  12. import {
  13. prepareV4ConversationE2E,
  14. sendV4Prompt,
  15. waitForV4Pane,
  16. waitForV4ConversationState,
  17. waitForV4AssistantMessageContaining,
  18. } from "../helpers/v4-conversation.js";
  19. const PARENT_MARKER = "E2E_SSC_PARENT_SELECTION_MARKER";
  20. const MAIN_DRAFT = "E2E_SSC_MAIN_DRAFT_KEEP";
  21. const SIDE_DRAFT = "E2E_SSC_SIDE_DRAFT_KEEP";
  22. describe("框选文字副屏会话 manual review", () => {
  23. after(async () => {
  24. await browser.electron.restoreAllMocks();
  25. await clearAppData();
  26. });
  27. it("SSC01/02/08/14/15/17/19/25/26/27/28/29/30/31: 隐藏历史、多开、关闭隔离、active 路由与 /side 命令", async function () {
  28. this.timeout(180000);
  29. await prepareV4ConversationE2E();
  30. await sendV4Prompt(`Reply with exactly ${PARENT_MARKER}`);
  31. await waitForSelectableMainTimelineText(PARENT_MARKER, 60000);
  32. const parent = await waitForV4Pane(
  33. (snapshot) => Boolean(snapshot.sessionId && snapshot.sessionId !== "draft"),
  34. "SSC parent session 没有建立",
  35. );
  36. await setComposerText(testId(TID_V4_SESSION_PANE, "workspace-main"), MAIN_DRAFT);
  37. await selectMainTimelineText(PARENT_MARKER);
  38. await clickSelectionAction("add-to-task");
  39. await expectComposerState(testId(TID_V4_SESSION_PANE, "workspace-main"), MAIN_DRAFT, 1);
  40. await selectMainTimelineText(PARENT_MARKER);
  41. await clickSelectionAction("ask-in-side-chat");
  42. const firstSide = await waitForSelectionSidePane();
  43. expect(firstSide.childSessionId).not.toBe(parent.sessionId);
  44. await expectComposerState(firstSide.paneTestId, "", 1);
  45. const inheritedHistoryVisible = await browser.execute(
  46. (paneTestId, marker) => {
  47. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  48. return pane?.innerText.includes(marker) ?? false;
  49. },
  50. firstSide.paneTestId,
  51. PARENT_MARKER,
  52. );
  53. expect(inheritedHistoryVisible).toBe(false);
  54. await setComposerText(firstSide.paneTestId, SIDE_DRAFT);
  55. await selectMainTimelineText("E2E_SSC_PARENT");
  56. await clickSelectionAction("ask-in-side-chat");
  57. const reusedSide = await waitForSelectionSidePane();
  58. expect(reusedSide.childSessionId).toBe(firstSide.childSessionId);
  59. await expectComposerState(reusedSide.paneTestId, SIDE_DRAFT, 2);
  60. await clickComposerSend(testId(TID_V4_SESSION_PANE, "workspace-main"));
  61. // 修复原因:timeline 容器也含 Composer,旧草稿会在请求发出前满足“完成”检查。
  62. // 先等本轮独有回答,再关闭副屏划词,避免新消息投影在拖选时移动文本。
  63. await waitForV4AssistantMessageContaining("E2E_SSC_MAIN_DRAFT_DONE", 30000);
  64. await waitForV4ConversationState(
  65. (state) => state.state === "idle" && state.activeInputId === null,
  66. "父会话追加输入没有完成",
  67. );
  68. const afterParentAdvance = await waitForSelectionSidePane();
  69. expect(afterParentAdvance.childSessionId).toBe(firstSide.childSessionId);
  70. await expectComposerState(afterParentAdvance.paneTestId, SIDE_DRAFT, 2);
  71. await closeSelectionSideTab();
  72. await browser.waitUntil(
  73. async () =>
  74. browser.execute(
  75. () => !document.querySelector('[data-side-pane-tab-id^="selection-side-chat:"]'),
  76. ),
  77. { timeout: 30000, timeoutMsg: "关闭后 selection side tab 仍存在" },
  78. );
  79. // 关闭最后一个标签会收起右侧面板;宽度动画持续触发时间线 scroll,scroll 会关闭选区浮层。
  80. // 等实际面板收至零宽后再划词,不能把 tab DOM 消失当作布局已稳定。
  81. await browser.waitUntil(
  82. () =>
  83. browser.execute(() => {
  84. const panel = document.querySelector('[data-workspace-side-frame="true"]')?.parentElement;
  85. return !panel || panel.getBoundingClientRect().width === 0;
  86. }),
  87. { timeout: 10000, timeoutMsg: "关闭最后一个辅助 tab 后面板没有收起" },
  88. );
  89. await selectMainTimelineText(PARENT_MARKER);
  90. await clickSelectionAction("ask-in-side-chat");
  91. const recreatedSide = await waitForSelectionSidePane();
  92. expect(recreatedSide.childSessionId).not.toBe(firstSide.childSessionId);
  93. await clickAddSelectionSideConversation();
  94. await waitForSelectionSidePanes(2);
  95. await clickAddSelectionSideConversation();
  96. const threeSides = await waitForSelectionSidePanes(3);
  97. expect(new Set(threeSides.map((side) => side.childSessionId)).size).toBe(3);
  98. expect(threeSides.map((side) => side.title)).toEqual([
  99. "辅助对话 1",
  100. "辅助对话 2",
  101. "辅助对话 3",
  102. ]);
  103. await activateSidePaneTab(recreatedSide.tabId);
  104. await selectMainTimelineText("E2E_SSC_PARENT");
  105. await clickSelectionAction("ask-in-side-chat");
  106. await expectComposerState(recreatedSide.paneTestId, "", 2);
  107. for (const side of threeSides.filter(
  108. (candidate) => candidate.childSessionId !== recreatedSide.childSessionId,
  109. )) {
  110. await expectNoSelectionReferences(side.paneTestId);
  111. }
  112. const siblingSides = threeSides.filter(
  113. (candidate) => candidate.childSessionId !== recreatedSide.childSessionId,
  114. );
  115. const sideToClose = siblingSides[0];
  116. const survivingSibling = siblingSides[1];
  117. if (!sideToClose || !survivingSibling) {
  118. throw new Error("multi-open sibling side panes missing");
  119. }
  120. // 隐藏 tab 的输入框不可交互;先走真实切换,再验证关闭另一个 tab 不丢草稿。
  121. await activateSidePaneTab(survivingSibling.tabId);
  122. await setComposerText(survivingSibling.paneTestId, "E2E_SSC_SIBLING_DRAFT");
  123. await closeSelectionSideTab(sideToClose.tabId);
  124. const remainingSides = await waitForSelectionSidePanes(2);
  125. expect(
  126. remainingSides.some((candidate) => candidate.childSessionId === sideToClose.childSessionId),
  127. ).toBe(false);
  128. await expectComposerText(survivingSibling.paneTestId, "E2E_SSC_SIBLING_DRAFT");
  129. await expectNoSelectionReferences(survivingSibling.paneTestId);
  130. await clickAddSidePaneItem("terminal");
  131. await waitForActiveSidePaneTab("terminal:");
  132. await selectMainTimelineText(PARENT_MARKER);
  133. await clickSelectionAction("ask-in-side-chat");
  134. const afterNoActiveAuxiliary = await waitForSelectionSidePanes(3);
  135. const remainingChildIds = new Set(remainingSides.map((side) => side.childSessionId));
  136. const createdForSelection = afterNoActiveAuxiliary.find(
  137. (side) => !remainingChildIds.has(side.childSessionId),
  138. );
  139. expect(createdForSelection).toBeDefined();
  140. if (!createdForSelection) {
  141. throw new Error("selection did not create a new auxiliary child");
  142. }
  143. await expectComposerState(createdForSelection.paneTestId, "", 1);
  144. // SSC28:/side 与 /btw App 层命令选中即开新辅助 tab,并移除输入中的命令 token。
  145. const mainPaneTestId = testId(TID_V4_SESSION_PANE, "workspace-main");
  146. const sidesBeforeSlashCommand = await waitForSelectionSidePanes(3);
  147. const knownChildIds = new Set(sidesBeforeSlashCommand.map((side) => side.childSessionId));
  148. await typeIntoComposerByKeyboard(mainPaneTestId, "/side");
  149. await clickSlashSuggestionOption("app-slash:side");
  150. const afterSideCommand = await waitForSelectionSidePanes(4);
  151. const sideCommandChild = afterSideCommand.find(
  152. (side) => !knownChildIds.has(side.childSessionId),
  153. );
  154. expect(sideCommandChild).toBeDefined();
  155. await expectComposerPlainText(mainPaneTestId, "");
  156. await typeIntoComposerByKeyboard(mainPaneTestId, "/btw");
  157. await clickSlashSuggestionOption("app-slash:btw");
  158. await waitForSelectionSidePanes(5);
  159. await expectComposerPlainText(mainPaneTestId, "");
  160. // SSC30:带参数的 `/side` 直接创建 child,并把参数作为首条普通输入提交。
  161. const childrenBeforeArgument = await waitForSelectionSidePanes(5);
  162. const childrenBeforeArgumentIds = new Set(
  163. childrenBeforeArgument.map((side) => side.childSessionId),
  164. );
  165. await setComposerText(mainPaneTestId, "/side E2E_SSC_SIDE_ARGUMENT_IDLE");
  166. await clickComposerSend(mainPaneTestId);
  167. const idleArgumentChildren = await waitForSelectionSidePanes(6);
  168. const idleArgumentChild = idleArgumentChildren.find(
  169. (side) => !childrenBeforeArgumentIds.has(side.childSessionId),
  170. );
  171. expect(idleArgumentChild).toBeDefined();
  172. if (!idleArgumentChild) throw new Error("带参数 /side 没有创建 child");
  173. await waitForSelectionSidePaneContaining(
  174. idleArgumentChild.paneTestId,
  175. "E2E_SSC_SIDE_ARGUMENT_IDLE",
  176. );
  177. await expectComposerPlainText(mainPaneTestId, "");
  178. // SSC31:父会话启动新 turn 后立即发送 `/btw <text>`,参数命令只启动 child,
  179. // 不把父会话当前 turn 改成 queue/guide。
  180. await setComposerText(mainPaneTestId, "Reply with exactly E2E_SSC_RUNNING_PARENT");
  181. await clickComposerSend(mainPaneTestId);
  182. await waitForV4ConversationState(
  183. // V4 运行态来自可见 Stop projection,不依赖旧 store 的 activeInputId 镜像。
  184. (state) => state.state === "streaming",
  185. "SSC31 父轮没有实际运行",
  186. );
  187. const childrenBeforeRunningArgument = await waitForSelectionSidePanes(6);
  188. const childrenBeforeRunningArgumentIds = new Set(
  189. childrenBeforeRunningArgument.map((side) => side.childSessionId),
  190. );
  191. await setComposerText(mainPaneTestId, "/btw E2E_SSC_SIDE_ARGUMENT_RUNNING");
  192. await clickComposerSend(mainPaneTestId);
  193. const runningArgumentChildren = await waitForSelectionSidePanes(7);
  194. const runningArgumentChild = runningArgumentChildren.find(
  195. (side) => !childrenBeforeRunningArgumentIds.has(side.childSessionId),
  196. );
  197. expect(runningArgumentChild).toBeDefined();
  198. if (!runningArgumentChild) throw new Error("运行中带参数 /btw 没有创建 child");
  199. await waitForSelectionSidePaneContaining(
  200. runningArgumentChild.paneTestId,
  201. "E2E_SSC_SIDE_ARGUMENT_RUNNING",
  202. );
  203. await expectComposerPlainText(mainPaneTestId, "");
  204. // SSC29:辅助对话自身 composer 的 `/` 面板不提供 /side、/btw,CLI 命令展示不受影响。
  205. const activeSideAfterBtw = await waitForActiveSelectionSidePane();
  206. await typeIntoComposerByKeyboard(activeSideAfterBtw.paneTestId, "/");
  207. await expectSlashPanelWithoutSideCommands();
  208. await dismissSlashPanel(activeSideAfterBtw.paneTestId);
  209. // SSC29:草稿态(未创建 session)不提供 /side、/btw。
  210. await openNewTaskDraft();
  211. await typeIntoComposerByKeyboard(mainPaneTestId, "/");
  212. await expectSlashPanelWithoutSideCommands();
  213. await dismissSlashPanel(mainPaneTestId);
  214. });
  215. });
  216. async function selectMainTimelineText(text: string): Promise<void> {
  217. const paneTestId = testId(TID_V4_SESSION_PANE, "workspace-main");
  218. await browser.execute(() => {
  219. const state = window as Window & { __selectionTrace?: { events: unknown[]; stop(): void } };
  220. state.__selectionTrace?.stop();
  221. const events: unknown[] = [];
  222. const types = ["mousedown", "mouseup", "selectionchange", "scroll", "resize", "focusin"];
  223. const listener = (event: Event) => {
  224. const selection = window.getSelection();
  225. events.push({
  226. type: event.type,
  227. time: performance.now(),
  228. text: selection?.toString(),
  229. target: (event.target as Element)?.getAttribute?.("data-testid"),
  230. anchor: selection?.anchorNode?.parentElement
  231. ?.closest("[data-row-id]")
  232. ?.getAttribute("data-row-id"),
  233. focused: document.activeElement?.getAttribute("data-testid"),
  234. tooltip: Boolean(document.querySelector("[data-conversation-selection-tooltip]")),
  235. });
  236. };
  237. for (const type of types) window.addEventListener(type, listener, true);
  238. state.__selectionTrace = {
  239. events,
  240. stop: () => {
  241. for (const type of types) window.removeEventListener(type, listener, true);
  242. },
  243. };
  244. });
  245. // 上一次引用动作可能保留选区;在旧选区上拖动会变成 HTML 拖放,而不是重新划词。
  246. await browser.execute(() => window.getSelection()?.removeAllRanges());
  247. // 旧 helper 直接改 DOM Range,再重试 mouseup;它绕过了原生选区与 pane 焦点更新。
  248. // 这里只读取文本坐标,交互由真实 pointer drag 完成;滚动先于 pointerdown。
  249. const locator = (id: string, targetText: string, scroll: boolean) => {
  250. const pane = document.querySelector<HTMLElement>(`[data-testid="${id}"]`);
  251. if (!pane) throw new Error("缺少主 pane");
  252. const walker = document.createTreeWalker(pane, NodeFilter.SHOW_TEXT);
  253. let found: { node: Node; offset: number } | null = null;
  254. for (let node = walker.nextNode(); node; node = walker.nextNode()) {
  255. const value = node.textContent ?? "";
  256. const offset = value.indexOf(targetText);
  257. if (offset < 0 || !node.parentElement?.closest("[data-row-id]")) continue;
  258. found ??= { node, offset };
  259. if (value.trim() === targetText) {
  260. found = { node, offset };
  261. break;
  262. }
  263. }
  264. if (!found) throw new Error(`主时间线缺少选区文本: ${targetText}`);
  265. if (scroll) found.node.parentElement?.scrollIntoView({ block: "center", behavior: "instant" });
  266. const range = document.createRange();
  267. range.setStart(found.node, found.offset);
  268. range.setEnd(found.node, found.offset + 1);
  269. const first = range.getBoundingClientRect();
  270. range.setStart(found.node, found.offset + targetText.length - 1);
  271. range.setEnd(found.node, found.offset + targetText.length);
  272. const last = range.getBoundingClientRect();
  273. return {
  274. x1: Math.ceil(first.left),
  275. y1: Math.round(first.top + first.height / 2),
  276. x2: Math.floor(last.right),
  277. y2: Math.round(last.top + last.height / 2),
  278. };
  279. };
  280. const readLayoutTransitions = (id: string): string[] => {
  281. const pane = document.querySelector<HTMLElement>(`[data-testid="${id}"]`);
  282. if (!pane) return ["missing-pane"];
  283. return document.getAnimations().flatMap((animation) => {
  284. if (!(animation instanceof CSSTransition) || animation.playState !== "running") return [];
  285. if (!["width", "max-width", "height", "transform"].includes(animation.transitionProperty))
  286. return [];
  287. const target = (animation.effect as KeyframeEffect | null)?.target;
  288. return target instanceof Element && (pane.contains(target) || target.contains(pane))
  289. ? [animation.transitionProperty]
  290. : [];
  291. });
  292. };
  293. // 辅助面板收起后,主列还会跨断点做宽度过渡;动态测高会把文字再滚动 59px。
  294. // 等实际布局过渡结束后才取坐标,避免用旧坐标拖选相邻行。
  295. await browser.waitUntil(
  296. async () => (await browser.execute(readLayoutTransitions, paneTestId)).length === 0,
  297. { timeout: 10000, timeoutMsg: "主时间线布局过渡未结束,不能开始原生划词" },
  298. );
  299. await browser.execute(locator, paneTestId, text, true);
  300. const position = await browser.execute(locator, paneTestId, text, false);
  301. expect(await browser.execute(readLayoutTransitions, paneTestId)).toEqual([]);
  302. await browser.performActions([
  303. {
  304. type: "pointer",
  305. id: "selection-drag",
  306. parameters: { pointerType: "mouse" },
  307. actions: [
  308. { type: "pointerMove", x: position.x1, y: position.y1, duration: 0 },
  309. { type: "pointerDown", button: 0 },
  310. { type: "pointerMove", x: position.x2, y: position.y2, duration: 200 },
  311. { type: "pointerUp", button: 0 },
  312. ],
  313. },
  314. ]);
  315. await browser.releaseActions();
  316. try {
  317. await browser.waitUntil(
  318. () => browser.execute((expected) => window.getSelection()?.toString() === expected, text),
  319. { timeout: 5000, timeoutMsg: `真实拖选未选中目标文本: ${text}` },
  320. );
  321. await $("[data-conversation-selection-tooltip]").waitForDisplayed({ timeout: 5000 });
  322. } catch (error) {
  323. const events = await browser.execute(
  324. () =>
  325. (window as Window & { __selectionTrace?: { events: unknown[] } }).__selectionTrace?.events,
  326. );
  327. await writeFile(
  328. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "selection-events.json"),
  329. JSON.stringify(
  330. {
  331. text,
  332. position,
  333. currentPosition: await browser.execute(locator, paneTestId, text, false),
  334. events,
  335. },
  336. null,
  337. 2,
  338. ),
  339. );
  340. throw error;
  341. } finally {
  342. await browser.execute(() =>
  343. (window as Window & { __selectionTrace?: { stop(): void } }).__selectionTrace?.stop(),
  344. );
  345. }
  346. }
  347. async function waitForSelectableMainTimelineText(text: string, timeout: number): Promise<void> {
  348. await browser.waitUntil(
  349. async () =>
  350. browser.execute(
  351. (paneTestId, targetText) => {
  352. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  353. if (!pane) return false;
  354. const walker = document.createTreeWalker(pane, NodeFilter.SHOW_TEXT);
  355. let node = walker.nextNode();
  356. while (node) {
  357. if (
  358. node.textContent?.trim() === targetText &&
  359. node.parentElement?.closest("[data-row-id]")
  360. ) {
  361. return true;
  362. }
  363. node = walker.nextNode();
  364. }
  365. return false;
  366. },
  367. testId(TID_V4_SESSION_PANE, "workspace-main"),
  368. text,
  369. ),
  370. {
  371. timeout,
  372. timeoutMsg: `主时间线没有出现可选文本: ${text}`,
  373. },
  374. );
  375. }
  376. async function clickSelectionAction(action: "add-to-task" | "ask-in-side-chat"): Promise<void> {
  377. // 修复原因:浮层在 selectionchange/rAF 中可能短暂重挂载;"先检查后点击"两次往返之间
  378. // 按钮会消失一瞬导致 flake。这里把检查与点击合成单个原子脚本并整体重试。
  379. await browser.waitUntil(
  380. async () =>
  381. browser.execute((nextAction) => {
  382. const button = document.querySelector<HTMLButtonElement>(
  383. `[data-conversation-selection-action="${nextAction}"]`,
  384. );
  385. if (!button || button.disabled) return false;
  386. button.click();
  387. return true;
  388. }, action),
  389. {
  390. timeout: 30000,
  391. timeoutMsg: `划词动作不可用: ${action}`,
  392. },
  393. );
  394. }
  395. async function waitForSelectionSidePane(): Promise<{
  396. childSessionId: string;
  397. paneTestId: string;
  398. tabId: string;
  399. }> {
  400. let result: { childSessionId: string; paneTestId: string; tabId: string } | null = null;
  401. await browser.waitUntil(
  402. async () => {
  403. result = await browser.execute((panePrefix) => {
  404. const tab = document.querySelector<HTMLElement>(
  405. '[data-side-pane-tab-id^="selection-side-chat:"]',
  406. );
  407. const tabId = tab?.dataset.sidePaneTabId;
  408. if (!tabId) return null;
  409. const paneTestId = `${panePrefix}-${tabId}`;
  410. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  411. const childSessionId = pane?.dataset.sessionId;
  412. return childSessionId ? { childSessionId, paneTestId, tabId } : null;
  413. }, TID_V4_SESSION_PANE);
  414. return result !== null;
  415. },
  416. { timeout: 30000, timeoutMsg: "selection side pane 没有打开" },
  417. );
  418. if (!result) throw new Error("selection side pane result missing");
  419. return result;
  420. }
  421. async function waitForSelectionSidePanes(expectedCount: number): Promise<
  422. Array<{
  423. childSessionId: string;
  424. paneTestId: string;
  425. tabId: string;
  426. title: string;
  427. }>
  428. > {
  429. let result: Array<{
  430. childSessionId: string;
  431. paneTestId: string;
  432. tabId: string;
  433. title: string;
  434. }> = [];
  435. await browser.waitUntil(
  436. async () => {
  437. result = await browser.execute(
  438. (panePrefix) =>
  439. Array.from(
  440. document.querySelectorAll<HTMLElement>(
  441. '[data-side-pane-tab-id^="selection-side-chat:"]',
  442. ),
  443. ).flatMap((tab) => {
  444. const tabId = tab.dataset.sidePaneTabId;
  445. if (!tabId) return [];
  446. const paneTestId = `${panePrefix}-${tabId}`;
  447. const pane = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`);
  448. const childSessionId = pane?.dataset.sessionId;
  449. return childSessionId
  450. ? [{ childSessionId, paneTestId, tabId, title: tab.innerText.trim() }]
  451. : [];
  452. }),
  453. TID_V4_SESSION_PANE,
  454. );
  455. return result.length === expectedCount;
  456. },
  457. {
  458. timeout: 30000,
  459. timeoutMsg: `selection side pane 数量不是 ${expectedCount}`,
  460. },
  461. );
  462. return result;
  463. }
  464. async function clickAddSelectionSideConversation(): Promise<void> {
  465. await clickAddSidePaneItem("selection-side-conversation");
  466. }
  467. async function clickAddSidePaneItem(
  468. itemId: "selection-side-conversation" | "terminal",
  469. ): Promise<void> {
  470. // 修复原因:Radix DropdownMenu trigger 依赖 pointerdown 手势,element.click()
  471. // 或单独的 WebDriver click 在 Electron 下不稳定;与 e2ecase-regression 同口径,
  472. // 派发完整 pointer/mouse/click 事件序列激活 trigger 与 menu item。
  473. const dispatchActivationScript = (selector: string) => {
  474. const target = document.querySelector<HTMLElement>(selector);
  475. if (!target) return false;
  476. target.scrollIntoView({ block: "center", inline: "nearest" });
  477. target.focus();
  478. for (const type of ["pointerdown", "mousedown", "pointerup", "mouseup", "click"]) {
  479. const event = type.startsWith("pointer")
  480. ? new PointerEvent(type, {
  481. bubbles: true,
  482. cancelable: true,
  483. button: 0,
  484. pointerId: 1,
  485. pointerType: "mouse",
  486. isPrimary: true,
  487. })
  488. : new MouseEvent(type, { bubbles: true, cancelable: true, button: 0 });
  489. target.dispatchEvent(event);
  490. }
  491. return true;
  492. };
  493. await browser.waitUntil(
  494. async () => browser.execute(dispatchActivationScript, "[data-side-pane-add-trigger]"),
  495. { timeout: 15000, timeoutMsg: "Side Pane 新增标签按钮不存在" },
  496. );
  497. const itemSelector = `[data-state="active"] [data-side-pane-open-tab-item="${itemId}"]`;
  498. await browser.waitUntil(
  499. async () =>
  500. browser.execute((selector) => Boolean(document.querySelector(selector)), itemSelector),
  501. { timeout: 15000, timeoutMsg: `${itemId} 新增菜单没有打开` },
  502. );
  503. const clicked = await browser.execute(dispatchActivationScript, itemSelector);
  504. expect(clicked).toBe(true);
  505. }
  506. async function waitForActiveSidePaneTab(idPrefix: string): Promise<void> {
  507. await browser.waitUntil(
  508. async () =>
  509. browser.execute((nextIdPrefix) => {
  510. const activeTab = document.querySelector<HTMLElement>(
  511. '[data-side-pane-tab-id][data-state="active"]',
  512. );
  513. return activeTab?.dataset.sidePaneTabId?.startsWith(nextIdPrefix) ?? false;
  514. }, idPrefix),
  515. {
  516. timeout: 30000,
  517. timeoutMsg: `Side Pane active tab 不是 ${idPrefix}`,
  518. },
  519. );
  520. }
  521. async function activateSidePaneTab(tabId: string): Promise<void> {
  522. const clicked = await browser.execute((targetTabId) => {
  523. const tab = document.querySelector<HTMLElement>(
  524. `[data-side-pane-tab-id="${CSS.escape(targetTabId)}"]`,
  525. );
  526. tab?.click();
  527. return Boolean(tab);
  528. }, tabId);
  529. expect(clicked).toBe(true);
  530. }
  531. async function setComposerText(paneTestId: string, text: string): Promise<void> {
  532. // 多 pane 共用 testid 时单点 Lexical bridge 可能不在目标输入上;通过真实键盘输入。
  533. await clearComposerByKeyboard(paneTestId);
  534. await browser.keys(text.split(""));
  535. await expectComposerPlainText(paneTestId, text);
  536. }
  537. async function expectComposerState(
  538. paneTestId: string,
  539. text: string,
  540. referenceCount: number,
  541. ): Promise<void> {
  542. await browser.waitUntil(
  543. async () =>
  544. browser.execute(
  545. (nextPaneTestId, inputTestId, expectedText, expectedReferenceCount) => {
  546. const pane = document.querySelector<HTMLElement>(`[data-testid="${nextPaneTestId}"]`);
  547. const input = pane?.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  548. return (
  549. (input?.textContent ?? "").trim() === expectedText &&
  550. pane?.querySelector(
  551. `[data-conversation-selection-reference-count="${expectedReferenceCount}"]`,
  552. ) !== null
  553. );
  554. },
  555. paneTestId,
  556. TID_V4_COMPOSER_INPUT,
  557. text,
  558. referenceCount,
  559. ),
  560. {
  561. timeout: 15000,
  562. timeoutMsg: `composer 草稿或引用数量不匹配: ${paneTestId}`,
  563. },
  564. );
  565. }
  566. async function expectNoSelectionReferences(paneTestId: string): Promise<void> {
  567. await browser.waitUntil(
  568. async () =>
  569. browser.execute((nextPaneTestId) => {
  570. const pane = document.querySelector<HTMLElement>(`[data-testid="${nextPaneTestId}"]`);
  571. return (
  572. pane !== null &&
  573. pane.querySelector("[data-conversation-selection-reference-count]") === null
  574. );
  575. }, paneTestId),
  576. {
  577. timeout: 15000,
  578. timeoutMsg: `非目标辅助对话出现了划词引用: ${paneTestId}`,
  579. },
  580. );
  581. }
  582. async function expectComposerText(paneTestId: string, text: string): Promise<void> {
  583. await browser.waitUntil(
  584. async () =>
  585. browser.execute(
  586. (nextPaneTestId, inputTestId, expectedText) => {
  587. const pane = document.querySelector<HTMLElement>(`[data-testid="${nextPaneTestId}"]`);
  588. const input = pane?.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  589. return (
  590. (
  591. input as
  592. | (HTMLElement & {
  593. __zcodeLexicalInputE2E?: { getText: () => string };
  594. })
  595. | undefined
  596. )?.__zcodeLexicalInputE2E?.getText() === expectedText
  597. );
  598. },
  599. paneTestId,
  600. TID_V4_COMPOSER_INPUT,
  601. text,
  602. ),
  603. {
  604. timeout: 15000,
  605. timeoutMsg: `composer 草稿不匹配: ${paneTestId}`,
  606. },
  607. );
  608. }
  609. async function clickComposerSend(paneTestId: string): Promise<void> {
  610. const clicked = await browser.execute(
  611. (nextPaneTestId, sendTestId) => {
  612. const pane = document.querySelector<HTMLElement>(`[data-testid="${nextPaneTestId}"]`);
  613. const button = pane?.querySelector<HTMLButtonElement>(`[data-testid="${sendTestId}"]`);
  614. if (!button || button.disabled) return false;
  615. button.click();
  616. return true;
  617. },
  618. paneTestId,
  619. TID_V4_COMPOSER_SEND,
  620. );
  621. expect(clicked).toBe(true);
  622. }
  623. async function waitForActiveSelectionSidePane(): Promise<{
  624. childSessionId: string;
  625. paneTestId: string;
  626. tabId: string;
  627. }> {
  628. let result: { childSessionId: string; paneTestId: string; tabId: string } | null = null;
  629. await browser.waitUntil(
  630. async () => {
  631. result = await browser.execute((panePrefix) => {
  632. const tab = document.querySelector<HTMLElement>(
  633. '[data-side-pane-tab-id^="selection-side-chat:"][data-state="active"]',
  634. );
  635. const tabId = tab?.dataset.sidePaneTabId;
  636. if (!tabId) return null;
  637. const paneTestId = `${panePrefix}-${tabId}`;
  638. const childSessionId = document.querySelector<HTMLElement>(`[data-testid="${paneTestId}"]`)
  639. ?.dataset.sessionId;
  640. return childSessionId ? { childSessionId, paneTestId, tabId } : null;
  641. }, TID_V4_SESSION_PANE);
  642. return result !== null;
  643. },
  644. { timeout: 30000, timeoutMsg: "没有 active 的 selection side pane" },
  645. );
  646. if (!result) throw new Error("active selection side pane missing");
  647. return result;
  648. }
  649. async function waitForSelectionSidePaneContaining(
  650. paneTestId: string,
  651. marker: string,
  652. ): Promise<void> {
  653. await browser.waitUntil(
  654. async () =>
  655. browser.execute(
  656. (nextPaneTestId, nextMarker) =>
  657. document
  658. .querySelector<HTMLElement>(`[data-testid="${nextPaneTestId}"]`)
  659. ?.innerText.includes(nextMarker) ?? false,
  660. paneTestId,
  661. marker,
  662. ),
  663. { timeout: 60000, timeoutMsg: `selection side pane 没有出现 ${marker}` },
  664. );
  665. }
  666. /** 斜杠面板由真实键盘事件触发,输入一次后等待可见正文收敛。 */
  667. async function typeIntoComposerByKeyboard(paneTestId: string, text: string): Promise<void> {
  668. await setComposerText(paneTestId, text);
  669. }
  670. /** 不依赖 bridge 的清空:全选 + Backspace(真实键序,Lexical 正常处理)。 */
  671. async function clearComposerByKeyboard(paneTestId: string): Promise<void> {
  672. const inputSelector = `[data-testid="${paneTestId}"] [data-testid="${TID_V4_COMPOSER_INPUT}"]`;
  673. const input = $(inputSelector);
  674. await input.waitForClickable({ timeout: 15000 });
  675. await input.click();
  676. const modifier = process.platform === "darwin" ? "Meta" : "Control";
  677. await browser.keys([modifier, "a"]);
  678. await browser.keys("Backspace");
  679. await browser.waitUntil(
  680. async () =>
  681. browser.execute(
  682. (selector) =>
  683. (document.querySelector<HTMLElement>(selector)?.textContent ?? "").trim() === "",
  684. inputSelector,
  685. ),
  686. { timeout: 10000, timeoutMsg: `composer 清空失败: ${paneTestId}` },
  687. );
  688. }
  689. /** 不依赖 bridge 的 composer 文本断言(bridge 在多 composer 场景可能脱落)。 */
  690. async function expectComposerPlainText(paneTestId: string, text: string): Promise<void> {
  691. const inputSelector = `[data-testid="${paneTestId}"] [data-testid="${TID_V4_COMPOSER_INPUT}"]`;
  692. await browser.waitUntil(
  693. async () =>
  694. browser.execute(
  695. (selector, expectedText) =>
  696. (document.querySelector<HTMLElement>(selector)?.textContent ?? "").trim() ===
  697. expectedText,
  698. inputSelector,
  699. text,
  700. ),
  701. { timeout: 15000, timeoutMsg: `composer 文本不匹配: ${paneTestId}` },
  702. );
  703. }
  704. async function clickSlashSuggestionOption(optionId: string): Promise<void> {
  705. // 修复原因:面板可能因编辑器失焦(新辅助 tab autofocus)瞬时关闭;"先查后点"两次
  706. // 往返之间选项会消失。这里把查找与 mousedown 合成单个原子脚本并整体重试。
  707. // MentionPanel 选项在 onMouseDown 触发 onSelect,element.click() 不会命中。
  708. await browser.waitUntil(
  709. async () =>
  710. browser.execute((nextOptionId) => {
  711. const option = document.querySelector<HTMLButtonElement>(
  712. `[data-option-id="${CSS.escape(nextOptionId)}"]`,
  713. );
  714. if (!option) return false;
  715. option.dispatchEvent(
  716. new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }),
  717. );
  718. return true;
  719. }, optionId),
  720. { timeout: 15000, timeoutMsg: `斜杠面板没有出现选项: ${optionId}` },
  721. );
  722. }
  723. async function expectSlashPanelWithoutSideCommands(): Promise<void> {
  724. await browser.waitUntil(
  725. async () =>
  726. browser.execute(
  727. (panelTestId) => Boolean(document.querySelector(`[data-testid="${panelTestId}"]`)),
  728. TID_PROMPT_SUGGESTION_PANEL,
  729. ),
  730. { timeout: 15000, timeoutMsg: "斜杠面板没有打开" },
  731. );
  732. // SSC29 只限制辅助对话入口;/plan 等后续加入的合法 App 命令不在禁止范围。
  733. const appCommands = await browser.execute(() =>
  734. [...document.querySelectorAll('[data-option-id^="app-slash:"]')].map((node) =>
  735. node.getAttribute("data-option-id"),
  736. ),
  737. );
  738. expect(appCommands).not.toContain("app-slash:side");
  739. expect(appCommands).not.toContain("app-slash:btw");
  740. }
  741. async function dismissSlashPanel(paneTestId: string): Promise<void> {
  742. await browser.keys("Escape");
  743. await clearComposerByKeyboard(paneTestId);
  744. }
  745. async function openNewTaskDraft(): Promise<void> {
  746. await startDraftFromProject(DEFAULT_WORKSPACE);
  747. await waitForV4ConversationState(
  748. (state) => state.sessionId === null && state.taskId === null,
  749. "项目没有进入空草稿",
  750. );
  751. }
  752. async function closeSelectionSideTab(tabId?: string): Promise<void> {
  753. const clicked = await browser.execute((targetTabId) => {
  754. const tab = document.querySelector<HTMLElement>(
  755. targetTabId
  756. ? `[data-side-pane-tab-id="${CSS.escape(targetTabId)}"]`
  757. : '[data-side-pane-tab-id^="selection-side-chat:"]',
  758. );
  759. const button = tab?.querySelector<HTMLButtonElement>("button");
  760. button?.click();
  761. return Boolean(button);
  762. }, tabId);
  763. expect(clicked).toBe(true);
  764. }