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

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