chat-scroll-contract.e2e.ts 36 KB

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