replay-round-trip.e2e.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. // Web e2e scenario: fresh round trip. A real chromium types a prompt into the
  2. // real composer; the wire, apiproxy, agent loop, and the REAL bash tool (echo
  3. // in the temp workspace) all run; the model seam is dsh-llm-replay (keyless)
  4. // or the live adapter (record). Drive steps run in every mode and wait only
  5. // on generic completion (whenTurnSettled — never model-content selectors, so
  6. // record cannot hang on a live model answering differently); assertion steps
  7. // run in replay/refresh only. Settled states only — streaming incrementality
  8. // is asserted from the persisted assistant/chunk events, not transient DOM.
  9. // Record: DSH_SNAPSHOT=record rewrites session.jsonl, then a keyless
  10. // DSH_SNAPSHOT=refresh regenerates ui.expected.md.
  11. import { readFile } from 'node:fs/promises'
  12. import { fileURLToPath } from 'node:url'
  13. import type { Browser, Page } from 'playwright'
  14. import { chromium } from 'playwright'
  15. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  16. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  17. import {
  18. assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
  19. launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
  20. } from './scaffold.ts'
  21. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  22. const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/fresh-round-trip', import.meta.url))
  23. const FIXTURE = fileURLToPath(new URL('./snapshots/fresh-round-trip/session.jsonl', import.meta.url))
  24. const UI_EXPECTED = fileURLToPath(new URL('./snapshots/fresh-round-trip/ui.expected.md', import.meta.url))
  25. const MODE = webSnapshotMode()
  26. // The scenario's one drive prompt. Record sends it; replay asserts the
  27. // committed fixture recorded exactly it, so drive script and fixture cannot
  28. // drift apart.
  29. const PROMPT = 'Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop.'
  30. describe('web e2e: fresh round trip through the real assembly', () => {
  31. let scaffold: WebScaffold
  32. let browser: Browser
  33. let page: Page
  34. let tripwire: ReturnType<typeof watchConsole>
  35. const sessionEvents: SessionEvent[] = []
  36. beforeAll(async () => {
  37. scaffold = await launchWebScaffold({
  38. ...(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 }),
  39. })
  40. scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
  41. browser = await chromium.launch()
  42. page = await newEnglishPage(browser)
  43. tripwire = watchConsole(page)
  44. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  45. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  46. // Fresh world: connect a Workspace so the composer scenarios start live.
  47. await connectFreshWorkspace(page)
  48. }, 120_000)
  49. afterAll(async () => {
  50. await browser?.close()
  51. await scaffold?.close()
  52. })
  53. it('drives the recorded prompt to a settled turn (all modes)', async () => {
  54. onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip'))
  55. if (MODE !== 'record') {
  56. // Drift guard: the committed fixture must carry exactly the drive prompt.
  57. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
  58. }
  59. const input = page.locator('textarea').first()
  60. await input.waitFor({ timeout: 10_000 })
  61. // Arm the host-side settled barrier BEFORE the send click.
  62. const settled = scaffold.whenTurnSettled()
  63. await input.fill(PROMPT)
  64. await input.press('Enter')
  65. const sessionId = await settled
  66. if (MODE === 'record') {
  67. await recordFixture(scaffold, sessionId, FIXTURE)
  68. }
  69. }, 200_000)
  70. it.skipIf(MODE === 'record')('rendered the settled turn: markdown, tool row, composer restore', async () => {
  71. onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip-settled'))
  72. // Browser settled-poll after host completion (host strictly precedes render).
  73. await page.locator('[data-streaming="true"]').waitFor({ state: 'detached', timeout: 15_000 }).catch(() => {
  74. // Chunks may coalesce into one commit; a never-mounted streaming node is
  75. // legal — the chunk-event assertions below carry incrementality.
  76. })
  77. await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
  78. // World state, not self-report: the real bash executor returned the exact
  79. // command output, and the turn closed cleanly.
  80. const bashCall = sessionEvents.find(event => event.type === 'tool/call' && event.data.name === 'bash')
  81. if (bashCall?.type !== 'tool/call') throw new Error('the replayed turn did not call the bash tool')
  82. const bashResult = sessionEvents.find(event =>
  83. event.type === 'tool/result' && event.data.message.source.callId === bashCall.data.callId)
  84. if (bashResult?.type !== 'tool/result') throw new Error('the bash tool call produced no durable result')
  85. expect(bashResult.data.message.content[0].isError).toBe(false)
  86. expect(bashResult.data.message.content[0].content.filter(block => block.type === 'text').map(block => block.text).join(''))
  87. .toBe('WEB_E2E_OK\n')
  88. const turnEnds = sessionEvents.filter(e => e.type === 'turn/end')
  89. expect(turnEnds.length).toBe(1)
  90. expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed')
  91. // The persisted chunk events are the authoritative incrementality proof.
  92. expect(sessionEvents.filter(e => e.type === 'assistant/chunk').length).toBeGreaterThan(10)
  93. }, 60_000)
  94. it.skipIf(MODE === 'record')('matches the conversation aria golden with stable anchors', async () => {
  95. onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip-aria'))
  96. // Anchor assertions survive a semantics-preserving component rewrite even
  97. // while the whole-region golden churns.
  98. await expect(page.getByRole('textbox').first().isVisible()).resolves.toBe(true)
  99. expect(await page.getByText('WEB_E2E_OK', { exact: false }).count()).toBeGreaterThanOrEqual(1)
  100. await page.getByRole('button', {
  101. name: 'Select model, current DeepSeek-V4-Flash',
  102. }).waitFor({ timeout: 10_000 })
  103. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  104. await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
  105. })
  106. it.skipIf(MODE === 'record')('expands and collapses the reasoning fold from its click target', async () => {
  107. onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip-think'))
  108. // Interaction over the REAL wire-delivered transcript (the fixture-client
  109. // tier pins the same gesture against FixtureApiClient; this one runs on
  110. // mux-frame-fed state). Runs after the golden capture so the committed
  111. // aria surface stays the untouched settled state.
  112. const think = page.getByRole('button', { name: /^Think/ }).first()
  113. expect(await think.getAttribute('aria-expanded')).toBe('false')
  114. await think.click()
  115. await expect.poll(() => think.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('true')
  116. await think.click()
  117. await expect.poll(() => think.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('false')
  118. })
  119. it.skipIf(MODE === 'record')('stayed clean: no pageerrors, no reconnect self-healing, no server errors', async () => {
  120. expect(tripwire.pageErrors).toEqual([])
  121. expect(tripwire.warnings).toEqual([])
  122. await assertFixtureInventory(SNAPSHOT_DIR, ['session.jsonl', 'ui.expected.md'])
  123. })
  124. })