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

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