details-session-lifecycle.e2e.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. // Recorded-session Sidebar geometry and per-Session view state through the shipped browser composition.
  2. import { mkdir, readFile } from 'node:fs/promises'
  3. import { fileURLToPath } from 'node:url'
  4. import { join } from 'node:path'
  5. import type { Browser, Locator, Page } from 'playwright'
  6. import { chromium } from 'playwright'
  7. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  8. import {
  9. acknowledgeReloadConnectionLoss, assertFixtureInventory, compareOrRefreshGolden,
  10. fixtureUserPrompts, launchWebScaffold, seedSession, watchConsole, webSnapshotMode,
  11. type WebScaffold,
  12. } from './scaffold.ts'
  13. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  14. const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/details-session-lifecycle', import.meta.url))
  15. const HANDLES_EXPECTED = join(SNAPSHOT_DIR, 'handles.expected.md')
  16. const SIDEBAR_EXPECTED = join(SNAPSHOT_DIR, 'sidebar.expected.md')
  17. const SHOT_DIR = fileURLToPath(new URL('../../../.artifacts/screenshots/0907-sidebar-rules', import.meta.url))
  18. const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/lifecycle-chrome/session.v3.jsonl', import.meta.url))
  19. const SEED_FIXTURE = fileURLToPath(new URL('../../../snapshots/web/seeded-history/session.v3.jsonl', import.meta.url))
  20. const PROMPT = 'Reply with the single word LIGHTHOUSE and stop.'
  21. const MODE = webSnapshotMode()
  22. /** Last AppFrame grid track in CSS pixels. */
  23. async function detailsTrack(page: Page): Promise<number> {
  24. return await appFrame(page).evaluate((element) => {
  25. const tracks = getComputedStyle(element).gridTemplateColumns.split(' ')
  26. return Number.parseFloat(tracks.at(-1) ?? 'NaN')
  27. })
  28. }
  29. /** First AppFrame grid track in CSS pixels. */
  30. async function sidebarTrack(page: Page): Promise<number> {
  31. return await appFrame(page).evaluate((element) => {
  32. const tracks = getComputedStyle(element).gridTemplateColumns.split(' ')
  33. return Number.parseFloat(tracks[0] ?? 'NaN')
  34. })
  35. }
  36. /** AppFrame is the only product element with an inline grid track template. */
  37. function appFrame(page: Page) {
  38. return page.locator('[style*="grid-template-columns"]').first()
  39. }
  40. /** Render the two column-resize handles without platform-dependent coordinates. */
  41. async function handleSnapshot(page: Page): Promise<string> {
  42. const handles = await page.locator('[class*="handle"]').evaluateAll(elements =>
  43. elements.map(element => ({
  44. side: element.getAttribute('data-side'),
  45. cursor: getComputedStyle(element).cursor,
  46. pillGenerated: getComputedStyle(element, '::after').content !== 'none',
  47. })))
  48. return [
  49. '# AppFrame drag handles',
  50. '',
  51. ...handles.flatMap(handle => [
  52. `## ${handle.side}`,
  53. '',
  54. '- hit strip present: true',
  55. `- cursor: ${handle.cursor}`,
  56. `- pill generated: ${String(handle.pillGenerated)}`,
  57. '',
  58. ]),
  59. ].join('\n').trimEnd()
  60. }
  61. /** Rendered frame tracks, rounded only to remove browser subpixel allocation. */
  62. async function columns(page: Page): Promise<number[]> {
  63. return await appFrame(page).evaluate(element =>
  64. getComputedStyle(element).gridTemplateColumns.split(' ').map(value => Math.round(Number.parseFloat(value))))
  65. }
  66. /** Tab order and selection inside each docked pane, independent of generated ids. */
  67. async function paneSnapshot(page: Page) {
  68. return await page.locator('[data-rightbar-col] [data-dockkit-pane]').evaluateAll(panes => panes.map(pane => ({
  69. active: pane.hasAttribute('data-dockkit-pane-active'),
  70. tabs: [...pane.querySelectorAll('[data-dockkit-tab]')].map(tab => ({
  71. title: tab.querySelector('[data-dockkit-tab-title]')?.textContent?.trim(),
  72. selected: tab.getAttribute('aria-selected') === 'true',
  73. })),
  74. })))
  75. }
  76. /** Product-visible geometry, pane state, and expanded Files directories at a settled checkpoint. */
  77. async function sidebarSnapshot(page: Page) {
  78. const geometry = await appFrame(page).evaluate((frame) => {
  79. const panel = frame.querySelector<HTMLElement>('[data-sidebar-right-panel]')
  80. if (panel === null) throw new Error('Sidebar panel is not mounted')
  81. const expanded = panel.hasAttribute('data-sidebar-right-open')
  82. const rect = panel.getBoundingClientRect()
  83. const style = getComputedStyle(panel)
  84. const handle = frame.querySelector('[data-side="rightbar"]')
  85. return {
  86. viewport: [window.innerWidth, window.innerHeight],
  87. columns: getComputedStyle(frame).gridTemplateColumns.split(' ').map(value => Math.round(Number.parseFloat(value))),
  88. columnTransition: getComputedStyle(frame).transitionProperty,
  89. expanded,
  90. mode: panel.getAttribute('data-sidebar-right-panel'),
  91. panelContentWidth: expanded ? Math.round(Number.parseFloat(style.width)) : 0,
  92. panelOuterWidth: expanded ? Math.round(rect.width) : 0,
  93. coversViewport: expanded && rect.x === 0 && rect.y === 0
  94. && Math.round(rect.width) === window.innerWidth && Math.round(rect.height) === window.innerHeight,
  95. resizeHandleWidth: handle === null ? 0 : Math.round(handle.getBoundingClientRect().width),
  96. expandedDirectories: [...panel.querySelectorAll('[data-files-entry="directory"] > button[aria-expanded="true"]')]
  97. .map(button => button.textContent?.trim()),
  98. }
  99. })
  100. return { ...geometry, panes: await paneSnapshot(page) }
  101. }
  102. /** The native pointer gesture used for the left column's width preference. */
  103. async function dragSidebar(page: Page, target: number): Promise<void> {
  104. const grip = await page.locator('[data-side="sidebar"]').boundingBox()
  105. if (grip === null) throw new Error('Sidebar resize handle is not rendered')
  106. await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2)
  107. await page.mouse.down()
  108. try {
  109. await page.mouse.move(target, grip.y + grip.height / 2, { steps: 6 })
  110. } finally {
  111. await page.mouse.up()
  112. }
  113. await expect.poll(() => sidebarTrack(page)).toBe(target)
  114. }
  115. describe.skipIf(MODE === 'record')('web e2e: details panel follows the current Session lifecycle', () => {
  116. let scaffold: WebScaffold
  117. let browser: Browser
  118. let page: Page
  119. let tripwire: ReturnType<typeof watchConsole>
  120. beforeAll(async () => {
  121. const fixture = await readFile(FIXTURE, 'utf8')
  122. expect(fixtureUserPrompts(fixture)).toEqual([PROMPT])
  123. scaffold = await launchWebScaffold({ replayFixture: FIXTURE, paceMs: 5, compareReplaySession: false })
  124. await seedSession(scaffold, await readFile(SEED_FIXTURE, 'utf8'), 'details-session-lifecycle-seed')
  125. browser = await chromium.launch()
  126. page = await newEnglishPage(browser)
  127. tripwire = watchConsole(page)
  128. await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  129. await appFrame(page).waitFor({ timeout: 30_000 })
  130. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  131. }, 120_000)
  132. afterAll(async () => {
  133. try {
  134. await browser?.close()
  135. } finally {
  136. await scaffold?.close()
  137. }
  138. })
  139. it('retains each Session sidebar and applies normal, fullscreen, and capacity-close geometry', async () => {
  140. onTestFailed(async () => {
  141. await mkdir(SHOT_DIR, { recursive: true })
  142. await saveFailureShot(page, `screenshots/0907-sidebar-rules/details-session-lifecycle-${MODE}-${process.pid}`)
  143. })
  144. const settled = scaffold.whenTurnSettled()
  145. const input = page.locator('[data-composer-input]').first()
  146. await input.fill(PROMPT)
  147. await input.press('Enter')
  148. await settled
  149. await page.getByText('LIGHTHOUSE', { exact: true }).waitFor({ timeout: 15_000 })
  150. await expect.poll(() => detailsTrack(page), { timeout: 5_000 }).toBe(0)
  151. expect(await page.getByText('Details', { exact: true }).isVisible()).toBe(false)
  152. await compareOrRefreshGolden(HANDLES_EXPECTED, await handleSnapshot(page), MODE)
  153. const sidebarBefore = await sidebarTrack(page)
  154. const sidebarHandle = page.locator('[data-side="sidebar"]')
  155. const sidebarBox = await sidebarHandle.boundingBox()
  156. expect(sidebarBox).not.toBeNull()
  157. const dragStartX = sidebarBox!.x + sidebarBox!.width / 2
  158. await page.mouse.move(dragStartX, sidebarBox!.y + 200)
  159. await page.mouse.down()
  160. await page.mouse.move(dragStartX + 70, sidebarBox!.y + 200, { steps: 6 })
  161. await page.mouse.up()
  162. await expect.poll(() => sidebarTrack(page), { timeout: 5_000 }).toBe(sidebarBefore + 70)
  163. const warningStart = tripwire.warnings.length
  164. await page.reload({ waitUntil: 'load' })
  165. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  166. await appFrame(page).waitFor({ timeout: 30_000 })
  167. await page.getByText('LIGHTHOUSE', { exact: true }).waitFor({ timeout: 15_000 })
  168. await expect.poll(() => detailsTrack(page), { timeout: 5_000 }).toBe(0)
  169. expect(await page.getByText('Details', { exact: true }).isVisible()).toBe(false)
  170. await page.getByRole('button', { name: /^(?:New session|新.*会话)$/ }).last().click()
  171. await page.getByText('Into the Unknown', { exact: false }).waitFor({ timeout: 15_000 })
  172. await expect.poll(() => detailsTrack(page), { timeout: 5_000 }).toBe(0)
  173. expect(await page.getByText('Details', { exact: true }).isVisible()).toBe(false)
  174. const original = page.locator('[role="treeitem"][aria-selected]').filter({ hasText: 'Reply with the single word' }).first()
  175. await original.click()
  176. await page.getByText('LIGHTHOUSE', { exact: true }).waitFor({ timeout: 15_000 })
  177. await expect.poll(() => detailsTrack(page), { timeout: 5_000 }).toBe(0)
  178. expect(await page.getByText('Details', { exact: true }).isVisible()).toBe(false)
  179. const ungrouped = page.getByText('Ungrouped', { exact: true })
  180. const ungroupedRow = ungrouped.locator('..').locator('..')
  181. if (await ungroupedRow.getAttribute('aria-expanded') !== 'true') await ungrouped.click()
  182. await expect.poll(() => ungroupedRow.getAttribute('aria-expanded')).toBe('true')
  183. // A cold Session's row may still show its cwd until its history loads.
  184. const seeded = ungroupedRow.locator('..').locator('[role="treeitem"][aria-selected]')
  185. await expect.poll(() => seeded.count()).toBe(1)
  186. await seeded.click()
  187. await page.getByText('DONE', { exact: true }).waitFor({ timeout: 15_000 })
  188. await expect.poll(() => detailsTrack(page), { timeout: 5_000 }).toBe(0)
  189. const viewport = page.viewportSize()
  190. if (viewport === null) throw new Error('expected a fixed viewport')
  191. const column = page.locator('[data-rightbar-col]')
  192. const panel = column.locator('[data-sidebar-right-panel]')
  193. const panes = column.locator('[data-dockkit-pane]')
  194. const normalWidth = Math.round(viewport.width * 0.45)
  195. const normalColumns = [280, viewport.width - 280 - normalWidth, normalWidth]
  196. const checkpoints: string[] = ['# Recorded-session Sidebar states']
  197. const checkpoint = async (label: string): Promise<void> => {
  198. checkpoints.push(`## ${label}\n\n\`\`\`json\n${JSON.stringify(await sidebarSnapshot(page), null, 2)}\n\`\`\``)
  199. }
  200. const select = async (row: Locator, reply: string): Promise<void> => {
  201. await row.click()
  202. await expect.poll(() => row.getAttribute('aria-selected')).toBe('true')
  203. await page.getByText(reply, { exact: true }).waitFor({ timeout: 15_000 })
  204. }
  205. const open = async (): Promise<void> => {
  206. await page.locator('[data-sidebar-right-expand]').click()
  207. await expect.poll(() => column.locator('[data-sidebar-right-open]').count()).toBe(1)
  208. await expect.poll(() => columns(page)).toEqual(normalColumns)
  209. // The panel's slide completes independently of the frame's grid tracks.
  210. await expect.poll(() => panel.evaluate(element => getComputedStyle(element).transform))
  211. .toBe('none')
  212. }
  213. const close = async (): Promise<void> => {
  214. await column.locator('[data-sidebar-right-toggle]').click()
  215. await expect.poll(() => column.locator('[data-sidebar-right-open]').count()).toBe(0)
  216. // Closing publishes state before the frame's grid transition finishes.
  217. await appFrame(page).evaluate(async (frame) => {
  218. await Promise.allSettled(frame.getAnimations().map(animation => animation.finished))
  219. })
  220. await expect.poll(() => detailsTrack(page)).toBe(0)
  221. await panel.waitFor({ state: 'hidden' })
  222. }
  223. await select(original, 'LIGHTHOUSE')
  224. await open()
  225. // The content-box panel adds its one rendered border pixel outside the
  226. // CSS width assigned by the grid solver.
  227. await expect.poll(() => sidebarSnapshot(page), { timeout: 5_000 })
  228. .toMatchObject({ mode: 'push', panelContentWidth: normalWidth, panelOuterWidth: normalWidth + 1, resizeHandleWidth: 8 })
  229. await expect.poll(async () => ({
  230. filesVisible: await column.locator('[data-files-state="tree"]').isVisible(),
  231. errors: tripwire.pageErrors,
  232. })).toEqual({ filesVisible: true, errors: [] })
  233. await column.locator('[data-dockkit-add-tab]').click()
  234. const split = column.locator('[data-dockkit-split-button]').first()
  235. await expect.poll(() => split.isDisabled()).toBe(false)
  236. await split.click()
  237. await expect.poll(() => panes.count()).toBe(2)
  238. await panes.first().locator('[data-dockkit-tab]').filter({ hasText: 'Files' }).click()
  239. await expect.poll(() => panes.first().locator('[data-files-state="tree"]').count()).toBe(1)
  240. const retainedA = await paneSnapshot(page)
  241. expect(retainedA.map(pane => pane.tabs.map(tab => tab.title))).toEqual([['Files', 'Start'], ['Files']])
  242. await checkpoint('A normal: two panes')
  243. await column.locator('[data-sidebar-right-mode="fullscreen"]').click()
  244. await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport })
  245. expect(await columns(page)).toEqual(normalColumns)
  246. expect(await sidebarSnapshot(page)).toMatchObject({ mode: 'fullscreen', resizeHandleWidth: 0, coversViewport: true })
  247. expect(await paneSnapshot(page)).toEqual(retainedA)
  248. await checkpoint('A manual fullscreen: underlying columns retained')
  249. // Closing the fullscreen panel exposes Session navigation without changing
  250. // its manual mode; reopening after the round trip must restore that mode.
  251. await close()
  252. expect((await sidebarSnapshot(page)).columnTransition).toBe('none')
  253. await checkpoint('A closed with manual fullscreen retained')
  254. await select(seeded, 'DONE')
  255. await expect.poll(() => detailsTrack(page)).toBe(0)
  256. await open()
  257. expect(await panel.getAttribute('data-sidebar-right-panel')).toBe('push')
  258. await column.locator('[data-files-state="tree"]').waitFor({ timeout: 15_000 })
  259. const workspaceDirectory = column.locator('[data-files-entry="directory"] > button').filter({ hasText: /^workspace$/ })
  260. await workspaceDirectory.waitFor({ timeout: 15_000 })
  261. await workspaceDirectory.click()
  262. await expect.poll(() => workspaceDirectory.getAttribute('aria-expanded')).toBe('true')
  263. // The child listing crosses the same Remote as the root listing above.
  264. await column.locator('[data-files-row="loading"]').waitFor({ state: 'hidden', timeout: 15_000 })
  265. expect(await column.locator('[data-files-row="failed"]').count()).toBe(0)
  266. const retainedB = await paneSnapshot(page)
  267. expect(retainedB.map(pane => pane.tabs.map(tab => tab.title))).toEqual([['Files']])
  268. await close()
  269. await checkpoint('B closed: independent pane and expanded workspace directory')
  270. await select(original, 'LIGHTHOUSE')
  271. await expect.poll(() => detailsTrack(page)).toBe(0)
  272. expect(await panel.getAttribute('data-sidebar-right-panel')).toBe('fullscreen')
  273. expect(await paneSnapshot(page)).toEqual(retainedA)
  274. await open()
  275. await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport })
  276. expect(await paneSnapshot(page)).toEqual(retainedA)
  277. await checkpoint('A restored: manual fullscreen, tabs, and panes')
  278. await column.locator('[data-sidebar-right-mode="push"]').click()
  279. await expect.poll(async () => (await sidebarSnapshot(page)).panelContentWidth, { timeout: 5_000 }).toBe(normalWidth)
  280. await select(seeded, 'DONE')
  281. await expect.poll(() => detailsTrack(page)).toBe(0)
  282. expect(await panel.getAttribute('data-sidebar-right-panel')).toBe('push')
  283. expect(await paneSnapshot(page)).toEqual(retainedB)
  284. await open()
  285. await expect.poll(() => workspaceDirectory.getAttribute('aria-expanded')).toBe('true')
  286. expect(await paneSnapshot(page)).toEqual(retainedB)
  287. await checkpoint('B restored: normal mode and Files directory state')
  288. await close()
  289. await select(original, 'LIGHTHOUSE')
  290. await expect.poll(() => columns(page)).toEqual(normalColumns)
  291. expect(await column.locator('[data-sidebar-right-open]').count()).toBe(1)
  292. expect(await paneSnapshot(page)).toEqual(retainedA)
  293. await checkpoint('A restored: expanded normal panel')
  294. try {
  295. await page.setViewportSize({ width: 1024, height: viewport.height })
  296. // Frame measurement and the grid transition can finish after setViewportSize returns.
  297. await expect.poll(() => columns(page), { timeout: 5_000 }).toEqual([280, 400, 344])
  298. await dragSidebar(page, 420)
  299. await expect.poll(() => columns(page)).toEqual([420, 604, 0])
  300. expect(await column.locator('[data-sidebar-right-open]').count()).toBe(0)
  301. expect(await paneSnapshot(page)).toEqual(retainedA)
  302. await checkpoint('A capacity-closed: wide left preference protected')
  303. await page.setViewportSize(viewport)
  304. await expect.poll(() => columns(page)).toEqual([420, viewport.width - 420, 0])
  305. expect(await column.locator('[data-sidebar-right-open]').count()).toBe(0)
  306. await checkpoint('A widened: remains closed')
  307. await page.locator('[data-sidebar-right-expand]').click()
  308. await expect.poll(() => columns(page)).toEqual([420, viewport.width - 420 - normalWidth, normalWidth])
  309. await page.setViewportSize({ width: 767, height: viewport.height })
  310. await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, width: 767, height: viewport.height })
  311. await expect.poll(() => columns(page)).toEqual([56, 711, 0])
  312. expect(await sidebarSnapshot(page)).toMatchObject({ mode: 'fullscreen', resizeHandleWidth: 0, coversViewport: true })
  313. await checkpoint('A automatic fullscreen at 767px')
  314. await column.locator('[data-sidebar-right-mode="push"]').click()
  315. await expect.poll(() => column.locator('[data-sidebar-right-open]').count()).toBe(0)
  316. await page.setViewportSize(viewport)
  317. await expect.poll(() => columns(page)).toEqual([420, viewport.width - 420, 0])
  318. expect(await paneSnapshot(page)).toEqual(retainedA)
  319. expect(await panel.getAttribute('data-sidebar-right-panel')).toBe('push')
  320. expect(await column.locator('[data-sidebar-right-open]').count()).toBe(0)
  321. await checkpoint('A automatic fullscreen exited: widening does not reopen')
  322. } finally {
  323. await page.setViewportSize(viewport)
  324. }
  325. await compareOrRefreshGolden(SIDEBAR_EXPECTED, checkpoints.join('\n\n'), MODE)
  326. expect(tripwire.pageErrors).toEqual([])
  327. expect(tripwire.warnings).toEqual([])
  328. await assertFixtureInventory(SNAPSHOT_DIR, ['handles.expected.md', 'sidebar.expected.md'])
  329. })
  330. })