lifecycle-chrome.e2e.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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 + WebSocket + 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, WebSocketRoute } from 'playwright'
  17. import { chromium } from 'playwright'
  18. import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished } from 'vitest'
  19. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  20. import {
  21. acknowledgeReloadConnectionLoss, assertFixtureInventory, captureExpandedTurnProcessAria,
  22. captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
  23. launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
  24. } from './scaffold.ts'
  25. import {
  26. connectFreshWorkspace, newEnglishPage, saveFailureShot, writeComposerDraft, ZH_BROWSER_LOCALE,
  27. } from './support.ts'
  28. const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/lifecycle-chrome', import.meta.url))
  29. const FIXTURE = join(SNAPSHOT_DIR, 'session.v3.jsonl')
  30. const REPLAY_OVERRIDE = join(SNAPSHOT_DIR, 'replay.override.json')
  31. const HERO_EXPECTED = join(SNAPSHOT_DIR, 'hero.expected.md')
  32. const COMMAND_MENU_EXPECTED = join(SNAPSHOT_DIR, 'command-menu.expected.md')
  33. const COMMAND_MENU_ZH_EXPECTED = join(SNAPSHOT_DIR, 'command-menu-zh.expected.md')
  34. const FUZZY_COMMAND_MENU_EXPECTED = join(SNAPSHOT_DIR, 'command-menu-fuzzy.expected.md')
  35. const PLAN_ACTIVE_EXPECTED = join(SNAPSHOT_DIR, 'plan-active.expected.md')
  36. const CONNECTION_ERROR_EXPECTED = join(SNAPSHOT_DIR, 'connection-error.expected.md')
  37. // Post-reload golden: the same settled conversation rebuilt purely from
  38. // persistence + history — byte-equal rendering is exactly the recovery claim.
  39. const RELOADED_EXPECTED = join(SNAPSHOT_DIR, 'reloaded.expected.md')
  40. const RELOADED_EXPANDED_EXPECTED = join(SNAPSHOT_DIR, 'reloaded-expanded.expected.md')
  41. const MODE = webSnapshotMode()
  42. const PROMPT = 'Reply with the single word LIGHTHOUSE and stop.'
  43. const REPLAY_PACE_MS = 100
  44. describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () => {
  45. let scaffold: WebScaffold
  46. let browser: Browser
  47. let page: Page
  48. let tripwire: ReturnType<typeof watchConsole>
  49. const sessionEvents: SessionEvent[] = []
  50. beforeAll(async () => {
  51. scaffold = await launchWebScaffold(MODE === 'record'
  52. ? {}
  53. : { replayFixture: FIXTURE, replayOverride: REPLAY_OVERRIDE, paceMs: REPLAY_PACE_MS })
  54. scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
  55. browser = await chromium.launch()
  56. page = await newEnglishPage(browser)
  57. tripwire = watchConsole(page)
  58. await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  59. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  60. // Fresh world: connect a Workspace so the composer scenarios start live.
  61. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  62. }, 120_000)
  63. afterAll(async () => {
  64. await browser?.close()
  65. await scaffold?.close()
  66. })
  67. it.skipIf(MODE === 'record')('opens the shared slash menu from plus with only Command candidates', async () => {
  68. onTestFailed(() => saveFailureShot(page, 'web-e2e-command-menu-launcher'))
  69. const input = page.locator('[data-composer-input]').first()
  70. onTestFinished(async () => {
  71. await input.press('Escape')
  72. await writeComposerDraft(page, input, '')
  73. await page.getByRole('listbox', { name: 'Trigger suggestions' }).waitFor({ state: 'hidden' })
  74. })
  75. const launcher = page.getByRole('button', { name: 'Add files or run commands' })
  76. await launcher.click()
  77. const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
  78. await menu.getByRole('option').first().waitFor({ timeout: 10_000 })
  79. await menu.getByRole('status').waitFor({ state: 'hidden', timeout: 10_000 })
  80. const snapshot = await captureStableAria(page, '[role="listbox"]', scaffold.workspaceCwd)
  81. await compareOrRefreshGolden(COMMAND_MENU_EXPECTED, snapshot, MODE)
  82. expect(snapshot).toContain('text: Add')
  83. expect(snapshot).toContain('text: Commands')
  84. expect(snapshot).not.toContain('text: Skills')
  85. expect(snapshot).not.toContain('text: Subagents')
  86. const launchedBox = await menu.boundingBox()
  87. await page.locator('[data-composer-input]').first().press('Escape')
  88. await expect.poll(() => menu.count()).toBe(0)
  89. await writeComposerDraft(page, input, '/')
  90. await menu.getByRole('option').first().waitFor({ timeout: 10_000 })
  91. await menu.getByRole('status').waitFor({ state: 'hidden', timeout: 10_000 })
  92. const typedBox = await menu.boundingBox()
  93. expect(launchedBox).not.toBeNull()
  94. expect(typedBox).not.toBeNull()
  95. expect(Math.abs(launchedBox!.x - typedBox!.x)).toBeLessThan(1)
  96. expect(Math.abs(
  97. launchedBox!.y + launchedBox!.height - typedBox!.y - typedBox!.height,
  98. )).toBeLessThan(1)
  99. await writeComposerDraft(page, input, '/cpt')
  100. await expect.poll(() => menu.getByRole('option').allTextContents()).toEqual([
  101. 'CompactCompact older conversation history',
  102. ])
  103. const fuzzySnapshot = await captureStableAria(page, '[role="listbox"]', scaffold.workspaceCwd)
  104. await compareOrRefreshGolden(FUZZY_COMMAND_MENU_EXPECTED, fuzzySnapshot, MODE)
  105. await writeComposerDraft(page, input, '')
  106. await expect.poll(() => menu.count()).toBe(0)
  107. })
  108. it.skipIf(MODE === 'record')('localizes slash-command descriptions from the browser language', async () => {
  109. const zhPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
  110. const zhTripwire = watchConsole(zhPage)
  111. onTestFailed(() => saveFailureShot(zhPage, 'web-e2e-command-menu-zh'))
  112. try {
  113. await zhPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  114. await zhPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  115. const launcher = zhPage.getByRole('button', { name: '添加文件或调用指令' })
  116. await launcher.click()
  117. const menu = zhPage.getByRole('listbox', { name: '触发候选建议' })
  118. await menu.getByRole('option').first().waitFor({ timeout: 10_000 })
  119. await menu.getByRole('status').waitFor({ state: 'hidden', timeout: 10_000 })
  120. const snapshot = await captureStableAria(zhPage, '[role="listbox"]', scaffold.workspaceCwd)
  121. await compareOrRefreshGolden(COMMAND_MENU_ZH_EXPECTED, snapshot, MODE)
  122. expect(zhTripwire.pageErrors).toEqual([])
  123. expect(zhTripwire.warnings).toEqual([])
  124. } finally {
  125. await zhPage.close()
  126. }
  127. })
  128. it.skipIf(MODE === 'record').each([
  129. { locale: 'en-US', token: '/goal', row: 'Goal Set or view the goal for a long-running task', hint: 'describe the objective for a long-running task' },
  130. { locale: 'en-US', token: '/plan', row: 'Plan Enter or leave plan mode', hint: 'describe your task to generate plan' },
  131. { locale: ZH_BROWSER_LOCALE, token: '/目标', row: '目标 goal 设置或查看长期任务目标', hint: '输入目标,智能体将持续执行' },
  132. { locale: ZH_BROWSER_LOCALE, token: '/计划', row: '计划 plan 进入或退出计划模式', hint: '描述你的任务以生成计划' },
  133. ])('keeps $token claimed across separator edits and hides hints during IME composition', async ({ locale, token, row, hint }) => {
  134. const inputPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale })
  135. const inputTripwire = watchConsole(inputPage)
  136. onTestFailed(() => saveFailureShot(inputPage, `web-e2e-command-input-${locale}-${token.slice(1)}`))
  137. try {
  138. await inputPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  139. await inputPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  140. const input = inputPage.locator('[data-composer-input]').first()
  141. await writeComposerDraft(inputPage, input, '/')
  142. await inputPage.getByRole('listbox').getByRole('option', { name: row, exact: true }).click()
  143. await expect.poll(() => input.textContent()).toBe(`${token} `)
  144. await input.press('End')
  145. await inputPage.keyboard.insertText('这是任务')
  146. await expect.poll(() => input.textContent()).toBe(`${token} 这是任务`)
  147. for (let i = 0; i < 5; i++) await input.press('Backspace')
  148. const tokenText = () => input.locator('[data-lexical-text][style*="warn-label"]').textContent()
  149. await expect.poll(() => input.textContent()).toBe(token)
  150. await expect.poll(() => input.getAttribute('data-phase')).toBe('claimed')
  151. await expect.poll(tokenText).toBe(token)
  152. await input.press('Space')
  153. await expect.poll(() => input.getAttribute('data-phase')).toBe('claimed')
  154. await expect.poll(() => input.textContent()).toBe(`${token} `)
  155. await expect.poll(async () => (await tokenText())?.trimEnd()).toBe(token)
  156. const shownHint = () => input.locator('p').last().evaluate(element => getComputedStyle(element, '::after').content)
  157. await expect.poll(shownHint).toBe(JSON.stringify(hint))
  158. const cdp = await inputPage.context().newCDPSession(inputPage)
  159. await cdp.send('Input.imeSetComposition', { text: 'z', selectionStart: 1, selectionEnd: 1 })
  160. await expect.poll(shownHint).toBe('none')
  161. await cdp.send('Input.imeSetComposition', { text: 'zh', selectionStart: 2, selectionEnd: 2 })
  162. await expect.poll(shownHint).toBe('none')
  163. await cdp.send('Input.insertText', { text: '这' })
  164. await expect.poll(() => input.textContent()).toBe(`${token} 这`)
  165. await expect.poll(shownHint).toBe('none')
  166. await input.press('Backspace')
  167. await expect.poll(shownHint).toBe(JSON.stringify(hint))
  168. await cdp.send('Input.imeSetComposition', { text: 'z', selectionStart: 1, selectionEnd: 1 })
  169. await expect.poll(shownHint).toBe('none')
  170. await cdp.send('Input.imeSetComposition', { text: '', selectionStart: 0, selectionEnd: 0 })
  171. await expect.poll(shownHint).toBe(JSON.stringify(hint))
  172. await input.press('Backspace')
  173. await input.press('Backspace')
  174. await expect.poll(() => input.getAttribute('data-phase')).toBe('plain')
  175. await writeComposerDraft(inputPage, input, '')
  176. const placeholder = inputPage.locator('[data-composer-placeholder]').first()
  177. await expect.poll(() => placeholder.isVisible()).toBe(true)
  178. await cdp.send('Input.imeSetComposition', { text: 'z', selectionStart: 1, selectionEnd: 1 })
  179. await expect.poll(() => placeholder.isVisible()).toBe(false)
  180. await cdp.send('Input.imeSetComposition', { text: '', selectionStart: 0, selectionEnd: 0 })
  181. await expect.poll(() => placeholder.isVisible()).toBe(true)
  182. await cdp.detach()
  183. expect(inputTripwire.pageErrors).toEqual([])
  184. expect(inputTripwire.warnings).toEqual([])
  185. } finally {
  186. await inputPage.close()
  187. }
  188. })
  189. it.skipIf(MODE === 'record')('shows active Plan as the warn-state status action', async () => {
  190. const activeScaffold = await launchWebScaffold()
  191. const activePage = await newEnglishPage(browser)
  192. const activeTripwire = watchConsole(activePage)
  193. try {
  194. await activePage.goto(activeScaffold.authenticatedUrl, { waitUntil: 'load' })
  195. await activePage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  196. await connectFreshWorkspace(activePage, activeScaffold.workspaceCwd)
  197. const input = activePage.locator('[data-composer-input]').first()
  198. await activePage.getByRole('button', { name: 'Add files or run commands' }).click()
  199. const menu = activePage.getByRole('listbox', { name: 'Trigger suggestions' })
  200. await menu.waitFor({ timeout: 10_000 })
  201. await menu.getByRole('option', { name: 'Plan Enter or leave plan mode' }).click()
  202. await expect.poll(() => input.textContent()).toBe('/plan ')
  203. await input.press('Enter')
  204. const planButton = activePage.getByRole('button', { name: 'Plan mode on, press to turn off' })
  205. await planButton.waitFor({ timeout: 10_000 })
  206. // The golden encodes an empty composer, and the button arriving does not
  207. // mean the submitted text is gone yet: under load the capture can catch
  208. // a textbox still holding `/plan`.
  209. await expect.poll(() => input.textContent(), { timeout: 10_000 }).toBe('')
  210. const planSnapshot = await captureStableAria(activePage, '[class*="frame"]', activeScaffold.workspaceCwd)
  211. await compareOrRefreshGolden(PLAN_ACTIVE_EXPECTED, planSnapshot, MODE)
  212. const planStyle = await planButton.evaluate((element) => {
  213. const probe = document.createElement('span')
  214. probe.style.color = 'var(--dsw-alias-state-warn-label)'
  215. probe.style.backgroundColor = 'var(--dsw-alias-state-warn-tertiary)'
  216. document.body.append(probe)
  217. const actual = getComputedStyle(element)
  218. const reference = getComputedStyle(probe)
  219. const result = {
  220. color: actual.color,
  221. backgroundColor: actual.backgroundColor,
  222. borderRadius: actual.borderRadius,
  223. fontSize: actual.fontSize,
  224. referenceColor: reference.color,
  225. referenceBackgroundColor: reference.backgroundColor,
  226. }
  227. probe.remove()
  228. return result
  229. })
  230. expect(planStyle.color).toBe(planStyle.referenceColor)
  231. expect(planStyle.backgroundColor).toBe(planStyle.referenceBackgroundColor)
  232. expect(planStyle.borderRadius).toBe('999px')
  233. expect(planStyle.fontSize).toBe('13px')
  234. await planButton.click()
  235. await expect.poll(() => planButton.count()).toBe(0)
  236. expect(activeTripwire.pageErrors).toEqual([])
  237. expect(activeTripwire.warnings).toEqual([])
  238. } catch (error) {
  239. await saveFailureShot(activePage, 'web-e2e-plan-active').catch(() => undefined)
  240. throw error
  241. } finally {
  242. await activePage.close()
  243. await activeScaffold.close()
  244. }
  245. })
  246. it('sends the first prompt from the empty-state hero (all modes)', async () => {
  247. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-send'))
  248. if (MODE !== 'record') {
  249. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
  250. }
  251. // The blank frame renders the hero, not the resident composer: the
  252. // headline plus the guidance placeholder are the empty state's anchors.
  253. await expect.poll(() => page.getByText('Into the Unknown', { exact: false }).count(), { timeout: 15_000 }).toBe(1)
  254. const input = page.locator('[data-composer-input]').first()
  255. await input.waitFor({ timeout: 10_000 })
  256. if (MODE !== 'record') {
  257. await page.getByText('Into the Unknown', { exact: false }).hover()
  258. await expect.poll(() => page.getByRole('tooltip').count()).toBe(0)
  259. // Golden of the hero's stable waiting state (captured before any send;
  260. // the conversation-region goldens belong to the other scenarios).
  261. const snapshot = await captureStableAria(page, '[class*="frame"]', scaffold.workspaceCwd)
  262. await compareOrRefreshGolden(HERO_EXPECTED, snapshot, MODE)
  263. }
  264. const settled = scaffold.whenTurnSettled()
  265. await writeComposerDraft(page, input, PROMPT)
  266. const observeTurn = async () => {
  267. const originalViewport = page.viewportSize() ?? { width: 1680, height: 1000 }
  268. if (MODE !== 'record') await page.setViewportSize({ width: 480, height: 1000 })
  269. const observedReasoning = Promise.withResolvers<undefined>()
  270. const releaseStream = MODE === 'record' ? undefined : scaffold.ctx.on('llm/stream', async function* (_options, next) {
  271. let reasoning = false
  272. for await (const chunk of next()) {
  273. if (reasoning && chunk.type !== 'reasoning-delta') {
  274. await observedReasoning.promise
  275. }
  276. if (chunk.type === 'reasoning-delta') reasoning = true
  277. yield chunk
  278. }
  279. })
  280. try {
  281. await input.press('Enter')
  282. if (MODE !== 'record') {
  283. const liveTail = page.locator('[data-variant="think"][data-state="running"] [data-follow-end]')
  284. await expect.poll(async () => {
  285. if (await liveTail.count() !== 1) return false
  286. return await liveTail.evaluate((element) => {
  287. const text = element.firstElementChild
  288. if (!(text instanceof HTMLElement)) return false
  289. const viewport = element.getBoundingClientRect()
  290. const content = text.getBoundingClientRect()
  291. return content.width > viewport.width && Math.abs(content.right - viewport.right) <= 1
  292. })
  293. }, { timeout: 10_000, interval: 10 }).toBe(true)
  294. }
  295. observedReasoning.resolve(undefined)
  296. return await settled
  297. } finally {
  298. observedReasoning.resolve(undefined)
  299. releaseStream?.()
  300. if (MODE !== 'record') await page.setViewportSize(originalViewport)
  301. }
  302. }
  303. const sessionId = await observeTurn()
  304. if (MODE === 'record') {
  305. await recordFixture(scaffold, sessionId, FIXTURE)
  306. }
  307. }, 200_000)
  308. it.skipIf(MODE === 'record')('materialized a real Workspace and Session over the wire', async () => {
  309. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-materialize'))
  310. // Browser: the sidebar tree now carries the auto-created workspace group
  311. // with its one session, and the opened session is the selected row. The
  312. // compact layout dropped group session counts, so the group row itself is
  313. // the barrier.
  314. await expect.poll(
  315. () => page.locator('[role="treeitem"][aria-expanded]').filter({ hasText: 'workspace' }).count(),
  316. { timeout: 15_000 },
  317. ).toBeGreaterThanOrEqual(1)
  318. await expect.poll(() => page.locator('[role="treeitem"][aria-selected="true"]').count(), { timeout: 10_000 }).toBe(1)
  319. await expect.poll(() => page.getByText('LIGHTHOUSE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
  320. // The usage pill's one label span concatenates the billed total and the cache-hit share.
  321. await expect.poll(() => page.getByRole('button', { name: /Cache hit 99\.5%/ }).count(), { timeout: 15_000 }).toBe(1)
  322. // Host: the session's durable header cwd is the folder the workspace
  323. // flow created and adopted (<workspaceCwd>/workspace) — the proof the
  324. // send went through workspace materialization rather than a bare
  325. // default-cwd session.
  326. const cwds = scaffold.ctx.sessions.list().map(session => session.header.cwd)
  327. expect(cwds).toEqual([join(scaffold.workspaceCwd, 'workspace')])
  328. const turnEnds = sessionEvents.filter(e => e.type === 'turn/end')
  329. expect(turnEnds).toHaveLength(1)
  330. expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed')
  331. }, 60_000)
  332. it.skipIf(MODE === 'record')('recovers the whole surface across a reload from the log alone', async () => {
  333. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-reload'))
  334. const warningStart = tripwire.warnings.length
  335. await page.reload({ waitUntil: 'load' })
  336. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  337. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  338. // Selection persisted (dsh.sessions.current) and history replayed: the
  339. // recorded turn re-renders from a Session Controller page with zero model calls —
  340. // the replay cursor was fully consumed before the reload, so any stray
  341. // request would fail the scenario loudly at close().
  342. await expect.poll(() => page.getByText('LIGHTHOUSE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
  343. await expect.poll(() => page.locator('[role="treeitem"][aria-selected="true"]').count(), { timeout: 10_000 }).toBe(1)
  344. // Golden of the recovered conversation region: rebuilt from the log, it
  345. // must render the same settled transcript the live turn produced.
  346. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  347. await compareOrRefreshGolden(RELOADED_EXPECTED, snapshot, MODE)
  348. const expanded = await captureExpandedTurnProcessAria(
  349. page,
  350. '[class*="centerCol"]',
  351. scaffold.workspaceCwd,
  352. )
  353. await compareOrRefreshGolden(RELOADED_EXPANDED_EXPECTED, expanded, MODE)
  354. expect(tripwire.pageErrors).toEqual([])
  355. }, 90_000)
  356. it.skipIf(MODE === 'record')('cascades the dark theme from the body attribute to painted surfaces', async () => {
  357. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-dark'))
  358. // This scenario pins the ThemeRuntime's DOM contract directly (the
  359. // body[data-ds-dark-theme] attribute -> stylesheet cascade); the REAL
  360. // user gesture above it (Settings -> Appearance cubes) is owned by
  361. // settings-chrome.e2e.ts. Driving the attribute here keeps the cascade
  362. // pinned independently of the settings surface's own lifecycle.
  363. const sample = async (): Promise<{ token: string; sidebarBg: string; bodyBg: string }> =>
  364. await page.evaluate(() => {
  365. const sidebar = document.querySelector('[class*="sidebar"], [class*="rail"]') ?? document.body
  366. return {
  367. token: getComputedStyle(document.body).getPropertyValue('--dsw-alias-bg-base').trim(),
  368. sidebarBg: getComputedStyle(sidebar).backgroundColor,
  369. bodyBg: getComputedStyle(document.body).backgroundColor,
  370. }
  371. })
  372. const light = await sample()
  373. await page.evaluate(() => { document.body.setAttribute('data-ds-dark-theme', '') })
  374. const dark = await sample()
  375. // The alias token itself must flip — the cascade's root fact.
  376. expect(dark.token).not.toBe(light.token)
  377. // And a real painted surface must consume it (not just variables in a
  378. // void): at least one of the sampled backgrounds repaints.
  379. expect(dark.sidebarBg !== light.sidebarBg || dark.bodyBg !== light.bodyBg).toBe(true)
  380. // Removing the attribute restores the light values exactly (the palettes
  381. // live in one stylesheet; activation is attribute-only by design).
  382. await page.evaluate(() => { document.body.removeAttribute('data-ds-dark-theme') })
  383. const restored = await sample()
  384. expect(restored).toEqual(light)
  385. expect(tripwire.pageErrors).toEqual([])
  386. }, 60_000)
  387. it.skipIf(MODE === 'record')('shows automatic and user-requested connection recovery beside Settings', async () => {
  388. const recoveryPage = await newEnglishPage(browser)
  389. const recoveryTripwire = watchConsole(recoveryPage)
  390. const sockets: WebSocketRoute[] = []
  391. let rejectConnections = false
  392. let holdConnections = false
  393. await recoveryPage.routeWebSocket('**/api/remote.mux', (route) => {
  394. sockets.push(route)
  395. if (rejectConnections || holdConnections) return
  396. route.connectToServer()
  397. })
  398. onTestFailed(() => saveFailureShot(recoveryPage, 'web-e2e-connection-recovery'))
  399. try {
  400. await recoveryPage.clock.install()
  401. await recoveryPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  402. await recoveryPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  403. await expect.poll(() => sockets.length).toBe(1)
  404. rejectConnections = true
  405. await recoveryPage.context().setOffline(true)
  406. await expect.poll(() => recoveryPage.evaluate(() => navigator.onLine)).toBe(false)
  407. const offline = recoveryPage.getByRole('button', {
  408. name: 'Disconnected, reconnect now', exact: true,
  409. })
  410. await offline.waitFor({ timeout: 2_000 })
  411. await recoveryPage.clock.fastForward(60_000)
  412. expect(sockets).toHaveLength(1)
  413. await recoveryPage.context().setOffline(false)
  414. await expect.poll(() => recoveryPage.evaluate(() => navigator.onLine)).toBe(true)
  415. const connecting = recoveryPage.getByRole('button', {
  416. name: 'Reconnecting, reconnect now', exact: true,
  417. })
  418. await connecting.waitFor({ timeout: 10_000 })
  419. expect(await connecting.innerText()).toMatch(/^Reconnecting\.{1,3}$/)
  420. const connectingGeometry = await connectionIndicatorGeometry(connecting)
  421. expect(await connectionIndicatorTextAlignment(connecting)).toBe('left')
  422. // Hover keeps the state label; the pill never swaps copy or resizes.
  423. await connecting.hover()
  424. expect(await connecting.innerText()).toMatch(/^Reconnecting\.{1,3}$/)
  425. expect(await connectionIndicatorGeometry(connecting)).toEqual(connectingGeometry)
  426. await recoveryPage.mouse.move(0, 0)
  427. for (let count = 2; count <= 9; count++) {
  428. await recoveryPage.clock.fastForward(10_000)
  429. await expect.poll(() => sockets.length).toBe(count)
  430. if (count === 2) {
  431. await recoveryPage.clock.fastForward(1_000)
  432. expect(sockets).toHaveLength(count)
  433. }
  434. await sockets.at(-1)!.close({ code: 4001, reason: 'connection recovery test' })
  435. // Drain the close event's promise continuations before advancing the next retry timer.
  436. await recoveryPage.evaluate(() => {})
  437. }
  438. const indicator = connecting
  439. expect(await connectionIndicatorGeometry(indicator)).toEqual(connectingGeometry)
  440. expect(await connectionIndicatorTextAlignment(indicator)).toBe('left')
  441. const snapshot = await captureStableAria(recoveryPage, '[class*="footArea"]', scaffold.workspaceCwd)
  442. await compareOrRefreshGolden(CONNECTION_ERROR_EXPECTED, snapshot, MODE)
  443. const style = await indicator.evaluate((element) => {
  444. const probe = document.createElement('span')
  445. probe.style.color = 'var(--dsw-alias-state-warn-label)'
  446. probe.style.backgroundColor = 'var(--dsw-alias-state-warn-tertiary)'
  447. document.body.append(probe)
  448. const actual = getComputedStyle(element)
  449. const reference = getComputedStyle(probe)
  450. const result = {
  451. background: actual.backgroundColor,
  452. color: actual.color,
  453. referenceBackground: reference.backgroundColor,
  454. referenceColor: reference.color,
  455. }
  456. probe.remove()
  457. return result
  458. })
  459. expect(style.background).toBe(style.referenceBackground)
  460. expect(style.color).toBe(style.referenceColor)
  461. expect(await indicator.locator('svg').count()).toBe(1)
  462. expect(await indicator.getAttribute('title')).toBeNull()
  463. rejectConnections = false
  464. await recoveryPage.clock.fastForward(10_000)
  465. await expect.poll(() => sockets.length).toBe(10)
  466. const automaticRecovery = recoveryPage.getByRole('status')
  467. await automaticRecovery.waitFor({ timeout: 10_000 })
  468. expect(await automaticRecovery.innerText()).toBe('Connected')
  469. await recoveryPage.clock.fastForward(2_000)
  470. await automaticRecovery.waitFor({ state: 'detached' })
  471. holdConnections = true
  472. await sockets.at(-1)!.close({ code: 4001, reason: 'manual recovery test' })
  473. await connecting.waitFor()
  474. await recoveryPage.clock.fastForward(500)
  475. await expect.poll(() => sockets.length).toBe(11)
  476. await indicator.hover()
  477. expect(await indicator.innerText()).toMatch(/^Reconnecting\.{1,3}$/)
  478. const hoverBackground = await indicator.evaluate(element => getComputedStyle(element).backgroundColor)
  479. await recoveryPage.mouse.down()
  480. await expect.poll(() => indicator.evaluate(element => getComputedStyle(element).backgroundColor))
  481. .not.toBe(hoverBackground)
  482. holdConnections = false
  483. await recoveryPage.mouse.up()
  484. await expect.poll(() => sockets.length).toBe(12)
  485. const recovered = recoveryPage.getByRole('status')
  486. await recovered.waitFor({ timeout: 10_000 })
  487. expect(await recovered.innerText()).toBe('Connected')
  488. // The pill sizes to its current label; chrome height and icon box stay fixed.
  489. const recoveredGeometry = await connectionIndicatorGeometry(recovered)
  490. expect(recoveredGeometry.outer[3]).toBe(connectingGeometry.outer[3])
  491. expect(recoveredGeometry.icon).toEqual(connectingGeometry.icon)
  492. expect(await connectionIndicatorTextAlignment(recovered)).toBe('left')
  493. await recoveryPage.clock.fastForward(2_000)
  494. await recovered.waitFor({ state: 'detached', timeout: 5_000 })
  495. expect(recoveryTripwire.pageErrors).toEqual([])
  496. expect(recoveryTripwire.warnings.filter(warning => /connection lost, retry #/i.test(warning)))
  497. .toHaveLength(11)
  498. } finally {
  499. await recoveryPage.close()
  500. }
  501. }, 60_000)
  502. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  503. expect(tripwire.warnings).toEqual([])
  504. await assertFixtureInventory(SNAPSHOT_DIR, [
  505. 'session.v3.jsonl', 'replay.override.json', 'command-menu.expected.md',
  506. 'command-menu-fuzzy.expected.md', 'command-menu-zh.expected.md', 'connection-error.expected.md',
  507. 'hero.expected.md', 'plan-active.expected.md',
  508. 'reloaded.expected.md', 'reloaded-expanded.expected.md',
  509. ])
  510. })
  511. })
  512. async function connectionIndicatorGeometry(locator: ReturnType<Page['getByRole']>): Promise<{
  513. readonly outer: readonly number[]
  514. readonly icon: readonly number[]
  515. readonly label: readonly number[]
  516. }> {
  517. return await locator.evaluate((element) => {
  518. const outer = element.getBoundingClientRect()
  519. const icon = element.children.item(0)?.getBoundingClientRect()
  520. const label = element.children.item(1)?.getBoundingClientRect()
  521. if (icon === undefined || label === undefined) throw new Error('connection indicator children missing')
  522. const rounded = (values: readonly number[]): readonly number[] => values.map(value => Math.round(value * 100) / 100)
  523. return {
  524. outer: rounded([outer.x, outer.y, outer.width, outer.height]),
  525. icon: rounded([icon.x - outer.x, icon.y - outer.y, icon.width, icon.height]),
  526. label: rounded([label.x - outer.x, label.y - outer.y, label.width, label.height]),
  527. }
  528. })
  529. }
  530. async function connectionIndicatorTextAlignment(
  531. locator: ReturnType<Page['getByRole']>,
  532. ): Promise<string> {
  533. return await locator.evaluate((element) => {
  534. const label = element.children.item(1)
  535. if (label === null) throw new Error('connection indicator label missing')
  536. return getComputedStyle(label).textAlign
  537. })
  538. }