chat-scroll-contract.e2e.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  1. // Browser geometry contracts for a long Chat transcript. These scenarios are
  2. // deliberately virtualizer-neutral: they assert semantic-row position,
  3. // bottom ownership, interaction state, and the real outer scroll host rather
  4. // than DOM cardinality or implementation-specific spacer markup.
  5. import { access, mkdtemp, rm, writeFile } from 'node:fs/promises'
  6. import { tmpdir } from 'node:os'
  7. import { join } from 'node:path'
  8. import type { Browser, Page } from 'playwright'
  9. import { chromium } from 'playwright'
  10. import { afterAll, beforeAll, describe, expect, it } from 'vitest'
  11. import type { StreamChunk } from '@deepseek-ai/dsh-llm'
  12. import { ToolCallId } from '@deepseek-ai/dsh-llm'
  13. import type { AssistantStreamFrame } from '@deepseek-ai/dsh-agent'
  14. import type { ReplayEntry, ReplayOverrideDoc } from '@deepseek-ai/dsh-llm-replay'
  15. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  16. import { createChatScrollFixture, type ChatScrollFixture } from './chat-scroll-fixture.ts'
  17. import {
  18. launchWebScaffold,
  19. seedSession,
  20. watchConsole,
  21. webSnapshotMode,
  22. type WebScaffold,
  23. } from './scaffold.ts'
  24. import { expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts'
  25. const MODE = webSnapshotMode()
  26. const HISTORY_SESSION_ID = 'chat-scroll-history-e2e'
  27. const TOOL_SESSION_ID = 'chat-scroll-tool-e2e'
  28. const RESTORE_SESSION_A_ID = 'chat-scroll-restore-a-e2e'
  29. const RESTORE_SESSION_B_ID = 'chat-scroll-restore-b-e2e'
  30. const REPLAY_CONTEXT_WINDOW = 10_000_000
  31. const STREAM_PACE_MS = 24
  32. const GEOMETRY_TOLERANCE = 2
  33. const RESPONSIVE_REFLOW_TOLERANCE = 32
  34. const LIVE_TEXT_PROMPT = 'CHAT_SCROLL_LIVE_USER Continue this long conversation while I inspect older history.'
  35. const LIVE_TEXT_FIRST = 'CHAT_SCROLL_LIVE_FIRST'
  36. const LIVE_TEXT_DONE = 'CHAT_SCROLL_LIVE_DONE'
  37. const LIVE_TOOL_PROMPT = 'CHAT_SCROLL_TOOL_USER Run the requested diagnostic and then summarize it.'
  38. const LIVE_TOOL_CALL_ID = ToolCallId('chat-scroll-live-tool-call')
  39. const LIVE_TOOL_RESULT = 'CHAT_SCROLL_LIVE_TOOL_RESULT'
  40. const LIVE_TOOL_FIRST = 'CHAT_SCROLL_TOOL_STREAM_FIRST'
  41. const LIVE_TOOL_DONE = 'CHAT_SCROLL_TOOL_STREAM_DONE'
  42. const TOOL_READY_FILE = '.chat-scroll-tool-ready'
  43. const TOOL_RELEASE_FILE = '.chat-scroll-tool-release'
  44. const INPUTS_SESSION_ID = 'chat-scroll-inputs-e2e'
  45. const RAIL_SESSION_ID = 'chat-scroll-rail-e2e'
  46. const FLING_SESSION_ID = 'chat-scroll-fling-e2e'
  47. const LIVE_FLING_PROMPT = 'CHAT_SCROLL_FLING_USER Keep streaming while I fling back through older output.'
  48. const LIVE_FLING_FIRST = 'CHAT_SCROLL_FLING_STREAM_FIRST'
  49. const LIVE_FLING_DONE = 'CHAT_SCROLL_FLING_STREAM_DONE'
  50. const HISTORY_FIXTURE = createChatScrollFixture({
  51. markerPrefix: 'HISTORY',
  52. title: 'CHAT_SCROLL_HISTORY long paging session',
  53. })
  54. const TOOL_FIXTURE = createChatScrollFixture({
  55. markerPrefix: 'TOOL',
  56. title: 'CHAT_SCROLL_TOOL live tool session',
  57. })
  58. const RESTORE_FIXTURE_A = createChatScrollFixture({
  59. markerPrefix: 'RESTORE_A',
  60. title: 'CHAT_SCROLL_RESTORE_A long session',
  61. })
  62. const RESTORE_FIXTURE_B = createChatScrollFixture({
  63. markerPrefix: 'RESTORE_B',
  64. title: 'CHAT_SCROLL_RESTORE_B comparison session',
  65. turns: 32,
  66. })
  67. const INPUTS_FIXTURE = createChatScrollFixture({
  68. markerPrefix: 'INPUTS',
  69. title: 'CHAT_SCROLL_INPUTS non-wheel reader input session',
  70. })
  71. interface ScrollGeometry {
  72. readonly distanceFromBottom: number
  73. readonly scrollTop: number
  74. }
  75. interface FlowAnchor {
  76. readonly key: string
  77. readonly top: number
  78. }
  79. interface ScrollWorld {
  80. readonly assistantFrames: AssistantStreamFrame[]
  81. readonly events: SessionEvent[]
  82. readonly page: Page
  83. readonly replayDir?: string
  84. readonly scaffold: WebScaffold
  85. readonly tripwire: ReturnType<typeof watchConsole>
  86. }
  87. interface ScrollWorldOptions {
  88. readonly failureShot: string
  89. readonly replay?: ReplayOverrideDoc
  90. readonly seeds: readonly { fixture: ChatScrollFixture; id: string }[]
  91. }
  92. function textStream(first: string, done: string, deltaCount: number): StreamChunk[] {
  93. const deltas = Array.from({ length: deltaCount }, (_, index) => {
  94. if (index === 0) return `${first} `
  95. if (index === deltaCount - 1) return `${done}.`
  96. return `stream-chunk-${String(index).padStart(3, '0')} ${'incremental response '.repeat(3)}`
  97. })
  98. const response = deltas.join('')
  99. return [
  100. { type: 'block-start', index: 0, blockType: 'text' },
  101. ...deltas.map(text => ({ type: 'text-delta' as const, index: 0, text })),
  102. { type: 'block-end', index: 0, block: { type: 'text', text: response } },
  103. {
  104. type: 'usage',
  105. usage: { inputTokens: 512, outputTokens: Math.ceil(response.length / 4) },
  106. },
  107. { type: 'finish', reason: { kind: 'stop' } },
  108. ]
  109. }
  110. function toolStream(): StreamChunk[] {
  111. const command = [
  112. `: > ${TOOL_READY_FILE}`,
  113. `while [ ! -f ${TOOL_RELEASE_FILE} ]; do sleep 0.02; done`,
  114. 'line=1',
  115. `while [ "$line" -le 64 ]; do printf '${LIVE_TOOL_RESULT} line %02d\\n' "$line"; line=$((line + 1)); done`,
  116. ].join('; ')
  117. const args = JSON.stringify({ command, description: LIVE_TOOL_RESULT })
  118. return [
  119. { type: 'block-start', index: 0, blockType: 'tool-call' },
  120. {
  121. type: 'tool-call-delta',
  122. index: 0,
  123. id: LIVE_TOOL_CALL_ID,
  124. name: 'bash',
  125. argumentsDelta: args,
  126. },
  127. {
  128. type: 'block-end',
  129. index: 0,
  130. block: { type: 'tool-call', id: LIVE_TOOL_CALL_ID, name: 'bash', arguments: args },
  131. },
  132. { type: 'usage', usage: { inputTokens: 256, outputTokens: 48 } },
  133. { type: 'finish', reason: { kind: 'tool-calls' } },
  134. ]
  135. }
  136. function replayEntry(chunks: StreamChunk[]): ReplayEntry {
  137. return { kind: 'chunks', chunks }
  138. }
  139. async function launchScrollWorld(options: ScrollWorldOptions): Promise<ScrollWorld> {
  140. let replayDir: string | undefined
  141. let scaffold: WebScaffold | undefined
  142. let page: Page | undefined
  143. try {
  144. if (options.replay !== undefined) {
  145. replayDir = await mkdtemp(join(tmpdir(), 'dsh-chat-scroll-replay-'))
  146. const replayOverride = join(replayDir, 'replay.override.json')
  147. await writeFile(replayOverride, JSON.stringify(options.replay))
  148. scaffold = await launchWebScaffold({
  149. replayFixture: join(replayDir, 'override-only.jsonl'),
  150. replayOverride,
  151. paceMs: STREAM_PACE_MS,
  152. replayContextWindow: REPLAY_CONTEXT_WINDOW,
  153. })
  154. } else {
  155. scaffold = await launchWebScaffold({})
  156. }
  157. for (const seed of options.seeds) await seedSession(scaffold, seed.fixture.log, seed.id)
  158. const events: SessionEvent[] = []
  159. const assistantFrames: AssistantStreamFrame[] = []
  160. scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { events.push(event) })
  161. scaffold.ctx.on('agent/assistant-stream', ({ frame }) => { assistantFrames.push(frame) })
  162. page = await newEnglishPage(browser, 900)
  163. const tripwire = watchConsole(page)
  164. await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  165. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  166. // Session-list bootstrap can replace the controlled search state. Wait
  167. // for the seeded baseline before openSeed starts the lazy content query
  168. // (the compact layout dropped group session counts; the Ungrouped bucket
  169. // row is the barrier).
  170. await page.getByText('Ungrouped', { exact: true }).waitFor({ timeout: 30_000 })
  171. return {
  172. assistantFrames,
  173. events,
  174. page,
  175. scaffold,
  176. tripwire,
  177. ...(replayDir === undefined ? {} : { replayDir }),
  178. }
  179. } catch (error) {
  180. const failures: unknown[] = [error]
  181. if (page !== undefined) await page.context().close().catch((cleanupError: unknown) => failures.push(cleanupError))
  182. if (scaffold !== undefined) await scaffold.close().catch((cleanupError: unknown) => failures.push(cleanupError))
  183. if (replayDir !== undefined) {
  184. await rm(replayDir, { recursive: true, force: true }).catch((cleanupError: unknown) => failures.push(cleanupError))
  185. }
  186. if (failures.length === 1) throw error
  187. throw new AggregateError(failures, 'chat-scroll browser world setup failed and cleanup was incomplete')
  188. }
  189. }
  190. async function closeScrollWorld(world: ScrollWorld): Promise<void> {
  191. const failures: unknown[] = []
  192. // newEnglishPage/browser.newPage owns an isolated context. Close the whole
  193. // context so its SSE connection and cache cannot leak into the next world
  194. // in this file's shared Chromium process.
  195. await world.page.context().close().catch((error: unknown) => failures.push(error))
  196. await world.scaffold.close().catch((error: unknown) => failures.push(error))
  197. if (world.replayDir !== undefined) {
  198. await rm(world.replayDir, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  199. }
  200. if (failures.length === 1) throw failures[0]
  201. if (failures.length > 1) throw new AggregateError(failures, 'chat-scroll browser world cleanup failed')
  202. }
  203. async function withScrollWorld(
  204. options: ScrollWorldOptions,
  205. run: (world: ScrollWorld) => Promise<void>,
  206. ): Promise<void> {
  207. const world = await launchScrollWorld(options)
  208. let runFailure: unknown
  209. try {
  210. await run(world)
  211. } catch (error) {
  212. runFailure = error
  213. try {
  214. await saveFailureShot(world.page, options.failureShot)
  215. } catch {
  216. // Best-effort evidence must never prevent cleanup of the owned world.
  217. }
  218. }
  219. let cleanupFailure: unknown
  220. try {
  221. await closeScrollWorld(world)
  222. } catch (error) {
  223. cleanupFailure = error
  224. }
  225. if (runFailure !== undefined && cleanupFailure !== undefined) {
  226. throw new AggregateError([runFailure, cleanupFailure], 'chat-scroll scenario and cleanup both failed')
  227. }
  228. if (runFailure !== undefined) throw runFailure
  229. if (cleanupFailure !== undefined) throw cleanupFailure
  230. }
  231. async function nextPaint(page: Page): Promise<void> {
  232. await page.evaluate(async () => {
  233. await document.fonts.ready
  234. await new Promise<void>(resolve => requestAnimationFrame(() => {
  235. requestAnimationFrame(() => { resolve() })
  236. }))
  237. })
  238. }
  239. function scrollGeometry(page: Page): Promise<ScrollGeometry> {
  240. return page.locator('[data-conversation-scroll]').evaluate(host => ({
  241. distanceFromBottom: host.scrollHeight - host.clientHeight - host.scrollTop,
  242. scrollTop: host.scrollTop,
  243. }))
  244. }
  245. /**
  246. * Rendered transcript rows in the loaded window. The stats strip cannot serve
  247. * as this probe: its turn/step counts ride the whole-log sessionStats
  248. * projection and stay fixed across paging by design, while the row count is
  249. * exactly what grows when an older page prepends or a live turn streams in.
  250. * @param page - the scenario page.
  251. * @returns the number of mounted chat flow rows.
  252. */
  253. async function loadedFlowRows(page: Page): Promise<number> {
  254. return page.locator('[data-chat-flow-key]').count()
  255. }
  256. async function openSeed(page: Page, fixture: ChatScrollFixture, tailMarker?: string): Promise<void> {
  257. // Search collapsed into a header action; expand it before filling.
  258. const searchButton = page.getByRole('button', { name: 'Search sessions' })
  259. if (await searchButton.getAttribute('aria-expanded') !== 'true') await searchButton.click()
  260. const search = page.getByRole('textbox', { name: 'Search sessions...', exact: true })
  261. // Cold summaries initially show the temporary workspace basename, so the
  262. // persisted first-prompt marker is the stable user-facing identity. The
  263. // query itself triggers lazy content-index reconciliation; no transient
  264. // empty-state paint is used as a barrier.
  265. await search.fill(fixture.markers.user(1))
  266. const results = page.getByRole('tree', { name: 'Search results' }).getByRole('treeitem')
  267. await expect.poll(() => results.count(), { timeout: 60_000 }).toBe(1)
  268. await results.click()
  269. await page.getByRole('tab', { name: 'Chat', exact: true }).waitFor({ timeout: 30_000 })
  270. if (tailMarker !== undefined) {
  271. await page.getByText(tailMarker, { exact: false }).last().waitFor({ timeout: 30_000 })
  272. }
  273. await nextPaint(page)
  274. }
  275. async function wheelTranscript(page: Page, deltaY: number): Promise<void> {
  276. const box = await page.locator('[data-conversation-scroll]').boundingBox()
  277. if (box === null) throw new Error('conversation scrollport has no layout box')
  278. await page.mouse.move(box.x + box.width / 2, box.y + Math.min(140, box.height / 3))
  279. await page.mouse.wheel(0, deltaY)
  280. await nextPaint(page)
  281. }
  282. /**
  283. * Touch-style momentum fling over the transcript. Headless Chromium in the
  284. * test lane cannot synthesize device scrolling (Input.synthesizeScrollGesture
  285. * and Input.dispatchTouchEvent both deliver DOM events without moving any
  286. * scroller, and compositor scrollbars ignore synthetic mouse input), so the
  287. * fling replays the signature a real pan leaves on the scrollport: per-frame
  288. * decaying displacements the component never authored, carrying no wheel
  289. * events. Wheel-sign semantics: positive deltaY reads downward.
  290. */
  291. async function flingTranscript(page: Page, deltaY: number): Promise<void> {
  292. await page.locator('[data-conversation-scroll]').evaluate(async (host, delta) => {
  293. const direction = Math.sign(delta)
  294. let remaining = Math.abs(delta)
  295. // Fast launch decaying toward a floor speed, like a released finger. The
  296. // floor stays above the follow threshold so contended frames (streaming
  297. // writes racing the fling) still deviate far enough to read as input.
  298. let velocity = Math.max(120, remaining / 8)
  299. while (remaining > 0) {
  300. const step = Math.min(velocity, remaining)
  301. host.scrollTop += direction * step
  302. remaining -= step
  303. velocity = Math.max(48, velocity * 0.9)
  304. await new Promise<void>(resolve => requestAnimationFrame(() => { resolve() }))
  305. }
  306. }, deltaY)
  307. await nextPaint(page)
  308. }
  309. async function wheelToHistoryStart(page: Page): Promise<void> {
  310. for (let attempt = 0; attempt < 12; attempt += 1) {
  311. if ((await scrollGeometry(page)).scrollTop <= 1) break
  312. await wheelTranscript(page, -2_400)
  313. }
  314. await expect.poll(async () => (await scrollGeometry(page)).scrollTop, { timeout: 10_000 })
  315. .toBeLessThanOrEqual(1)
  316. }
  317. async function wheelUntilMounted(page: Page, selector: string, deltaY: number): Promise<void> {
  318. for (let attempt = 0; attempt < 16; attempt += 1) {
  319. if (await page.locator(selector).count() > 0) return
  320. await wheelTranscript(page, deltaY)
  321. }
  322. throw new Error(`selector did not mount during transcript wheel: ${selector}`)
  323. }
  324. async function wheelUntilVisible(page: Page, selector: string, deltaY: number): Promise<void> {
  325. const target = page.locator(selector)
  326. for (let attempt = 0; attempt < 32; attempt += 1) {
  327. if (await target.count() > 0 && await target.evaluate((row) => {
  328. const host = row.closest<HTMLElement>('[data-conversation-scroll]')
  329. if (host === null) return false
  330. const viewport = host.getBoundingClientRect()
  331. const composer = host.querySelector<HTMLElement>('[data-composer-seat]')
  332. const visibleBottom = composer?.getBoundingClientRect().top ?? viewport.bottom
  333. const rect = row.getBoundingClientRect()
  334. return rect.bottom > viewport.top && rect.top < visibleBottom
  335. })) return
  336. await wheelTranscript(page, deltaY)
  337. }
  338. throw new Error(`selector did not become visible during transcript wheel: ${selector}`)
  339. }
  340. function visibleFlowAnchor(page: Page): Promise<FlowAnchor> {
  341. return page.locator('[data-conversation-scroll]').evaluate((host) => {
  342. const rows = [...host.querySelectorAll<HTMLElement>('[data-chat-anchor-key]:not([hidden])')]
  343. const viewport = host.getBoundingClientRect()
  344. const composer = host.querySelector<HTMLElement>('[data-composer-seat]')
  345. const visibleBottom = composer?.getBoundingClientRect().top ?? viewport.bottom
  346. const visible = rows.filter((candidate) => {
  347. const rect = candidate.getBoundingClientRect()
  348. return rect.bottom > viewport.top && rect.top < visibleBottom
  349. })
  350. const row = visible[0]
  351. if (row?.dataset.chatAnchorKey === undefined) {
  352. throw new Error(`no visible settled Chat row: ${JSON.stringify({
  353. composerTop: visibleBottom,
  354. host: { bottom: viewport.bottom, top: viewport.top },
  355. rows: rows.slice(0, 4).map(candidate => ({
  356. callId: candidate.dataset.chatCallId,
  357. key: candidate.dataset.chatAnchorKey,
  358. rect: {
  359. bottom: candidate.getBoundingClientRect().bottom,
  360. top: candidate.getBoundingClientRect().top,
  361. },
  362. })),
  363. totalRows: rows.length,
  364. })}`)
  365. }
  366. return {
  367. key: row.dataset.chatAnchorKey,
  368. top: row.getBoundingClientRect().top - viewport.top,
  369. }
  370. })
  371. }
  372. function flowTop(page: Page, key: string): Promise<number> {
  373. return page.locator('[data-chat-anchor-key]').evaluateAll((rows, anchorKey) => {
  374. const row = rows.find(candidate => (candidate as HTMLElement).dataset.chatAnchorKey === anchorKey)
  375. if (!(row instanceof HTMLElement)) throw new Error(`stable Chat anchor ${anchorKey} is not mounted`)
  376. const host = row.closest('[data-conversation-scroll]')
  377. if (!(host instanceof HTMLElement)) throw new Error('flow row has no conversation scrollport')
  378. return row.getBoundingClientRect().top - host.getBoundingClientRect().top
  379. }, key)
  380. }
  381. async function expectSameFlowTop(
  382. page: Page,
  383. anchor: FlowAnchor,
  384. tolerance = GEOMETRY_TOLERANCE,
  385. ): Promise<void> {
  386. await expect.poll(async () => Math.abs((await flowTop(page, anchor.key)) - anchor.top), {
  387. timeout: 10_000,
  388. message: `flow row ${anchor.key} moved relative to the transcript viewport`,
  389. }).toBeLessThanOrEqual(tolerance)
  390. }
  391. async function expectBottom(page: Page): Promise<void> {
  392. await expect.poll(async () => Math.abs((await scrollGeometry(page)).distanceFromBottom), {
  393. timeout: 10_000,
  394. }).toBeLessThanOrEqual(1)
  395. }
  396. async function expectMarkerAboveComposer(page: Page, marker: string): Promise<void> {
  397. const geometry = await page.getByText(marker, { exact: false }).last().evaluate((node) => {
  398. const row = node.closest('[data-chat-flow-key], [data-streaming]')
  399. const composer = node.closest('[data-conversation-scroll]')?.querySelector('[data-composer-seat]')
  400. if (!(row instanceof HTMLElement) || !(composer instanceof HTMLElement)) {
  401. throw new Error('latest marker or composer geometry is unavailable')
  402. }
  403. return {
  404. composerTop: composer.getBoundingClientRect().top,
  405. rowBottom: row.getBoundingClientRect().bottom,
  406. }
  407. })
  408. expect(geometry.rowBottom).toBeLessThanOrEqual(geometry.composerTop + GEOMETRY_TOLERANCE)
  409. }
  410. async function loadEarlierWithAnchor(page: Page): Promise<void> {
  411. await wheelToHistoryStart(page)
  412. const older = page.getByRole('button', { name: 'Load earlier', exact: true })
  413. const loading = page.getByRole('button', { name: 'Loading…', exact: true })
  414. await older.waitFor({ timeout: 10_000 })
  415. const anchor = await visibleFlowAnchor(page)
  416. const before = await loadedFlowRows(page)
  417. await older.click()
  418. await expect.poll(async () => (
  419. await loadedFlowRows(page) > before && await loading.count() === 0
  420. ), { timeout: 30_000 }).toBe(true)
  421. await nextPaint(page)
  422. if (await page.getByRole('button', { name: 'Load earlier', exact: true }).count() === 0) {
  423. expect(await page.locator('[data-turn-process][aria-expanded="false"]').count()).toBeGreaterThan(0)
  424. return
  425. }
  426. await expectSameFlowTop(page, anchor)
  427. }
  428. async function fileExists(path: string): Promise<boolean> {
  429. try {
  430. await access(path)
  431. return true
  432. } catch {
  433. return false
  434. }
  435. }
  436. function eventCarries(event: SessionEvent, marker: string): boolean {
  437. return JSON.stringify(event).includes(marker)
  438. }
  439. function assertClean(world: ScrollWorld): void {
  440. expect(world.tripwire.pageErrors).toEqual([])
  441. expect(world.tripwire.warnings).toEqual([])
  442. }
  443. let browser: Browser
  444. describe('web e2e: long Chat scroll contract', () => {
  445. beforeAll(async () => {
  446. browser = await chromium.launch()
  447. })
  448. afterAll(async () => {
  449. await browser?.close()
  450. })
  451. it.skipIf(MODE === 'record')('preserves the reader anchor when history and streaming arrive concurrently', async () => {
  452. await withScrollWorld({
  453. failureShot: 'web-e2e-chat-scroll-history-stream',
  454. replay: [replayEntry(textStream(LIVE_TEXT_FIRST, LIVE_TEXT_DONE, 120))],
  455. seeds: [{ fixture: HISTORY_FIXTURE, id: HISTORY_SESSION_ID }],
  456. }, async (world) => {
  457. await openSeed(
  458. world.page,
  459. HISTORY_FIXTURE,
  460. HISTORY_FIXTURE.markers.assistant(HISTORY_FIXTURE.turns),
  461. )
  462. await expectBottom(world.page)
  463. let releaseHistory = (): void => {}
  464. let held = false
  465. let releaseGate: (() => void) | undefined
  466. const gate = new Promise<void>((resolve) => { releaseGate = resolve })
  467. releaseHistory = () => { releaseGate?.() }
  468. await world.page.route('**/api/session/page', async (route) => {
  469. const request = route.request().postDataJSON() as {
  470. method?: string
  471. payload?: { args?: { request?: { beforeSeq?: number } } }
  472. }
  473. if (!held && request.method === 'session/page'
  474. && request.payload?.args?.request?.beforeSeq !== undefined) {
  475. held = true
  476. await gate
  477. }
  478. await route.continue()
  479. })
  480. const settled = world.scaffold.whenTurnSettled(60_000)
  481. try {
  482. const composer = world.page.locator('[data-composer-input][contenteditable="true"]').last()
  483. await composer.fill(LIVE_TEXT_PROMPT)
  484. await world.page.getByRole('button', { name: 'Send message', exact: true }).click()
  485. await world.page.getByText(LIVE_TEXT_FIRST, { exact: false }).last().waitFor({ timeout: 15_000 })
  486. await wheelToHistoryStart(world.page)
  487. const beforeRows = await loadedFlowRows(world.page)
  488. await world.page.getByRole('button', { name: 'Load earlier', exact: true }).click()
  489. await expect.poll(() => held, { timeout: 10_000 }).toBe(true)
  490. await wheelTranscript(world.page, 420)
  491. const readerAnchor = await visibleFlowAnchor(world.page)
  492. const chunksAfterAnchor = world.assistantFrames.filter(frame => frame.type === 'chunk').length
  493. await expect.poll(
  494. () => world.assistantFrames.filter(frame => frame.type === 'chunk').length,
  495. { timeout: 10_000 },
  496. ).toBeGreaterThan(chunksAfterAnchor + 5)
  497. releaseHistory()
  498. await expect.poll(() => loadedFlowRows(world.page), { timeout: 30_000 }).toBeGreaterThan(beforeRows)
  499. await nextPaint(world.page)
  500. await expectSameFlowTop(world.page, readerAnchor)
  501. } finally {
  502. releaseHistory()
  503. }
  504. await settled
  505. await expect.poll(() => world.page.locator('[data-streaming="true"]').count(), { timeout: 15_000 }).toBe(0)
  506. await world.page.getByText(LIVE_TEXT_DONE, { exact: false }).last().waitFor({ timeout: 15_000 })
  507. await world.page.unroute('**/api/session/page')
  508. let additionalPages = 0
  509. while (additionalPages < 8) {
  510. await wheelToHistoryStart(world.page)
  511. if (await world.page.getByRole('button', { name: 'Load earlier', exact: true }).count() === 0) break
  512. await loadEarlierWithAnchor(world.page)
  513. additionalPages += 1
  514. }
  515. expect(additionalPages).toBeGreaterThan(0)
  516. // The whole log is loaded: turn 1's unique marker renders in the
  517. // transcript (scoped: the sidebar search row also carries it) and no
  518. // page remains.
  519. expect(await world.page.locator('[data-conversation-scroll]')
  520. .getByText(HISTORY_FIXTURE.markers.user(1), { exact: false }).count()).toBe(1)
  521. expect(await world.page.getByRole('button', { name: 'Load earlier', exact: true }).count()).toBe(0)
  522. assertClean(world)
  523. })
  524. }, 180_000)
  525. it.skipIf(MODE === 'record')('offers every outline turn on the rail and jumps to an unloaded one', async () => {
  526. await withScrollWorld({
  527. failureShot: 'web-e2e-turn-rail-jump',
  528. seeds: [{ fixture: HISTORY_FIXTURE, id: RAIL_SESSION_ID }],
  529. }, async (world) => {
  530. await openSeed(world.page, HISTORY_FIXTURE, HISTORY_FIXTURE.markers.assistant(HISTORY_FIXTURE.turns))
  531. await expectBottom(world.page)
  532. // The whole-log outline reaches the rail before any paging: one mark
  533. // per fixture turn, the oldest still in its load-and-jump form.
  534. const rail = world.page.getByRole('navigation', { name: 'Turn navigation' })
  535. await expect.poll(() => rail.getByRole('button').count(), { timeout: 15_000 })
  536. .toBe(HISTORY_FIXTURE.turns)
  537. const firstUnloaded = rail.getByRole('button', { name: 'Load and jump to turn 1', exact: true })
  538. expect(await firstUnloaded.count()).toBe(1)
  539. // Fixed pitch: the ladder keeps its natural height, scrolls inside the
  540. // frame, and (following the active tail mark) fades its upper end.
  541. expect(await rail.evaluate(nav => nav.style.getPropertyValue('--turn-natural-height')))
  542. .toBe(`${String((HISTORY_FIXTURE.turns - 1) * 10 + 12)}px`)
  543. const railScroller = rail.locator('[class*="scroller"]')
  544. await expect.poll(() => railScroller.evaluate(el => el.scrollHeight > el.clientHeight)).toBe(true)
  545. await expect.poll(() => rail.locator('[class*="fadeTop"]').count(), { timeout: 15_000 }).toBe(1)
  546. // Activate the unloaded mark by keyboard: pointer input belongs to the
  547. // rail frame, while each mark is the keyboard/AT destination. Focus
  548. // first shows the outline-backed preview: prompt and settled response
  549. // both travel ahead of the events.
  550. const beforeRows = await loadedFlowRows(world.page)
  551. await firstUnloaded.focus()
  552. const tooltip = world.page.getByRole('tooltip')
  553. await expect.poll(() => tooltip.count(), { timeout: 15_000 }).toBe(1)
  554. expect(await tooltip.textContent()).toContain(HISTORY_FIXTURE.markers.user(1))
  555. expect(await tooltip.textContent()).toContain(HISTORY_FIXTURE.markers.assistant(1))
  556. const transcriptLayers = await tooltip.evaluate((preview) => {
  557. const railSlot = preview.closest('nav')?.parentElement
  558. const codeBanner = document.querySelector<HTMLElement>('.md-code-block > :first-child')
  559. if (!(railSlot instanceof HTMLElement) || codeBanner === null) {
  560. throw new Error('turn preview or code-block banner stacking context is unavailable')
  561. }
  562. return {
  563. codeBanner: Number(getComputedStyle(codeBanner).zIndex),
  564. rail: Number(getComputedStyle(railSlot).zIndex),
  565. }
  566. })
  567. expect(transcriptLayers.rail).toBeGreaterThan(transcriptLayers.codeBanner)
  568. await world.page.keyboard.press('Enter')
  569. // The jump pages history in and lands on turn 1: its mark flips to the
  570. // loaded label and becomes current, the window grew, and the turn-1
  571. // user row sits at the reading line.
  572. const firstLoaded = rail.getByRole('button', { name: 'Jump to turn 1', exact: true })
  573. await expect.poll(() => firstLoaded.count(), { timeout: 60_000 }).toBe(1)
  574. await expect.poll(() => firstLoaded.getAttribute('aria-current'), { timeout: 15_000 }).toBe('true')
  575. expect(await loadedFlowRows(world.page)).toBeGreaterThan(beforeRows)
  576. // Drop mark focus so its hover/focus preview (which echoes the prompt
  577. // marker) leaves the DOM before the transcript count below.
  578. await firstLoaded.evaluate((el) => { (el as HTMLElement).blur() })
  579. await expect.poll(() => world.page.getByRole('tooltip').count(), { timeout: 15_000 }).toBe(0)
  580. await nextPaint(world.page)
  581. const marker = world.page.locator('[data-conversation-scroll]')
  582. .getByText(HISTORY_FIXTURE.markers.user(1), { exact: false })
  583. expect(await marker.count()).toBe(1)
  584. const scrollport = await world.page.locator('[data-conversation-scroll]').boundingBox()
  585. const row = await marker.boundingBox()
  586. if (scrollport === null || row === null) throw new Error('turn-1 row or scrollport has no layout box')
  587. expect(row.y - scrollport.y).toBeGreaterThanOrEqual(0)
  588. expect(row.y - scrollport.y).toBeLessThanOrEqual(160)
  589. // The rail followed the landing to the ladder top, so the fade now
  590. // marks the other (downward) end.
  591. await expect.poll(() => rail.locator('[class*="fadeBottom"]').count(), { timeout: 15_000 }).toBe(1)
  592. assertClean(world)
  593. })
  594. }, 180_000)
  595. it.skipIf(MODE === 'record')('keeps streaming ownership and tool disclosure state across a long scroll-away cycle', async () => {
  596. await withScrollWorld({
  597. failureShot: 'web-e2e-chat-scroll-live-tool',
  598. replay: [
  599. replayEntry(toolStream()),
  600. replayEntry(textStream(LIVE_TOOL_FIRST, LIVE_TOOL_DONE, 84)),
  601. ],
  602. seeds: [{ fixture: TOOL_FIXTURE, id: TOOL_SESSION_ID }],
  603. }, async (world) => {
  604. const readyPath = join(world.scaffold.workspaceCwd, TOOL_READY_FILE)
  605. const releasePath = join(world.scaffold.workspaceCwd, TOOL_RELEASE_FILE)
  606. await openSeed(world.page, TOOL_FIXTURE, TOOL_FIXTURE.markers.assistant(TOOL_FIXTURE.turns))
  607. const settled = world.scaffold.whenTurnSettled(60_000)
  608. let released = false
  609. try {
  610. const composer = world.page.locator('[data-composer-input][contenteditable="true"]').last()
  611. await composer.fill(LIVE_TOOL_PROMPT)
  612. await world.page.getByRole('button', { name: 'Send message', exact: true }).click()
  613. await expect.poll(() => fileExists(readyPath), { timeout: 15_000 }).toBe(true)
  614. const liveRow = world.page.locator(`[data-chat-call-id="${LIVE_TOOL_CALL_ID}"] [data-sample="bash"]`)
  615. await liveRow.waitFor({ timeout: 15_000 })
  616. expect(await liveRow.getAttribute('data-state')).toBe('running')
  617. await expectBottom(world.page)
  618. await wheelTranscript(world.page, -1_200)
  619. await world.page.getByRole('button', { name: 'Back to bottom', exact: true }).waitFor({ timeout: 10_000 })
  620. const awayAnchor = await visibleFlowAnchor(world.page)
  621. const chunksBeforeRelease = world.assistantFrames.filter(frame => frame.type === 'chunk').length
  622. await writeFile(releasePath, 'release\n')
  623. released = true
  624. await expect.poll(
  625. () => world.assistantFrames.filter(frame => frame.type === 'chunk').length,
  626. { timeout: 15_000 },
  627. ).toBeGreaterThan(chunksBeforeRelease + 5)
  628. await nextPaint(world.page)
  629. // The loop appends tool/result before starting the next model request;
  630. // these synchronous Host listeners therefore observe it before later chunks.
  631. expect(world.events.some(event => event.type === 'tool/result')).toBe(true)
  632. expect(Math.abs((await flowTop(world.page, awayAnchor.key)) - awayAnchor.top))
  633. .toBeLessThanOrEqual(GEOMETRY_TOLERANCE)
  634. const chunksAtRepin = world.assistantFrames.filter(frame => frame.type === 'chunk').length
  635. await world.page.getByRole('button', { name: 'Back to bottom', exact: true }).click()
  636. await expect.poll(
  637. () => world.assistantFrames.filter(frame => frame.type === 'chunk').length,
  638. { timeout: 15_000 },
  639. ).toBeGreaterThan(chunksAtRepin + 5)
  640. await nextPaint(world.page)
  641. expect(Math.abs((await scrollGeometry(world.page)).distanceFromBottom)).toBeLessThanOrEqual(1)
  642. } finally {
  643. if (!released) await writeFile(releasePath, 'release\n').catch(() => {})
  644. }
  645. await settled
  646. expect(world.events.some(event => eventCarries(event, LIVE_TOOL_FIRST))).toBe(true)
  647. await expect.poll(() => world.page.locator('[data-streaming="true"]').count(), { timeout: 15_000 }).toBe(0)
  648. await world.page.getByText(LIVE_TOOL_DONE, { exact: false }).last().waitFor({ timeout: 15_000 })
  649. await expectBottom(world.page)
  650. await expectMarkerAboveComposer(world.page, LIVE_TOOL_DONE)
  651. const liveRowSelector = `[data-chat-call-id="${LIVE_TOOL_CALL_ID}"] [data-sample="bash"]`
  652. const liveRow = world.page.locator(liveRowSelector)
  653. await expandOwningTurnProcess(world.page, liveRow)
  654. await wheelUntilVisible(world.page, liveRowSelector, -300)
  655. const toolAnchor = await liveRow.evaluate((row) => {
  656. const flow = row.closest<HTMLElement>('[data-chat-anchor-key]')
  657. const host = row.closest<HTMLElement>('[data-conversation-scroll]')
  658. if (flow?.dataset.chatAnchorKey === undefined || host === null) {
  659. throw new Error('live tool row has no settled flow identity')
  660. }
  661. return {
  662. key: flow.dataset.chatAnchorKey,
  663. top: flow.getBoundingClientRect().top - host.getBoundingClientRect().top,
  664. }
  665. })
  666. await liveRow.click()
  667. await expect.poll(() => liveRow.getAttribute('aria-expanded'), { timeout: 10_000 }).toBe('true')
  668. await expectSameFlowTop(world.page, toolAnchor)
  669. await wheelToHistoryStart(world.page)
  670. await world.page.getByRole('button', { name: 'Back to bottom', exact: true }).click()
  671. await expectBottom(world.page)
  672. await wheelUntilMounted(world.page, liveRowSelector, -1_100)
  673. const restoredRow = world.page.locator(liveRowSelector)
  674. await restoredRow.waitFor({ timeout: 10_000 })
  675. expect(await restoredRow.getAttribute('aria-expanded')).toBe('true')
  676. expect(await world.page.getByText(LIVE_TOOL_RESULT, { exact: false }).count()).toBeGreaterThan(0)
  677. assertClean(world)
  678. })
  679. }, 180_000)
  680. it.skipIf(MODE === 'record')('restores tab/session position and keeps composer resizing on the correct scroll owner', async () => {
  681. await withScrollWorld({
  682. failureShot: 'web-e2e-chat-scroll-restore-composer',
  683. seeds: [
  684. { fixture: RESTORE_FIXTURE_A, id: RESTORE_SESSION_A_ID },
  685. { fixture: RESTORE_FIXTURE_B, id: RESTORE_SESSION_B_ID },
  686. ],
  687. }, async (world) => {
  688. await openSeed(
  689. world.page,
  690. RESTORE_FIXTURE_A,
  691. RESTORE_FIXTURE_A.markers.assistant(RESTORE_FIXTURE_A.turns),
  692. )
  693. await loadEarlierWithAnchor(world.page)
  694. await loadEarlierWithAnchor(world.page)
  695. await wheelToHistoryStart(world.page)
  696. await wheelTranscript(world.page, 1_300)
  697. const sessionAnchor = await visibleFlowAnchor(world.page)
  698. await world.page.getByRole('tab', { name: 'Trajectory', exact: true }).click()
  699. await world.page.getByLabel('Trajectory timeline').waitFor({ timeout: 30_000 })
  700. await world.page.setViewportSize({ width: 700, height: 900 })
  701. // The narrow breakpoint auto-collapses the sidebar. Re-open it because
  702. // this scenario switches sessions while pinning the narrow Chat scroll owner.
  703. await world.page.getByRole('button', { name: 'Open sidebar', exact: true }).click()
  704. await world.page.getByRole('tab', { name: 'Chat', exact: true }).click()
  705. await nextPaint(world.page)
  706. await expectSameFlowTop(world.page, sessionAnchor, RESPONSIVE_REFLOW_TOLERANCE)
  707. const narrowSessionAnchor = await visibleFlowAnchor(world.page)
  708. await openSeed(
  709. world.page,
  710. RESTORE_FIXTURE_B,
  711. RESTORE_FIXTURE_B.markers.assistant(RESTORE_FIXTURE_B.turns),
  712. )
  713. await openSeed(
  714. world.page,
  715. RESTORE_FIXTURE_A,
  716. )
  717. await expectSameFlowTop(world.page, narrowSessionAnchor)
  718. const backToBottom = world.page.getByRole('button', { name: 'Back to bottom', exact: true })
  719. await backToBottom.evaluate((button) => {
  720. if (!(button instanceof HTMLElement)) throw new Error('Back-to-bottom control is not an HTML element')
  721. button.click()
  722. const trajectory = [...document.querySelectorAll<HTMLElement>('[role="tab"]')]
  723. .find(tab => tab.textContent?.trim() === 'Trajectory')
  724. if (!(trajectory instanceof HTMLElement)) {
  725. throw new Error('Trajectory tab is unavailable during pinned remount')
  726. }
  727. trajectory.click()
  728. })
  729. await world.page.getByLabel('Trajectory timeline').waitFor({ timeout: 30_000 })
  730. await world.page.getByRole('tab', { name: 'Chat', exact: true }).click()
  731. await expectBottom(world.page)
  732. await openSeed(
  733. world.page,
  734. RESTORE_FIXTURE_B,
  735. RESTORE_FIXTURE_B.markers.assistant(RESTORE_FIXTURE_B.turns),
  736. )
  737. await openSeed(
  738. world.page,
  739. RESTORE_FIXTURE_A,
  740. RESTORE_FIXTURE_A.markers.assistant(RESTORE_FIXTURE_A.turns),
  741. )
  742. await expectBottom(world.page)
  743. const composer = world.page.locator('[data-composer-input][contenteditable="true"]').last()
  744. const longDraft = Array.from(
  745. { length: 18 },
  746. (_, index) => `composer resize line ${String(index + 1).padStart(2, '0')}`,
  747. ).join('\n')
  748. await composer.fill(longDraft)
  749. await nextPaint(world.page)
  750. await expectBottom(world.page)
  751. await expectMarkerAboveComposer(
  752. world.page,
  753. RESTORE_FIXTURE_A.markers.assistant(RESTORE_FIXTURE_A.turns),
  754. )
  755. await composer.fill('short draft')
  756. await nextPaint(world.page)
  757. await wheelTranscript(world.page, -900)
  758. const resizeAnchor = await visibleFlowAnchor(world.page)
  759. await composer.fill(longDraft)
  760. await nextPaint(world.page)
  761. await expectSameFlowTop(world.page, resizeAnchor)
  762. await composer.fill('short draft')
  763. await nextPaint(world.page)
  764. await expectSameFlowTop(world.page, resizeAnchor)
  765. const beforeChain = await scrollGeometry(world.page)
  766. await composer.hover()
  767. await world.page.mouse.wheel(0, -320)
  768. await expect.poll(async () => (await scrollGeometry(world.page)).scrollTop, { timeout: 10_000 })
  769. .toBeLessThan(beforeChain.scrollTop)
  770. assertClean(world)
  771. })
  772. }, 180_000)
  773. // Keyboard is the only non-wheel device this lane's Chromium can drive for
  774. // real (see flingTranscript for the probe results on touch and scrollbars),
  775. // so it stands in for the whole hardware input pipeline here.
  776. it.skipIf(MODE === 'record')('keyboard paging owns bottom-follow without wheel input', async () => {
  777. await withScrollWorld({
  778. failureShot: 'web-e2e-chat-scroll-keyboard',
  779. seeds: [{ fixture: INPUTS_FIXTURE, id: INPUTS_SESSION_ID }],
  780. }, async (world) => {
  781. await openSeed(
  782. world.page,
  783. INPUTS_FIXTURE,
  784. INPUTS_FIXTURE.markers.assistant(INPUTS_FIXTURE.turns),
  785. )
  786. await expectBottom(world.page)
  787. const backToBottom = world.page.getByRole('button', { name: 'Back to bottom', exact: true })
  788. // Focus rides the last seeded tool row (a tabbable button whose keydown
  789. // handler passes scrolling keys through). End first normalizes the
  790. // focus-driven scrollIntoView back to the floor.
  791. const lastToolRow = world.page.locator(
  792. `[data-chat-call-id="chat-scroll-${String(INPUTS_FIXTURE.turns).padStart(3, '0')}-1"] [data-sample="bash"]`,
  793. )
  794. await expandOwningTurnProcess(world.page, lastToolRow)
  795. await lastToolRow.focus()
  796. await world.page.keyboard.press('End')
  797. await expectBottom(world.page)
  798. await expect.poll(() => backToBottom.count(), { timeout: 10_000 }).toBe(0)
  799. for (let press = 0; press < 3; press += 1) {
  800. await world.page.keyboard.press('PageUp')
  801. await nextPaint(world.page)
  802. }
  803. await backToBottom.waitFor({ timeout: 10_000 })
  804. await expect.poll(async () => (await scrollGeometry(world.page)).distanceFromBottom, { timeout: 10_000 })
  805. .toBeGreaterThan(100)
  806. await world.page.keyboard.press('End')
  807. await expectBottom(world.page)
  808. await expect.poll(() => backToBottom.count(), { timeout: 10_000 }).toBe(0)
  809. assertClean(world)
  810. })
  811. }, 180_000)
  812. it.skipIf(MODE === 'record')('touch-style fling scrolling owns streaming bottom-follow without wheel input', async () => {
  813. await withScrollWorld({
  814. failureShot: 'web-e2e-chat-scroll-fling-stream',
  815. replay: [
  816. replayEntry(toolStream()),
  817. replayEntry(textStream(LIVE_FLING_FIRST, LIVE_FLING_DONE, 240)),
  818. ],
  819. seeds: [{ fixture: INPUTS_FIXTURE, id: FLING_SESSION_ID }],
  820. }, async (world) => {
  821. const readyPath = join(world.scaffold.workspaceCwd, TOOL_READY_FILE)
  822. const releasePath = join(world.scaffold.workspaceCwd, TOOL_RELEASE_FILE)
  823. await openSeed(world.page, INPUTS_FIXTURE, INPUTS_FIXTURE.markers.assistant(INPUTS_FIXTURE.turns))
  824. const backToBottom = world.page.getByRole('button', { name: 'Back to bottom', exact: true })
  825. const settled = world.scaffold.whenTurnSettled(60_000)
  826. let released = false
  827. try {
  828. const composer = world.page.locator('[data-composer-input][contenteditable="true"]').last()
  829. await composer.fill(LIVE_FLING_PROMPT)
  830. await world.page.getByRole('button', { name: 'Send message', exact: true }).click()
  831. await expect.poll(() => fileExists(readyPath), { timeout: 15_000 }).toBe(true)
  832. await expectBottom(world.page)
  833. // Fling away while the turn is mid-flight: the scroll burst alone must
  834. // release bottom ownership, exactly like a wheel scroll would, even
  835. // while streaming keeps re-asserting the floor between frames.
  836. await flingTranscript(world.page, -900)
  837. await backToBottom.waitFor({ timeout: 10_000 })
  838. const awayAnchor = await visibleFlowAnchor(world.page)
  839. const chunksBeforeRelease = world.assistantFrames.filter(frame => frame.type === 'chunk').length
  840. await writeFile(releasePath, 'release\n')
  841. released = true
  842. await expect.poll(
  843. () => world.events.some(event => event.type === 'tool/result'),
  844. { timeout: 15_000 },
  845. ).toBe(true)
  846. await expect.poll(
  847. () => world.assistantFrames.filter(frame => frame.type === 'chunk').length,
  848. { timeout: 15_000 },
  849. ).toBeGreaterThan(chunksBeforeRelease + 5)
  850. await expectSameFlowTop(world.page, awayAnchor)
  851. // Fling back to the floor: re-pin must come from the reader's scroll
  852. // itself, and follow must then own the still-streaming tail. The
  853. // retry loop chases the floor that streaming keeps pushing down.
  854. for (let attempt = 0; attempt < 8; attempt += 1) {
  855. if ((await scrollGeometry(world.page)).distanceFromBottom <= 1) break
  856. await flingTranscript(world.page, 1_600)
  857. }
  858. await expectBottom(world.page)
  859. await expect.poll(() => backToBottom.count(), { timeout: 10_000 }).toBe(0)
  860. const chunksAtRepin = world.assistantFrames.filter(frame => frame.type === 'chunk').length
  861. await expect.poll(
  862. () => world.assistantFrames.filter(frame => frame.type === 'chunk').length,
  863. { timeout: 15_000 },
  864. ).toBeGreaterThan(chunksAtRepin + 5)
  865. await expectBottom(world.page)
  866. } finally {
  867. if (!released) await writeFile(releasePath, 'release\n').catch(() => {})
  868. }
  869. await settled
  870. await expect.poll(() => world.page.locator('[data-streaming="true"]').count(), { timeout: 15_000 }).toBe(0)
  871. await world.page.getByText(LIVE_FLING_DONE, { exact: false }).last().waitFor({ timeout: 15_000 })
  872. await expectBottom(world.page)
  873. assertClean(world)
  874. })
  875. }, 180_000)
  876. })