conversation-session-selection-streaming.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. import { join } from "node:path";
  2. import { clearAppData, pinE2ELocale } from "#e2e/helpers/desktop-app";
  3. import {
  4. clickSelectionAction,
  5. dragSelectMainTimelineRange,
  6. dragSelectMainTimelineText,
  7. readMainComposerSelectionChip,
  8. readMainTimelineAnnotationMarks,
  9. typeSelectionComment,
  10. } from "#e2e/helpers/conversation-selection-comment";
  11. import {
  12. countUpstreamRequests,
  13. waitForUpstreamRequest,
  14. } from "#e2e/helpers/conversation-session-network";
  15. import { ensureReadonlyToolFixtureFile } from "#e2e/helpers/conversation-session-readonly-tool";
  16. import {
  17. getV4PaneSnapshot,
  18. prepareV4ConversationE2E,
  19. selectV4TaskById,
  20. sendV4Prompt,
  21. startNewV4Draft,
  22. waitForV4AssistantMessageContaining,
  23. waitForV4ConversationState,
  24. } from "#e2e/helpers/v4-conversation";
  25. const artifacts = () => process.env.ZCODE_E2E_ARTIFACT_DIR!;
  26. const HISTORY_PARA = "E2E_SCS_HISTORY_PARA";
  27. const LIVE_PARA = "E2E_SCS_LIVE_PARA";
  28. const COMMENT = "E2E_SCS_COMMENT";
  29. const CROSS_START = "E2E_SCS_CROSS_START";
  30. const CROSS_END = "E2E_SCS_CROSS_END";
  31. const MIX_START = "E2E_SCS_MIX_START";
  32. const MIX_END = "E2E_SCS_MIX_END";
  33. const MATH_START = "E2E_SCS_MATH_START";
  34. const MATH_END = "E2E_SCS_MATH_END";
  35. const line = (index: number) => `E2E_SCS_LINE_${String(index).padStart(2, "0")}`;
  36. interface SelectionProbeEvent {
  37. at: number;
  38. type: string;
  39. detail?: string;
  40. }
  41. /** 记录输出过程中会影响选区的运行时事件:时间线滚动、选区变化、选区所在节点被替换、浮层增删。 */
  42. async function installSelectionProbe(): Promise<void> {
  43. await browser.execute(() => {
  44. const target = window as typeof window & { __scsProbe?: SelectionProbeEvent[] };
  45. if (target.__scsProbe) return;
  46. const events: SelectionProbeEvent[] = [];
  47. target.__scsProbe = events;
  48. const push = (type: string, detail?: string) => {
  49. if (events.length < 400) events.push({ at: Math.round(performance.now()), type, detail });
  50. };
  51. document.addEventListener(
  52. "scroll",
  53. (event) => {
  54. const element = event.target instanceof HTMLElement ? event.target : null;
  55. push(
  56. "scroll",
  57. `${element?.dataset.testid ?? element?.className.slice(0, 40)}@${element?.scrollTop}`,
  58. );
  59. },
  60. { capture: true, passive: true },
  61. );
  62. document.addEventListener("selectionchange", () => {
  63. const selection = window.getSelection();
  64. push(
  65. "selectionchange",
  66. selection?.isCollapsed ? "collapsed" : `len=${selection?.toString().length}`,
  67. );
  68. });
  69. window.addEventListener("resize", () => push("resize"));
  70. new MutationObserver((records) => {
  71. const anchor = window.getSelection()?.anchorNode ?? null;
  72. for (const record of records) {
  73. for (const node of record.removedNodes) {
  74. if (
  75. node instanceof HTMLElement &&
  76. node.hasAttribute("data-conversation-selection-tooltip")
  77. )
  78. push("tooltip-removed");
  79. else if (anchor && node.contains(anchor)) push("anchor-removed", node.nodeName);
  80. else if (node instanceof HTMLElement && node.querySelector("[data-row-id]"))
  81. push("row-container-removed", node.className.slice(0, 60));
  82. }
  83. for (const node of record.addedNodes) {
  84. if (
  85. node instanceof HTMLElement &&
  86. node.hasAttribute("data-conversation-selection-tooltip")
  87. )
  88. push("tooltip-added");
  89. }
  90. }
  91. }).observe(document.body, { childList: true, subtree: true });
  92. });
  93. }
  94. async function readSelectionProbe(): Promise<SelectionProbeEvent[]> {
  95. return browser.execute(
  96. () => (window as typeof window & { __scsProbe?: SelectionProbeEvent[] }).__scsProbe ?? [],
  97. );
  98. }
  99. /**
  100. * 当前选区文字;浮层底边到选区顶边的距离(浮层在选区上方时接近 8px)与两者中心的水平偏差,
  101. * 没有浮层时为 null;以及选区是否还在时间线可视范围内。
  102. */
  103. async function readSelectionState(): Promise<{
  104. text: string;
  105. tooltipGap: number | null;
  106. tooltipOffset: number | null;
  107. visible: boolean;
  108. }> {
  109. return browser.execute(() => {
  110. const selection = window.getSelection();
  111. const tooltip = document.querySelector("[data-conversation-selection-tooltip]");
  112. const range = selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
  113. const rect = range?.getBoundingClientRect() ?? null;
  114. const box = tooltip?.getBoundingClientRect() ?? null;
  115. const timeline = document.querySelector('[data-testid="v4-timeline"]')?.getBoundingClientRect();
  116. return {
  117. text: selection?.toString() ?? "",
  118. tooltipGap: box && rect ? Math.round(rect.top - box.bottom) : null,
  119. tooltipOffset:
  120. box && rect
  121. ? Math.round(Math.abs(box.left + box.width / 2 - (rect.left + rect.width / 2)))
  122. : null,
  123. visible: Boolean(
  124. rect && timeline && rect.bottom > timeline.top && rect.top < timeline.bottom,
  125. ),
  126. };
  127. });
  128. }
  129. /** 浮层正对选区:在选区上方约 8px、水平居中。 */
  130. function tooltipFollowsSelection(state: {
  131. tooltipGap: number | null;
  132. tooltipOffset: number | null;
  133. }) {
  134. return (
  135. state.tooltipGap !== null &&
  136. Math.abs(state.tooltipGap) <= 24 &&
  137. state.tooltipOffset !== null &&
  138. state.tooltipOffset <= 6
  139. );
  140. }
  141. /** 在时间线上滚动真实滚轮(正数向下)。 */
  142. async function wheelTimeline(deltaY: number): Promise<void> {
  143. await browser.performActions([
  144. {
  145. type: "wheel",
  146. id: "scs-wheel",
  147. actions: [{ type: "scroll", x: 700, y: 400, deltaX: 0, deltaY, duration: 50 }],
  148. },
  149. ]);
  150. await browser.releaseActions();
  151. }
  152. /** 用产品快捷键开关右侧面板(macOS ⌥⌘B,其他平台 Ctrl+Alt+B),等时间线宽度变化。 */
  153. async function toggleSidePane(): Promise<void> {
  154. const width = () =>
  155. browser.execute(
  156. () =>
  157. document.querySelector('[data-testid="v4-timeline"]')?.getBoundingClientRect().width ?? 0,
  158. );
  159. const before = await width();
  160. await browser.execute(() => {
  161. const mac = navigator.platform.startsWith("Mac");
  162. window.dispatchEvent(
  163. new KeyboardEvent("keydown", {
  164. key: "b",
  165. code: "KeyB",
  166. altKey: true,
  167. metaKey: mac,
  168. ctrlKey: !mac,
  169. bubbles: true,
  170. cancelable: true,
  171. }),
  172. );
  173. });
  174. await browser.waitUntil(async () => Math.abs((await width()) - before) > 40, {
  175. timeout: 10000,
  176. timeoutMsg: "右侧面板开关后时间线宽度没有变化",
  177. });
  178. // 面板展开有过渡动画,等宽度稳定。
  179. let last = -1;
  180. await browser.waitUntil(
  181. async () => {
  182. const current = await width();
  183. const stable = current === last;
  184. last = current;
  185. return stable;
  186. },
  187. { timeout: 5000, interval: 150 },
  188. );
  189. }
  190. interface Box {
  191. left: number;
  192. top: number;
  193. bottom: number;
  194. width: number;
  195. }
  196. /** 正文注释标记的几何:各段下划线、编号气泡、代码块与正文栏的位置。 */
  197. /** 把时间线里第一个代码块横向滚到指定位置,返回实际的 scrollLeft。 */
  198. async function scrollCodeBlock(left: number): Promise<number> {
  199. return browser.execute((target) => {
  200. const shadow = document.querySelector(
  201. '[data-v4-timeline-message-layer="true"] diffs-container',
  202. )?.shadowRoot;
  203. for (const element of shadow?.querySelectorAll<HTMLElement>("*") ?? []) {
  204. if (element.scrollWidth <= element.clientWidth + 10) continue;
  205. element.scrollLeft = target;
  206. if (target === 0 || element.scrollLeft > 0) return element.scrollLeft;
  207. }
  208. return -1;
  209. }, left);
  210. }
  211. async function readAnnotationGeometry(): Promise<{
  212. lines: Box[];
  213. number: Box;
  214. codeBlockTop: number;
  215. codeBlockBottom: number;
  216. codeBlockWidth: number;
  217. columnWidth: number;
  218. }> {
  219. return browser.execute(() => {
  220. const box = (element: Element) => {
  221. const rect = element.getBoundingClientRect();
  222. return {
  223. left: Math.round(rect.left),
  224. top: Math.round(rect.top),
  225. bottom: Math.round(rect.bottom),
  226. width: Math.round(rect.width),
  227. };
  228. };
  229. const overlay = document.querySelector("[data-conversation-annotation-marks]");
  230. const code = document.querySelector("[data-row-id] diffs-container");
  231. const number = overlay?.querySelector("[data-annotation-number-variant]");
  232. if (!overlay || !code || !number) throw new Error("缺少注释标记或代码块");
  233. // 代码正文在 Shadow DOM 里;向上找到带圆角的代码块外壳。
  234. const block = code.closest(".rounded-xl") ?? code;
  235. return {
  236. lines: Array.from(overlay.querySelectorAll("[data-annotation-mark] > div")).map(box),
  237. number: box(number),
  238. codeBlockTop: box(block).top,
  239. codeBlockBottom: box(block).bottom,
  240. codeBlockWidth: box(block).width,
  241. columnWidth: box(code.closest("[data-row-id]")!).width,
  242. };
  243. });
  244. }
  245. describe("选区注释 · 回答输出过程中 manual review", () => {
  246. after(async () => {
  247. await clearAppData();
  248. });
  249. it("SCM07-09、SCM11-13: 跨代码块、Markdown 混排与公式的标记位置;浮层随滚动、侧栏、切会话的表现;回答输出过程中框选,浮层保持到完成注释", async function () {
  250. this.timeout(240000);
  251. await prepareV4ConversationE2E();
  252. await pinE2ELocale("zh-CN");
  253. await ensureReadonlyToolFixtureFile();
  254. await sendV4Prompt("E2E_SCS_SEED: answer briefly");
  255. await waitForV4AssistantMessageContaining(HISTORY_PARA, 60000);
  256. await waitForV4ConversationState(
  257. (state) => state.state === "idle" && state.activeInputId === null,
  258. "第一轮回答没有完成",
  259. 60000,
  260. );
  261. // SCM08:选区从一段正文开始,跨过一整段正文和一个代码块,到下一段正文中间结束。
  262. await dragSelectMainTimelineRange(CROSS_START, CROSS_END);
  263. await clickSelectionAction("comment");
  264. await $("[data-conversation-selection-comment-input]").waitForDisplayed({ timeout: 5000 });
  265. await browser.saveScreenshot(join(artifacts(), "scm08-cross-block-pending.png"));
  266. const pending = await readAnnotationGeometry();
  267. // 正文划线已经标出原文,输入卡片不再重复显示原文。
  268. expect(await $("[data-conversation-selection-comment-editor]").getText()).not.toContain(
  269. CROSS_END,
  270. );
  271. await browser.keys("Enter");
  272. await $("[data-conversation-selection-comment-editor]").waitForDisplayed({ reverse: true });
  273. await browser.waitUntil(
  274. async () =>
  275. JSON.stringify((await readMainTimelineAnnotationMarks()).map((mark) => mark.variant)) ===
  276. JSON.stringify(["quote"]),
  277. { timeout: 10000, timeoutMsg: "跨块注释保存后正文没有出现空心编号" },
  278. );
  279. await browser.saveScreenshot(join(artifacts(), "scm08-cross-block-saved.png"));
  280. const saved = await readAnnotationGeometry();
  281. for (const [label, geometry] of [
  282. ["输入时", pending],
  283. ["保存后", saved],
  284. ] as const) {
  285. const last = geometry.lines.at(-1);
  286. const inCode = (line: Box) =>
  287. line.top >= geometry.codeBlockTop && line.bottom <= geometry.codeBlockBottom;
  288. const problems = [
  289. // 三段正文各一条线,被跨过的代码块里三行有字的代码各一条线(空行不画),裁在代码块
  290. // 宽度内;代码块语言标签不画线,整段选中的段落也不多出撑满整行的线。
  291. geometry.lines.length === 6 ? null : "下划线不是 6 段",
  292. geometry.lines.every((line) => line.width < geometry.columnWidth * 0.6 || inCode(line))
  293. ? null
  294. : "有下划线撑满整行",
  295. geometry.lines.filter(inCode).length === 3 ? null : "代码块里应当正好三条线",
  296. geometry.lines.filter(inCode).every((line) => line.width <= geometry.codeBlockWidth)
  297. ? null
  298. : "代码块里的线超出了代码块",
  299. // 角标贴在末行右上方:探入文字行不超过 5px,大小 18px。
  300. last && geometry.number.bottom - last.top <= 5 && geometry.number.width === 18
  301. ? null
  302. : "角标压住了文字行或大小不对",
  303. ].filter(Boolean);
  304. if (problems.length > 0) {
  305. throw new Error(
  306. `${label}标记位置不对(${problems.join(";")}): ${JSON.stringify(geometry)}`,
  307. );
  308. }
  309. }
  310. await browser.execute(() => window.getSelection()?.removeAllRanges());
  311. // 代码块横向滚动后下划线跟着重算:滚动容器在 Shadow DOM 里,scroll 事件传不到外面。
  312. // 第一行很长,滚动后仍在可视范围内;后两行很短,滚出左边后不应再留线,滚回后恢复。
  313. const scrolled = await scrollCodeBlock(400);
  314. expect(scrolled).toBeGreaterThan(100);
  315. await browser.waitUntil(
  316. async () => {
  317. const geometry = await readAnnotationGeometry();
  318. return (
  319. geometry.lines.filter(
  320. (line) => line.top >= geometry.codeBlockTop && line.bottom <= geometry.codeBlockBottom,
  321. ).length === 1
  322. );
  323. },
  324. { timeout: 3000, timeoutMsg: "代码块横向滚动后,滚出可视范围的代码行还留着下划线" },
  325. );
  326. await browser.saveScreenshot(join(artifacts(), "scm08-code-scrolled.png"));
  327. await scrollCodeBlock(0);
  328. await browser.waitUntil(
  329. async () => {
  330. const geometry = await readAnnotationGeometry();
  331. return (
  332. geometry.lines.filter(
  333. (line) => line.top >= geometry.codeBlockTop && line.bottom <= geometry.codeBlockBottom,
  334. ).length === 3
  335. );
  336. },
  337. { timeout: 3000, timeoutMsg: "代码块滚回后代码行的下划线没有恢复" },
  338. );
  339. // SCM09:选区覆盖加粗、行内代码、有序列表和自动换行的列表项。
  340. await dragSelectMainTimelineRange(MIX_START, MIX_END);
  341. await clickSelectionAction("comment");
  342. await $("[data-conversation-selection-comment-input]").waitForDisplayed({ timeout: 5000 });
  343. await browser.keys("Enter");
  344. await $("[data-conversation-selection-comment-editor]").waitForDisplayed({ reverse: true });
  345. await browser.waitUntil(async () => (await readMainTimelineAnnotationMarks()).length === 2, {
  346. timeout: 10000,
  347. timeoutMsg: "Markdown 混排注释保存后正文没有出现第 2 个编号",
  348. });
  349. await browser.saveScreenshot(join(artifacts(), "scm09-markdown-mix-saved.png"));
  350. const mix = await browser.execute(
  351. (startText, endText) => {
  352. const overlay = document.querySelector("[data-conversation-annotation-marks]")!;
  353. const marks = Array.from(overlay.querySelectorAll("[data-annotation-mark]")).at(-1)!;
  354. const lines = Array.from(marks.querySelectorAll(":scope > div")).map((line) => {
  355. const rect = line.getBoundingClientRect();
  356. return { left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom };
  357. });
  358. // 期望:按选中文字本身的矩形数出视觉行,每行从第一个字到最后一个字。
  359. const row = Array.from(document.querySelectorAll<HTMLElement>("[data-row-id]")).find(
  360. (candidate) => candidate.textContent?.includes(startText),
  361. )!;
  362. const walker = document.createTreeWalker(row, NodeFilter.SHOW_TEXT);
  363. const rows: { left: number; right: number; top: number; bottom: number }[] = [];
  364. let inside = false;
  365. for (let node = walker.nextNode(); node; node = walker.nextNode()) {
  366. const value = node.textContent ?? "";
  367. const from = value.indexOf(startText);
  368. const to = value.indexOf(endText);
  369. if (!inside && from < 0) continue;
  370. inside = true;
  371. const range = document.createRange();
  372. range.setStart(node, from >= 0 ? from : 0);
  373. range.setEnd(node, to >= 0 ? to + endText.length : value.length);
  374. for (const rect of range.getClientRects()) {
  375. if (rect.width < 0.5) continue;
  376. const middle = (rect.top + rect.bottom) / 2;
  377. const hit = rows.find((item) => middle > item.top && middle < item.bottom);
  378. if (hit) {
  379. hit.left = Math.min(hit.left, rect.left);
  380. hit.right = Math.max(hit.right, rect.right);
  381. } else {
  382. rows.push({ left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom });
  383. }
  384. }
  385. if (to >= 0) break;
  386. }
  387. return { lines, rows };
  388. },
  389. MIX_START,
  390. MIX_END,
  391. );
  392. const round = (value: number) => Math.round(value);
  393. const mixProblems = [
  394. // 不断线、不双线:每个视觉行正好一条线。
  395. mix.lines.length === mix.rows.length
  396. ? null
  397. : `下划线 ${mix.lines.length} 段,文字 ${mix.rows.length} 行`,
  398. // 不缺线:每条线画到该行最后一个字;左端从第一个选中的字开始,
  399. // 列表项的首行(第 2、3、5 行)还要向左带上序号,与换行后的第 4 行左端对齐。
  400. ...mix.rows.map((row, index) => {
  401. const line = mix.lines.find(
  402. (item) =>
  403. (row.top + row.bottom) / 2 > item.top && (row.top + row.bottom) / 2 < item.bottom,
  404. );
  405. if (!line) return `第 ${index + 1} 行没有下划线`;
  406. const expectedLeft = [1, 2, 4].includes(index) ? mix.rows[3]!.left : row.left;
  407. return Math.abs(line.left - expectedLeft) <= 1.5 && Math.abs(line.right - row.right) <= 1.5
  408. ? null
  409. : `第 ${index + 1} 行下划线 ${round(line.left)}–${round(line.right)},应为 ${round(expectedLeft)}–${round(row.right)}`;
  410. }),
  411. ].filter(Boolean);
  412. if (mixProblems.length > 0) {
  413. throw new Error(
  414. `Markdown 混排的下划线不对(${mixProblems.join(";")}): ${JSON.stringify(mix)}`,
  415. );
  416. }
  417. // SCM11:选区含行内公式和独立公式。每个公式整体算一段,不能碎成一堆小线。
  418. await dragSelectMainTimelineRange(MATH_START, MATH_END);
  419. await clickSelectionAction("comment");
  420. await $("[data-conversation-selection-comment-input]").waitForDisplayed({ timeout: 5000 });
  421. await browser.keys("Enter");
  422. await $("[data-conversation-selection-comment-editor]").waitForDisplayed({ reverse: true });
  423. await browser.waitUntil(async () => (await readMainTimelineAnnotationMarks()).length === 3, {
  424. timeout: 10000,
  425. timeoutMsg: "公式注释保存后正文没有出现第 3 个编号",
  426. });
  427. await browser.saveScreenshot(join(artifacts(), "scm11-math-saved.png"));
  428. const mathLines = await browser.execute(() => {
  429. const overlay = document.querySelector("[data-conversation-annotation-marks]")!;
  430. const marks = Array.from(overlay.querySelectorAll("[data-annotation-mark]")).at(-1)!;
  431. return Array.from(marks.querySelectorAll(":scope > div")).map((line) => {
  432. const rect = line.getBoundingClientRect();
  433. return {
  434. top: Math.round(rect.top),
  435. bottom: Math.round(rect.bottom),
  436. width: Math.round(rect.width),
  437. };
  438. });
  439. });
  440. // 带行内公式的一行、独立公式、公式后的一行:正好三条线,互不重叠。
  441. const mathOverlap = mathLines.some((line, index) =>
  442. mathLines.some(
  443. (other, otherIndex) =>
  444. otherIndex > index && other.top < line.bottom && line.top < other.bottom,
  445. ),
  446. );
  447. // 独立公式(第 2 条)的线只有公式那么宽,不撑满整行。
  448. if (
  449. mathLines.length !== 3 ||
  450. mathOverlap ||
  451. mathLines.some((line) => line.width < 20) ||
  452. mathLines[1]!.width > 400
  453. ) {
  454. throw new Error(`公式处的下划线不对: ${JSON.stringify(mathLines)}`);
  455. }
  456. await browser.execute(() => window.getSelection()?.removeAllRanges());
  457. // SCM12:框选后浮层的位置与消失。
  458. await dragSelectMainTimelineText(HISTORY_PARA);
  459. expect(tooltipFollowsSelection(await readSelectionState())).toBe(true);
  460. // ① 滚到选区离开可视范围:浮层隐藏,选区还在;滚回来浮层重新出现并对准选区。
  461. await browser.waitUntil(
  462. async () => {
  463. if (!(await readSelectionState()).visible) return true;
  464. await wheelTimeline(240);
  465. return false;
  466. },
  467. { timeout: 15000, timeoutMsg: "滚轮没能把选区滚出可视范围" },
  468. );
  469. await browser.waitUntil(async () => (await readSelectionState()).tooltipGap === null, {
  470. timeout: 5000,
  471. timeoutMsg: "选区滚出可视范围后浮层没有隐藏",
  472. });
  473. expect((await readSelectionState()).text).toBe(HISTORY_PARA);
  474. await browser.waitUntil(
  475. async () => {
  476. const state = await readSelectionState();
  477. if (state.visible && tooltipFollowsSelection(state)) return true;
  478. if (!state.visible) await wheelTimeline(-240);
  479. return false;
  480. },
  481. { timeout: 15000, timeoutMsg: "选区滚回可视范围后浮层没有重新对准选区" },
  482. );
  483. await browser.saveScreenshot(join(artifacts(), "scm12-scrolled-back.png"));
  484. // SCM13:按 Esc 关掉浮层。选区还在,但之后的滚动不能把浮层弹回来。
  485. // (回答输出过程中按 Esc 会停止生成,所以在回答完成后用滚轮验证同一条规则。)
  486. await browser.keys("Escape");
  487. await $("[data-conversation-selection-tooltip]").waitForExist({ reverse: true, timeout: 3000 });
  488. for (const delta of [120, -120, 80, -80]) {
  489. await wheelTimeline(delta);
  490. await browser.pause(200);
  491. const state = await readSelectionState();
  492. if (state.tooltipGap !== null) {
  493. throw new Error(`按 Esc 关掉的浮层在滚动后又出现了: ${JSON.stringify(state)}`);
  494. }
  495. expect(state.text).toBe(HISTORY_PARA);
  496. }
  497. // 重新框选后浮层照常出现。
  498. await dragSelectMainTimelineText(HISTORY_PARA);
  499. expect(tooltipFollowsSelection(await readSelectionState())).toBe(true);
  500. // ② 打开右侧面板,时间线变窄、文字重排:选区还在时浮层必须跟到新位置,不能停在原地。
  501. await toggleSidePane();
  502. await browser.waitUntil(
  503. async () => {
  504. const state = await readSelectionState();
  505. return state.text === "" ? state.tooltipGap === null : tooltipFollowsSelection(state);
  506. },
  507. {
  508. timeout: 5000,
  509. timeoutMsg: `打开右侧面板后浮层没有跟随选区: ${JSON.stringify(await readSelectionState())}`,
  510. },
  511. );
  512. await browser.saveScreenshot(join(artifacts(), "scm12-side-pane-open.png"));
  513. await toggleSidePane();
  514. // ③ 切到别的会话再切回来:浮层不带到新会话,切回后也不留旧浮层。
  515. const sessionId = (await getV4PaneSnapshot()).sessionId!;
  516. await dragSelectMainTimelineText(HISTORY_PARA);
  517. await startNewV4Draft();
  518. expect(await $("[data-conversation-selection-tooltip]").isExisting()).toBe(false);
  519. await selectV4TaskById(sessionId);
  520. await waitForV4AssistantMessageContaining(HISTORY_PARA, 30000);
  521. const afterSwitch = await readSelectionState();
  522. expect(
  523. afterSwitch.text === ""
  524. ? afterSwitch.tooltipGap === null
  525. : tooltipFollowsSelection(afterSwitch),
  526. ).toBe(true);
  527. await browser.execute(() => window.getSelection()?.removeAllRanges());
  528. // 三条注释还在 composer 里。
  529. expect((await readMainComposerSelectionChip()).count).toBe(3);
  530. // SCM07:跨块注释随这条提问一起发出;回答分多步输出,期间框选并完成注释。
  531. await sendV4Prompt("E2E_SCS_STREAM: run the scripted steps");
  532. // 被跨过的代码块正文随引用发给模型(原先 Shadow DOM 里的代码不在选区文本里)。
  533. await waitForUpstreamRequest(
  534. // 代码紧跟在它上方那段正文之后,没有被插到别处。
  535. {
  536. lastUserMessageIncludes: [
  537. "E2E_SCS_STREAM",
  538. CROSS_END,
  539. // 引用以 JSON 形式嵌在消息文本里,换行是转义后的两个字符。
  540. "中间这一段会被整段选中。\\n\\n```\\nDesktop (Mac)",
  541. // 代码正文逐字保留:模板字符串里的连续空行不能被压缩。
  542. "0123456789\\nconst value = `A\\n\\n\\nB`;\\n```",
  543. ],
  544. },
  545. "跨块注释的原文没有带上代码块正文",
  546. 30000,
  547. );
  548. // 公式以 TeX 源码进入引用(行内 $…$,独立 $$…$$),而不是浏览器给出的逐字符 MathML 碎片。
  549. // 引用是嵌在消息文本里的 JSON,TeX 里的反斜杠是转义后的两个字符。
  550. await waitForUpstreamRequest(
  551. {
  552. lastUserMessageIncludes: [
  553. "E2E_SCS_STREAM",
  554. "这一行有行内公式 $E = mc^2$ 和 $\\\\sum_{i=1}^{n} i = \\\\frac{n(n+1)}{2}$,下面是独立公式:",
  555. "$$\\\\int_0^1 x^2 \\\\, dx = \\\\frac{1}{3}$$",
  556. MATH_END,
  557. ],
  558. },
  559. "公式没有以 TeX 源码进入引用原文",
  560. 30000,
  561. );
  562. expect(await countUpstreamRequests({ lastUserMessageIncludes: ["E2E_SCS_STREAM", "𝐸"] })).toBe(
  563. 0,
  564. );
  565. // 等第二段正文出现再框选第一段:第一段的逐词渐显已结束,文字节点稳定,真实拖选才可靠。
  566. await waitForV4AssistantMessageContaining("E2E_SCS_SECOND_PARA", 60000);
  567. await installSelectionProbe();
  568. // 输出仍在继续:后面还有工具调用、思考块、工具行分组和约 15 秒的流式正文(含跟随滚动)。
  569. // 框选本轮已经输出完成的第一段正文,不滚动时间线。
  570. await dragSelectMainTimelineText(LIVE_PARA, { scroll: false });
  571. await browser.saveScreenshot(join(artifacts(), "scm07-streaming-selection-menu.png"));
  572. await waitForV4AssistantMessageContaining(line(6), 30000);
  573. const afterStreaming = await readSelectionState();
  574. await browser.saveScreenshot(join(artifacts(), "scm07-streaming-selection-after.png"));
  575. if (afterStreaming.text !== LIVE_PARA || !tooltipFollowsSelection(afterStreaming)) {
  576. throw new Error(
  577. `输出过程中选区丢失,或浮层消失/没有跟随选区: ${JSON.stringify(afterStreaming)}\nprobe=${JSON.stringify(
  578. await readSelectionProbe(),
  579. )}`,
  580. );
  581. }
  582. // 输出继续时完成注释:输入不被打断,保存后正文出现实心编号。
  583. await clickSelectionAction("comment");
  584. await typeSelectionComment(COMMENT);
  585. // 输入期间回答继续输出、时间线继续滚动:输入卡片要跟着正文里的虚线标记走,不能留在原地。
  586. const lineBeforeFollow = await browser.execute(
  587. () =>
  588. document
  589. .querySelector('[data-annotation-mark="__pending__"] > div')
  590. ?.getBoundingClientRect().top ?? null,
  591. );
  592. await browser.waitUntil(
  593. async () => {
  594. const follow = await browser.execute(() => {
  595. const line = document
  596. .querySelector('[data-annotation-mark="__pending__"] > div')
  597. ?.getBoundingClientRect();
  598. const editor = document
  599. .querySelector("[data-conversation-selection-comment-editor]")
  600. ?.getBoundingClientRect();
  601. if (!line || !editor) return null;
  602. return {
  603. lineTop: line.top,
  604. // 卡片在标记上方时看卡片底边到标记顶边的距离,在下方时看卡片顶边到标记底边。
  605. gap: Math.min(Math.abs(line.top - editor.bottom), Math.abs(editor.top - line.bottom)),
  606. };
  607. });
  608. // 等标记至少移动过 40px 再核对,确认是在滚动之后仍然对准。
  609. return (
  610. follow !== null &&
  611. lineBeforeFollow !== null &&
  612. Math.abs(follow.lineTop - lineBeforeFollow) >= 40 &&
  613. follow.gap <= 24
  614. );
  615. },
  616. { timeout: 15000, timeoutMsg: "输出过程中输入卡片没有跟随正文里的标记" },
  617. );
  618. expect(await $("[data-conversation-selection-comment-input]").getValue()).toBe(COMMENT);
  619. await browser.saveScreenshot(join(artifacts(), "scm07-editor-follows.png"));
  620. await browser.keys("Enter");
  621. await $("[data-conversation-selection-comment-editor]").waitForDisplayed({ reverse: true });
  622. try {
  623. await browser.waitUntil(
  624. async () =>
  625. // SCM08、SCM09 的注释已随本轮提问发出(变成灰色已发送标记),这里是新的第 1 条。
  626. (await readMainComposerSelectionChip()).count === 1 &&
  627. (await readMainTimelineAnnotationMarks()).some(
  628. (mark) => mark.number === 1 && mark.variant === "comment",
  629. ),
  630. { timeout: 10000 },
  631. );
  632. } catch {
  633. await browser.saveScreenshot(join(artifacts(), "scm07-save-failed.png"));
  634. throw new Error(
  635. `输出过程中保存的注释没有出现在 composer 与正文: ${JSON.stringify({
  636. chip: await readMainComposerSelectionChip(),
  637. marks: await readMainTimelineAnnotationMarks(),
  638. })}`,
  639. );
  640. }
  641. await waitForV4AssistantMessageContaining("E2E_SCS_STREAM_DONE", 60000);
  642. expect((await readMainComposerSelectionChip()).count).toBe(1);
  643. // SCM13:点“在辅助对话中提问”后右侧面板打开、时间线变窄。浮层已被这次点击关掉,
  644. // 不能因为容器尺寸变化在原选区上重新出现。
  645. await dragSelectMainTimelineText("E2E_SCS_STREAM_DONE");
  646. const widthBeforeAsk = await browser.execute(
  647. () =>
  648. document.querySelector('[data-testid="v4-timeline"]')?.getBoundingClientRect().width ?? 0,
  649. );
  650. await clickSelectionAction("ask-in-side-chat");
  651. await browser.waitUntil(
  652. async () =>
  653. Math.abs(
  654. (await browser.execute(
  655. () =>
  656. document.querySelector('[data-testid="v4-timeline"]')?.getBoundingClientRect()
  657. .width ?? 0,
  658. )) - widthBeforeAsk,
  659. ) > 40,
  660. { timeout: 15000, timeoutMsg: "点“在辅助对话中提问”后右侧面板没有打开" },
  661. );
  662. const askedAt = Date.now();
  663. while (Date.now() - askedAt < 1500) {
  664. if (await $("[data-conversation-selection-tooltip]").isExisting()) {
  665. throw new Error("点“在辅助对话中提问”后,主时间线上又出现了选区浮层");
  666. }
  667. await browser.pause(120);
  668. }
  669. await browser.saveScreenshot(join(artifacts(), "scm13-ask-in-side-chat.png"));
  670. });
  671. });