chat-scroll-contract.e2e.ts 42 KB

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