sidebar-scrollbar.e2e.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. // Web e2e scenario: the sidebar session list's scrollbar as the browser
  2. // actually lays it out — the observable half of the themed-scrollbar change
  3. // (packages/client/ui-theme/src/styles/scrollbar.css plus the
  4. // `scrollbar-gutter: stable` reservation on WorkspaceBrowser's `.list`). The
  5. // ui-theme/ui-workspace unit specs read the CSS text; only a real engine
  6. // reports the reserved gutter width and the substituted `scrollbar-color`, so
  7. // those two facts live here.
  8. //
  9. // Zero model calls: the list only has to overflow, so the scenario seeds many
  10. // cold sessions from another spec's committed fixture (seeded-history's
  11. // seed.jsonl, reused read-only — this spec needs row count, not new recorded
  12. // content) and never launches a replay row. A stray stream would fail loud
  13. // with NO_ADAPTER.
  14. //
  15. // Headless-chromium caveats, load-bearing for what is asserted below.
  16. //
  17. // Headless chromium defaults to an OVERLAY scrollbar: one drawn on top of the
  18. // content, consuming no layout width unless something reserves space. That is
  19. // the mode in which the reported symptom exists at all, so this environment
  20. // reproduces it rather than merely approximating it — measured against clean
  21. // master, where the list's band is 0 and the bar covers 7px of the relative
  22. // time. (Under a classic space-consuming bar, `clientWidth` already excludes
  23. // the bar and nothing can be covered; a headed run under xvfb behaves that way
  24. // and cannot show the symptom.)
  25. //
  26. // The consequence for assertions: comparing the time element's right edge
  27. // against the list's CLIENT-area right edge holds in both states and proves
  28. // nothing, because with an overlay bar the client edge is the border edge. The
  29. // two signals that do separate the states are the reserved band width and
  30. // `timeCoveredBy`, which measures the overlap against the bar's own width.
  31. //
  32. // Both the `scrollbar-gutter: stable` reservation and the sheet's
  33. // `::-webkit-scrollbar` width are needed for that band, and neither suffices:
  34. // measured on the running app, deleting either one takes the band from 8 to 0
  35. // while the other stays in force. The gutter states that space be reserved; the
  36. // pseudo-element width is what makes chromium treat the bar as occupying layout
  37. // space in the first place.
  38. //
  39. // That conjunction is why `band` and `timeCoveredBy` are both asserted and
  40. // neither replaces the other. Removing only the gutter leaves `timeCoveredBy` at
  41. // 0, because the bar is then 8px wide and the row's right padding is also 8px,
  42. // so it abuts the timestamp without covering it; `band` catches that case.
  43. // Removing both — the actual master state — is what produces the reported
  44. // overlap, and `timeCoveredBy` measures it at 7. Each was mutation-checked with
  45. // the other assertions in its test silenced.
  46. //
  47. // Chromium also takes the `::-webkit-scrollbar*` path, not the standard
  48. // properties: scrollbar.css gates `scrollbar-width`/`scrollbar-color` behind
  49. // `@supports not selector(::-webkit-scrollbar)`, which is false here. The
  50. // resolved standard properties therefore read `auto`, and that reading is
  51. // asserted — a concrete value would mean the gate leaked and silenced the
  52. // pseudo-element rules. What the theme test measures instead is the pair the
  53. // pseudo-element rules read: the indirection variables as they resolve ON the
  54. // list, plus the `::-webkit-scrollbar-thumb:hover` declaration as it stands in
  55. // the cascade. The hover thumb colour is not observable any other way —
  56. // chromium folds the `:hover` rule into `getComputedStyle(el,
  57. // '::-webkit-scrollbar-thumb')`, so that query reports the hover colour at
  58. // rest and cannot pin either state (measured by deleting the hover rule live:
  59. // the same query flipped from the hover colour to the resting one).
  60. import { readFile } from 'node:fs/promises'
  61. import { fileURLToPath } from 'node:url'
  62. import { join } from 'node:path'
  63. import type { Browser, Page } from 'playwright'
  64. import { chromium } from 'playwright'
  65. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  66. import {
  67. assertFixtureInventory, compareOrRefreshGolden, launchWebScaffold, seedSession, watchConsole,
  68. webSnapshotMode, type WebScaffold,
  69. } from './scaffold.ts'
  70. import { saveFailureShot } from './support.ts'
  71. const SEED = fileURLToPath(new URL('./snapshots/seeded-history/seed.jsonl', import.meta.url))
  72. const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/sidebar-scrollbar', import.meta.url))
  73. /**
  74. * Committed golden of the resolved scrollbar style and geometry, in both
  75. * palettes. The aria goldens the other scenarios commit cannot carry this
  76. * change: it alters no DOM and no accessible name, so their normalized trees are
  77. * byte-identical with and without it. This one records the values instead, which
  78. * makes an unintended shift in thumb colour, band width, or rendering path a
  79. * reviewable diff rather than an assertion someone has to think about.
  80. */
  81. const GEOMETRY_EXPECTED = join(SNAPSHOT_DIR, 'geometry.expected.md')
  82. const MODE = webSnapshotMode()
  83. /** Enough rows that the list overflows the 800px-tall viewport's sidebar; the scenario asserts the overflow rather than trusting it. */
  84. const SEED_COUNT = 24
  85. /** Geometry and resolved scrollbar style of one scroll container, measured in the page. */
  86. interface ListMetrics {
  87. /** Resolved `scrollbar-gutter`. */
  88. gutter: string
  89. /** Resolved `::-webkit-scrollbar` width: the pseudo-element path's own sizing. */
  90. width: string
  91. /** Resolved `::-webkit-scrollbar-track` background. */
  92. track: string
  93. /** Resolved `scrollbar-width`, expected `auto` because the gate excludes chromium. */
  94. standardWidth: string
  95. /** Resolved `scrollbar-color`, expected `auto` for the same reason. */
  96. standardColor: string
  97. /** `::-webkit-scrollbar-thumb:hover` background declarations found in the cascade, in sheet order. */
  98. hoverRules: string[]
  99. /** `--dsh-scrollbar-thumb` resolved on the list, serialized as a colour. */
  100. token: string
  101. /** `--dsh-scrollbar-thumb-hover` resolved on the list, serialized the same way. */
  102. hoverToken: string
  103. /** True when the list actually scrolls. */
  104. overflows: boolean
  105. /** Border-box width minus client width: the space the scrollbar takes out of the content area. */
  106. band: number
  107. /** Client-area right edge in viewport coordinates (`clientWidth` excludes the scrollbar band). */
  108. clientRight: number
  109. /** Border-box right edge in viewport coordinates. */
  110. borderRight: number
  111. /** Right edge of the first row's relative-time element, the content the unreserved bar covered. */
  112. timeRight: number
  113. /**
  114. * Pixels of the relative time the scrollbar paints over: how far its right
  115. * edge reaches into the band the bar occupies, `[borderRight - barWidth,
  116. * borderRight]`. This is the reported symptom as a number, and it is the one
  117. * geometric signal that separates the two states in this environment — see
  118. * the file header on why `clientWidth` comparisons cannot.
  119. */
  120. timeCoveredBy: number
  121. }
  122. /**
  123. * Measure the sidebar list in the page.
  124. * @param page - the page under test.
  125. * @returns the list's resolved scrollbar style and the geometry the fix changes.
  126. */
  127. function measureList(page: Page): Promise<ListMetrics> {
  128. return page.evaluate(() => {
  129. const list = document.querySelector<HTMLElement>('[role="tree"][aria-label="Sessions"]')
  130. if (list === null) throw new Error('sidebar session list not in the DOM')
  131. const time = list.querySelector<HTMLElement>('[class*="time"]')
  132. if (time === null) throw new Error('no row relative-time element in the sidebar list')
  133. // Each indirection variable is resolved through its own throwaway probe
  134. // appended to the list: `var()` substitution then happens where the list
  135. // sits in the cascade, which is the claim, and `color` normalizes whatever
  136. // notation the palette sheet chose into one comparable serialization. A
  137. // REUSED probe would report only the last value read — `getComputedStyle`
  138. // returns a live declaration, so reassigning `style.color` retroactively
  139. // changes every earlier read.
  140. const resolve = (name: string): string => {
  141. const probe = document.createElement('span')
  142. probe.style.color = `var(${name})`
  143. list.append(probe)
  144. const value = getComputedStyle(probe).color
  145. probe.remove()
  146. return value
  147. }
  148. // The hover colour is read out of the cascade rather than computed:
  149. // chromium reports the `:hover` background for the resting pseudo-element
  150. // too (see the file header), so no computed query separates the states.
  151. // Cross-origin sheets throw on `cssRules`; none is expected, and skipping
  152. // them cannot mask the rule under test, which ships in the app's own CSS.
  153. const hoverRules = [...document.styleSheets]
  154. .flatMap((sheet) => {
  155. try {
  156. return [...sheet.cssRules]
  157. } catch {
  158. return []
  159. }
  160. })
  161. .filter((rule): rule is CSSStyleRule => rule instanceof CSSStyleRule)
  162. .filter(rule => rule.selectorText === '::-webkit-scrollbar-thumb:hover')
  163. .map(rule => rule.style.getPropertyValue('background'))
  164. const style = getComputedStyle(list)
  165. const pseudoWidth = getComputedStyle(list, '::-webkit-scrollbar').width
  166. const barWidth = pseudoWidth === 'auto' ? 15 : Number.parseFloat(pseudoWidth)
  167. return {
  168. gutter: style.scrollbarGutter,
  169. width: pseudoWidth,
  170. track: getComputedStyle(list, '::-webkit-scrollbar-track').backgroundColor,
  171. standardWidth: style.scrollbarWidth,
  172. standardColor: style.scrollbarColor,
  173. hoverRules,
  174. token: resolve('--dsh-scrollbar-thumb'),
  175. hoverToken: resolve('--dsh-scrollbar-thumb-hover'),
  176. overflows: list.scrollHeight > list.clientHeight,
  177. band: list.getBoundingClientRect().width - list.clientWidth,
  178. clientRight: list.getBoundingClientRect().left + list.clientWidth,
  179. borderRight: list.getBoundingClientRect().right,
  180. timeRight: time.getBoundingClientRect().right,
  181. // The bar is drawn in the rightmost `barWidth` of the border box, whether
  182. // or not that space was reserved. Its width comes from the sheet where the
  183. // sheet applies, and from the UA's own overlay bar otherwise — 15px is
  184. // what this chromium paints, measured against master where the rule is
  185. // absent. Taking the UA width as the fallback is what keeps the assertion
  186. // honest: assuming 0 there would report no occlusion precisely in the
  187. // state that has it.
  188. timeCoveredBy: Math.max(0, time.getBoundingClientRect().right - (list.getBoundingClientRect().right - barWidth)),
  189. }
  190. })
  191. }
  192. /**
  193. * Render the golden body: the resolved scrollbar style of the list in each
  194. * palette, plus the geometric relations the fix establishes.
  195. *
  196. * Absolute coordinates are deliberately absent. `timeRight`, `clientRight`, and
  197. * `borderRight` depend on the sidebar's laid-out width and on font metrics, so
  198. * committing them would make the golden fail on a machine whose fonts measure
  199. * differently — a fixture that has to be re-recorded per platform documents the
  200. * platform, not the change. What is recorded instead is the band, the overlap,
  201. * and the two orderings, each of which is a difference or a comparison and so
  202. * survives any layout that keeps the reservation.
  203. * @param light - metrics measured under the light palette.
  204. * @param dark - metrics measured under the dark palette.
  205. * @returns the golden body, without a trailing newline.
  206. */
  207. function renderGeometry(light: ListMetrics, dark: ListMetrics): string {
  208. const palette = (name: string, metrics: ListMetrics): string[] => [
  209. `## ${name}`,
  210. '',
  211. `- scrollbar-gutter: ${metrics.gutter}`,
  212. `- ::-webkit-scrollbar width: ${metrics.width}`,
  213. `- ::-webkit-scrollbar-track background: ${metrics.track}`,
  214. `- scrollbar-width: ${metrics.standardWidth}`,
  215. `- scrollbar-color: ${metrics.standardColor}`,
  216. `- ::-webkit-scrollbar-thumb:hover declarations: ${metrics.hoverRules.join(' | ')}`,
  217. `- --dsh-scrollbar-thumb: ${metrics.token}`,
  218. `- --dsh-scrollbar-thumb-hover: ${metrics.hoverToken}`,
  219. `- list overflows: ${String(metrics.overflows)}`,
  220. `- reserved band: ${String(metrics.band)}px`,
  221. `- relative time covered by the bar: ${String(metrics.timeCoveredBy)}px`,
  222. `- relative time ends inside the content area: ${String(metrics.timeRight <= metrics.clientRight)}`,
  223. `- content area ends before the border box: ${String(metrics.clientRight < metrics.borderRight)}`,
  224. '',
  225. ]
  226. return [
  227. '# Sidebar session list scrollbar',
  228. '',
  229. ...palette('Light palette', light),
  230. ...palette('Dark palette', dark),
  231. ].join('\n').trimEnd()
  232. }
  233. /**
  234. * Reveal the seeded rows: every seeded session is unattached, so they all sit
  235. * in the collapsed Ungrouped bucket. Converges on expanded rather than
  236. * clicking once — startup auto-selection can expand the bucket first, and a
  237. * second click would collapse it again. Hand-rolled polling because
  238. * `expect.poll` is test-scoped and this runs in `beforeAll`.
  239. * @param page - the page under test.
  240. */
  241. async function expandSeededSessions(page: Page): Promise<void> {
  242. const bucket = page.getByText('Ungrouped', { exact: true }).locator('..').locator('..')
  243. await bucket.waitFor({ timeout: 15_000 })
  244. const rows = page.locator('[role="tree"][aria-label="Sessions"] [role="treeitem"]')
  245. const deadline = Date.now() + 30_000
  246. for (;;) {
  247. if (await bucket.getAttribute('aria-expanded') !== 'true') {
  248. await page.getByText('Ungrouped', { exact: true }).click()
  249. }
  250. if (await bucket.getAttribute('aria-expanded') === 'true' && await rows.count() > SEED_COUNT / 2) return
  251. if (Date.now() > deadline) {
  252. throw new Error(`Ungrouped bucket never revealed more than ${SEED_COUNT / 2} rows`)
  253. }
  254. await page.waitForTimeout(200)
  255. }
  256. }
  257. describe('web e2e: sidebar session list scrollbar (reserved gutter / themed thumb)', () => {
  258. let scaffold: WebScaffold
  259. let browser: Browser
  260. let page: Page
  261. let tripwire: ReturnType<typeof watchConsole>
  262. beforeAll(async () => {
  263. scaffold = await launchWebScaffold({})
  264. const fixture = await readFile(SEED, 'utf8')
  265. for (let index = 0; index < SEED_COUNT; index += 1) {
  266. await seedSession(scaffold, fixture, `sidebar-scrollbar-web-e2e-${String(index).padStart(2, '0')}`)
  267. }
  268. browser = await chromium.launch()
  269. // Shorter than the other scenarios' 1000px so SEED_COUNT rows overflow
  270. // the list with room to spare.
  271. page = await browser.newPage({ viewport: { width: 1680, height: 800 } })
  272. tripwire = watchConsole(page)
  273. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  274. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  275. await expandSeededSessions(page)
  276. }, 180_000)
  277. afterAll(async () => {
  278. await browser?.close()
  279. await scaffold?.close()
  280. })
  281. it('reserves a scrollbar gutter on the overflowing session list', async () => {
  282. onTestFailed(() => saveFailureShot(page, 'web-e2e-sidebar-scrollbar-gutter'))
  283. // Vacuity guard: with a non-overflowing list `stable` still reserves, but
  284. // the scenario would no longer be reproducing the reported situation.
  285. await expect.poll(async () => (await measureList(page)).overflows, { timeout: 10_000 }).toBe(true)
  286. const metrics = await measureList(page)
  287. expect(metrics.gutter).toBe('stable')
  288. // The control. `band > 0` is the whole observable effect of the
  289. // reservation: the scrollbar is taken out of the content area instead of
  290. // drawn over it. Removing the declaration makes it exactly 0. The value
  291. // itself is not pinned — it tracks `scrollbar-width` and the platform.
  292. expect(metrics.band).toBeGreaterThan(0)
  293. // The reported symptom, stated directly: no part of the row's relative time
  294. // lies under the bar. Measures 7 on clean master — the `h` of `1h` is the
  295. // covered part. Unlike the client-edge comparison below it does not go
  296. // vacuous under an overlay scrollbar, because it measures against the bar's
  297. // own width rather than against a content edge the overlay bar does not
  298. // move. It is not a replacement for the band assertion above; see the file
  299. // header for which regression each one catches.
  300. expect(metrics.timeCoveredBy).toBe(0)
  301. // Corollaries of the reservation, kept because they pin where the band sits
  302. // rather than only that it exists: the time ends inside the content area,
  303. // and the content area ends before the border box. Each holds in both
  304. // states on its own (see the file header) and is meaningful only alongside
  305. // the two assertions above.
  306. expect(metrics.timeRight).toBeLessThanOrEqual(metrics.clientRight)
  307. expect(metrics.clientRight).toBeLessThan(metrics.borderRight)
  308. expect(tripwire.pageErrors).toEqual([])
  309. }, 60_000)
  310. it('renders the themed thumb through the WebKit path in both palettes', async () => {
  311. onTestFailed(() => saveFailureShot(page, 'web-e2e-sidebar-scrollbar-theme'))
  312. const light = await measureList(page)
  313. // The gate's signature on this engine, and the reason it exists: chromium
  314. // implements `::-webkit-scrollbar`, so the standard properties stay at
  315. // their initial `auto`. A concrete value here would mean the gate leaked,
  316. // which is exactly what makes chromium discard the pseudo-element rules —
  317. // the hover token included.
  318. expect(light.standardWidth).toBe('auto')
  319. expect(light.standardColor).toBe('auto')
  320. // The pseudo-element path is the one in force: the sheet's own 8px sizing
  321. // and transparent track reached a container it never names.
  322. expect(light.width).toBe('8px')
  323. expect(light.track).toBe('rgba(0, 0, 0, 0)')
  324. // The resting and the hover rule each read the rebindable indirection, and
  325. // the two resolve to DIFFERENT colours on this list: the l1 pair arrived
  326. // here intact rather than collapsing to one value or falling back.
  327. expect(light.hoverRules).toEqual(['var(--dsh-scrollbar-thumb-hover)'])
  328. expect(light.token).toMatch(/^rgba?\(/)
  329. expect(light.hoverToken).not.toBe(light.token)
  330. // The dark palette declares different scrollbar tokens; driving the body
  331. // attribute pins the cascade the way lifecycle-chrome does (the Settings
  332. // gesture that sets it is owned there).
  333. await page.evaluate(() => { document.body.setAttribute('data-ds-dark-theme', '') })
  334. const dark = await measureList(page)
  335. expect(dark.token).not.toBe(light.token)
  336. expect(dark.hoverToken).not.toBe(dark.token)
  337. expect(dark.hoverToken).not.toBe(light.hoverToken)
  338. await page.evaluate(() => { document.body.removeAttribute('data-ds-dark-theme') })
  339. const restored = await measureList(page)
  340. expect(restored.token).toBe(light.token)
  341. expect(restored.hoverToken).toBe(light.hoverToken)
  342. expect(tripwire.pageErrors).toEqual([])
  343. }, 60_000)
  344. it('matches the committed scrollbar geometry golden in both palettes', async () => {
  345. onTestFailed(() => saveFailureShot(page, 'web-e2e-sidebar-scrollbar-golden'))
  346. const light = await measureList(page)
  347. await page.evaluate(() => { document.body.setAttribute('data-ds-dark-theme', '') })
  348. const dark = await measureList(page)
  349. await page.evaluate(() => { document.body.removeAttribute('data-ds-dark-theme') })
  350. await compareOrRefreshGolden(GEOMETRY_EXPECTED, renderGeometry(light, dark), MODE)
  351. expect(tripwire.pageErrors).toEqual([])
  352. }, 60_000)
  353. it('commits exactly the fixtures it reads', async () => {
  354. // The scenario borrows seeded-history's seed.jsonl rather than committing a
  355. // second copy, so this directory holds the golden alone.
  356. await assertFixtureInventory(SNAPSHOT_DIR, ['geometry.expected.md'])
  357. })
  358. it.skipIf(MODE === 'record')('issued zero model calls and stayed clean', () => {
  359. expect(tripwire.warnings).toEqual([])
  360. expect(tripwire.pageErrors).toEqual([])
  361. })
  362. })