lifecycle-chrome.e2e.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. await expect.poll(() => page.getByText('Cache hit 99.5%', { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  237. // Host: the session's durable header cwd is the folder the workspace
  238. // flow created and adopted (<workspaceCwd>/workspace) — the proof the
  239. // send went through workspace materialization rather than a bare
  240. // default-cwd session.
  241. const cwds = scaffold.ctx.sessions.list().map(session => session.header.cwd)
  242. expect(cwds).toEqual([join(scaffold.workspaceCwd, 'workspace')])
  243. const turnEnds = sessionEvents.filter(e => e.type === 'turn/end')
  244. expect(turnEnds).toHaveLength(1)
  245. expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed')
  246. }, 60_000)
  247. it.skipIf(MODE === 'record')('recovers the whole surface across a reload from the log alone', async () => {
  248. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-reload'))
  249. const warningStart = tripwire.warnings.length
  250. await page.reload({ waitUntil: 'load' })
  251. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  252. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  253. // Selection persisted (dsh.sessions.current) and history replayed: the
  254. // recorded turn re-renders from a Session Controller page with zero model calls —
  255. // the replay cursor was fully consumed before the reload, so any stray
  256. // request would fail the scenario loudly at close().
  257. await expect.poll(() => page.getByText('LIGHTHOUSE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
  258. await expect.poll(() => page.locator('[role="treeitem"][aria-selected="true"]').count(), { timeout: 10_000 }).toBe(1)
  259. // Golden of the recovered conversation region: rebuilt from the log, it
  260. // must render the same settled transcript the live turn produced.
  261. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  262. await compareOrRefreshGolden(RELOADED_EXPECTED, snapshot, MODE)
  263. const expanded = await captureExpandedTurnProcessAria(
  264. page,
  265. '[class*="centerCol"]',
  266. scaffold.workspaceCwd,
  267. )
  268. await compareOrRefreshGolden(RELOADED_EXPANDED_EXPECTED, expanded, MODE)
  269. expect(tripwire.pageErrors).toEqual([])
  270. }, 90_000)
  271. it.skipIf(MODE === 'record')('cascades the dark theme from the body attribute to painted surfaces', async () => {
  272. onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-dark'))
  273. // This scenario pins the ThemeRuntime's DOM contract directly (the
  274. // body[data-ds-dark-theme] attribute -> stylesheet cascade); the REAL
  275. // user gesture above it (Settings -> Appearance cubes) is owned by
  276. // settings-chrome.e2e.ts. Driving the attribute here keeps the cascade
  277. // pinned independently of the settings surface's own lifecycle.
  278. const sample = async (): Promise<{ token: string; sidebarBg: string; bodyBg: string }> =>
  279. await page.evaluate(() => {
  280. const sidebar = document.querySelector('[class*="sidebar"], [class*="rail"]') ?? document.body
  281. return {
  282. token: getComputedStyle(document.body).getPropertyValue('--dsw-alias-bg-base').trim(),
  283. sidebarBg: getComputedStyle(sidebar).backgroundColor,
  284. bodyBg: getComputedStyle(document.body).backgroundColor,
  285. }
  286. })
  287. const light = await sample()
  288. await page.evaluate(() => { document.body.setAttribute('data-ds-dark-theme', '') })
  289. const dark = await sample()
  290. // The alias token itself must flip — the cascade's root fact.
  291. expect(dark.token).not.toBe(light.token)
  292. // And a real painted surface must consume it (not just variables in a
  293. // void): at least one of the sampled backgrounds repaints.
  294. expect(dark.sidebarBg !== light.sidebarBg || dark.bodyBg !== light.bodyBg).toBe(true)
  295. // Removing the attribute restores the light values exactly (the palettes
  296. // live in one stylesheet; activation is attribute-only by design).
  297. await page.evaluate(() => { document.body.removeAttribute('data-ds-dark-theme') })
  298. const restored = await sample()
  299. expect(restored).toEqual(light)
  300. expect(tripwire.pageErrors).toEqual([])
  301. }, 60_000)
  302. it.skipIf(MODE === 'record')('shows automatic and user-requested connection recovery beside Settings', async () => {
  303. const recoveryPage = await newEnglishPage(browser)
  304. const recoveryTripwire = watchConsole(recoveryPage)
  305. const sockets: WebSocketRoute[] = []
  306. let rejectConnections = false
  307. await recoveryPage.routeWebSocket('**/api/remote.mux', (route) => {
  308. sockets.push(route)
  309. if (rejectConnections) {
  310. void route.close({ code: 4001, reason: 'connection recovery test' })
  311. return
  312. }
  313. route.connectToServer()
  314. })
  315. onTestFailed(() => saveFailureShot(recoveryPage, 'web-e2e-connection-recovery'))
  316. try {
  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.waitForTimeout(750)
  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: 'Connecting, restart now', exact: true,
  333. })
  334. await connecting.waitFor({ timeout: 10_000 })
  335. expect(await connecting.innerText()).toMatch(/^Connecting\.{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. await expect.poll(() => sockets.length, { timeout: 40_000 }).toBe(7)
  343. const indicator = recoveryPage.getByRole('button', {
  344. name: 'Disconnected, reconnect now', exact: true,
  345. })
  346. await indicator.waitFor({ timeout: 10_000 })
  347. expect(await connectionIndicatorGeometry(indicator)).toEqual(connectingGeometry)
  348. expect(await connectionIndicatorTextAlignment(indicator)).toBe('left')
  349. const snapshot = await captureStableAria(recoveryPage, '[class*="footArea"]', scaffold.workspaceCwd)
  350. await compareOrRefreshGolden(CONNECTION_ERROR_EXPECTED, snapshot, MODE)
  351. const style = await indicator.evaluate((element) => {
  352. const probe = document.createElement('span')
  353. probe.style.color = 'var(--dsw-alias-state-warn-label)'
  354. probe.style.backgroundColor = 'var(--dsw-alias-state-warn-tertiary)'
  355. document.body.append(probe)
  356. const actual = getComputedStyle(element)
  357. const reference = getComputedStyle(probe)
  358. const result = {
  359. background: actual.backgroundColor,
  360. color: actual.color,
  361. referenceBackground: reference.backgroundColor,
  362. referenceColor: reference.color,
  363. }
  364. probe.remove()
  365. return result
  366. })
  367. expect(style.background).toBe(style.referenceBackground)
  368. expect(style.color).toBe(style.referenceColor)
  369. expect(await indicator.locator('svg').count()).toBe(1)
  370. expect(await indicator.getAttribute('title')).toBeNull()
  371. const idleBackground = await indicator.evaluate(element => getComputedStyle(element).backgroundColor)
  372. await indicator.hover()
  373. expect(await indicator.innerText()).toBe('Reconnect now')
  374. const hoverBackground = await indicator.evaluate(element => getComputedStyle(element).backgroundColor)
  375. expect(hoverBackground).toBe(idleBackground)
  376. await recoveryPage.mouse.down()
  377. await expect.poll(() => indicator.evaluate(element => getComputedStyle(element).backgroundColor))
  378. .not.toBe(hoverBackground)
  379. rejectConnections = false
  380. await recoveryPage.mouse.up()
  381. await expect.poll(() => sockets.length).toBe(8)
  382. const recovered = recoveryPage.getByRole('status')
  383. await recovered.waitFor({ timeout: 10_000 })
  384. expect(await recovered.innerText()).toBe('Connected')
  385. expect(await connectionIndicatorGeometry(recovered)).toEqual(connectingGeometry)
  386. expect(await connectionIndicatorTextAlignment(recovered)).toBe('left')
  387. await recovered.waitFor({ state: 'detached', timeout: 5_000 })
  388. expect(recoveryTripwire.pageErrors).toEqual([])
  389. expect(recoveryTripwire.warnings.filter(warning => /connection lost, retry #[1-6]/i.test(warning)))
  390. .toHaveLength(7)
  391. } finally {
  392. await recoveryPage.close()
  393. }
  394. }, 60_000)
  395. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  396. expect(tripwire.warnings).toEqual([])
  397. await assertFixtureInventory(SNAPSHOT_DIR, [
  398. 'session.v2.jsonl', 'replay.override.json', 'command-menu.expected.md',
  399. 'command-menu-fuzzy.expected.md', 'command-menu-zh.expected.md', 'connection-error.expected.md',
  400. 'hero.expected.md', 'plan-active.expected.md',
  401. 'reloaded.expected.md', 'reloaded-expanded.expected.md',
  402. ])
  403. })
  404. })
  405. async function connectionIndicatorGeometry(locator: ReturnType<Page['getByRole']>): Promise<{
  406. readonly outer: readonly number[]
  407. readonly icon: readonly number[]
  408. readonly label: readonly number[]
  409. }> {
  410. return await locator.evaluate((element) => {
  411. const outer = element.getBoundingClientRect()
  412. const icon = element.children.item(0)?.getBoundingClientRect()
  413. const label = element.children.item(1)?.getBoundingClientRect()
  414. if (icon === undefined || label === undefined) throw new Error('connection indicator children missing')
  415. const rounded = (values: readonly number[]): readonly number[] => values.map(value => Math.round(value * 100) / 100)
  416. return {
  417. outer: rounded([outer.x, outer.y, outer.width, outer.height]),
  418. icon: rounded([icon.x - outer.x, icon.y - outer.y, icon.width, icon.height]),
  419. label: rounded([label.x - outer.x, label.y - outer.y, label.width, label.height]),
  420. }
  421. })
  422. }
  423. async function connectionIndicatorTextAlignment(
  424. locator: ReturnType<Page['getByRole']>,
  425. ): Promise<string> {
  426. return await locator.evaluate((element) => {
  427. const label = element.children.item(1)
  428. if (label === null) throw new Error('connection indicator label missing')
  429. return getComputedStyle(label).textAlign
  430. })
  431. }