lifecycle-chrome.e2e.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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: '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: Commands')
  83. expect(snapshot).not.toContain('text: Skills')
  84. expect(snapshot).not.toContain('text: Subagents')
  85. const launchedBox = await menu.boundingBox()
  86. await page.locator('[data-composer-input]').first().press('Escape')
  87. await expect.poll(() => menu.count()).toBe(0)
  88. await writeComposerDraft(page, input, '/')
  89. await menu.getByRole('option').first().waitFor({ timeout: 10_000 })
  90. await menu.getByRole('status').waitFor({ state: 'hidden', timeout: 10_000 })
  91. const typedBox = await menu.boundingBox()
  92. expect(launchedBox).not.toBeNull()
  93. expect(typedBox).not.toBeNull()
  94. expect(Math.abs(launchedBox!.x - typedBox!.x)).toBeLessThan(1)
  95. expect(Math.abs(
  96. launchedBox!.y + launchedBox!.height - typedBox!.y - typedBox!.height,
  97. )).toBeLessThan(1)
  98. await writeComposerDraft(page, input, '/cpt')
  99. await expect.poll(() => menu.getByRole('option').allTextContents()).toEqual([
  100. 'compactCompact older conversation history',
  101. ])
  102. const fuzzySnapshot = await captureStableAria(page, '[role="listbox"]', scaffold.workspaceCwd)
  103. await compareOrRefreshGolden(FUZZY_COMMAND_MENU_EXPECTED, fuzzySnapshot, MODE)
  104. await writeComposerDraft(page, input, '')
  105. await expect.poll(() => menu.count()).toBe(0)
  106. })
  107. it.skipIf(MODE === 'record')('localizes slash-command descriptions from the browser language', async () => {
  108. const zhPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
  109. const zhTripwire = watchConsole(zhPage)
  110. onTestFailed(() => saveFailureShot(zhPage, 'web-e2e-command-menu-zh'))
  111. try {
  112. await zhPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  113. await zhPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  114. const launcher = zhPage.getByRole('button', { name: '指令' })
  115. await launcher.click()
  116. const menu = zhPage.getByRole('listbox', { name: '触发候选建议' })
  117. await menu.getByRole('option').first().waitFor({ timeout: 10_000 })
  118. await menu.getByRole('status').waitFor({ state: 'hidden', timeout: 10_000 })
  119. const snapshot = await captureStableAria(zhPage, '[role="listbox"]', scaffold.workspaceCwd)
  120. await compareOrRefreshGolden(COMMAND_MENU_ZH_EXPECTED, snapshot, MODE)
  121. expect(zhTripwire.pageErrors).toEqual([])
  122. expect(zhTripwire.warnings).toEqual([])
  123. } finally {
  124. await zhPage.close()
  125. }
  126. })
  127. it.skipIf(MODE === 'record')('shows active Plan as the warn-state status action', async () => {
  128. const activeScaffold = await launchWebScaffold()
  129. const activePage = await newEnglishPage(browser)
  130. const activeTripwire = watchConsole(activePage)
  131. try {
  132. await activePage.goto(activeScaffold.authenticatedUrl, { waitUntil: 'load' })
  133. await activePage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  134. await connectFreshWorkspace(activePage, activeScaffold.workspaceCwd)
  135. const input = activePage.locator('[data-composer-input]').first()
  136. await activePage.getByRole('button', { name: 'Commands' }).click()
  137. const menu = activePage.getByRole('listbox', { name: 'Trigger suggestions' })
  138. await menu.waitFor({ timeout: 10_000 })
  139. await menu.getByRole('option', { name: 'plan Enter or leave plan mode' }).click()
  140. await expect.poll(() => input.textContent()).toBe('/plan ')
  141. await input.press('Enter')
  142. const planButton = activePage.getByRole('button', { name: 'Plan mode on, press to turn off' })
  143. await planButton.waitFor({ timeout: 10_000 })
  144. // The golden encodes an empty composer, and the button arriving does not
  145. // mean the submitted text is gone yet: under load the capture can catch
  146. // a textbox still holding `/plan`.
  147. await expect.poll(() => input.textContent(), { timeout: 10_000 }).toBe('')
  148. const planSnapshot = await captureStableAria(activePage, '[class*="frame"]', activeScaffold.workspaceCwd)
  149. await compareOrRefreshGolden(PLAN_ACTIVE_EXPECTED, planSnapshot, MODE)
  150. const planStyle = await planButton.evaluate((element) => {
  151. const probe = document.createElement('span')
  152. probe.style.color = 'var(--dsw-alias-state-warn-label)'
  153. probe.style.backgroundColor = 'var(--dsw-alias-state-warn-tertiary)'
  154. document.body.append(probe)
  155. const actual = getComputedStyle(element)
  156. const reference = getComputedStyle(probe)
  157. const result = {
  158. color: actual.color,
  159. backgroundColor: actual.backgroundColor,
  160. borderRadius: actual.borderRadius,
  161. fontSize: actual.fontSize,
  162. referenceColor: reference.color,
  163. referenceBackgroundColor: reference.backgroundColor,
  164. }
  165. probe.remove()
  166. return result
  167. })
  168. expect(planStyle.color).toBe(planStyle.referenceColor)
  169. expect(planStyle.backgroundColor).toBe(planStyle.referenceBackgroundColor)
  170. expect(planStyle.borderRadius).toBe('999px')
  171. expect(planStyle.fontSize).toBe('13px')
  172. await planButton.click()
  173. await expect.poll(() => planButton.count()).toBe(0)
  174. expect(activeTripwire.pageErrors).toEqual([])
  175. expect(activeTripwire.warnings).toEqual([])
  176. } catch (error) {
  177. await saveFailureShot(activePage, 'web-e2e-plan-active').catch(() => undefined)
  178. throw error
  179. } finally {
  180. await activePage.close()
  181. await activeScaffold.close()
  182. }
  183. })
  184. it('sends the first prompt from the empty-state hero (all modes)', async () => {
  185. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-send'))
  186. if (MODE !== 'record') {
  187. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
  188. }
  189. // The blank frame renders the hero, not the resident composer: the
  190. // headline plus the guidance placeholder are the empty state's anchors.
  191. await expect.poll(() => page.getByText('Into the Unknown', { exact: false }).count(), { timeout: 15_000 }).toBe(1)
  192. const input = page.locator('[data-composer-input]').first()
  193. await input.waitFor({ timeout: 10_000 })
  194. if (MODE !== 'record') {
  195. await page.getByText('Into the Unknown', { exact: false }).hover()
  196. await expect.poll(() => page.getByRole('tooltip').count()).toBe(0)
  197. // Golden of the hero's stable waiting state (captured before any send;
  198. // the conversation-region goldens belong to the other scenarios).
  199. const snapshot = await captureStableAria(page, '[class*="frame"]', scaffold.workspaceCwd)
  200. await compareOrRefreshGolden(HERO_EXPECTED, snapshot, MODE)
  201. }
  202. const settled = scaffold.whenTurnSettled()
  203. await writeComposerDraft(page, input, PROMPT)
  204. const observeTurn = async () => {
  205. const originalViewport = page.viewportSize() ?? { width: 1680, height: 1000 }
  206. if (MODE !== 'record') await page.setViewportSize({ width: 480, height: 1000 })
  207. const observedReasoning = Promise.withResolvers<undefined>()
  208. const releaseStream = MODE === 'record' ? undefined : scaffold.ctx.on('llm/stream', async function* (_options, next) {
  209. let reasoning = false
  210. for await (const chunk of next()) {
  211. if (reasoning && chunk.type !== 'reasoning-delta') {
  212. await observedReasoning.promise
  213. }
  214. if (chunk.type === 'reasoning-delta') reasoning = true
  215. yield chunk
  216. }
  217. })
  218. try {
  219. await input.press('Enter')
  220. if (MODE !== 'record') {
  221. const liveTail = page.locator('[data-variant="think"][data-state="running"] [data-follow-end]')
  222. await expect.poll(async () => {
  223. if (await liveTail.count() !== 1) return false
  224. return await liveTail.evaluate((element) => {
  225. const text = element.firstElementChild
  226. if (!(text instanceof HTMLElement)) return false
  227. const viewport = element.getBoundingClientRect()
  228. const content = text.getBoundingClientRect()
  229. return content.width > viewport.width && Math.abs(content.right - viewport.right) <= 1
  230. })
  231. }, { timeout: 10_000, interval: 10 }).toBe(true)
  232. }
  233. observedReasoning.resolve(undefined)
  234. return await settled
  235. } finally {
  236. observedReasoning.resolve(undefined)
  237. releaseStream?.()
  238. if (MODE !== 'record') await page.setViewportSize(originalViewport)
  239. }
  240. }
  241. const sessionId = await observeTurn()
  242. if (MODE === 'record') {
  243. await recordFixture(scaffold, sessionId, FIXTURE)
  244. }
  245. }, 200_000)
  246. it.skipIf(MODE === 'record')('materialized a real Workspace and Session over the wire', async () => {
  247. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-materialize'))
  248. // Browser: the sidebar tree now carries the auto-created workspace group
  249. // with its one session, and the opened session is the selected row. The
  250. // compact layout dropped group session counts, so the group row itself is
  251. // the barrier.
  252. await expect.poll(
  253. () => page.locator('[role="treeitem"][aria-expanded]').filter({ hasText: 'workspace' }).count(),
  254. { timeout: 15_000 },
  255. ).toBeGreaterThanOrEqual(1)
  256. await expect.poll(() => page.locator('[role="treeitem"][aria-selected="true"]').count(), { timeout: 10_000 }).toBe(1)
  257. await expect.poll(() => page.getByText('LIGHTHOUSE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
  258. // The usage pill's one label span concatenates the billed total and the cache-hit share.
  259. await expect.poll(() => page.getByRole('button', { name: /Cache hit 99\.5%/ }).count(), { timeout: 15_000 }).toBe(1)
  260. // Host: the session's durable header cwd is the folder the workspace
  261. // flow created and adopted (<workspaceCwd>/workspace) — the proof the
  262. // send went through workspace materialization rather than a bare
  263. // default-cwd session.
  264. const cwds = scaffold.ctx.sessions.list().map(session => session.header.cwd)
  265. expect(cwds).toEqual([join(scaffold.workspaceCwd, 'workspace')])
  266. const turnEnds = sessionEvents.filter(e => e.type === 'turn/end')
  267. expect(turnEnds).toHaveLength(1)
  268. expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed')
  269. }, 60_000)
  270. it.skipIf(MODE === 'record')('recovers the whole surface across a reload from the log alone', async () => {
  271. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-reload'))
  272. const warningStart = tripwire.warnings.length
  273. await page.reload({ waitUntil: 'load' })
  274. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  275. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  276. // Selection persisted (dsh.sessions.current) and history replayed: the
  277. // recorded turn re-renders from a Session Controller page with zero model calls —
  278. // the replay cursor was fully consumed before the reload, so any stray
  279. // request would fail the scenario loudly at close().
  280. await expect.poll(() => page.getByText('LIGHTHOUSE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
  281. await expect.poll(() => page.locator('[role="treeitem"][aria-selected="true"]').count(), { timeout: 10_000 }).toBe(1)
  282. // Golden of the recovered conversation region: rebuilt from the log, it
  283. // must render the same settled transcript the live turn produced.
  284. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  285. await compareOrRefreshGolden(RELOADED_EXPECTED, snapshot, MODE)
  286. const expanded = await captureExpandedTurnProcessAria(
  287. page,
  288. '[class*="centerCol"]',
  289. scaffold.workspaceCwd,
  290. )
  291. await compareOrRefreshGolden(RELOADED_EXPANDED_EXPECTED, expanded, MODE)
  292. expect(tripwire.pageErrors).toEqual([])
  293. }, 90_000)
  294. it.skipIf(MODE === 'record')('cascades the dark theme from the body attribute to painted surfaces', async () => {
  295. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-dark'))
  296. // This scenario pins the ThemeRuntime's DOM contract directly (the
  297. // body[data-ds-dark-theme] attribute -> stylesheet cascade); the REAL
  298. // user gesture above it (Settings -> Appearance cubes) is owned by
  299. // settings-chrome.e2e.ts. Driving the attribute here keeps the cascade
  300. // pinned independently of the settings surface's own lifecycle.
  301. const sample = async (): Promise<{ token: string; sidebarBg: string; bodyBg: string }> =>
  302. await page.evaluate(() => {
  303. const sidebar = document.querySelector('[class*="sidebar"], [class*="rail"]') ?? document.body
  304. return {
  305. token: getComputedStyle(document.body).getPropertyValue('--dsw-alias-bg-base').trim(),
  306. sidebarBg: getComputedStyle(sidebar).backgroundColor,
  307. bodyBg: getComputedStyle(document.body).backgroundColor,
  308. }
  309. })
  310. const light = await sample()
  311. await page.evaluate(() => { document.body.setAttribute('data-ds-dark-theme', '') })
  312. const dark = await sample()
  313. // The alias token itself must flip — the cascade's root fact.
  314. expect(dark.token).not.toBe(light.token)
  315. // And a real painted surface must consume it (not just variables in a
  316. // void): at least one of the sampled backgrounds repaints.
  317. expect(dark.sidebarBg !== light.sidebarBg || dark.bodyBg !== light.bodyBg).toBe(true)
  318. // Removing the attribute restores the light values exactly (the palettes
  319. // live in one stylesheet; activation is attribute-only by design).
  320. await page.evaluate(() => { document.body.removeAttribute('data-ds-dark-theme') })
  321. const restored = await sample()
  322. expect(restored).toEqual(light)
  323. expect(tripwire.pageErrors).toEqual([])
  324. }, 60_000)
  325. it.skipIf(MODE === 'record')('shows automatic and user-requested connection recovery beside Settings', async () => {
  326. const recoveryPage = await newEnglishPage(browser)
  327. const recoveryTripwire = watchConsole(recoveryPage)
  328. const sockets: WebSocketRoute[] = []
  329. let rejectConnections = false
  330. let holdConnections = false
  331. await recoveryPage.routeWebSocket('**/api/remote.mux', (route) => {
  332. sockets.push(route)
  333. if (rejectConnections || holdConnections) return
  334. route.connectToServer()
  335. })
  336. onTestFailed(() => saveFailureShot(recoveryPage, 'web-e2e-connection-recovery'))
  337. try {
  338. await recoveryPage.clock.install()
  339. await recoveryPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  340. await recoveryPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  341. await expect.poll(() => sockets.length).toBe(1)
  342. rejectConnections = true
  343. await recoveryPage.context().setOffline(true)
  344. await expect.poll(() => recoveryPage.evaluate(() => navigator.onLine)).toBe(false)
  345. const offline = recoveryPage.getByRole('button', {
  346. name: 'Disconnected, reconnect now', exact: true,
  347. })
  348. await offline.waitFor({ timeout: 2_000 })
  349. await recoveryPage.clock.fastForward(60_000)
  350. expect(sockets).toHaveLength(1)
  351. await recoveryPage.context().setOffline(false)
  352. await expect.poll(() => recoveryPage.evaluate(() => navigator.onLine)).toBe(true)
  353. const connecting = recoveryPage.getByRole('button', {
  354. name: 'Reconnecting automatically, reconnect now', exact: true,
  355. })
  356. await connecting.waitFor({ timeout: 10_000 })
  357. expect(await connecting.innerText()).toMatch(/^Reconnecting\.{1,3}$/)
  358. const connectingGeometry = await connectionIndicatorGeometry(connecting)
  359. expect(await connectionIndicatorTextAlignment(connecting)).toBe('left')
  360. // Animated dots must remain hidden with their state label during hover.
  361. await connecting.evaluate((element) => {
  362. for (const animation of element.getAnimations({ subtree: true })) {
  363. if (!(animation instanceof CSSAnimation)) continue
  364. animation.pause()
  365. animation.currentTime = 1_250
  366. }
  367. })
  368. await connecting.hover()
  369. expect(await connecting.innerText()).toBe('Reconnect now')
  370. expect(await connectionIndicatorGeometry(connecting)).toEqual(connectingGeometry)
  371. await recoveryPage.mouse.move(0, 0)
  372. for (let count = 2; count <= 9; count++) {
  373. await recoveryPage.clock.fastForward(10_000)
  374. await expect.poll(() => sockets.length).toBe(count)
  375. if (count === 2) {
  376. await recoveryPage.clock.fastForward(1_000)
  377. expect(sockets).toHaveLength(count)
  378. }
  379. await sockets.at(-1)!.close({ code: 4001, reason: 'connection recovery test' })
  380. // Drain the close event's promise continuations before advancing the next retry timer.
  381. await recoveryPage.evaluate(() => {})
  382. }
  383. const indicator = connecting
  384. expect(await connectionIndicatorGeometry(indicator)).toEqual(connectingGeometry)
  385. expect(await connectionIndicatorTextAlignment(indicator)).toBe('left')
  386. await indicator.hover()
  387. const snapshot = await captureStableAria(recoveryPage, '[class*="footArea"]', scaffold.workspaceCwd)
  388. await compareOrRefreshGolden(CONNECTION_ERROR_EXPECTED, snapshot, MODE)
  389. const style = await indicator.evaluate((element) => {
  390. const probe = document.createElement('span')
  391. probe.style.color = 'var(--dsw-alias-state-warn-label)'
  392. probe.style.backgroundColor = 'var(--dsw-alias-state-warn-tertiary)'
  393. document.body.append(probe)
  394. const actual = getComputedStyle(element)
  395. const reference = getComputedStyle(probe)
  396. const result = {
  397. background: actual.backgroundColor,
  398. color: actual.color,
  399. referenceBackground: reference.backgroundColor,
  400. referenceColor: reference.color,
  401. }
  402. probe.remove()
  403. return result
  404. })
  405. expect(style.background).toBe(style.referenceBackground)
  406. expect(style.color).toBe(style.referenceColor)
  407. expect(await indicator.locator('svg').count()).toBe(1)
  408. expect(await indicator.getAttribute('title')).toBeNull()
  409. rejectConnections = false
  410. await recoveryPage.clock.fastForward(10_000)
  411. await expect.poll(() => sockets.length).toBe(10)
  412. const automaticRecovery = recoveryPage.getByRole('status')
  413. await automaticRecovery.waitFor({ timeout: 10_000 })
  414. expect(await automaticRecovery.innerText()).toBe('Connected')
  415. await recoveryPage.clock.fastForward(2_000)
  416. await automaticRecovery.waitFor({ state: 'detached' })
  417. holdConnections = true
  418. await sockets.at(-1)!.close({ code: 4001, reason: 'manual recovery test' })
  419. await connecting.waitFor()
  420. await recoveryPage.clock.fastForward(500)
  421. await expect.poll(() => sockets.length).toBe(11)
  422. const idleBackground = await indicator.evaluate(element => getComputedStyle(element).backgroundColor)
  423. await indicator.hover()
  424. expect(await indicator.innerText()).toBe('Reconnect now')
  425. const hoverBackground = await indicator.evaluate(element => getComputedStyle(element).backgroundColor)
  426. expect(hoverBackground).toBe(idleBackground)
  427. await recoveryPage.mouse.down()
  428. await expect.poll(() => indicator.evaluate(element => getComputedStyle(element).backgroundColor))
  429. .not.toBe(hoverBackground)
  430. holdConnections = false
  431. await recoveryPage.mouse.up()
  432. await expect.poll(() => sockets.length).toBe(12)
  433. const recovered = recoveryPage.getByRole('status')
  434. await recovered.waitFor({ timeout: 10_000 })
  435. expect(await recovered.innerText()).toBe('Connected')
  436. expect(await connectionIndicatorGeometry(recovered)).toEqual(connectingGeometry)
  437. expect(await connectionIndicatorTextAlignment(recovered)).toBe('left')
  438. await recoveryPage.clock.fastForward(2_000)
  439. await recovered.waitFor({ state: 'detached', timeout: 5_000 })
  440. expect(recoveryTripwire.pageErrors).toEqual([])
  441. expect(recoveryTripwire.warnings.filter(warning => /connection lost, retry #/i.test(warning)))
  442. .toHaveLength(11)
  443. } finally {
  444. await recoveryPage.close()
  445. }
  446. }, 60_000)
  447. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  448. expect(tripwire.warnings).toEqual([])
  449. await assertFixtureInventory(SNAPSHOT_DIR, [
  450. 'session.v3.jsonl', 'replay.override.json', 'command-menu.expected.md',
  451. 'command-menu-fuzzy.expected.md', 'command-menu-zh.expected.md', 'connection-error.expected.md',
  452. 'hero.expected.md', 'plan-active.expected.md',
  453. 'reloaded.expected.md', 'reloaded-expanded.expected.md',
  454. ])
  455. })
  456. })
  457. async function connectionIndicatorGeometry(locator: ReturnType<Page['getByRole']>): Promise<{
  458. readonly outer: readonly number[]
  459. readonly icon: readonly number[]
  460. readonly label: readonly number[]
  461. }> {
  462. return await locator.evaluate((element) => {
  463. const outer = element.getBoundingClientRect()
  464. const icon = element.children.item(0)?.getBoundingClientRect()
  465. const label = element.children.item(1)?.getBoundingClientRect()
  466. if (icon === undefined || label === undefined) throw new Error('connection indicator children missing')
  467. const rounded = (values: readonly number[]): readonly number[] => values.map(value => Math.round(value * 100) / 100)
  468. return {
  469. outer: rounded([outer.x, outer.y, outer.width, outer.height]),
  470. icon: rounded([icon.x - outer.x, icon.y - outer.y, icon.width, icon.height]),
  471. label: rounded([label.x - outer.x, label.y - outer.y, label.width, label.height]),
  472. }
  473. })
  474. }
  475. async function connectionIndicatorTextAlignment(
  476. locator: ReturnType<Page['getByRole']>,
  477. ): Promise<string> {
  478. return await locator.evaluate((element) => {
  479. const label = element.children.item(1)
  480. if (label === null) throw new Error('connection indicator label missing')
  481. return getComputedStyle(label).textAlign
  482. })
  483. }