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

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