lifecycle-chrome.e2e.ts 15 KB

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