live-interactions.e2e.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. // Web e2e scenarios: live-turn interactions — cancellation, error surfacing,
  2. // and transient-retry recovery, all through the real composition and wire.
  3. // The model seam is dsh-llm-replay with override sidecars: `hang` (+ a
  4. // readyFile marker) makes mid-stream cancel deterministic by construction,
  5. // `throw` entries express provider failures by stable code, and `{ patches }`
  6. // augmentation injects a transient throw before the recorded success so
  7. // llm-retry's recovery is proven end-to-end in the browser. Sidecar CONTENT
  8. // is authored here (single-sourced against the fixture via deriveReplayScript
  9. // — no committed copy of recorded chunks); the file is a per-run artifact in
  10. // the temp workspace. One recorded base fixture serves all three scenarios.
  11. import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
  12. import { existsSync } from 'node:fs'
  13. import { tmpdir } from 'node:os'
  14. import { fileURLToPath } from 'node:url'
  15. import { join } from 'node:path'
  16. import type { Browser, Page } from 'playwright'
  17. import { chromium } from 'playwright'
  18. import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
  19. import { deriveReplayScript, parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
  20. import type { ReplayOverrideDoc } from '@deepseek-ai/dsh-llm-replay'
  21. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  22. import {
  23. assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
  24. launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
  25. } from './scaffold.ts'
  26. import { connectFreshWorkspace, saveFailureShot } from './support.ts'
  27. const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/live-interactions', import.meta.url))
  28. const FIXTURE = join(SNAPSHOT_DIR, 'session.jsonl')
  29. // One golden per interactive end-state: what the user is left looking at
  30. // after cancel, after a non-retryable failure (pins the FIXME(web-error-surface)
  31. // gap as a reviewable artifact: NO error copy in the tree), and after retry
  32. // recovery — three genuinely different terminal surfaces of one fixture.
  33. const CANCEL_EXPECTED = join(SNAPSHOT_DIR, 'cancel.expected.md')
  34. const ERROR_EXPECTED = join(SNAPSHOT_DIR, 'error-auth.expected.md')
  35. const RETRY_EXPECTED = join(SNAPSHOT_DIR, 'retry.expected.md')
  36. const MODE = webSnapshotMode()
  37. // The recorded base: one text-only turn whose derived script the sidecars
  38. // patch. Kept deliberately tool-free so the derived script is exactly one
  39. // model call.
  40. const PROMPT = 'Reply with a one-sentence description of event sourcing, then stop.'
  41. /** turn/end reasons observed, in order. */
  42. function turnEndReasons(events: SessionEvent[]): string[] {
  43. return events
  44. .filter(e => e.type === 'turn/end')
  45. .map(e => (e as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind)
  46. }
  47. describe('web e2e: live-turn interactions (cancel / error / retry)', () => {
  48. let scaffold: WebScaffold | undefined
  49. let browser: Browser | undefined
  50. let page: Page
  51. let tripwire: ReturnType<typeof watchConsole>
  52. let sessionEvents: SessionEvent[]
  53. let sidecarDir: string | undefined
  54. afterEach(async () => {
  55. // scaffold.close() failures MUST fail the scenario: assertConsumed() is
  56. // the fixture-drift tripwire and cleanup problems are real defects. Run
  57. // every teardown step regardless, then rethrow what failed.
  58. const failures: unknown[] = []
  59. await browser?.close().catch((error: unknown) => failures.push(error))
  60. browser = undefined
  61. const closing = scaffold
  62. scaffold = undefined
  63. await closing?.close().catch((error: unknown) => failures.push(error))
  64. if (sidecarDir !== undefined) await rm(sidecarDir, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  65. sidecarDir = undefined
  66. if (failures.length === 1) throw failures[0]
  67. if (failures.length > 1) throw new AggregateError(failures, 'live-interactions teardown failed')
  68. })
  69. /** Boot scaffold + page with an optional override doc materialized per run. */
  70. async function launch(buildOverride?: (sidecarHome: string) => ReplayOverrideDoc): Promise<void> {
  71. sessionEvents = []
  72. let overridePath: string | undefined
  73. if (buildOverride !== undefined) {
  74. // The sidecar CONTENT is authored in this spec; the file is a per-run
  75. // artifact minted in a spec-owned temp dir. It must exist BEFORE the
  76. // scaffold boots — installLlmReplay resolves the script at install.
  77. sidecarDir = await mkdtemp(join(tmpdir(), 'dsh-web-e2e-sidecar-'))
  78. overridePath = join(sidecarDir, 'replay.override.json')
  79. await writeFile(overridePath, JSON.stringify(buildOverride(sidecarDir)))
  80. }
  81. scaffold = await launchWebScaffold({
  82. replayFixture: FIXTURE,
  83. ...(overridePath === undefined ? {} : { replayOverride: overridePath }),
  84. })
  85. scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
  86. browser = await chromium.launch()
  87. page = await browser.newPage({ viewport: { width: 1680, height: 1000 } })
  88. tripwire = watchConsole(page)
  89. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  90. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  91. // Fresh world: connect a Workspace so the composer scenarios start live.
  92. await connectFreshWorkspace(page)
  93. }
  94. /**
  95. * Type the recorded prompt and send, with the settled barrier pre-armed.
  96. * Returned WRAPPED ({ settled }) — a bare returned promise would be
  97. * flattened by the caller's await, blocking on turn/end before the caller
  98. * can act mid-turn (the cancel scenario's whole point).
  99. */
  100. async function sendPrompt(timeoutMs?: number): Promise<{ settled: ReturnType<WebScaffold['whenTurnSettled']> }> {
  101. const input = page.locator('textarea').first()
  102. await input.waitFor({ timeout: 10_000 })
  103. const settled = scaffold!.whenTurnSettled(timeoutMs)
  104. await input.fill(PROMPT)
  105. await input.press('Enter')
  106. return { settled }
  107. }
  108. it.skipIf(MODE !== 'record')('records the base fixture live through the composer', async () => {
  109. await launch()
  110. onTestFailed(() => saveFailureShot(page, 'web-e2e-interactions-record'))
  111. const { settled } = await sendPrompt(180_000)
  112. const sessionId = await settled
  113. await recordFixture(scaffold!, sessionId, FIXTURE)
  114. }, 200_000)
  115. it.skipIf(MODE === 'record')('cancels a hung stream deterministically via the readyFile marker', async () => {
  116. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
  117. let marker = ''
  118. await launch((sidecarHome) => {
  119. marker = join(sidecarHome, '.hang-ready')
  120. return { patches: [{ at: 0, entry: { kind: 'hang', readyFile: marker } }] }
  121. })
  122. onTestFailed(() => saveFailureShot(page, 'web-e2e-cancel'))
  123. const { settled } = await sendPrompt()
  124. // The marker IS the synchronization: the stream is provably parked in the
  125. // hang (prefix chunks delivered to the loop) before the stop click.
  126. await expect.poll(() => existsSync(marker), { timeout: 15_000 }).toBe(true)
  127. await page.getByRole('button', { name: 'Stop generating' }).click()
  128. await settled
  129. expect(turnEndReasons(sessionEvents).at(-1)).toBe('aborted')
  130. // Composer recovered; no streaming node lingers. The host settled first
  131. // (awaited above), but the abort frame reaches the browser over SSE — the
  132. // frozen-partial swap is eventually consistent, so poll rather than count.
  133. await expect.poll(() => page.locator('textarea').first().isEnabled(), { timeout: 10_000 }).toBe(true)
  134. await expect.poll(() => page.locator('[data-streaming="true"]').count(), { timeout: 10_000 }).toBe(0)
  135. // Golden of the aborted end-state: the prompt bubble plus the frozen
  136. // partial ('partial' is the hang entry's replayed prefix) and no more.
  137. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
  138. await compareOrRefreshGolden(CANCEL_EXPECTED, snapshot, MODE)
  139. expect(tripwire.pageErrors).toEqual([])
  140. expect(tripwire.warnings).toEqual([])
  141. }, 120_000)
  142. it.skipIf(MODE === 'record')('surfaces a non-retryable AUTH failure without retrying', async () => {
  143. await launch(() => ({
  144. patches: [{ at: 0, entry: { kind: 'throw', chunks: [], message: 'invalid api key', code: 'AUTH' } }],
  145. }))
  146. onTestFailed(() => saveFailureShot(page, 'web-e2e-error-auth'))
  147. const { settled } = await sendPrompt()
  148. await settled
  149. expect(turnEndReasons(sessionEvents).at(-1)).toBe('error')
  150. // AUTH is outside llm-retry's retryable set: no retry record.
  151. expect(sessionEvents.filter(e => e.type === 'llm/retry').length).toBe(0)
  152. // Product gap found by this lane, pinned as-is: the client consumes no
  153. // agent/error frames and a pre-chunk failure freezes no partial, so THIS
  154. // failure renders no error copy anywhere — the user sees the send simply
  155. // stop. FIXME(web-error-surface): assert visible error text here once the
  156. // web UI grows an error rendering; until then the pinned contract is
  157. // "no crash, composer recovers, turn logged as error".
  158. await expect.poll(() => page.locator('textarea').first().isEnabled(), { timeout: 10_000 }).toBe(true)
  159. expect(await page.locator('[data-streaming="true"]').count()).toBe(0)
  160. // Golden of the same gap: the prompt bubble alone, no error copy in the
  161. // tree — the diff that changes when web-error-surface lands.
  162. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
  163. await compareOrRefreshGolden(ERROR_EXPECTED, snapshot, MODE)
  164. expect(tripwire.pageErrors).toEqual([])
  165. expect(tripwire.warnings).toEqual([])
  166. }, 120_000)
  167. it.skipIf(MODE === 'record')('recovers a transient SERVER failure through llm-retry and completes', async () => {
  168. const derived = deriveReplayScript(parseSessionLog(await readFile(FIXTURE, 'utf8')))
  169. expect(derived).toHaveLength(1)
  170. await launch(() => ({
  171. patches: [
  172. { at: 0, entry: { kind: 'throw', chunks: [], message: 'upstream 503', code: 'SERVER' } },
  173. // Append the fixture's own success as the retry attempt — single-
  174. // sourced from the recording, never copied into a committed sidecar.
  175. { at: 1, entry: derived[0]! },
  176. ],
  177. }))
  178. onTestFailed(() => saveFailureShot(page, 'web-e2e-retry'))
  179. // llm-retry backs off ~500ms before the second attempt.
  180. const { settled } = await sendPrompt(60_000)
  181. await settled
  182. expect(turnEndReasons(sessionEvents).at(-1)).toBe('completed')
  183. // The durable retry record proves the second attempt (request/header logs
  184. // only on change, so attempt count is invisible there).
  185. expect(sessionEvents.filter(e => e.type === 'llm/retry').length).toBeGreaterThanOrEqual(1)
  186. await expect.poll(() => page.getByText('event sourcing', { exact: false }).count(), { timeout: 10_000 }).toBeGreaterThan(0)
  187. // Golden of the recovered end-state: indistinguishable from a clean
  188. // completion — retries are deliberately invisible in the transcript.
  189. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
  190. await compareOrRefreshGolden(RETRY_EXPECTED, snapshot, MODE)
  191. expect(tripwire.pageErrors).toEqual([])
  192. expect(tripwire.warnings).toEqual([])
  193. }, 120_000)
  194. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  195. await assertFixtureInventory(SNAPSHOT_DIR, [
  196. 'session.jsonl', 'cancel.expected.md', 'error-auth.expected.md', 'retry.expected.md',
  197. ])
  198. })
  199. })