chat-scroll-contract.e2e.ts 36 KB

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