replay-round-trip.e2e.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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 { join } from 'node:path'
  13. import { fileURLToPath } from 'node:url'
  14. import type { Browser, Page } from 'playwright'
  15. import { chromium } from 'playwright'
  16. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  17. import { CallId } from '@deepseek-ai/dsh-llm'
  18. import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
  19. import {
  20. assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
  21. launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
  22. } from './scaffold.ts'
  23. import { connectFreshWorkspace, newEnglishPage, REPO_ROOT, saveFailureShot } from './support.ts'
  24. const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/fresh-round-trip', import.meta.url))
  25. const FIXTURE = fileURLToPath(new URL('./snapshots/fresh-round-trip/session.jsonl', import.meta.url))
  26. const UI_EXPECTED = fileURLToPath(new URL('./snapshots/fresh-round-trip/ui.expected.md', import.meta.url))
  27. const SYSTEM_PROMPT_EXPECTED = fileURLToPath(new URL('./snapshots/fresh-round-trip/system-prompt.expected.md', import.meta.url))
  28. const MODE = webSnapshotMode()
  29. // The scenario's one drive prompt. Record sends it; replay asserts the
  30. // committed fixture recorded exactly it, so drive script and fixture cannot
  31. // drift apart.
  32. const PROMPT = 'Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop.'
  33. describe('web e2e: fresh round trip through the real assembly', () => {
  34. let scaffold: WebScaffold
  35. let browser: Browser
  36. let page: Page
  37. let tripwire: ReturnType<typeof watchConsole>
  38. let settledSessionId: SessionId | undefined
  39. const sessionEvents: SessionEvent[] = []
  40. beforeAll(async () => {
  41. scaffold = await launchWebScaffold({
  42. ...(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 }),
  43. })
  44. scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
  45. browser = await chromium.launch()
  46. page = await newEnglishPage(browser)
  47. tripwire = watchConsole(page)
  48. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  49. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  50. // Fresh world: connect a Workspace so the composer scenarios start live.
  51. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  52. }, 120_000)
  53. afterAll(async () => {
  54. await browser?.close()
  55. await scaffold?.close()
  56. })
  57. it('drives the recorded prompt to a settled turn (all modes)', async () => {
  58. onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip'))
  59. if (MODE !== 'record') {
  60. // Drift guard: the committed fixture must carry exactly the drive prompt.
  61. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
  62. }
  63. const input = page.locator('textarea').first()
  64. await input.waitFor({ timeout: 10_000 })
  65. // Arm the host-side settled barrier BEFORE the send click.
  66. const settled = scaffold.whenTurnSettled()
  67. await input.fill(PROMPT)
  68. await input.press('Enter')
  69. const sessionId = await settled
  70. settledSessionId = sessionId
  71. if (MODE === 'record') {
  72. await recordFixture(scaffold, sessionId, FIXTURE)
  73. }
  74. }, 200_000)
  75. it('records the Web surface, source checkout, and session cwd in the request header', async () => {
  76. if (settledSessionId === undefined) throw new Error('the drive turn did not publish a session id')
  77. const agent = scaffold.ctx.agents.get(settledSessionId)
  78. if (agent === undefined) throw new Error(`the settled Web agent ${settledSessionId} is no longer live`)
  79. const system = agent.session.requestHeader()?.system
  80. if (system === undefined) throw new Error('the settled Web request has no system prompt')
  81. const prefix = system.split('\n\n').slice(0, 4).join('\n\n')
  82. .split(REPO_ROOT).join('{{sourceRoot}}')
  83. .split(join(scaffold.workspaceCwd, 'workspace')).join('{{cwd}}')
  84. .split(scaffold.baseUrl).join('{{webUrl}}')
  85. await compareOrRefreshGolden(SYSTEM_PROMPT_EXPECTED, prefix, MODE)
  86. })
  87. it('exposes the assembled Web URL to the real bash tool', async () => {
  88. if (settledSessionId === undefined) throw new Error('the drive turn did not publish a session id')
  89. const agent = scaffold.ctx.agents.get(settledSessionId)
  90. if (agent === undefined) throw new Error(`the settled Web agent ${settledSessionId} is no longer live`)
  91. const result = await scaffold.ctx.tools.execute({
  92. signal: AbortSignal.timeout(5_000),
  93. callId: CallId('web-url-probe'),
  94. name: 'bash',
  95. arguments: {
  96. command: 'printf \'%s\\n%s\\n\' "$DSH_WEB_URL" "$DSH_WEB_MODE"',
  97. description: 'Print current Web runtime',
  98. },
  99. agent,
  100. })
  101. expect(result.isError).toBe(false)
  102. expect(result.content.filter(block => block.type === 'text').map(block => block.text).join(''))
  103. .toBe(`${scaffold.baseUrl}\nproduction\n`)
  104. })
  105. it.skipIf(MODE === 'record')('rendered the settled turn: markdown, tool row, composer restore', async () => {
  106. onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip-settled'))
  107. // Browser settled-poll after host completion (host strictly precedes render).
  108. await page.locator('[data-streaming="true"]').waitFor({ state: 'detached', timeout: 15_000 }).catch(() => {
  109. // Chunks may coalesce into one commit; a never-mounted streaming node is
  110. // legal — the chunk-event assertions below carry incrementality.
  111. })
  112. await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
  113. // World state, not self-report: the real bash executor returned the exact
  114. // command output, and the turn closed cleanly.
  115. const bashCall = sessionEvents.find(event => event.type === 'tool/call' && event.data.name === 'bash')
  116. if (bashCall?.type !== 'tool/call') throw new Error('the replayed turn did not call the bash tool')
  117. const bashResult = sessionEvents.find(event =>
  118. event.type === 'tool/result' && event.data.message.source.callId === bashCall.data.callId)
  119. if (bashResult?.type !== 'tool/result') throw new Error('the bash tool call produced no durable result')
  120. expect(bashResult.data.message.content[0].isError).toBe(false)
  121. expect(bashResult.data.message.content[0].content.filter(block => block.type === 'text').map(block => block.text).join(''))
  122. .toBe('WEB_E2E_OK\n')
  123. const turnEnds = sessionEvents.filter(e => e.type === 'turn/end')
  124. expect(turnEnds.length).toBe(1)
  125. expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed')
  126. // The persisted chunk events are the authoritative incrementality proof.
  127. expect(sessionEvents.filter(e => e.type === 'assistant/chunk').length).toBeGreaterThan(10)
  128. }, 60_000)
  129. it.skipIf(MODE === 'record')('matches the conversation aria golden with stable anchors', async () => {
  130. onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip-aria'))
  131. // Anchor assertions survive a semantics-preserving component rewrite even
  132. // while the whole-region golden churns.
  133. await expect(page.getByRole('textbox').first().isVisible()).resolves.toBe(true)
  134. expect(await page.getByText('WEB_E2E_OK', { exact: false }).count()).toBeGreaterThanOrEqual(1)
  135. await page.getByRole('button', {
  136. name: 'Select model, current DeepSeek-V4-Flash',
  137. }).waitFor({ timeout: 10_000 })
  138. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  139. await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
  140. })
  141. it.skipIf(MODE === 'record')('expands and collapses the reasoning fold from its click target', async () => {
  142. onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip-think'))
  143. // Interaction over the REAL wire-delivered transcript (the fixture-client
  144. // tier pins the same gesture against FixtureApiClient; this one runs on
  145. // mux-frame-fed state). Runs after the golden capture so the committed
  146. // aria surface stays the untouched settled state.
  147. const think = page.getByRole('button', { name: /^Think/ }).first()
  148. expect(await think.getAttribute('aria-expanded')).toBe('false')
  149. await think.click()
  150. await expect.poll(() => think.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('true')
  151. await think.click()
  152. await expect.poll(() => think.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('false')
  153. })
  154. it.skipIf(MODE === 'record')('stayed clean: no pageerrors, no reconnect self-healing, no server errors', async () => {
  155. expect(tripwire.pageErrors).toEqual([])
  156. expect(tripwire.warnings).toEqual([])
  157. await assertFixtureInventory(SNAPSHOT_DIR, ['session.jsonl', 'system-prompt.expected.md', 'ui.expected.md'])
  158. })
  159. })