document-preview.e2e.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /** Keyless document-preview smoke through a real Session, Files tab, and shipped renderers. */
  2. import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
  3. import { tmpdir } from 'node:os'
  4. import { join, relative } from 'node:path'
  5. import { fileURLToPath } from 'node:url'
  6. import type { Browser, Locator, Page } from 'playwright'
  7. import { chromium } from 'playwright'
  8. import { afterAll, beforeAll, describe, expect, it, onTestFailed, vi } from 'vitest'
  9. import { pdfFixture } from '../../../packages/client/ui-sidebar-documentpreview/tests/pdf-fixture.ts'
  10. import { assertFixtureInventory, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts'
  11. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  12. const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/lifecycle-chrome/session.v3.jsonl', import.meta.url))
  13. const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/document-preview', import.meta.url))
  14. const EXPECTED = join(SNAPSHOT_DIR, 'document.expected.md')
  15. const PAGING_PATCH = join(SNAPSHOT_DIR, 'paging.patch.yml')
  16. const PAGE_LINES = 64
  17. const SHOT_DIR = fileURLToPath(new URL('../../../.artifacts/screenshots/0908-document-preview', import.meta.url))
  18. const PROMPT = 'Reply with the single word LIGHTHOUSE and stop.'
  19. const MODE = webSnapshotMode()
  20. /** Successful render evidence stays outside the committed snapshot inventory. */
  21. async function successShot(page: Page, name: string): Promise<void> {
  22. await mkdir(SHOT_DIR, { recursive: true })
  23. await page.screenshot({ path: join(SHOT_DIR, `${name}-${MODE}-${process.pid}.png`), fullPage: true })
  24. }
  25. /** Trigger the document owner's native scroll handler after a real first page overflows. */
  26. async function scrollForNextPage(body: Locator): Promise<void> {
  27. await body.evaluate((node) => {
  28. if (node.scrollHeight <= node.clientHeight) throw new Error('paging fixture does not overflow the document body')
  29. node.scrollTop = node.scrollHeight
  30. })
  31. }
  32. /** Read the solid vector fill away from antialiased page edges. */
  33. async function canvasColor(canvas: Locator): Promise<string> {
  34. return await canvas.evaluate((node) => {
  35. const surface = node as HTMLCanvasElement
  36. const context = surface.getContext('2d')
  37. if (context === null) throw new Error('PDF canvas has no 2D context')
  38. const pixel = context.getImageData(Math.floor(surface.width / 2), Math.floor(surface.height / 2), 1, 1).data
  39. if (Number(pixel[3]) !== 255) return 'transparent'
  40. if (Number(pixel[0]) - Number(pixel[2]) > 150) return 'red'
  41. if (Number(pixel[2]) - Number(pixel[0]) > 150) return 'blue'
  42. return 'other'
  43. })
  44. }
  45. describe.skipIf(MODE === 'record')('web e2e: document preview through Files', () => {
  46. let scaffold: WebScaffold
  47. let browser: Browser
  48. let page: Page
  49. let tripwire: ReturnType<typeof watchConsole>
  50. let outsideRoot: string | undefined
  51. beforeAll(async () => {
  52. outsideRoot = await mkdtemp(join(tmpdir(), 'dsh-preview-outside-'))
  53. scaffold = await launchWebScaffold({ replayFixture: FIXTURE, paceMs: 5, compareReplaySession: false, extraOverlayPath: PAGING_PATCH })
  54. browser = await chromium.launch()
  55. page = await newEnglishPage(browser)
  56. tripwire = watchConsole(page)
  57. await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  58. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  59. })
  60. afterAll(async () => {
  61. try {
  62. await browser?.close()
  63. } finally {
  64. try {
  65. await scaffold?.close()
  66. } finally {
  67. if (outsideRoot !== undefined) await rm(outsideRoot, { recursive: true, force: true })
  68. }
  69. }
  70. })
  71. it('opens Markdown, isolated HTML, and a rendered PDF from the Session workspace', async () => {
  72. onTestFailed(async () => {
  73. await mkdir(SHOT_DIR, { recursive: true })
  74. await saveFailureShot(page, `screenshots/0908-document-preview/smoke-${process.pid}`)
  75. })
  76. const settled = scaffold.whenTurnSettled()
  77. const input = page.locator('[data-composer-input]').first()
  78. await input.fill(PROMPT)
  79. await input.press('Enter')
  80. const sessionId = await settled
  81. await page.getByText('LIGHTHOUSE', { exact: true }).waitFor({ timeout: 15_000 })
  82. const cwd = scaffold.ctx.agents.get(sessionId)?.session.header.cwd
  83. if (cwd === undefined) throw new Error('settled Session has no workspace cwd')
  84. if (outsideRoot === undefined) throw new Error('outside fixture directory is unavailable')
  85. const outsideScript = join(outsideRoot, 'outside.js')
  86. const outsideReference = relative(cwd, outsideScript).replace(/\\/g, '/')
  87. const markdownText = [
  88. '# Markdown smoke', '', 'Rendered from the workspace.', '',
  89. ...Array.from({ length: (PAGE_LINES - 4) / 2 }, (_, index) => [`Paragraph ${index + 1}: ${'visible prefix '.repeat(20)}`, '']).flat(),
  90. '# Markdown tail',
  91. ].join('\n')
  92. const codeLines = [
  93. ...Array.from({ length: PAGE_LINES }, (_, index) => index === 0 ? 'const prefix = "CODE_PREFIX";' : `// prefix line ${index + 1}`),
  94. 'const tail = "CODE_TAIL";',
  95. ]
  96. await Promise.all([
  97. writeFile(join(cwd, 'smoke.md'), markdownText),
  98. writeFile(join(cwd, 'pages.ts'), codeLines.join('\n')),
  99. writeFile(join(cwd, 'notes.unknown'), 'UNKNOWN_SUFFIX\nPlain fallback.'),
  100. writeFile(join(cwd, 'smoke.html'), [
  101. '<!doctype html><link rel="stylesheet" href="./local.css">',
  102. '<h1>HTML smoke</h1><p id="result">pending</p><p id="local-result">pending</p><p id="parent-result">pending</p>',
  103. '<p id="outside-result">pending</p>',
  104. '<script>document.getElementById("result").textContent="INLINE_OK";',
  105. 'try{parent.document.documentElement.setAttribute("data-document-preview-escape","true");document.getElementById("parent-result").textContent="parent-accessible"}',
  106. 'catch(error){const result=document.getElementById("parent-result");result.textContent="parent-blocked";result.dataset.error=error.name}</script>',
  107. '<script src="./local.js"></script>',
  108. `<script src="${outsideReference}"></script>`,
  109. ].join('\n')),
  110. writeFile(join(cwd, 'local.js'), 'document.getElementById("local-result").textContent="LOCAL_JS_OK";'),
  111. writeFile(join(cwd, 'local.css'), '#local-result { color: rgb(12, 34, 56); }'),
  112. writeFile(outsideScript, 'document.getElementById("outside-result").textContent="OUTSIDE_JS_OK";'),
  113. writeFile(join(cwd, 'smoke.pdf'), pdfFixture()),
  114. ])
  115. const column = page.locator('[data-rightbar-col]')
  116. await page.locator('[data-sidebar-right-expand]').click()
  117. await column.locator('[data-files-state="tree"]').waitFor({ state: 'visible' })
  118. await column.locator('[data-files-reload]').click()
  119. const filesTab = column.locator('[data-dockkit-tab]').filter({ has: page.getByText('Files', { exact: true }) })
  120. const addTab = column.locator('[data-dockkit-add-tab]')
  121. expect(await column.locator('[data-dockkit-tab]').count()).toBe(1)
  122. const defaultTitle = await filesTab.locator('[data-dockkit-tab-title]').innerText()
  123. const initialFilesClose = await filesTab.locator('[data-dockkit-tab-close]').count()
  124. expect(initialFilesClose).toBe(1)
  125. await filesTab.click({ button: 'right' })
  126. expect(await page.locator('[data-dockkit-tab-menu]:visible').count()).toBe(1)
  127. await page.keyboard.press('Escape')
  128. await addTab.waitFor({ state: 'visible' })
  129. const initialAdd = await addTab.count()
  130. expect(initialAdd).toBe(1)
  131. await addTab.click()
  132. await column.locator('[data-sidebar-right-guide]').waitFor({ state: 'visible' })
  133. await expect.poll(() => column.locator('[data-dockkit-tab]').count()).toBe(2)
  134. const guideTab = column.locator('[data-dockkit-tab]').filter({ hasNot: page.getByText('Files', { exact: true }) })
  135. const guideClose = await guideTab.locator('[data-dockkit-tab-close]').count()
  136. const filesCloseWithGuide = await filesTab.locator('[data-dockkit-tab-close]').count()
  137. expect(guideClose).toBe(1)
  138. expect(filesCloseWithGuide).toBe(1)
  139. await expect.poll(() => addTab.count()).toBe(0)
  140. const addWithGuide = await addTab.count()
  141. await guideTab.hover()
  142. await guideTab.locator('[data-dockkit-tab-close]').click()
  143. await column.locator('[data-files-state="tree"]').waitFor({ state: 'visible' })
  144. await expect.poll(() => column.locator('[data-sidebar-right-guide]').count()).toBe(0)
  145. await expect.poll(() => column.locator('[data-dockkit-tab]').count()).toBe(1)
  146. await addTab.waitFor({ state: 'visible' })
  147. const restoredFilesClose = await filesTab.locator('[data-dockkit-tab-close]').count()
  148. const restoredAdd = await addTab.count()
  149. expect(restoredFilesClose).toBe(1)
  150. expect(restoredAdd).toBe(1)
  151. const preview = column.locator('[data-document-preview]')
  152. const openFile = async (name: string): Promise<void> => {
  153. await filesTab.click()
  154. await column.locator('[data-files-entry="file"]').getByRole('button', { name, exact: true }).click()
  155. await expect.poll(async () => (await preview.getAttribute('data-textpreview-url'))?.endsWith(`/${name}`)).toBe(true)
  156. }
  157. const viewer = preview.locator('[data-document-viewer-menu]')
  158. const body = preview.locator('[data-textpreview-body]')
  159. const sections = ['# Document preview']
  160. sections.push([
  161. '## Sidebar tabs', '',
  162. `- Default tab: ${defaultTitle}`,
  163. `- Files close buttons (alone -> with guide -> restored): ${[initialFilesClose, filesCloseWithGuide, restoredFilesClose].join(' -> ')}`,
  164. `- Manual guide close buttons: ${guideClose}`,
  165. `- Add buttons (Files -> guide -> Files): ${[initialAdd, addWithGuide, restoredAdd].join(' -> ')}`,
  166. ].join('\n'))
  167. await openFile('smoke.md')
  168. await expect.poll(() => viewer.innerText()).toBe('Markdown')
  169. await preview.getByRole('heading', { name: 'Markdown smoke', exact: true }).waitFor({ timeout: 15_000 })
  170. expect(await preview.getByText('Rendered from the workspace.', { exact: true }).isVisible()).toBe(true)
  171. const heading = await preview.getByRole('heading', { name: 'Markdown smoke', exact: true }).innerText()
  172. const markdownTail = preview.getByRole('heading', { name: 'Markdown tail', exact: true })
  173. await expect.poll(() => preview.locator('[data-textpreview-more]').isEnabled()).toBe(true)
  174. expect(await markdownTail.count()).toBe(0)
  175. await scrollForNextPage(body)
  176. await markdownTail.waitFor({ timeout: 15_000 })
  177. await expect.poll(() => preview.locator('[data-textpreview-more]').count()).toBe(0)
  178. expect(await preview.getByRole('heading', { name: heading, exact: true }).count()).toBe(1)
  179. expect(await preview.getByText('Rendered from the workspace.', { exact: true }).count()).toBe(1)
  180. const tailHeading = await markdownTail.innerText()
  181. await preview.getByRole('heading', { name: heading, exact: true }).scrollIntoViewIfNeeded()
  182. await successShot(page, 'markdown')
  183. const markdownTab = column.locator('[data-dockkit-tab]').filter({ has: page.getByText('smoke.md', { exact: true }) })
  184. const markdownTabId = await markdownTab.getAttribute('data-dockkit-tab')
  185. expect(markdownTabId).not.toBeNull()
  186. const tabCount = await column.locator('[data-dockkit-tab]').count()
  187. const markdownViewers = [await viewer.innerText()]
  188. const sourceFonts: Array<{ fontSize: string; lineHeight: string }> = []
  189. for (const label of ['Code', 'Plain text']) {
  190. await viewer.click()
  191. await page.getByRole('menuitem', { name: label, exact: true }).click()
  192. await expect.poll(() => viewer.innerText()).toBe(label)
  193. if (label === 'Code') {
  194. await preview.locator('.shiki').waitFor({ timeout: 15_000 })
  195. expect(await preview.locator('.shiki').textContent()).toBe(markdownText)
  196. } else {
  197. await expect.poll(async () => (await preview.locator('[data-textpreview-line]').first().textContent())?.trim()).toBe('# Markdown smoke')
  198. }
  199. const source = label === 'Code' ? preview.locator('.shiki') : preview.locator('[data-textpreview-line]').first()
  200. sourceFonts.push(await source.evaluate((node) => {
  201. const style = getComputedStyle(node)
  202. return { fontSize: style.fontSize, lineHeight: style.lineHeight }
  203. }))
  204. expect(await markdownTab.getAttribute('data-dockkit-tab')).toBe(markdownTabId)
  205. expect(await column.locator('[data-dockkit-tab]').count()).toBe(tabCount)
  206. markdownViewers.push(await viewer.innerText())
  207. }
  208. expect(sourceFonts[1]).toEqual(sourceFonts[0])
  209. sections.push([
  210. '## Markdown', '',
  211. `- Heading: ${heading}`,
  212. `- Tail loaded by scrolling: ${tailHeading}`,
  213. `- Viewers: ${markdownViewers.join(' -> ')}`,
  214. `- Same tab: ${String(await markdownTab.getAttribute('data-dockkit-tab') === markdownTabId)}`,
  215. ].join('\n'))
  216. await openFile('smoke.html')
  217. await expect.poll(() => viewer.innerText()).toBe('HTML')
  218. const iframe = preview.locator('[data-html-preview]')
  219. await iframe.waitFor({ timeout: 15_000 })
  220. expect(await iframe.getAttribute('sandbox')).toBe('allow-scripts')
  221. const html = page.frameLocator('[data-html-preview]')
  222. await html.getByRole('heading', { name: 'HTML smoke', exact: true }).waitFor({ timeout: 15_000 })
  223. await expect.poll(() => html.locator('#result').innerText()).toBe('INLINE_OK')
  224. await expect.poll(() => html.locator('#local-result').innerText()).toBe('LOCAL_JS_OK')
  225. await expect.poll(() => html.locator('#outside-result').innerText()).toBe('OUTSIDE_JS_OK')
  226. await expect.poll(() => html.locator('#local-result').evaluate(node => getComputedStyle(node).color)).toBe('rgb(12, 34, 56)')
  227. await expect.poll(() => html.locator('#parent-result').innerText()).toBe('parent-blocked')
  228. expect(await html.locator('#parent-result').getAttribute('data-error')).toBe('SecurityError')
  229. expect(await page.locator('html').getAttribute('data-document-preview-escape')).toBeNull()
  230. await successShot(page, 'html')
  231. sections.push([
  232. '## HTML', '',
  233. `- Viewer: ${await viewer.innerText()}`,
  234. `- Sandbox: ${await iframe.getAttribute('sandbox')}`,
  235. `- Inline script: ${await html.locator('#result').innerText()}`,
  236. `- Local script: ${await html.locator('#local-result').innerText()}`,
  237. `- Outside-workspace script: ${await html.locator('#outside-result').innerText()}`,
  238. `- Local stylesheet: ${await html.locator('#local-result').evaluate(node => getComputedStyle(node).color)}`,
  239. `- Parent access: ${await html.locator('#parent-result').innerText()} (${await html.locator('#parent-result').getAttribute('data-error')})`,
  240. `- Parent unchanged: ${String(await page.locator('html').getAttribute('data-document-preview-escape') === null)}`,
  241. ].join('\n'))
  242. await openFile('smoke.pdf')
  243. await expect.poll(() => viewer.innerText()).toBe('PDF')
  244. const canvas = preview.getByRole('img', { name: 'PDF page 1', exact: true })
  245. await canvas.waitFor({ state: 'visible', timeout: 30_000 })
  246. expect(await preview.locator('[role="toolbar"]').count()).toBe(0)
  247. expect(await preview.locator('[data-pdf-page]').count()).toBe(2)
  248. await expect.poll(() => canvasColor(canvas), { timeout: 30_000 }).toBe('red')
  249. const firstColor = await canvasColor(canvas)
  250. expect(firstColor).toBe('red')
  251. const workerNames = await Promise.all(page.workers().map(worker => worker.evaluate(() => self.name)))
  252. expect(workerNames).toContain('dsh-pdf')
  253. await preview.locator('[data-pdf-page="2"]').scrollIntoViewIfNeeded()
  254. const secondPage = preview.getByRole('img', { name: 'PDF page 2', exact: true })
  255. await secondPage.waitFor({ state: 'visible', timeout: 30_000 })
  256. await expect.poll(() => canvasColor(secondPage), { timeout: 30_000 }).toBe('blue')
  257. const secondColor = await canvasColor(secondPage)
  258. expect(secondColor).toBe('blue')
  259. expect(await body.evaluate(node => node.scrollWidth <= node.clientWidth)).toBe(true)
  260. const pdfTab = column.locator('[data-dockkit-tab]').filter({ has: page.getByText('smoke.pdf', { exact: true }) })
  261. const pdfTabId = await pdfTab.getAttribute('data-dockkit-tab')
  262. expect(pdfTabId).not.toBeNull()
  263. await filesTab.click()
  264. await column.locator('[data-files-state="tree"]').waitFor({ state: 'visible' })
  265. await pdfTab.click()
  266. await preview.locator('[data-pdf-page="2"]').scrollIntoViewIfNeeded()
  267. await secondPage.waitFor({ state: 'visible', timeout: 30_000 })
  268. await expect.poll(() => canvasColor(secondPage), { timeout: 30_000 }).toBe('blue')
  269. const restoredColor = await canvasColor(secondPage)
  270. expect(restoredColor).toBe('blue')
  271. expect(await pdfTab.getAttribute('data-dockkit-tab')).toBe(pdfTabId)
  272. await successShot(page, 'pdf')
  273. sections.push([
  274. '## PDF', '',
  275. `- Viewer: ${await viewer.innerText()}`,
  276. `- Worker: ${workerNames.find(name => name === 'dsh-pdf')}`,
  277. `- Continuous pages: ${await preview.locator('[data-pdf-page]').count()}`,
  278. `- Horizontal overflow: ${String(await body.evaluate(node => node.scrollWidth > node.clientWidth))}`,
  279. `- Canvas fills: ${[firstColor, secondColor, restoredColor].join(' -> ')}`,
  280. `- Same tab: ${String(await pdfTab.getAttribute('data-dockkit-tab') === pdfTabId)}`,
  281. ].join('\n'))
  282. const releaseRead = Promise.withResolvers<undefined>()
  283. let waitingForRead = false
  284. const readPage = scaffold.ctx.workspaceFiles.read.bind(scaffold.ctx.workspaceFiles)
  285. const heldRead = vi.spyOn(scaffold.ctx.workspaceFiles, 'read').mockImplementation(async (agent, path, range, signal) => {
  286. if (path === 'pages.ts' && (range.offset ?? 1) === 1) {
  287. waitingForRead = true
  288. await releaseRead.promise
  289. }
  290. return readPage(agent, path, range, signal)
  291. })
  292. let initialReading = false
  293. try {
  294. await openFile('pages.ts')
  295. await expect.poll(() => waitingForRead).toBe(true)
  296. const reading = preview.locator('[data-document-loading]')
  297. initialReading = await reading.isVisible()
  298. expect(initialReading).toBe(true)
  299. expect(await preview.locator('[data-code-preview]').count()).toBe(0)
  300. const indicator = await reading.boundingBox()
  301. const scroller = await body.boundingBox()
  302. if (indicator === null || scroller === null) throw new Error('reading indicator or document body is not rendered')
  303. expect(indicator.y).toBeGreaterThanOrEqual(scroller.y)
  304. expect(indicator.y + indicator.height).toBeLessThanOrEqual(scroller.y + scroller.height)
  305. await successShot(page, 'code-reading')
  306. } finally {
  307. releaseRead.resolve(undefined)
  308. heldRead.mockRestore()
  309. }
  310. await expect.poll(() => viewer.innerText()).toBe('Code')
  311. const highlightedLines = preview.locator('.shiki .line')
  312. await expect.poll(() => highlightedLines.count(), { timeout: 15_000 }).toBe(PAGE_LINES)
  313. const codeBlock = preview.locator('.md-code-block')
  314. expect(await codeBlock.getAttribute('data-line-numbers')).toBe('true')
  315. await expect.poll(() => highlightedLines.first().evaluate(node => getComputedStyle(node, '::before').content))
  316. .not.toMatch(/^(?:none|normal)$/u)
  317. const numbering = await highlightedLines.first().evaluate((node) => {
  318. const line = getComputedStyle(node)
  319. const before = getComputedStyle(node, '::before')
  320. return {
  321. counterIncrement: line.counterIncrement,
  322. gutterWidth: Number.parseFloat(before.width),
  323. sourceInset: Number.parseFloat(line.paddingInlineStart),
  324. }
  325. })
  326. expect(numbering.counterIncrement).toBe('source-line 1')
  327. expect(numbering.gutterWidth).toBeGreaterThan(0)
  328. expect(numbering.sourceInset).toBeGreaterThan(numbering.gutterWidth)
  329. const prefix = await highlightedLines.allTextContents()
  330. expect(prefix).toEqual(codeLines.slice(0, PAGE_LINES))
  331. await expect.poll(() => preview.locator('[data-textpreview-more]').isEnabled()).toBe(true)
  332. await scrollForNextPage(body)
  333. await expect.poll(() => highlightedLines.count(), { timeout: 15_000 }).toBe(codeLines.length)
  334. const completed = await highlightedLines.allTextContents()
  335. expect(completed).toEqual(codeLines)
  336. await expect.poll(() => preview.locator('[data-textpreview-more]').count()).toBe(0)
  337. const scrollTop = await body.evaluate((node) => {
  338. const target = Math.floor((node.scrollHeight - node.clientHeight) / 2)
  339. if (target <= 0) throw new Error('code fixture does not overflow the document body')
  340. node.scrollTop = target
  341. return target
  342. })
  343. await expect.poll(() => body.evaluate((node) => {
  344. const banner = node.querySelector('.md-code-block')?.firstElementChild
  345. const firstLine = node.querySelector('.shiki .line')
  346. if (!(banner instanceof HTMLElement) || firstLine === null) throw new Error('missing rendered code banner or source line')
  347. const bounds = node.getBoundingClientRect()
  348. const clipTop = bounds.top + node.clientTop
  349. const bannerBounds = banner.getBoundingClientRect()
  350. const hit = document.elementFromPoint(bounds.left + node.clientLeft + node.clientWidth / 2, clipTop + 1)
  351. return {
  352. scrollTop: node.scrollTop,
  353. position: getComputedStyle(banner).position,
  354. topGap: bannerBounds.top - clipTop,
  355. firstLineAbove: firstLine.getBoundingClientRect().top < clipTop,
  356. topCoveredByBanner: hit !== null && banner.contains(hit),
  357. }
  358. })).toEqual({ scrollTop, position: 'sticky', topGap: 0, firstLineAbove: true, topCoveredByBanner: true })
  359. await page.context().grantPermissions(['clipboard-read', 'clipboard-write'], { origin: new URL(page.url()).origin })
  360. await page.evaluate(() => navigator.clipboard.writeText(''))
  361. await codeBlock.getByRole('button', { name: 'Copy', exact: true }).click()
  362. await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(codeLines.join('\n'))
  363. sections.push([
  364. '## Code paging', '',
  365. `- Viewer: ${await viewer.innerText()}`,
  366. `- Initial reading indicator: ${initialReading}`,
  367. `- Lines: ${prefix.length} -> ${completed.length}`,
  368. `- Prefix retained: ${String(JSON.stringify(completed.slice(0, prefix.length)) === JSON.stringify(prefix))}`,
  369. `- Tail: ${completed.at(-1)}`,
  370. ].join('\n'))
  371. await openFile('notes.unknown')
  372. await expect.poll(() => viewer.innerText()).toBe('Plain text')
  373. const plainLines = preview.locator('[data-textpreview-line]')
  374. await expect.poll(() => plainLines.count()).toBe(2)
  375. const fallback = (await plainLines.allTextContents()).map(line => line.trim())
  376. expect(fallback).toEqual(['UNKNOWN_SUFFIX', 'Plain fallback.'])
  377. sections.push(['## Unknown suffix', '', `- Viewer: ${await viewer.innerText()}`, `- Text: ${fallback.join(' | ')}`].join('\n'))
  378. expect(tripwire.pageErrors).toEqual([])
  379. expect(tripwire.warnings).toEqual([])
  380. await compareOrRefreshGolden(EXPECTED, sections.join('\n\n'), MODE)
  381. await assertFixtureInventory(SNAPSHOT_DIR, ['document.expected.md', 'paging.patch.yml'])
  382. })
  383. })