lifecycle-chrome.e2e.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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.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 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. const observedReasoning = Promise.withResolvers<undefined>()
  200. const releaseStream = MODE === 'record' ? undefined : scaffold.ctx.on('llm/stream', async function* (_options, next) {
  201. let reasoning = false
  202. for await (const chunk of next()) {
  203. if (reasoning && chunk.type !== 'reasoning-delta') {
  204. await observedReasoning.promise
  205. }
  206. if (chunk.type === 'reasoning-delta') reasoning = true
  207. yield chunk
  208. }
  209. })
  210. try {
  211. await input.press('Enter')
  212. if (MODE !== 'record') {
  213. const liveTail = page.locator('[data-variant="think"][data-state="running"] [data-follow-end]')
  214. await expect.poll(async () => {
  215. if (await liveTail.count() !== 1) return false
  216. return await liveTail.evaluate((element) => {
  217. const text = element.firstElementChild
  218. if (!(text instanceof HTMLElement)) return false
  219. const viewport = element.getBoundingClientRect()
  220. const content = text.getBoundingClientRect()
  221. return content.width > viewport.width && Math.abs(content.right - viewport.right) <= 1
  222. })
  223. }, { timeout: 10_000, interval: 10 }).toBe(true)
  224. }
  225. observedReasoning.resolve(undefined)
  226. return await settled
  227. } finally {
  228. observedReasoning.resolve(undefined)
  229. releaseStream?.()
  230. if (MODE !== 'record') await page.setViewportSize(originalViewport)
  231. }
  232. }
  233. const sessionId = await observeTurn()
  234. if (MODE === 'record') {
  235. await recordFixture(scaffold, sessionId, FIXTURE)
  236. }
  237. }, 200_000)
  238. it.skipIf(MODE === 'record')('materialized a real Workspace and Session over the wire', async () => {
  239. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-materialize'))
  240. // Browser: the sidebar tree now carries the auto-created workspace group
  241. // with its one session, and the opened session is the selected row. The
  242. // compact layout dropped group session counts, so the group row itself is
  243. // the barrier.
  244. await expect.poll(
  245. () => page.locator('[role="treeitem"][aria-expanded]').filter({ hasText: 'workspace' }).count(),
  246. { timeout: 15_000 },
  247. ).toBeGreaterThanOrEqual(1)
  248. await expect.poll(() => page.locator('[role="treeitem"][aria-selected="true"]').count(), { timeout: 10_000 }).toBe(1)
  249. await expect.poll(() => page.getByText('LIGHTHOUSE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
  250. // The usage pill's one label span concatenates the billed total and the cache-hit share.
  251. await expect.poll(() => page.getByRole('button', { name: /Cache hit 99\.5%/ }).count(), { timeout: 15_000 }).toBe(1)
  252. // Host: the session's durable header cwd is the folder the workspace
  253. // flow created and adopted (<workspaceCwd>/workspace) — the proof the
  254. // send went through workspace materialization rather than a bare
  255. // default-cwd session.
  256. const cwds = scaffold.ctx.sessions.list().map(session => session.header.cwd)
  257. expect(cwds).toEqual([join(scaffold.workspaceCwd, 'workspace')])
  258. const turnEnds = sessionEvents.filter(e => e.type === 'turn/end')
  259. expect(turnEnds).toHaveLength(1)
  260. expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed')
  261. }, 60_000)
  262. it.skipIf(MODE === 'record')('recovers the whole surface across a reload from the log alone', async () => {
  263. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-reload'))
  264. const warningStart = tripwire.warnings.length
  265. await page.reload({ waitUntil: 'load' })
  266. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  267. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  268. // Selection persisted (dsh.sessions.current) and history replayed: the
  269. // recorded turn re-renders from a Session Controller page with zero model calls —
  270. // the replay cursor was fully consumed before the reload, so any stray
  271. // request would fail the scenario loudly at close().
  272. await expect.poll(() => page.getByText('LIGHTHOUSE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
  273. await expect.poll(() => page.locator('[role="treeitem"][aria-selected="true"]').count(), { timeout: 10_000 }).toBe(1)
  274. // Golden of the recovered conversation region: rebuilt from the log, it
  275. // must render the same settled transcript the live turn produced.
  276. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  277. await compareOrRefreshGolden(RELOADED_EXPECTED, snapshot, MODE)
  278. const expanded = await captureExpandedTurnProcessAria(
  279. page,
  280. '[class*="centerCol"]',
  281. scaffold.workspaceCwd,
  282. )
  283. await compareOrRefreshGolden(RELOADED_EXPANDED_EXPECTED, expanded, MODE)
  284. expect(tripwire.pageErrors).toEqual([])
  285. }, 90_000)
  286. it.skipIf(MODE === 'record')('cascades the dark theme from the body attribute to painted surfaces', async () => {
  287. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-dark'))
  288. // This scenario pins the ThemeRuntime's DOM contract directly (the
  289. // body[data-ds-dark-theme] attribute -> stylesheet cascade); the REAL
  290. // user gesture above it (Settings -> Appearance cubes) is owned by
  291. // settings-chrome.e2e.ts. Driving the attribute here keeps the cascade
  292. // pinned independently of the settings surface's own lifecycle.
  293. const sample = async (): Promise<{ token: string; sidebarBg: string; bodyBg: string }> =>
  294. await page.evaluate(() => {
  295. const sidebar = document.querySelector('[class*="sidebar"], [class*="rail"]') ?? document.body
  296. return {
  297. token: getComputedStyle(document.body).getPropertyValue('--dsw-alias-bg-base').trim(),
  298. sidebarBg: getComputedStyle(sidebar).backgroundColor,
  299. bodyBg: getComputedStyle(document.body).backgroundColor,
  300. }
  301. })
  302. const light = await sample()
  303. await page.evaluate(() => { document.body.setAttribute('data-ds-dark-theme', '') })
  304. const dark = await sample()
  305. // The alias token itself must flip — the cascade's root fact.
  306. expect(dark.token).not.toBe(light.token)
  307. // And a real painted surface must consume it (not just variables in a
  308. // void): at least one of the sampled backgrounds repaints.
  309. expect(dark.sidebarBg !== light.sidebarBg || dark.bodyBg !== light.bodyBg).toBe(true)
  310. // Removing the attribute restores the light values exactly (the palettes
  311. // live in one stylesheet; activation is attribute-only by design).
  312. await page.evaluate(() => { document.body.removeAttribute('data-ds-dark-theme') })
  313. const restored = await sample()
  314. expect(restored).toEqual(light)
  315. expect(tripwire.pageErrors).toEqual([])
  316. }, 60_000)
  317. it.skipIf(MODE === 'record')('shows automatic and user-requested connection recovery beside Settings', async () => {
  318. const recoveryPage = await newEnglishPage(browser)
  319. const recoveryTripwire = watchConsole(recoveryPage)
  320. const sockets: WebSocketRoute[] = []
  321. let rejectConnections = false
  322. let holdConnections = false
  323. await recoveryPage.routeWebSocket('**/api/remote.mux', (route) => {
  324. sockets.push(route)
  325. if (rejectConnections || holdConnections) return
  326. route.connectToServer()
  327. })
  328. onTestFailed(() => saveFailureShot(recoveryPage, 'web-e2e-connection-recovery'))
  329. try {
  330. await recoveryPage.clock.install()
  331. await recoveryPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  332. await recoveryPage.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  333. await expect.poll(() => sockets.length).toBe(1)
  334. rejectConnections = true
  335. await recoveryPage.context().setOffline(true)
  336. await expect.poll(() => recoveryPage.evaluate(() => navigator.onLine)).toBe(false)
  337. const offline = recoveryPage.getByRole('button', {
  338. name: 'Disconnected, reconnect now', exact: true,
  339. })
  340. await offline.waitFor({ timeout: 2_000 })
  341. await recoveryPage.clock.fastForward(60_000)
  342. expect(sockets).toHaveLength(1)
  343. await recoveryPage.context().setOffline(false)
  344. await expect.poll(() => recoveryPage.evaluate(() => navigator.onLine)).toBe(true)
  345. const connecting = recoveryPage.getByRole('button', {
  346. name: 'Reconnecting automatically, reconnect now', exact: true,
  347. })
  348. await connecting.waitFor({ timeout: 10_000 })
  349. expect(await connecting.innerText()).toMatch(/^Reconnecting\.{1,3}$/)
  350. const connectingGeometry = await connectionIndicatorGeometry(connecting)
  351. expect(await connectionIndicatorTextAlignment(connecting)).toBe('left')
  352. // Animated dots must remain hidden with their state label during hover.
  353. await connecting.evaluate((element) => {
  354. for (const animation of element.getAnimations({ subtree: true })) {
  355. if (!(animation instanceof CSSAnimation)) continue
  356. animation.pause()
  357. animation.currentTime = 1_250
  358. }
  359. })
  360. await connecting.hover()
  361. expect(await connecting.innerText()).toBe('Reconnect now')
  362. expect(await connectionIndicatorGeometry(connecting)).toEqual(connectingGeometry)
  363. await recoveryPage.mouse.move(0, 0)
  364. for (let count = 2; count <= 9; count++) {
  365. await recoveryPage.clock.fastForward(10_000)
  366. await expect.poll(() => sockets.length).toBe(count)
  367. if (count === 2) {
  368. await recoveryPage.clock.fastForward(1_000)
  369. expect(sockets).toHaveLength(count)
  370. }
  371. await sockets.at(-1)!.close({ code: 4001, reason: 'connection recovery test' })
  372. // Drain the close event's promise continuations before advancing the next retry timer.
  373. await recoveryPage.evaluate(() => {})
  374. }
  375. const indicator = connecting
  376. expect(await connectionIndicatorGeometry(indicator)).toEqual(connectingGeometry)
  377. expect(await connectionIndicatorTextAlignment(indicator)).toBe('left')
  378. await indicator.hover()
  379. const snapshot = await captureStableAria(recoveryPage, '[class*="footArea"]', scaffold.workspaceCwd)
  380. await compareOrRefreshGolden(CONNECTION_ERROR_EXPECTED, snapshot, MODE)
  381. const style = await indicator.evaluate((element) => {
  382. const probe = document.createElement('span')
  383. probe.style.color = 'var(--dsw-alias-state-warn-label)'
  384. probe.style.backgroundColor = 'var(--dsw-alias-state-warn-tertiary)'
  385. document.body.append(probe)
  386. const actual = getComputedStyle(element)
  387. const reference = getComputedStyle(probe)
  388. const result = {
  389. background: actual.backgroundColor,
  390. color: actual.color,
  391. referenceBackground: reference.backgroundColor,
  392. referenceColor: reference.color,
  393. }
  394. probe.remove()
  395. return result
  396. })
  397. expect(style.background).toBe(style.referenceBackground)
  398. expect(style.color).toBe(style.referenceColor)
  399. expect(await indicator.locator('svg').count()).toBe(1)
  400. expect(await indicator.getAttribute('title')).toBeNull()
  401. rejectConnections = false
  402. await recoveryPage.clock.fastForward(10_000)
  403. await expect.poll(() => sockets.length).toBe(10)
  404. const automaticRecovery = recoveryPage.getByRole('status')
  405. await automaticRecovery.waitFor({ timeout: 10_000 })
  406. expect(await automaticRecovery.innerText()).toBe('Connected')
  407. await recoveryPage.clock.fastForward(2_000)
  408. await automaticRecovery.waitFor({ state: 'detached' })
  409. holdConnections = true
  410. await sockets.at(-1)!.close({ code: 4001, reason: 'manual recovery test' })
  411. await connecting.waitFor()
  412. await recoveryPage.clock.fastForward(500)
  413. await expect.poll(() => sockets.length).toBe(11)
  414. const idleBackground = await indicator.evaluate(element => getComputedStyle(element).backgroundColor)
  415. await indicator.hover()
  416. expect(await indicator.innerText()).toBe('Reconnect now')
  417. const hoverBackground = await indicator.evaluate(element => getComputedStyle(element).backgroundColor)
  418. expect(hoverBackground).toBe(idleBackground)
  419. await recoveryPage.mouse.down()
  420. await expect.poll(() => indicator.evaluate(element => getComputedStyle(element).backgroundColor))
  421. .not.toBe(hoverBackground)
  422. holdConnections = false
  423. await recoveryPage.mouse.up()
  424. await expect.poll(() => sockets.length).toBe(12)
  425. const recovered = recoveryPage.getByRole('status')
  426. await recovered.waitFor({ timeout: 10_000 })
  427. expect(await recovered.innerText()).toBe('Connected')
  428. expect(await connectionIndicatorGeometry(recovered)).toEqual(connectingGeometry)
  429. expect(await connectionIndicatorTextAlignment(recovered)).toBe('left')
  430. await recoveryPage.clock.fastForward(2_000)
  431. await recovered.waitFor({ state: 'detached', timeout: 5_000 })
  432. expect(recoveryTripwire.pageErrors).toEqual([])
  433. expect(recoveryTripwire.warnings.filter(warning => /connection lost, retry #/i.test(warning)))
  434. .toHaveLength(11)
  435. } finally {
  436. await recoveryPage.close()
  437. }
  438. }, 60_000)
  439. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  440. expect(tripwire.warnings).toEqual([])
  441. await assertFixtureInventory(SNAPSHOT_DIR, [
  442. 'session.v3.jsonl', 'replay.override.json', 'command-menu.expected.md',
  443. 'command-menu-fuzzy.expected.md', 'command-menu-zh.expected.md', 'connection-error.expected.md',
  444. 'hero.expected.md', 'plan-active.expected.md',
  445. 'reloaded.expected.md', 'reloaded-expanded.expected.md',
  446. ])
  447. })
  448. })
  449. async function connectionIndicatorGeometry(locator: ReturnType<Page['getByRole']>): Promise<{
  450. readonly outer: readonly number[]
  451. readonly icon: readonly number[]
  452. readonly label: readonly number[]
  453. }> {
  454. return await locator.evaluate((element) => {
  455. const outer = element.getBoundingClientRect()
  456. const icon = element.children.item(0)?.getBoundingClientRect()
  457. const label = element.children.item(1)?.getBoundingClientRect()
  458. if (icon === undefined || label === undefined) throw new Error('connection indicator children missing')
  459. const rounded = (values: readonly number[]): readonly number[] => values.map(value => Math.round(value * 100) / 100)
  460. return {
  461. outer: rounded([outer.x, outer.y, outer.width, outer.height]),
  462. icon: rounded([icon.x - outer.x, icon.y - outer.y, icon.width, icon.height]),
  463. label: rounded([label.x - outer.x, label.y - outer.y, label.width, label.height]),
  464. }
  465. })
  466. }
  467. async function connectionIndicatorTextAlignment(
  468. locator: ReturnType<Page['getByRole']>,
  469. ): Promise<string> {
  470. return await locator.evaluate((element) => {
  471. const label = element.children.item(1)
  472. if (label === null) throw new Error('connection indicator label missing')
  473. return getComputedStyle(label).textAlign
  474. })
  475. }