lifecycle-chrome.e2e.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. // Web e2e scenarios: lifecycle & chrome — the workspace-aware first-send
  2. // flow over the real wire, reload recovery, and the dark-mode token cascade.
  3. // One tiny recorded turn (text-only) drives the whole spec: the empty-state
  4. // hero materializes a real Workspace + Session on first send (the jsdom
  5. // workspace-flow suite pins the object-layer state machine over the fixture
  6. // client; THIS spec pins the same flow through HTTP RPC + SSE + the host
  7. // gateway), reload replays everything from the log (zero further model
  8. // calls), and the theme scenario proves the shipped dark palette actually
  9. // cascades: attribute -> alias token flip -> painted surface change. Per the
  10. // lane's scope ruling there is no theme/layout golden (aria is color-blind);
  11. // the hero's waiting state gets the one golden here.
  12. import { readFile } from 'node:fs/promises'
  13. import { fileURLToPath } from 'node:url'
  14. import { join } from 'node:path'
  15. import type { Browser, Page } from 'playwright'
  16. import { chromium } from 'playwright'
  17. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  18. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  19. import {
  20. acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
  21. launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
  22. } from './scaffold.ts'
  23. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  24. const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/lifecycle-chrome', import.meta.url))
  25. const FIXTURE = join(SNAPSHOT_DIR, 'session.jsonl')
  26. const HERO_EXPECTED = join(SNAPSHOT_DIR, 'hero.expected.md')
  27. const COMMAND_MENU_EXPECTED = join(SNAPSHOT_DIR, 'command-menu.expected.md')
  28. const PLAN_ACTIVE_EXPECTED = join(SNAPSHOT_DIR, 'plan-active.expected.md')
  29. // Post-reload golden: the same settled conversation rebuilt purely from
  30. // persistence + history — byte-equal rendering is exactly the recovery claim.
  31. const RELOADED_EXPECTED = join(SNAPSHOT_DIR, 'reloaded.expected.md')
  32. const MODE = webSnapshotMode()
  33. const PROMPT = 'Reply with the single word LIGHTHOUSE and stop.'
  34. const REPLAY_PACE_MS = 100
  35. describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () => {
  36. let scaffold: WebScaffold
  37. let browser: Browser
  38. let page: Page
  39. let tripwire: ReturnType<typeof watchConsole>
  40. const sessionEvents: SessionEvent[] = []
  41. beforeAll(async () => {
  42. scaffold = await launchWebScaffold(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: REPLAY_PACE_MS })
  43. scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
  44. browser = await chromium.launch()
  45. page = await newEnglishPage(browser)
  46. tripwire = watchConsole(page)
  47. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  48. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  49. // Fresh world: connect a Workspace so the composer scenarios start live.
  50. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  51. }, 120_000)
  52. afterAll(async () => {
  53. await browser?.close()
  54. await scaffold?.close()
  55. })
  56. it.skipIf(MODE === 'record')('opens the shared slash menu from plus with only Command candidates', async () => {
  57. onTestFailed(() => saveFailureShot(page, 'web-e2e-command-menu-launcher'))
  58. const launcher = page.getByRole('button', { name: 'Commands' })
  59. await launcher.click()
  60. const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
  61. await menu.waitFor({ timeout: 10_000 })
  62. const snapshot = await captureStableAria(page, '[role="listbox"]', scaffold.workspaceCwd)
  63. await compareOrRefreshGolden(COMMAND_MENU_EXPECTED, snapshot, MODE)
  64. expect(snapshot).toContain('text: Commands')
  65. expect(snapshot).not.toContain('text: Skills')
  66. expect(snapshot).not.toContain('text: Subagents')
  67. const launchedBox = await menu.boundingBox()
  68. await page.locator('textarea').first().press('Escape')
  69. await expect.poll(() => menu.count()).toBe(0)
  70. const input = page.locator('textarea').first()
  71. await input.fill('/')
  72. await menu.waitFor({ timeout: 10_000 })
  73. const typedBox = await menu.boundingBox()
  74. expect(launchedBox).not.toBeNull()
  75. expect(typedBox).not.toBeNull()
  76. expect(Math.abs(launchedBox!.x - typedBox!.x)).toBeLessThan(1)
  77. expect(Math.abs(
  78. launchedBox!.y + launchedBox!.height - typedBox!.y - typedBox!.height,
  79. )).toBeLessThan(1)
  80. await input.fill('')
  81. await expect.poll(() => menu.count()).toBe(0)
  82. })
  83. it.skipIf(MODE === 'record')('shows active Plan as the warn-state status action', async () => {
  84. const activeScaffold = await launchWebScaffold()
  85. const activePage = await newEnglishPage(browser)
  86. const activeTripwire = watchConsole(activePage)
  87. try {
  88. await activePage.goto(activeScaffold.baseUrl, { waitUntil: 'load' })
  89. await activePage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  90. await connectFreshWorkspace(activePage, activeScaffold.workspaceCwd)
  91. const input = activePage.locator('textarea').first()
  92. await activePage.getByRole('button', { name: 'Commands' }).click()
  93. const menu = activePage.getByRole('listbox', { name: 'Trigger suggestions' })
  94. await menu.waitFor({ timeout: 10_000 })
  95. await menu.getByRole('option', { name: 'plan Enter or leave plan mode' }).click()
  96. await expect.poll(() => input.inputValue()).toBe('/plan ')
  97. await input.press('Enter')
  98. const planButton = activePage.getByRole('button', { name: 'Plan mode on, press to turn off' })
  99. await planButton.waitFor({ timeout: 10_000 })
  100. // The golden encodes an empty composer, and the button arriving does not
  101. // mean the submitted text is gone yet: under load the capture caught a
  102. // textbox still holding `/plan`.
  103. await expect.poll(() => input.inputValue(), { timeout: 10_000 }).toBe('')
  104. const planSnapshot = await captureStableAria(activePage, '[class*="frame"]', activeScaffold.workspaceCwd)
  105. await compareOrRefreshGolden(PLAN_ACTIVE_EXPECTED, planSnapshot, MODE)
  106. const planStyle = await planButton.evaluate((element) => {
  107. const probe = document.createElement('span')
  108. probe.style.color = 'var(--dsw-alias-state-warn-label)'
  109. probe.style.backgroundColor = 'var(--dsw-alias-state-warn-tertiary)'
  110. document.body.append(probe)
  111. const actual = getComputedStyle(element)
  112. const reference = getComputedStyle(probe)
  113. const result = {
  114. color: actual.color,
  115. backgroundColor: actual.backgroundColor,
  116. borderRadius: actual.borderRadius,
  117. fontSize: actual.fontSize,
  118. referenceColor: reference.color,
  119. referenceBackgroundColor: reference.backgroundColor,
  120. }
  121. probe.remove()
  122. return result
  123. })
  124. expect(planStyle.color).toBe(planStyle.referenceColor)
  125. expect(planStyle.backgroundColor).toBe(planStyle.referenceBackgroundColor)
  126. expect(planStyle.borderRadius).toBe('999px')
  127. expect(planStyle.fontSize).toBe('13px')
  128. await planButton.click()
  129. await expect.poll(() => planButton.count()).toBe(0)
  130. expect(activeTripwire.pageErrors).toEqual([])
  131. expect(activeTripwire.warnings).toEqual([])
  132. } catch (error) {
  133. await saveFailureShot(activePage, 'web-e2e-plan-active').catch(() => undefined)
  134. throw error
  135. } finally {
  136. await activePage.close()
  137. await activeScaffold.close()
  138. }
  139. })
  140. it('sends the first prompt from the empty-state hero (all modes)', async () => {
  141. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-send'))
  142. if (MODE !== 'record') {
  143. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
  144. }
  145. // The blank frame renders the hero, not the resident composer: the
  146. // headline plus the guidance placeholder are the empty state's anchors.
  147. await expect.poll(() => page.getByText("Let's start building", { exact: false }).count(), { timeout: 15_000 }).toBe(1)
  148. const input = page.locator('textarea').first()
  149. await input.waitFor({ timeout: 10_000 })
  150. if (MODE !== 'record') {
  151. // Golden of the hero's stable waiting state (captured before any send;
  152. // the conversation-region goldens belong to the other scenarios).
  153. const snapshot = await captureStableAria(page, '[class*="frame"]', scaffold.workspaceCwd)
  154. await compareOrRefreshGolden(HERO_EXPECTED, snapshot, MODE)
  155. }
  156. const settled = scaffold.whenTurnSettled()
  157. await input.fill(PROMPT)
  158. const observeTurn = async () => {
  159. const originalViewport = page.viewportSize() ?? { width: 1680, height: 1000 }
  160. if (MODE !== 'record') await page.setViewportSize({ width: 480, height: 1000 })
  161. try {
  162. await input.press('Enter')
  163. if (MODE !== 'record') {
  164. const liveTail = page.locator('[data-variant="think"][data-state="running"] [data-follow-end]')
  165. await expect.poll(async () => await liveTail.evaluate(element => (
  166. element.scrollWidth > element.clientWidth
  167. && element.scrollLeft >= element.scrollWidth - element.clientWidth - 1
  168. )), { timeout: 10_000, interval: 10 }).toBe(true)
  169. }
  170. return await settled
  171. } finally {
  172. if (MODE !== 'record') await page.setViewportSize(originalViewport)
  173. }
  174. }
  175. const sessionId = await observeTurn()
  176. if (MODE === 'record') {
  177. await recordFixture(scaffold, sessionId, FIXTURE)
  178. }
  179. }, 200_000)
  180. it.skipIf(MODE === 'record')('materialized a real Workspace and Session over the wire', async () => {
  181. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-materialize'))
  182. // Browser: the sidebar tree now carries the auto-created workspace group
  183. // with its one session, and the opened session is the selected row.
  184. await expect.poll(() => page.getByText('1 session', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
  185. await expect.poll(() => page.locator('[role="treeitem"][aria-selected="true"]').count(), { timeout: 10_000 }).toBe(1)
  186. await expect.poll(() => page.getByText('LIGHTHOUSE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
  187. // Host: the session's durable header cwd is the folder the workspace
  188. // flow created and adopted (<workspaceCwd>/workspace) — the proof the
  189. // send went through workspace materialization rather than a bare
  190. // default-cwd session.
  191. const cwds = scaffold.ctx.sessions.list().map(session => session.header.cwd)
  192. expect(cwds).toEqual([join(scaffold.workspaceCwd, 'workspace')])
  193. const turnEnds = sessionEvents.filter(e => e.type === 'turn/end')
  194. expect(turnEnds).toHaveLength(1)
  195. expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed')
  196. }, 60_000)
  197. it.skipIf(MODE === 'record')('recovers the whole surface across a reload from the log alone', async () => {
  198. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-reload'))
  199. const warningStart = tripwire.warnings.length
  200. await page.reload({ waitUntil: 'load' })
  201. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  202. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  203. // Selection persisted (dsh.sessions.current) and history replayed: the
  204. // recorded turn re-renders from session.history with zero model calls —
  205. // the replay cursor was fully consumed before the reload, so any stray
  206. // request would fail the scenario loudly at close().
  207. await expect.poll(() => page.getByText('LIGHTHOUSE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
  208. await expect.poll(() => page.locator('[role="treeitem"][aria-selected="true"]').count(), { timeout: 10_000 }).toBe(1)
  209. // Golden of the recovered conversation region: rebuilt from the log, it
  210. // must render the same settled transcript the live turn produced.
  211. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  212. await compareOrRefreshGolden(RELOADED_EXPECTED, snapshot, MODE)
  213. expect(tripwire.pageErrors).toEqual([])
  214. }, 90_000)
  215. it.skipIf(MODE === 'record')('cascades the dark theme from the body attribute to painted surfaces', async () => {
  216. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-dark'))
  217. // This scenario pins the ThemeService's DOM contract seam directly (the
  218. // body[data-ds-dark-theme] attribute -> stylesheet cascade); the REAL
  219. // user gesture above it (Settings -> Appearance cubes) is owned by
  220. // settings-chrome.e2e.ts. Driving the attribute here keeps the cascade
  221. // pinned independently of the settings surface's own lifecycle.
  222. const sample = async (): Promise<{ token: string; sidebarBg: string; bodyBg: string }> =>
  223. await page.evaluate(() => {
  224. const sidebar = document.querySelector('[class*="sidebar"], [class*="rail"]') ?? document.body
  225. return {
  226. token: getComputedStyle(document.body).getPropertyValue('--dsw-alias-bg-base').trim(),
  227. sidebarBg: getComputedStyle(sidebar).backgroundColor,
  228. bodyBg: getComputedStyle(document.body).backgroundColor,
  229. }
  230. })
  231. const light = await sample()
  232. await page.evaluate(() => { document.body.setAttribute('data-ds-dark-theme', '') })
  233. const dark = await sample()
  234. // The alias token itself must flip — the cascade's root fact.
  235. expect(dark.token).not.toBe(light.token)
  236. // And a real painted surface must consume it (not just variables in a
  237. // void): at least one of the sampled backgrounds repaints.
  238. expect(dark.sidebarBg !== light.sidebarBg || dark.bodyBg !== light.bodyBg).toBe(true)
  239. // Removing the attribute restores the light values exactly (the palettes
  240. // live in one stylesheet; activation is attribute-only by design).
  241. await page.evaluate(() => { document.body.removeAttribute('data-ds-dark-theme') })
  242. const restored = await sample()
  243. expect(restored).toEqual(light)
  244. expect(tripwire.pageErrors).toEqual([])
  245. }, 60_000)
  246. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  247. expect(tripwire.warnings).toEqual([])
  248. await assertFixtureInventory(SNAPSHOT_DIR, [
  249. 'session.jsonl', 'command-menu.expected.md', 'hero.expected.md', 'plan-active.expected.md', 'reloaded.expected.md',
  250. ])
  251. })
  252. })