composer-draft-scroll.e2e.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. // Web e2e scenario: a composer draft longer than the 14-line cap scrolls its
  2. // GLYPHS, not just its caret.
  3. //
  4. // The composer paints its text in two stacked layers (see
  5. // packages/client/ui-conversation/src/client/skeleton/InputBar.module.css): the
  6. // `<textarea>` carries the value, the selection and the caret but renders its
  7. // own glyphs `color: transparent`, and every visible character is painted by the
  8. // `[data-input-backdrop]` div underneath it, which also carries the claim-token
  9. // highlight, the chips and the ghost hint. The backdrop is `position: absolute;
  10. // inset: 0; overflow: hidden` — it is CLIPPED, not scrolled, and nothing in the
  11. // browser links its scroll offset to the textarea's.
  12. //
  13. // So past the cap the textarea scrolled and the words did not: the caret walked
  14. // off the bottom of a block of text frozen at line 1, and no gesture — wheel,
  15. // drag, arrow key — moved it. `InputBar` now mirrors the offset onto the
  16. // backdrop on every textarea `scroll`, which is the one event every way of
  17. // moving the box ends in.
  18. //
  19. // Mirroring an offset is only correct while both layers can reach it, so the
  20. // geometry underneath is asserted here alongside the visible outcome: the
  21. // backdrop's trailing-line sentinel (a textarea reserves a line box for the
  22. // caret after a final newline; `pre-wrap` collapses one), and one wrap width
  23. // across all three layers (only the textarea scrolls, so only it can lose
  24. // width to a scrollbar that consumes layout space). Either breaks the extent
  25. // equality, and an unreachable offset clamps the glyphs below the caret.
  26. //
  27. // Only a real engine can show this. Scrolling is layout: jsdom reports
  28. // `scrollHeight === clientHeight` for every element and never scrolls one, so
  29. // the unit spec in packages/client/ui-conversation/tests/input-bar.spec.tsx has
  30. // to stub both offsets and can only prove the mirroring code path runs. What is
  31. // asserted here instead is the user-visible fact that path exists for — after
  32. // scrolling to the end of a long draft, the LAST line is the one on screen —
  33. // measured with a DOM Range over the backdrop's own text.
  34. //
  35. // Zero model calls: a fresh workspace's blank session already carries a live
  36. // composer, and the scenario only types into it. A stray stream would fail loud
  37. // with NO_ADAPTER.
  38. import { fileURLToPath } from 'node:url'
  39. import { join } from 'node:path'
  40. import type { Browser, Page } from 'playwright'
  41. import { chromium } from 'playwright'
  42. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  43. import {
  44. assertFixtureInventory, compareOrRefreshGolden, launchWebScaffold, watchConsole,
  45. webSnapshotMode, type WebScaffold,
  46. } from './scaffold.ts'
  47. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  48. const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/composer-draft-scroll', import.meta.url))
  49. /**
  50. * Committed golden of the composer's two-layer scroll geometry. The change
  51. * alters no DOM and no accessible name, so the aria goldens the other scenarios
  52. * commit are byte-identical with and without it; this records the relations
  53. * instead, which makes a shift in the cap or in the layer coupling a reviewable
  54. * diff rather than an assertion someone has to reconstruct.
  55. */
  56. const GEOMETRY_EXPECTED = join(SNAPSHOT_DIR, 'geometry.expected.md')
  57. const MODE = webSnapshotMode()
  58. /** Marks the first and last line so a Range can find them in the backdrop's text. */
  59. const FIRST_MARKER = 'FIRST-LINE-MARKER'
  60. const LAST_MARKER = 'LAST-LINE-MARKER'
  61. /** Comfortably past the 14-line cap, so the draft overflows however the lines wrap. */
  62. const DRAFT_LINES = 40
  63. const DRAFT = Array.from({ length: DRAFT_LINES }, (_unused, index) => {
  64. if (index === 0) return FIRST_MARKER
  65. if (index === DRAFT_LINES - 1) return LAST_MARKER
  66. return `draft line ${String(index + 1).padStart(2, '0')}`
  67. }).join('\n')
  68. /**
  69. * A draft ending in a newline: the shape whose layer extents diverge without
  70. * the backdrop's trailing-line sentinel. A textarea reserves a line box for the
  71. * caret after a final newline; `white-space: pre-wrap` collapses a text node's
  72. * trailing newline and generates none, so the backdrop would come out exactly
  73. * one line shorter and the mirrored offset would clamp a line above the caret.
  74. */
  75. const DRAFT_TRAILING_NEWLINE = `${DRAFT}\n`
  76. /** The composer's two text layers as the browser lays them out. */
  77. interface ComposerMetrics {
  78. /** True when the draft is taller than the capped box — the situation under test. */
  79. overflows: boolean
  80. /** Visible height of the textarea's content box: the cap in pixels. */
  81. clientHeight: number
  82. /** Whole lines that fit in the visible box, at the composer's own line-height. */
  83. visibleLines: number
  84. /** The textarea's scroll offset, which the caret and the selection follow. */
  85. inputScrollTop: number
  86. /** The backdrop's scroll offset, which every visible glyph follows. */
  87. backdropScrollTop: number
  88. /** True when the two layers agree — the coupling this scenario exists for. */
  89. layersAgree: boolean
  90. /**
  91. * Top of the LAST draft line relative to the visible box's top, in pixels: at
  92. * most `clientHeight` when that line is on screen. This is the reported
  93. * symptom as a number — with the layers uncoupled the backdrop stays at offset
  94. * 0, so the last line sits a full draft-height below the box.
  95. */
  96. lastLineOffset: number
  97. /** Top of the FIRST draft line relative to the visible box's top: negative once it has scrolled out. */
  98. firstLineOffset: number
  99. /** Furthest the textarea can scroll. */
  100. inputMax: number
  101. /** Furthest the backdrop can scroll — equal to `inputMax`, or the mirror clamps below the caret. */
  102. backdropMax: number
  103. /** Content width the textarea wraps at. */
  104. inputWrapWidth: number
  105. /** Content width the backdrop wraps at — equal, or the layers break lines in different places. */
  106. backdropWrapWidth: number
  107. /** Content width the hidden auto-grow mirror wraps at — it decides the box's height. */
  108. mirrorWrapWidth: number
  109. }
  110. /**
  111. * Measure both composer layers in the page.
  112. * @param page - the page under test.
  113. * @returns the two layers' offsets and where the draft's first and last lines sit.
  114. */
  115. function measureComposer(page: Page): Promise<ComposerMetrics> {
  116. return page.evaluate(({ first, last }) => {
  117. const input = document.querySelector<HTMLTextAreaElement>('textarea:enabled')
  118. if (input === null) throw new Error('no live composer textarea in the DOM')
  119. const backdrop = input.parentElement?.querySelector<HTMLElement>('[data-input-backdrop]')
  120. if (backdrop === undefined || backdrop === null) throw new Error('no decoration backdrop beside the composer textarea')
  121. // The hidden auto-grow mirror: the textarea's next sibling, and the layer
  122. // that decides the box's height, so its wrap width matters as much as the
  123. // two that carry glyphs.
  124. const mirror = input.nextElementSibling
  125. if (!(mirror instanceof HTMLElement)) throw new Error('no auto-grow mirror after the composer textarea')
  126. const box = input.getBoundingClientRect()
  127. // The draft carries no chips or claim token, so the decoration walk emits it
  128. // as one text node — the backdrop's first, ahead of the trailing-line
  129. // sentinel React renders as a second one. Both markers live in that first
  130. // node, which is what the Range below needs.
  131. const text = backdrop.firstChild
  132. if (!(text instanceof Text)) throw new Error('backdrop does not open with a plain text node')
  133. const offsetOf = (marker: string): number => {
  134. const at = text.data.indexOf(marker)
  135. if (at < 0) throw new Error(`marker ${marker} missing from the backdrop text`)
  136. const range = document.createRange()
  137. range.setStart(text, at)
  138. range.setEnd(text, at + marker.length)
  139. return range.getBoundingClientRect().top - box.top
  140. }
  141. const lineHeight = Number.parseFloat(getComputedStyle(input).lineHeight)
  142. // Each layer's own maximum, probed by asking for an impossible offset and
  143. // reading back what it clamped to, then restored. Reading scrollHeight -
  144. // clientHeight instead would compute the maximum rather than observe it.
  145. const restore = input.scrollTop
  146. const restoreBackdrop = backdrop.scrollTop
  147. input.scrollTop = 1e7
  148. backdrop.scrollTop = 1e7
  149. const inputMax = input.scrollTop
  150. const backdropMax = backdrop.scrollTop
  151. input.scrollTop = restore
  152. backdrop.scrollTop = restoreBackdrop
  153. return {
  154. inputMax,
  155. backdropMax,
  156. inputWrapWidth: input.clientWidth,
  157. backdropWrapWidth: backdrop.clientWidth,
  158. mirrorWrapWidth: mirror.clientWidth,
  159. overflows: input.scrollHeight > input.clientHeight,
  160. clientHeight: input.clientHeight,
  161. visibleLines: Math.floor(input.clientHeight / lineHeight),
  162. inputScrollTop: input.scrollTop,
  163. backdropScrollTop: backdrop.scrollTop,
  164. layersAgree: input.scrollTop === backdrop.scrollTop,
  165. lastLineOffset: offsetOf(last),
  166. firstLineOffset: offsetOf(first),
  167. }
  168. }, { first: FIRST_MARKER, last: LAST_MARKER })
  169. }
  170. /**
  171. * Render the golden body.
  172. *
  173. * Absolute glyph coordinates are deliberately absent: they depend on font
  174. * metrics and would make the fixture fail on a machine that measures text
  175. * differently — a golden that needs re-recording per platform documents the
  176. * platform, not the change. What is recorded is the cap, the layer agreement,
  177. * and which lines are on screen, each a comparison that survives any layout
  178. * keeping the coupling.
  179. * @param top - metrics with the draft scrolled to its start.
  180. * @param bottom - metrics with the draft scrolled to its end.
  181. * @param trailingNewline - metrics with the trailing-newline draft scrolled to its end.
  182. * @returns the golden body, without a trailing newline.
  183. */
  184. function renderGeometry(top: ComposerMetrics, bottom: ComposerMetrics, trailingNewline: ComposerMetrics): string {
  185. return [
  186. '# Composer draft scrolling (14-line cap, two text layers)',
  187. '',
  188. '## At the start of the draft',
  189. '',
  190. `- draft overflows the capped box: ${String(top.overflows)}`,
  191. `- visible lines: ${String(top.visibleLines)}`,
  192. `- both layers share one scroll extent: ${String(top.inputMax === top.backdropMax)}`,
  193. `- all three layers wrap at one width: ${String(
  194. top.inputWrapWidth === top.backdropWrapWidth && top.backdropWrapWidth === top.mirrorWrapWidth,
  195. )}`,
  196. `- textarea scroll offset: ${String(top.inputScrollTop)}px`,
  197. `- glyph layer tracks it: ${String(top.layersAgree)}`,
  198. `- first draft line is on screen: ${String(top.firstLineOffset >= 0 && top.firstLineOffset < top.clientHeight)}`,
  199. `- last draft line is on screen: ${String(top.lastLineOffset >= 0 && top.lastLineOffset < top.clientHeight)}`,
  200. '',
  201. '## Scrolled to the end of the draft',
  202. '',
  203. `- textarea moved: ${String(bottom.inputScrollTop > 0)}`,
  204. `- glyph layer tracks it: ${String(bottom.layersAgree)}`,
  205. `- first draft line has scrolled out above: ${String(bottom.firstLineOffset < 0)}`,
  206. `- last draft line is on screen: ${String(bottom.lastLineOffset >= 0 && bottom.lastLineOffset < bottom.clientHeight)}`,
  207. '',
  208. '## Draft ending in a newline, scrolled to the end',
  209. '',
  210. `- both layers share one scroll extent: ${String(trailingNewline.inputMax === trailingNewline.backdropMax)}`,
  211. `- glyph layer tracks the caret: ${String(trailingNewline.layersAgree)}`,
  212. `- last draft line is on screen: ${String(trailingNewline.lastLineOffset >= 0 && trailingNewline.lastLineOffset < trailingNewline.clientHeight)}`,
  213. ].join('\n').trimEnd()
  214. }
  215. describe('web e2e: composer draft scrolling', () => {
  216. let scaffold: WebScaffold
  217. let browser: Browser
  218. let page: Page
  219. let tripwire: ReturnType<typeof watchConsole>
  220. beforeAll(async () => {
  221. scaffold = await launchWebScaffold({})
  222. browser = await chromium.launch()
  223. page = await newEnglishPage(browser)
  224. tripwire = watchConsole(page)
  225. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  226. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  227. await connectFreshWorkspace(page, scaffold.workspaceCwd, 'composer-draft-scroll')
  228. await page.locator('textarea:enabled').first().fill(DRAFT)
  229. }, 180_000)
  230. afterAll(async () => {
  231. await browser?.close()
  232. await scaffold?.close()
  233. })
  234. it('caps the draft box and keeps both text layers at the start', async () => {
  235. onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-draft-scroll-top'))
  236. // Vacuity guard: without an overflowing draft there is nothing to scroll and
  237. // every assertion below holds trivially.
  238. await expect.poll(async () => (await measureComposer(page)).overflows, { timeout: 10_000 }).toBe(true)
  239. // Typing the draft left the caret — and the box — at its end, so reach the
  240. // start by the same gesture a user would, and leave it there for the wheel
  241. // case below.
  242. await page.locator('textarea:enabled').first().hover()
  243. await page.mouse.wheel(0, -2000)
  244. await expect.poll(async () => (await measureComposer(page)).inputScrollTop, { timeout: 10_000 }).toBe(0)
  245. const metrics = await measureComposer(page)
  246. // The cap is the composer seat's `--dsh-composer-text-max-height` (336px =
  247. // 14 x 24px lines). The count, not the pixels: it is the figma constant and
  248. // survives a device-pixel-ratio change.
  249. expect(metrics.visibleLines).toBe(14)
  250. // Resting state: the draft's head is what a 40-line draft shows, and its
  251. // tail is far below the box. Both layers sit at the origin, which is why the
  252. // uncoupled build looks correct until something scrolls.
  253. expect(metrics.inputScrollTop).toBe(0)
  254. expect(metrics.layersAgree).toBe(true)
  255. expect(metrics.firstLineOffset).toBeGreaterThanOrEqual(0)
  256. expect(metrics.firstLineOffset).toBeLessThan(metrics.clientHeight)
  257. expect(metrics.lastLineOffset).toBeGreaterThan(metrics.clientHeight)
  258. expect(tripwire.pageErrors).toEqual([])
  259. }, 60_000)
  260. it('lays out all three text layers at one wrap width', async () => {
  261. onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-draft-scroll-wrap-width'))
  262. // The premise under the mirror, asserted rather than assumed. Only .input
  263. // scrolls, so only .input can lose content width to a scrollbar that
  264. // consumes layout space; a narrower .input wraps a long draft onto more
  265. // lines, ends up taller, and its larger maximum makes the mirrored offset
  266. // clamp below the caret. Measured on a standalone harness, an 8px width
  267. // difference is worth 2 to 5 lines on a wrap-sensitive draft.
  268. //
  269. // This holds on the lane's engine and is what a regression would break —
  270. // it is NOT vacuous: measured on the same app, WebKit reports 768 against
  271. // 776 here, which is the divergence the Agent Note records as a
  272. // pre-existing, engine-specific limitation. The mirror is unaffected there
  273. // today because the extents still agree; this assertion is what would
  274. // notice if the lane's engine ever moved into the same state.
  275. const metrics = await measureComposer(page)
  276. expect(metrics.backdropWrapWidth).toBe(metrics.inputWrapWidth)
  277. // The mirror decides the box height, so it belongs in the same equality —
  278. // were it alone to wrap wider, the box would be measured too short and
  279. // clip content before the 14-line cap, with every other assertion green.
  280. expect(metrics.mirrorWrapWidth).toBe(metrics.inputWrapWidth)
  281. expect(tripwire.pageErrors).toEqual([])
  282. }, 60_000)
  283. it('a wheel gesture over a long draft moves the words, not only the caret', async () => {
  284. onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-draft-scroll-wheel'))
  285. const input = page.locator('textarea:enabled').first()
  286. await input.hover()
  287. // One delta past the whole draft: the textarea clamps at its own end, and
  288. // the wheel-chaining handler leaves it native because the box is not yet at
  289. // its edge when the gesture starts (the chaining itself is owned by the
  290. // unit spec).
  291. await page.mouse.wheel(0, 2000)
  292. await expect.poll(async () => (await measureComposer(page)).inputScrollTop, { timeout: 10_000 })
  293. .toBeGreaterThan(0)
  294. const metrics = await measureComposer(page)
  295. // The coupling, stated directly.
  296. expect(metrics.layersAgree).toBe(true)
  297. // The reported symptom, stated as what the user sees: the end of the draft
  298. // is on screen and its beginning is not. On the uncoupled build the glyph
  299. // layer stays at offset 0, so `lastLineOffset` is still a full draft below
  300. // the box and `firstLineOffset` is still 0 — the text never moved.
  301. expect(metrics.lastLineOffset).toBeGreaterThanOrEqual(0)
  302. expect(metrics.lastLineOffset).toBeLessThan(metrics.clientHeight)
  303. expect(metrics.firstLineOffset).toBeLessThan(0)
  304. expect(tripwire.pageErrors).toEqual([])
  305. }, 60_000)
  306. it('typing at the end of a scrolled draft keeps the layers together', async () => {
  307. onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-draft-scroll-edit'))
  308. // The other way the box moves. Typing at the caret — parked at the draft's
  309. // end by the wheel gesture — scrolls it into view, which is a `scroll` like
  310. // any other; this pins that an edit is not a separate case needing its own
  311. // mirror, which is why one listener is the whole implementation.
  312. const input = page.locator('textarea:enabled').first()
  313. await input.press('End')
  314. await input.pressSequentially(' tail')
  315. const metrics = await measureComposer(page)
  316. expect(metrics.layersAgree).toBe(true)
  317. expect(metrics.lastLineOffset).toBeGreaterThanOrEqual(0)
  318. expect(metrics.lastLineOffset).toBeLessThan(metrics.clientHeight)
  319. expect(tripwire.pageErrors).toEqual([])
  320. }, 60_000)
  321. it('a draft ending in a newline scrolls to its true end, not a line above it', async () => {
  322. onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-draft-scroll-trailing-newline'))
  323. // The layers reserve a final line box on different terms, so this shape is
  324. // the one that separates equal extents from a mirror that clamps early.
  325. const input = page.locator('textarea:enabled').first()
  326. await input.fill(DRAFT_TRAILING_NEWLINE)
  327. await expect.poll(async () => (await measureComposer(page)).overflows, { timeout: 10_000 }).toBe(true)
  328. const extents = await measureComposer(page)
  329. // The invariant the sentinel exists for. Without it the textarea measured
  330. // 652 against the backdrop's 628 — one 24px line apart.
  331. expect(extents.backdropMax).toBe(extents.inputMax)
  332. await input.hover()
  333. await page.mouse.wheel(0, 4000)
  334. await expect.poll(async () => {
  335. const m = await measureComposer(page)
  336. return m.inputScrollTop === m.inputMax
  337. }, { timeout: 10_000 }).toBe(true)
  338. const bottom = await measureComposer(page)
  339. // At the very bottom the glyphs are level with the caret, not a line behind.
  340. expect(bottom.layersAgree).toBe(true)
  341. expect(bottom.lastLineOffset).toBeGreaterThanOrEqual(0)
  342. expect(bottom.lastLineOffset).toBeLessThan(bottom.clientHeight)
  343. expect(tripwire.pageErrors).toEqual([])
  344. }, 60_000)
  345. it('matches the committed composer scroll geometry golden', async () => {
  346. onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-draft-scroll-golden'))
  347. const input = page.locator('textarea:enabled').first()
  348. // Restore the pristine draft (the edit case appended to it) and return to
  349. // its start, both through ordinary gestures.
  350. await input.fill(DRAFT)
  351. await input.hover()
  352. await page.mouse.wheel(0, -2000)
  353. await expect.poll(async () => (await measureComposer(page)).inputScrollTop, { timeout: 10_000 }).toBe(0)
  354. const top = await measureComposer(page)
  355. await input.hover()
  356. await page.mouse.wheel(0, 2000)
  357. await expect.poll(async () => (await measureComposer(page)).inputScrollTop, { timeout: 10_000 })
  358. .toBeGreaterThan(0)
  359. const bottom = await measureComposer(page)
  360. await input.fill(DRAFT_TRAILING_NEWLINE)
  361. await input.hover()
  362. await page.mouse.wheel(0, 4000)
  363. await expect.poll(async () => {
  364. const m = await measureComposer(page)
  365. return m.inputScrollTop === m.inputMax
  366. }, { timeout: 10_000 }).toBe(true)
  367. const trailingNewline = await measureComposer(page)
  368. await compareOrRefreshGolden(GEOMETRY_EXPECTED, renderGeometry(top, bottom, trailingNewline), MODE)
  369. expect(tripwire.pageErrors).toEqual([])
  370. }, 60_000)
  371. it('commits exactly the fixtures it reads', async () => {
  372. // Zero model calls, so the scenario records no session fixture: the geometry
  373. // golden is the whole inventory.
  374. await assertFixtureInventory(SNAPSHOT_DIR, ['geometry.expected.md'])
  375. })
  376. it.skipIf(MODE === 'record')('issued zero model calls and stayed clean', () => {
  377. expect(tripwire.warnings).toEqual([])
  378. expect(tripwire.pageErrors).toEqual([])
  379. })
  380. })