chat-scroll-contract.e2e.ts 36 KB

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