conversation-session-chat-loading-live-tail.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. import { clearAppData } from "../helpers/desktop-app.js";
  2. import {
  3. prepareV4ConversationE2E,
  4. sendV4Prompt,
  5. waitForV4Pane,
  6. waitForV4TimelineContaining,
  7. } from "../helpers/v4-conversation.js";
  8. interface ChatLoadingLayoutSample {
  9. backToBottomVisible: boolean;
  10. bottomGap: number;
  11. clientHeight: number;
  12. dockTop: number | null;
  13. following: boolean;
  14. hasLiveTail: boolean;
  15. historyOpen: boolean | null;
  16. liveHeight: number | null;
  17. loadingTop: number | null;
  18. loadingVisible: boolean;
  19. scrollHeight: number;
  20. scrollTop: number;
  21. slotTop: number | null;
  22. time: number;
  23. }
  24. interface ChatLoadingLayoutProbe {
  25. animationFrameId: number | null;
  26. liveTailObserver: ResizeObserver | null;
  27. mutationObserver: MutationObserver | null;
  28. resizeAnimationFrameIds: number[];
  29. resizeSamples: ChatLoadingLayoutSample[];
  30. running: boolean;
  31. samples: ChatLoadingLayoutSample[];
  32. }
  33. interface ChatLoadingLayoutProbeResult {
  34. resizeSamples: ChatLoadingLayoutSample[];
  35. samples: ChatLoadingLayoutSample[];
  36. }
  37. interface AssistantHistoryToggleSample {
  38. backToBottomVisible: boolean;
  39. bottomGap: number;
  40. contentDisplay: string;
  41. contentHeight: number;
  42. contentHidden: boolean;
  43. following: boolean;
  44. historyOpen: boolean;
  45. nextTop: number | null;
  46. scrollTop: number;
  47. time: number;
  48. triggerTop: number;
  49. }
  50. interface AssistantHistoryToggleProbe {
  51. error?: string;
  52. samples: AssistantHistoryToggleSample[];
  53. targetOpen: boolean;
  54. }
  55. declare global {
  56. interface Window {
  57. __zcodeChatLoadingLayoutProbe?: ChatLoadingLayoutProbe;
  58. }
  59. }
  60. const LAYOUT_EPSILON_PX = 1.5;
  61. const TOGGLE_POSITION_EPSILON_PX = 2;
  62. const REAL_LINE_GROWTH_PX = 8;
  63. describe("CHL05/CHL07/CHL08/P08 ChatLoading、终态与手动折叠滚动权", () => {
  64. after(async () => {
  65. await browser.electron.restoreAllMocks();
  66. await clearAppData();
  67. });
  68. it("长正文增长、终态折叠吸底和用户主动离底互不冲突", async function () {
  69. this.timeout(220000);
  70. await prepareV4ConversationE2E();
  71. await installChatLoadingLayoutProbe();
  72. await sendV4Prompt(
  73. "E2E_CHAT_LOADING_REAL_LINES FOLLOWING 请输出足够长的完整说明文字,不要只依赖换行数量",
  74. );
  75. await waitForV4TimelineContaining("CHAT_LOADING_LINE_36", 45000);
  76. await waitForV4Pane(
  77. (snapshot) => !snapshot.canStop,
  78. "逐段流式回复结束后会话没有回到 idle",
  79. 30000,
  80. );
  81. const followingTerminal = await waitForTerminalScrollState("following");
  82. const followingProbeResult = await stopChatLoadingLayoutProbe();
  83. const followingReport = analyzeChatLoadingLayout(followingProbeResult);
  84. if (
  85. followingReport.loadingVisibleSamples <= 0 ||
  86. followingReport.overflowGrowthCount < 8 ||
  87. followingReport.flickers.length > 0 ||
  88. followingTerminal.bottomGap > 48 ||
  89. followingTerminal.following !== true ||
  90. followingTerminal.historyOpen !== false
  91. ) {
  92. throw new Error(
  93. `CHL05/CHL07 跟随态采样未通过: ${JSON.stringify({ followingReport, followingTerminal })}`,
  94. );
  95. }
  96. await assertAssistantHistoryToggleStability("following");
  97. await installChatLoadingLayoutProbe();
  98. await sendV4Prompt(
  99. "E2E_CHAT_LOADING_REAL_LINES DETACHED 请继续输出足够长的完整说明文字,确保自然换行后仍然超过一屏",
  100. );
  101. await waitForLiveTailContaining("CHAT_LOADING_LINE_31");
  102. const detachedBeforeTerminal = await detachTimelineWithUpwardWheel();
  103. if (
  104. detachedBeforeTerminal.following !== false ||
  105. detachedBeforeTerminal.bottomGap <= 48
  106. ) {
  107. throw new Error(
  108. `CHL08 用户上滚没有先进入离底态: ${JSON.stringify(detachedBeforeTerminal)}`,
  109. );
  110. }
  111. await waitForV4TimelineContaining("CHAT_LOADING_LINE_36", 45000);
  112. await waitForV4Pane(
  113. (snapshot) => !snapshot.canStop,
  114. "用户离底后的流式回复结束后会话没有回到 idle",
  115. 30000,
  116. );
  117. const detachedTerminal = await waitForTerminalScrollState("detached");
  118. const detachedProbeResult = await stopChatLoadingLayoutProbe();
  119. const detachedReport = analyzeTerminalScrollOwnership(detachedProbeResult);
  120. if (
  121. detachedTerminal.following !== false ||
  122. detachedTerminal.bottomGap <= 48 ||
  123. detachedTerminal.historyOpen !== false ||
  124. detachedReport.terminalDetachedSamples <= 0 ||
  125. detachedReport.forcedFollowingSamples.length > 0
  126. ) {
  127. throw new Error(
  128. `CHL08 离底终态采样未通过: ${JSON.stringify({ detachedReport, detachedTerminal })}`,
  129. );
  130. }
  131. await positionLatestHistoryTriggerForDetachedToggle();
  132. await assertAssistantHistoryToggleStability("detached");
  133. });
  134. });
  135. interface TimelineScrollState {
  136. backToBottomVisible: boolean;
  137. bottomGap: number;
  138. following: boolean;
  139. hasLiveTail: boolean;
  140. historyOpen: boolean | null;
  141. scrollHeight: number;
  142. scrollTop: number;
  143. }
  144. async function readTimelineScrollState(): Promise<TimelineScrollState | null> {
  145. return browser.execute(() => {
  146. const timeline = document.querySelector<HTMLElement>(
  147. '[data-testid="v4-timeline"]',
  148. );
  149. if (!timeline) return null;
  150. const historyStateElements = Array.from(
  151. document.querySelectorAll<HTMLElement>("[data-history-open]"),
  152. );
  153. const historyState = historyStateElements.at(-1)?.dataset.historyOpen;
  154. return {
  155. backToBottomVisible: Boolean(
  156. document.querySelector('[data-testid="v4-timeline-bottom"]'),
  157. ),
  158. bottomGap: Math.max(
  159. 0,
  160. timeline.scrollHeight - timeline.clientHeight - timeline.scrollTop,
  161. ),
  162. following: timeline.dataset.following === "true",
  163. hasLiveTail: Boolean(
  164. document.querySelector('[data-v4-running-live-tail="true"]'),
  165. ),
  166. historyOpen:
  167. historyState === "true"
  168. ? true
  169. : historyState === "false"
  170. ? false
  171. : null,
  172. scrollHeight: timeline.scrollHeight,
  173. scrollTop: timeline.scrollTop,
  174. };
  175. });
  176. }
  177. async function waitForLiveTailContaining(marker: string): Promise<void> {
  178. await browser.waitUntil(
  179. async () =>
  180. browser.execute((expectedMarker) => {
  181. const liveTail = document.querySelector<HTMLElement>(
  182. '[data-v4-running-live-tail="true"]',
  183. );
  184. return liveTail?.textContent?.includes(expectedMarker) === true;
  185. }, marker),
  186. {
  187. timeout: 45000,
  188. interval: 100,
  189. timeoutMsg: `running live tail 未出现 marker: ${marker}`,
  190. },
  191. );
  192. }
  193. async function waitForTerminalScrollState(
  194. expected: "following" | "detached",
  195. ): Promise<TimelineScrollState> {
  196. await browser.waitUntil(
  197. async () => {
  198. const state = await readTimelineScrollState();
  199. if (!state || state.hasLiveTail || state.historyOpen !== false)
  200. return false;
  201. return expected === "following"
  202. ? state.following && state.bottomGap <= 48 && !state.backToBottomVisible
  203. : !state.following && state.bottomGap > 48 && state.backToBottomVisible;
  204. },
  205. {
  206. timeout: 15000,
  207. interval: 100,
  208. timeoutMsg: `terminal ${expected} 滚动状态未稳定`,
  209. },
  210. );
  211. const state = await readTimelineScrollState();
  212. if (!state) throw new Error("terminal 稳定后无法读取 timeline");
  213. return state;
  214. }
  215. async function detachTimelineWithUpwardWheel(): Promise<TimelineScrollState> {
  216. await browser.execute(() => {
  217. const timeline = document.querySelector<HTMLElement>(
  218. '[data-testid="v4-timeline"]',
  219. );
  220. if (!timeline) throw new Error("找不到 v4 timeline");
  221. // 先触发真实 wheel capture 语义,再改变浏览器滚动位置;这能覆盖 scroll 事件
  222. // 尚未派发、terminal commit 已经到达的用户意图竞态。
  223. timeline.dispatchEvent(
  224. new WheelEvent("wheel", {
  225. bubbles: true,
  226. cancelable: true,
  227. deltaY: -600,
  228. }),
  229. );
  230. timeline.scrollTop = Math.max(0, timeline.scrollTop - 600);
  231. timeline.dispatchEvent(new Event("scroll"));
  232. });
  233. await browser.waitUntil(
  234. async () => {
  235. const state = await readTimelineScrollState();
  236. return Boolean(state && !state.following && state.bottomGap > 48);
  237. },
  238. {
  239. timeout: 5000,
  240. interval: 50,
  241. timeoutMsg: "向上 wheel 后 timeline 没有进入 detached",
  242. },
  243. );
  244. const state = await readTimelineScrollState();
  245. if (!state) throw new Error("向上 wheel 后无法读取 timeline");
  246. return state;
  247. }
  248. async function positionLatestHistoryTriggerForDetachedToggle(): Promise<void> {
  249. const positioned = await browser.execute(() => {
  250. const timeline = document.querySelector<HTMLElement>(
  251. '[data-testid="v4-timeline"]',
  252. );
  253. const trigger = Array.from(
  254. document.querySelectorAll<HTMLElement>(
  255. '[data-testid^="chat-assistant-history-trigger-"]',
  256. ),
  257. ).at(-1);
  258. if (!timeline || !trigger) return false;
  259. const timelineRect = timeline.getBoundingClientRect();
  260. const triggerRect = trigger.getBoundingClientRect();
  261. const targetTop = timelineRect.top + Math.min(120, timeline.clientHeight / 4);
  262. const nextScrollTop = Math.max(
  263. 0,
  264. timeline.scrollTop + triggerRect.top - targetTop,
  265. );
  266. timeline.dispatchEvent(
  267. new WheelEvent("wheel", {
  268. bubbles: true,
  269. cancelable: true,
  270. deltaY: nextScrollTop - timeline.scrollTop,
  271. }),
  272. );
  273. timeline.scrollTop = nextScrollTop;
  274. timeline.dispatchEvent(new Event("scroll"));
  275. return true;
  276. });
  277. if (!positioned) {
  278. throw new Error("P08 无法把最新“已工作”触发器定位到 detached 视口");
  279. }
  280. await browser.waitUntil(
  281. async () =>
  282. browser.execute(() => {
  283. const timeline = document.querySelector<HTMLElement>(
  284. '[data-testid="v4-timeline"]',
  285. );
  286. const trigger = Array.from(
  287. document.querySelectorAll<HTMLElement>(
  288. '[data-testid^="chat-assistant-history-trigger-"]',
  289. ),
  290. ).at(-1);
  291. if (!timeline || !trigger || timeline.dataset.following !== "false") {
  292. return false;
  293. }
  294. const timelineRect = timeline.getBoundingClientRect();
  295. const triggerRect = trigger.getBoundingClientRect();
  296. return (
  297. triggerRect.top >= timelineRect.top &&
  298. triggerRect.bottom <= timelineRect.bottom
  299. );
  300. }),
  301. {
  302. timeout: 5000,
  303. interval: 50,
  304. timeoutMsg: "P08 detached 触发器没有稳定进入可见视口",
  305. },
  306. );
  307. }
  308. async function assertAssistantHistoryToggleStability(
  309. ownership: "following" | "detached",
  310. ): Promise<void> {
  311. const opening = await probeLatestAssistantHistoryToggle(true);
  312. assertAssistantHistoryToggleProbe(opening, ownership);
  313. const closing = await probeLatestAssistantHistoryToggle(false);
  314. assertAssistantHistoryToggleProbe(closing, ownership);
  315. }
  316. function probeLatestAssistantHistoryToggle(
  317. targetOpen: boolean,
  318. ): Promise<AssistantHistoryToggleProbe> {
  319. return browser.executeAsync(
  320. (shouldOpen, done) => {
  321. const timeline = document.querySelector<HTMLElement>(
  322. '[data-testid="v4-timeline"]',
  323. );
  324. const trigger = Array.from(
  325. document.querySelectorAll<HTMLElement>(
  326. '[data-testid^="chat-assistant-history-trigger-"]',
  327. ),
  328. ).at(-1);
  329. const collapsible = trigger?.closest<HTMLElement>(
  330. '[data-slot="collapsible"]',
  331. );
  332. const content = collapsible?.querySelector<HTMLElement>(
  333. '[data-slot="collapsible-content"]',
  334. );
  335. const next = content?.nextElementSibling as HTMLElement | null;
  336. if (!timeline || !trigger || !content || !next) {
  337. done({
  338. error: "toggle-elements-missing",
  339. samples: [],
  340. targetOpen: shouldOpen,
  341. });
  342. return;
  343. }
  344. const samples: AssistantHistoryToggleSample[] = [];
  345. const readSample = (): AssistantHistoryToggleSample => {
  346. const contentStyle = window.getComputedStyle(content);
  347. return {
  348. backToBottomVisible: Boolean(
  349. document.querySelector('[data-testid="v4-timeline-bottom"]'),
  350. ),
  351. bottomGap: Math.max(
  352. 0,
  353. timeline.scrollHeight - timeline.clientHeight - timeline.scrollTop,
  354. ),
  355. contentDisplay: contentStyle.display,
  356. contentHeight: content.getBoundingClientRect().height,
  357. contentHidden: content.hasAttribute("hidden"),
  358. following: timeline.dataset.following === "true",
  359. historyOpen: trigger.dataset.historyOpen === "true",
  360. nextTop: next.getBoundingClientRect().top,
  361. scrollTop: timeline.scrollTop,
  362. time: performance.now(),
  363. triggerTop: trigger.getBoundingClientRect().top,
  364. };
  365. };
  366. samples.push(readSample());
  367. if ((trigger.dataset.historyOpen === "true") === shouldOpen) {
  368. done({
  369. error: "toggle-already-at-target",
  370. samples,
  371. targetOpen: shouldOpen,
  372. });
  373. return;
  374. }
  375. trigger.click();
  376. const startedAt = performance.now();
  377. const sampleAnimation = () => {
  378. const current = readSample();
  379. samples.push(current);
  380. const elapsed = performance.now() - startedAt;
  381. const settled = shouldOpen
  382. ? current.historyOpen &&
  383. !current.contentHidden &&
  384. current.contentDisplay !== "none" &&
  385. current.contentHeight > 0
  386. : !current.historyOpen &&
  387. (current.contentHidden || current.contentDisplay === "none");
  388. if (elapsed >= 450 && settled) {
  389. done({ samples, targetOpen: shouldOpen });
  390. return;
  391. }
  392. if (elapsed >= 1200) {
  393. done({
  394. error: "toggle-animation-not-settled",
  395. samples,
  396. targetOpen: shouldOpen,
  397. });
  398. return;
  399. }
  400. requestAnimationFrame(sampleAnimation);
  401. };
  402. requestAnimationFrame(sampleAnimation);
  403. },
  404. targetOpen,
  405. ) as Promise<AssistantHistoryToggleProbe>;
  406. }
  407. function assertAssistantHistoryToggleProbe(
  408. probe: AssistantHistoryToggleProbe,
  409. ownership: "following" | "detached",
  410. ): void {
  411. if (probe.error || probe.samples.length < 10) {
  412. throw new Error(
  413. `P08 折叠采样不完整: ${JSON.stringify({ ownership, probe })}`,
  414. );
  415. }
  416. const samples = probe.samples;
  417. const finalSample = samples.at(-1)!;
  418. if (finalSample.historyOpen !== probe.targetOpen) {
  419. throw new Error(
  420. `P08 折叠终态不正确: ${JSON.stringify({ ownership, probe })}`,
  421. );
  422. }
  423. assertMonotonicToggleValues(
  424. samples.map((sample) => sample.contentHeight),
  425. probe.targetOpen ? "increasing" : "decreasing",
  426. "contentHeight",
  427. ownership,
  428. );
  429. const nextContentTops = samples.flatMap((sample) =>
  430. sample.nextTop === null ? [] : [sample.nextTop + sample.scrollTop],
  431. );
  432. assertMonotonicToggleValues(
  433. nextContentTops,
  434. probe.targetOpen ? "increasing" : "decreasing",
  435. "nextContentTop",
  436. ownership,
  437. );
  438. if (ownership === "following") {
  439. const invalidOwnership = samples.filter(
  440. (sample) =>
  441. !sample.following ||
  442. sample.bottomGap > 48 ||
  443. sample.backToBottomVisible,
  444. );
  445. if (invalidOwnership.length > 0) {
  446. throw new Error(
  447. `P08 跟随态手动折叠发生滚动竞争: ${JSON.stringify({ invalidOwnership, probe })}`,
  448. );
  449. }
  450. } else {
  451. const invalidOwnership = samples.filter(
  452. (sample) =>
  453. sample.following ||
  454. sample.bottomGap <= 48 ||
  455. !sample.backToBottomVisible,
  456. );
  457. const scrollTopRange =
  458. Math.max(...samples.map((sample) => sample.scrollTop)) -
  459. Math.min(...samples.map((sample) => sample.scrollTop));
  460. const triggerTopRange =
  461. Math.max(...samples.map((sample) => sample.triggerTop)) -
  462. Math.min(...samples.map((sample) => sample.triggerTop));
  463. if (
  464. invalidOwnership.length > 0 ||
  465. scrollTopRange > TOGGLE_POSITION_EPSILON_PX ||
  466. triggerTopRange > TOGGLE_POSITION_EPSILON_PX
  467. ) {
  468. throw new Error(
  469. `P08 离底态手动折叠改变了阅读位置: ${JSON.stringify({ invalidOwnership, scrollTopRange, triggerTopRange, probe })}`,
  470. );
  471. }
  472. }
  473. if (!probe.targetOpen) {
  474. const firstHiddenIndex = samples.findIndex(
  475. (sample) => sample.contentHidden || sample.contentDisplay === "none",
  476. );
  477. const lastVisible =
  478. firstHiddenIndex <= 0 ? undefined : samples[firstHiddenIndex - 1];
  479. const firstHidden =
  480. firstHiddenIndex < 0 ? undefined : samples[firstHiddenIndex];
  481. const finalGapJump =
  482. lastVisible?.nextTop === null ||
  483. lastVisible?.nextTop === undefined ||
  484. firstHidden?.nextTop === null ||
  485. firstHidden?.nextTop === undefined
  486. ? Number.POSITIVE_INFINITY
  487. : Math.abs(firstHidden.nextTop - lastVisible.nextTop);
  488. if (finalGapJump > TOGGLE_POSITION_EPSILON_PX) {
  489. throw new Error(
  490. `P08 收起隐藏前后仍有尾部间距跳变: ${JSON.stringify({ finalGapJump, ownership, probe })}`,
  491. );
  492. }
  493. }
  494. }
  495. function assertMonotonicToggleValues(
  496. values: readonly number[],
  497. direction: "increasing" | "decreasing",
  498. label: string,
  499. ownership: "following" | "detached",
  500. ): void {
  501. const reversals = values.flatMap((value, index) => {
  502. const previous = values[index - 1];
  503. if (previous === undefined) return [];
  504. const reversed =
  505. direction === "increasing"
  506. ? value + LAYOUT_EPSILON_PX < previous
  507. : value - LAYOUT_EPSILON_PX > previous;
  508. return reversed ? [{ index, previous, value }] : [];
  509. });
  510. if (reversals.length > 0) {
  511. throw new Error(
  512. `P08 ${ownership} ${label} 动画方向反转: ${JSON.stringify(reversals)}`,
  513. );
  514. }
  515. }
  516. async function installChatLoadingLayoutProbe() {
  517. await browser.execute(() => {
  518. const existing = window.__zcodeChatLoadingLayoutProbe;
  519. if (
  520. existing?.animationFrameId !== null &&
  521. existing?.animationFrameId !== undefined
  522. ) {
  523. window.cancelAnimationFrame(existing.animationFrameId);
  524. }
  525. const probe: ChatLoadingLayoutProbe = {
  526. animationFrameId: null,
  527. liveTailObserver: null,
  528. mutationObserver: null,
  529. resizeAnimationFrameIds: [],
  530. resizeSamples: [],
  531. running: true,
  532. samples: [],
  533. };
  534. window.__zcodeChatLoadingLayoutProbe = probe;
  535. const readSample = (): ChatLoadingLayoutSample | null => {
  536. const timeline = document.querySelector<HTMLElement>(
  537. '[data-testid="v4-timeline"]',
  538. );
  539. if (!timeline) return null;
  540. const liveTail = document.querySelector<HTMLElement>(
  541. '[data-v4-running-live-tail="true"]',
  542. );
  543. const slot = document.querySelector<HTMLElement>(
  544. '[data-zcode-chat-loading-slot="true"]',
  545. );
  546. const loading = document.querySelector<HTMLElement>(
  547. '[data-testid="chat-loading"]',
  548. );
  549. const dock = document.querySelector<HTMLElement>(
  550. '[data-v4-composer-dock="true"]',
  551. );
  552. const historyStateElements = Array.from(
  553. document.querySelectorAll<HTMLElement>("[data-history-open]"),
  554. );
  555. const historyState = historyStateElements.at(-1)?.dataset.historyOpen;
  556. const liveRect = liveTail?.getBoundingClientRect();
  557. const slotRect = slot?.getBoundingClientRect();
  558. const loadingRect = loading?.getBoundingClientRect();
  559. const dockRect = dock?.getBoundingClientRect();
  560. const bottomGap = Math.max(
  561. 0,
  562. timeline.scrollHeight - timeline.clientHeight - timeline.scrollTop,
  563. );
  564. return {
  565. backToBottomVisible: Boolean(
  566. document.querySelector('[data-testid="v4-timeline-bottom"]'),
  567. ),
  568. bottomGap,
  569. clientHeight: timeline.clientHeight,
  570. dockTop: dockRect?.top ?? null,
  571. following: timeline.dataset.following === "true",
  572. hasLiveTail: liveTail !== null,
  573. historyOpen:
  574. historyState === "true"
  575. ? true
  576. : historyState === "false"
  577. ? false
  578. : null,
  579. liveHeight: liveRect?.height ?? null,
  580. loadingTop: loadingRect?.top ?? null,
  581. loadingVisible: Boolean(
  582. loading &&
  583. loadingRect &&
  584. loadingRect.width > 0 &&
  585. loadingRect.height > 0 &&
  586. window.getComputedStyle(loading).display !== "none" &&
  587. window.getComputedStyle(loading).visibility !== "hidden",
  588. ),
  589. scrollHeight: timeline.scrollHeight,
  590. scrollTop: timeline.scrollTop,
  591. slotTop: slotRect?.top ?? null,
  592. time: performance.now(),
  593. };
  594. };
  595. const sampleAfterPaint = () => {
  596. if (!probe.running) return;
  597. probe.animationFrameId = window.requestAnimationFrame(() => {
  598. const sample = readSample();
  599. if (sample) probe.samples.push(sample);
  600. sampleAfterPaint();
  601. });
  602. };
  603. let observedLiveTail: HTMLElement | null = null;
  604. const attachLiveTailObserver = () => {
  605. const liveTail = document.querySelector<HTMLElement>(
  606. '[data-v4-running-live-tail="true"]',
  607. );
  608. if (liveTail === observedLiveTail) return;
  609. probe.liveTailObserver?.disconnect();
  610. probe.liveTailObserver = null;
  611. observedLiveTail = liveTail;
  612. if (!liveTail) return;
  613. probe.liveTailObserver = new ResizeObserver(() => {
  614. const animationFrameId = window.requestAnimationFrame(() => {
  615. probe.resizeAnimationFrameIds = probe.resizeAnimationFrameIds.filter(
  616. (id) => id !== animationFrameId,
  617. );
  618. const sample = readSample();
  619. if (sample) probe.resizeSamples.push(sample);
  620. });
  621. probe.resizeAnimationFrameIds.push(animationFrameId);
  622. });
  623. probe.liveTailObserver.observe(liveTail);
  624. };
  625. probe.mutationObserver = new MutationObserver(attachLiveTailObserver);
  626. probe.mutationObserver.observe(document.body, {
  627. childList: true,
  628. subtree: true,
  629. });
  630. attachLiveTailObserver();
  631. sampleAfterPaint();
  632. });
  633. }
  634. async function stopChatLoadingLayoutProbe(): Promise<ChatLoadingLayoutProbeResult> {
  635. return browser.execute(() => {
  636. const probe = window.__zcodeChatLoadingLayoutProbe;
  637. if (!probe) return { resizeSamples: [], samples: [] };
  638. probe.running = false;
  639. if (probe.animationFrameId !== null) {
  640. window.cancelAnimationFrame(probe.animationFrameId);
  641. }
  642. probe.liveTailObserver?.disconnect();
  643. probe.mutationObserver?.disconnect();
  644. for (const animationFrameId of probe.resizeAnimationFrameIds) {
  645. window.cancelAnimationFrame(animationFrameId);
  646. }
  647. const compactSamples = probe.samples.filter((sample, index, samples) => {
  648. const previous = samples[index - 1];
  649. if (!previous) return true;
  650. return (
  651. sample.following !== previous.following ||
  652. sample.hasLiveTail !== previous.hasLiveTail ||
  653. sample.historyOpen !== previous.historyOpen ||
  654. sample.backToBottomVisible !== previous.backToBottomVisible ||
  655. sample.bottomGap !== previous.bottomGap ||
  656. sample.liveHeight !== previous.liveHeight ||
  657. sample.loadingVisible !== previous.loadingVisible ||
  658. sample.scrollHeight !== previous.scrollHeight ||
  659. sample.scrollTop !== previous.scrollTop ||
  660. sample.slotTop !== previous.slotTop
  661. );
  662. });
  663. return { resizeSamples: probe.resizeSamples, samples: compactSamples };
  664. });
  665. }
  666. function analyzeChatLoadingLayout({
  667. resizeSamples,
  668. samples,
  669. }: ChatLoadingLayoutProbeResult) {
  670. const flickers: Array<{
  671. at: number;
  672. growthPx: number;
  673. slotJumpPx: number;
  674. }> = [];
  675. const growths: Array<{
  676. at: number;
  677. bottomGapBeforePx: number;
  678. following: boolean;
  679. growthPx: number;
  680. overflowing: boolean;
  681. scrollDeltaPx: number;
  682. slotDeltaPx: number | null;
  683. }> = [];
  684. let overflowGrowthCount = 0;
  685. let pinnedSlotTop: number | null = null;
  686. for (let index = 1; index < resizeSamples.length; index += 1) {
  687. const previous = resizeSamples[index - 1];
  688. const current = resizeSamples[index];
  689. if (
  690. !previous ||
  691. !current ||
  692. previous.liveHeight === null ||
  693. current.liveHeight === null
  694. ) {
  695. continue;
  696. }
  697. const growthPx = current.liveHeight - previous.liveHeight;
  698. if (growthPx >= REAL_LINE_GROWTH_PX) {
  699. growths.push({
  700. at: current.time,
  701. bottomGapBeforePx: Math.max(
  702. 0,
  703. previous.scrollHeight - previous.clientHeight - previous.scrollTop,
  704. ),
  705. following: previous.following,
  706. growthPx,
  707. overflowing:
  708. previous.scrollHeight > previous.clientHeight + REAL_LINE_GROWTH_PX,
  709. scrollDeltaPx: current.scrollTop - previous.scrollTop,
  710. slotDeltaPx:
  711. previous.slotTop === null || current.slotTop === null
  712. ? null
  713. : current.slotTop - previous.slotTop,
  714. });
  715. }
  716. const wasPinnedAndOverflowing =
  717. previous.following &&
  718. previous.scrollHeight > previous.clientHeight + REAL_LINE_GROWTH_PX &&
  719. previous.scrollHeight - previous.clientHeight - previous.scrollTop <= 48;
  720. if (!wasPinnedAndOverflowing) {
  721. pinnedSlotTop = null;
  722. continue;
  723. }
  724. if (growthPx < REAL_LINE_GROWTH_PX) continue;
  725. overflowGrowthCount += 1;
  726. if (previous.slotTop === null || current.slotTop === null) continue;
  727. if (pinnedSlotTop === null) {
  728. // 修复原因:从未溢出切到溢出的首个 ResizeObserver 样本仍可能带着
  729. // scrollTop 补偿前的 8px 过渡偏移。用补偿后的 current 建立贴底基线,
  730. // 后续样本才用于检测真正的“下移再回位”,避免把正常边界切换判成闪烁。
  731. pinnedSlotTop = current.slotTop;
  732. continue;
  733. }
  734. const slotJumpPx = current.slotTop - pinnedSlotTop;
  735. if (slotJumpPx <= LAYOUT_EPSILON_PX) continue;
  736. flickers.push({
  737. at: current.time,
  738. growthPx,
  739. slotJumpPx,
  740. });
  741. }
  742. return {
  743. flickers,
  744. growths,
  745. loadingVisibleSamples: samples.filter((sample) => sample.loadingVisible)
  746. .length,
  747. overflowGrowthCount,
  748. };
  749. }
  750. function analyzeTerminalScrollOwnership({
  751. samples,
  752. }: ChatLoadingLayoutProbeResult) {
  753. const detachedStart = samples.findIndex(
  754. (sample) => !sample.following && sample.bottomGap > 48,
  755. );
  756. // 修复原因:第二轮探针安装后、第二条消息开始前会先采到上一轮正确的
  757. // FOLLOWING 终态;CHL08 的所有权窗口只能从本轮首次用户离底开始计算。
  758. const ownershipSamples =
  759. detachedStart < 0 ? [] : samples.slice(detachedStart);
  760. const terminalSamples = ownershipSamples.filter(
  761. (sample) => !sample.hasLiveTail && sample.historyOpen === false,
  762. );
  763. return {
  764. terminalDetachedSamples: terminalSamples.filter(
  765. (sample) => !sample.following && sample.bottomGap > 48,
  766. ).length,
  767. forcedFollowingSamples: terminalSamples.filter(
  768. (sample) => sample.following || sample.bottomGap <= 48,
  769. ),
  770. };
  771. }