lifecycle-chrome.e2e.ts 25 KB

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