queue-actions.e2e.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // Keyless browser coverage for pending queue actions through the shipped Web
  2. // composition and real HTTP/SSE wire. Replay overrides park consecutive turns
  3. // so the page can edit and remove exact occurrences, then stop the active turn
  4. // while proving the preserved Queue advances in FIFO order.
  5. import { existsSync } from 'node:fs'
  6. import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
  7. import { tmpdir } from 'node:os'
  8. import { fileURLToPath } from 'node:url'
  9. import { join } from 'node:path'
  10. import type { Browser, Page } from 'playwright'
  11. import { chromium } from 'playwright'
  12. import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
  13. import { deriveReplayScript, parseSessionLog, type ReplayEntry } from '@deepseek-ai/dsh-llm-replay'
  14. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  15. import {
  16. assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
  17. launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold,
  18. } from './scaffold.ts'
  19. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  20. const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/queue-actions', import.meta.url))
  21. const FIXTURE = fileURLToPath(new URL('./snapshots/live-interactions/session.jsonl', import.meta.url))
  22. const COLLAPSED_EXPECTED = join(SNAPSHOT_DIR, 'collapsed.expected.md')
  23. const EDITING_EXPECTED = join(SNAPSHOT_DIR, 'editing.expected.md')
  24. const LAYOUT_EXPECTED = join(SNAPSHOT_DIR, 'layout.expected.md')
  25. const PRESERVED_EXPECTED = join(SNAPSHOT_DIR, 'preserved.expected.md')
  26. const UI_EXPECTED = join(SNAPSHOT_DIR, 'ui.expected.md')
  27. const MODE = webSnapshotMode()
  28. const ACTIVE_PROMPT = 'Reply with a one-sentence description of event sourcing, then stop.'
  29. const REMOVE = 'Queue item to remove'
  30. const EDIT = 'Queue item to edit'
  31. const EDITED = 'Edited queue item'
  32. const TAIL = 'Queue item preserved after stop'
  33. /** Durable turn-end classifications observed by the scenario. */
  34. function turnEndReasons(events: readonly SessionEvent[]): string[] {
  35. return events.flatMap(event => event.type === 'turn/end' ? [event.data.reason.kind] : [])
  36. }
  37. describe('web e2e: queue row actions', () => {
  38. let scaffold: WebScaffold | undefined
  39. let browser: Browser | undefined
  40. let page: Page
  41. let overrideDir: string | undefined
  42. afterEach(async () => {
  43. const failures: unknown[] = []
  44. await browser?.close().catch((error: unknown) => failures.push(error))
  45. browser = undefined
  46. const closing = scaffold
  47. scaffold = undefined
  48. await closing?.close().catch((error: unknown) => failures.push(error))
  49. if (overrideDir !== undefined) {
  50. await rm(overrideDir, { recursive: true, force: true })
  51. .catch((error: unknown) => failures.push(error))
  52. }
  53. overrideDir = undefined
  54. if (failures.length === 1) throw failures[0]
  55. if (failures.length > 1) throw new AggregateError(failures, 'queue-actions teardown failed')
  56. })
  57. it.skipIf(MODE === 'record')('edits and removes exact occurrences and preserves Queue across stop', async () => {
  58. overrideDir = await mkdtemp(join(tmpdir(), 'dsh-web-queue-actions-'))
  59. const readyFile = join(overrideDir, '.hang-ready')
  60. const nextReadyFile = join(overrideDir, '.next-hang-ready')
  61. const overridePath = join(overrideDir, 'replay.override.json')
  62. const recorded = deriveReplayScript(parseSessionLog(await readFile(FIXTURE, 'utf8')))
  63. expect(recorded).toHaveLength(1)
  64. const replay: ReplayEntry[] = [
  65. { kind: 'hang', readyFile },
  66. { kind: 'hang', readyFile: nextReadyFile },
  67. recorded[0]!,
  68. ]
  69. await writeFile(overridePath, JSON.stringify(replay))
  70. const sessionEvents: SessionEvent[] = []
  71. scaffold = await launchWebScaffold({ replayFixture: FIXTURE, replayOverride: overridePath })
  72. scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
  73. browser = await chromium.launch()
  74. page = await newEnglishPage(browser)
  75. const tripwire = watchConsole(page)
  76. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  77. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  78. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  79. onTestFailed(() => saveFailureShot(page, 'web-e2e-queue-actions'))
  80. const input = page.locator('textarea').first()
  81. const settled = scaffold.whenTurnSettled()
  82. await input.fill(ACTIVE_PROMPT)
  83. await input.press('Enter')
  84. await expect.poll(() => existsSync(readyFile), { timeout: 15_000 }).toBe(true)
  85. for (const text of [REMOVE, EDIT]) {
  86. await input.fill(text)
  87. await input.press('Enter')
  88. }
  89. const queueHeader = page.getByRole('button', { name: '2 queued messages' })
  90. await expect.poll(() => queueHeader.getAttribute('aria-expanded'), { timeout: 10_000 })
  91. .toBe('false')
  92. const collapsedSnapshot = await captureStableAria(
  93. page,
  94. '[class*="centerCol"]',
  95. scaffold.workspaceCwd,
  96. )
  97. await compareOrRefreshGolden(COLLAPSED_EXPECTED, collapsedSnapshot, MODE)
  98. await queueHeader.click()
  99. await expect.poll(
  100. () => page.getByRole('button', { name: 'Remove queued message' }).count(),
  101. { timeout: 10_000 },
  102. ).toBe(2)
  103. await page.setViewportSize({ width: 640, height: 1000 })
  104. const queueBox = await page.locator('[data-queue-dock]').boundingBox()
  105. const composerBox = await page.locator('[data-composer-card]').boundingBox()
  106. expect(queueBox).not.toBeNull()
  107. expect(composerBox).not.toBeNull()
  108. expect(queueBox!.x).toBeGreaterThanOrEqual(composerBox!.x)
  109. expect(queueBox!.x + queueBox!.width)
  110. .toBeLessThanOrEqual(composerBox!.x + composerBox!.width)
  111. const queueLeftInset = queueBox!.x - composerBox!.x
  112. const queueRightInset = composerBox!.x + composerBox!.width - queueBox!.x - queueBox!.width
  113. const composerMetrics = await page.locator('[data-composer-card]').evaluate((element) => {
  114. const style = getComputedStyle(element)
  115. return {
  116. dockInset: Number.parseFloat(style.getPropertyValue('--dsh-composer-dock-inset')),
  117. }
  118. })
  119. expect(queueLeftInset).toBeCloseTo(composerMetrics.dockInset, 1)
  120. expect(queueRightInset).toBeCloseTo(composerMetrics.dockInset, 1)
  121. await page.setViewportSize({ width: 1680, height: 1000 })
  122. const editRow = page.getByText(EDIT, { exact: true }).locator('..')
  123. await editRow.getByRole('button', { name: 'Edit queued message' }).click()
  124. const editor = page.getByRole('textbox', { name: 'Edit queued message' })
  125. await editor.fill(EDITED)
  126. const editingSnapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  127. await compareOrRefreshGolden(EDITING_EXPECTED, editingSnapshot, MODE)
  128. await page.getByRole('button', { name: 'Save queued message' }).click()
  129. await page.getByText(EDITED, { exact: true }).waitFor()
  130. const removeRow = page.getByText(REMOVE, { exact: true }).locator('..')
  131. await removeRow.getByRole('button', { name: 'Remove queued message' }).click()
  132. await expect.poll(() => page.getByText(REMOVE, { exact: true }).count()).toBe(0)
  133. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  134. await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
  135. expect(sessionEvents.filter(event => event.type === 'user/message' && event.data.source.kind === 'user')).toHaveLength(1)
  136. expect(tripwire.pageErrors).toEqual([])
  137. expect(tripwire.warnings).toEqual([])
  138. await input.fill(TAIL)
  139. await input.press('Enter')
  140. await expect.poll(
  141. () => page.getByRole('button', { name: 'Remove queued message' }).count(),
  142. { timeout: 10_000 },
  143. ).toBe(2)
  144. await page.getByRole('button', { name: 'Stop generating' }).click()
  145. await expect.poll(() => existsSync(nextReadyFile), { timeout: 15_000 }).toBe(true)
  146. await page.getByText(TAIL, { exact: true }).waitFor()
  147. await expect.poll(() => page.getByRole('button', { name: 'Remove queued message' }).count())
  148. .toBe(1)
  149. const preservedSnapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  150. await compareOrRefreshGolden(PRESERVED_EXPECTED, preservedSnapshot, MODE)
  151. await page.getByRole('button', { name: 'Stop generating' }).click()
  152. await settled
  153. expect(turnEndReasons(sessionEvents)).toEqual(['aborted', 'aborted', 'completed'])
  154. expect(sessionEvents.filter(event => event.type === 'user/message' && event.data.source.kind === 'user'))
  155. .toHaveLength(3)
  156. await expect.poll(() => page.locator('[data-queue-dock]').count()).toBe(0)
  157. }, 120_000)
  158. it.skipIf(MODE === 'record')('orders Todo before Goal and Queue on one responsive card column', async () => {
  159. overrideDir = await mkdtemp(join(tmpdir(), 'dsh-web-context-layout-'))
  160. const readyFile = join(overrideDir, '.hang-ready')
  161. const overridePath = join(overrideDir, 'replay.override.json')
  162. await writeFile(overridePath, JSON.stringify([{ kind: 'hang', readyFile } satisfies ReplayEntry]))
  163. const sessionEvents: SessionEvent[] = []
  164. scaffold = await launchWebScaffold({ replayFixture: FIXTURE, replayOverride: overridePath })
  165. scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
  166. browser = await chromium.launch()
  167. page = await newEnglishPage(browser)
  168. const tripwire = watchConsole(page)
  169. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  170. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  171. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  172. onTestFailed(() => saveFailureShot(page, 'web-e2e-context-layout'))
  173. const input = page.locator('textarea').first()
  174. const settled = scaffold.whenTurnSettled()
  175. await input.fill('/goal Keep the composer context panels aligned')
  176. await input.press('Enter')
  177. await expect.poll(() => existsSync(readyFile), { timeout: 15_000 }).toBe(true)
  178. await page.locator('[data-goal-bar]').waitFor({ timeout: 10_000 })
  179. const sessions = scaffold.ctx.sessions.list()
  180. expect(sessions).toHaveLength(1)
  181. sessions[0]!.append('todo/write', {
  182. todos: [
  183. { content: 'Confirm the panel order', status: 'completed' },
  184. { content: 'Align the panel widths', status: 'in_progress' },
  185. ],
  186. })
  187. await page.locator('[data-testid="todo-panel"]').waitFor({ timeout: 10_000 })
  188. for (const text of ['Layout queue first', 'Layout queue second']) {
  189. await input.fill(text)
  190. await input.press('Enter')
  191. }
  192. const queueHeader = page.getByRole('button', { name: '2 queued messages' })
  193. await expect.poll(() => queueHeader.getAttribute('aria-expanded'), { timeout: 10_000 })
  194. .toBe('false')
  195. const layoutSnapshot = await captureStableAria(
  196. page,
  197. '[class*="centerCol"]',
  198. scaffold.workspaceCwd,
  199. )
  200. await compareOrRefreshGolden(LAYOUT_EXPECTED, layoutSnapshot, MODE)
  201. const expectAlignedContextPanels = async () => {
  202. const queuePanelBox = await page.locator('[data-queue-dock] > div').boundingBox()
  203. const todoBox = await page.locator('[data-testid="todo-panel"]').boundingBox()
  204. const goalBox = await page.locator('[data-goal-bar] > div').boundingBox()
  205. expect(queuePanelBox).not.toBeNull()
  206. expect(todoBox).not.toBeNull()
  207. expect(goalBox).not.toBeNull()
  208. expect(todoBox!.y).toBeLessThan(goalBox!.y)
  209. expect(goalBox!.y).toBeLessThan(queuePanelBox!.y)
  210. expect(todoBox!.x).toBeCloseTo(goalBox!.x, 1)
  211. expect(todoBox!.x).toBeCloseTo(queuePanelBox!.x, 1)
  212. expect(todoBox!.width).toBeCloseTo(goalBox!.width, 1)
  213. expect(todoBox!.width).toBeCloseTo(queuePanelBox!.width, 1)
  214. }
  215. await expectAlignedContextPanels()
  216. await page.setViewportSize({ width: 640, height: 1000 })
  217. await expectAlignedContextPanels()
  218. await page.setViewportSize({ width: 1680, height: 1000 })
  219. await queueHeader.click()
  220. const removeButtons = page.getByRole('button', { name: 'Remove queued message' })
  221. await expect.poll(() => removeButtons.count(), { timeout: 10_000 }).toBe(2)
  222. await removeButtons.first().click()
  223. await expect.poll(() => removeButtons.count(), { timeout: 10_000 }).toBe(1)
  224. await removeButtons.first().click()
  225. await expect.poll(() => page.locator('[data-queue-dock]').count(), { timeout: 10_000 }).toBe(0)
  226. await page.getByRole('button', { name: 'Clear goal' }).click()
  227. await expect.poll(() => page.locator('[data-goal-bar]').count(), { timeout: 10_000 }).toBe(0)
  228. await page.getByRole('button', { name: 'Stop generating' }).click()
  229. await settled
  230. expect(turnEndReasons(sessionEvents)).toEqual(['aborted'])
  231. expect(tripwire.pageErrors).toEqual([])
  232. expect(tripwire.warnings).toEqual([])
  233. }, 120_000)
  234. it.skipIf(MODE === 'record')('keeps its snapshot inventory closed', async () => {
  235. await assertFixtureInventory(
  236. SNAPSHOT_DIR,
  237. ['collapsed.expected.md', 'editing.expected.md', 'layout.expected.md', 'preserved.expected.md', 'ui.expected.md'],
  238. )
  239. })
  240. })