live-interactions.e2e.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. // Web e2e scenarios: live-turn interactions — running-draft submission,
  2. // cancellation, error surfacing, transient-retry recovery, and retry
  3. // exhaustion, all through the real composition and wire. The model adapter is
  4. // dsh-llm-replay with override
  5. // sidecars: `hang` (+ a readyFile marker) makes mid-stream cancel
  6. // deterministic by construction, `throw` entries express provider failures by
  7. // stable code, and `{ patches }` augmentation injects transient throws before
  8. // (or instead of) the recorded success so llm-retry's recovery and exhaustion
  9. // are proven end-to-end in the browser. Sidecar CONTENT is authored here
  10. // (single-sourced against the fixture via deriveReplayScript — no committed
  11. // copy of recorded chunks); the file is a per-run artifact in the temp
  12. // workspace. One recorded base fixture serves every scenario.
  13. import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
  14. import { existsSync } from 'node:fs'
  15. import { tmpdir } from 'node:os'
  16. import { fileURLToPath } from 'node:url'
  17. import { join } from 'node:path'
  18. import type { Browser, Page } from 'playwright'
  19. import { chromium } from 'playwright'
  20. import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
  21. import type { RetryPolicyConfig } from '@deepseek-ai/dsh-llm'
  22. import { deriveReplayScript, parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
  23. import type { ReplayEntry, ReplayOverrideDoc } from '@deepseek-ai/dsh-llm-replay'
  24. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  25. import {
  26. assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
  27. launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
  28. } from './scaffold.ts'
  29. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  30. const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/live-interactions', import.meta.url))
  31. const FIXTURE = join(SNAPSHOT_DIR, 'session.jsonl')
  32. // One golden pins the empty mid-turn loading state, one pins the sendable draft
  33. // state, and the other four capture what remains after cancel, after a
  34. // non-retryable failure, after retry recovery, and after retry exhaustion.
  35. const CANCEL_EXPECTED = join(SNAPSHOT_DIR, 'cancel.expected.md')
  36. const LOADING_EXPECTED = join(SNAPSHOT_DIR, 'loading.expected.md')
  37. const RUNNING_DRAFT_EXPECTED = join(SNAPSHOT_DIR, 'running-draft.expected.md')
  38. const ERROR_EXPECTED = join(SNAPSHOT_DIR, 'error-auth.expected.md')
  39. const RETRY_EXPECTED = join(SNAPSHOT_DIR, 'retry.expected.md')
  40. const RETRY_EXHAUSTED_EXPECTED = join(SNAPSHOT_DIR, 'retry-exhausted.expected.md')
  41. const MODE = webSnapshotMode()
  42. const AUTH_PROVIDER_MESSAGE = 'Authentication Fails, Your api key: sk-preview-secret is invalid'
  43. // The recorded base: one text-only turn whose derived script the sidecars
  44. // patch. Kept deliberately tool-free so the derived script is exactly one
  45. // model call.
  46. const PROMPT = 'Reply with a one-sentence description of event sourcing, then stop.'
  47. const RUNNING_DRAFT = 'Queue this follow-up while the current turn is running.'
  48. /** turn/end reasons observed, in order. */
  49. function turnEndReasons(events: SessionEvent[]): string[] {
  50. return events
  51. .filter(e => e.type === 'turn/end')
  52. .map(e => (e as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind)
  53. }
  54. describe('web e2e: live-turn interactions (cancel / error / retry)', () => {
  55. let scaffold: WebScaffold | undefined
  56. let browser: Browser | undefined
  57. let page: Page
  58. let tripwire: ReturnType<typeof watchConsole>
  59. let sessionEvents: SessionEvent[]
  60. let sidecarDir: string | undefined
  61. afterEach(async () => {
  62. // scaffold.close() failures MUST fail the scenario: assertConsumed() is
  63. // the fixture-drift tripwire and cleanup problems are real defects. Run
  64. // every teardown step regardless, then rethrow what failed.
  65. const failures: unknown[] = []
  66. await browser?.close().catch((error: unknown) => failures.push(error))
  67. browser = undefined
  68. const closing = scaffold
  69. scaffold = undefined
  70. await closing?.close().catch((error: unknown) => failures.push(error))
  71. if (sidecarDir !== undefined) await rm(sidecarDir, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  72. sidecarDir = undefined
  73. if (failures.length === 1) throw failures[0]
  74. if (failures.length > 1) throw new AggregateError(failures, 'live-interactions teardown failed')
  75. })
  76. /** Boot scaffold + page with an optional override doc materialized per run. */
  77. async function launch(
  78. buildOverride?: (sidecarHome: string) => ReplayOverrideDoc,
  79. retryPolicy?: RetryPolicyConfig,
  80. ): Promise<void> {
  81. sessionEvents = []
  82. let overridePath: string | undefined
  83. if (buildOverride !== undefined) {
  84. // The sidecar CONTENT is authored in this spec; the file is a per-run
  85. // artifact minted in a spec-owned temp dir. It must exist BEFORE the
  86. // scaffold boots — installLlmReplay resolves the script at install.
  87. sidecarDir = await mkdtemp(join(tmpdir(), 'dsh-web-e2e-sidecar-'))
  88. overridePath = join(sidecarDir, 'replay.override.json')
  89. await writeFile(overridePath, JSON.stringify(buildOverride(sidecarDir)))
  90. }
  91. scaffold = await launchWebScaffold({
  92. replayFixture: FIXTURE,
  93. ...(overridePath === undefined ? {} : { replayOverride: overridePath }),
  94. ...(overridePath === undefined ? {} : { compareReplaySession: false }),
  95. ...(retryPolicy === undefined ? {} : { replayRetryPolicy: retryPolicy }),
  96. })
  97. scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
  98. browser = await chromium.launch()
  99. page = await newEnglishPage(browser)
  100. tripwire = watchConsole(page)
  101. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  102. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  103. // Fresh world: connect a Workspace so the composer scenarios start live.
  104. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  105. }
  106. /**
  107. * Type the recorded prompt and send, with the settled barrier pre-armed.
  108. * Returned WRAPPED ({ settled }) — a bare returned promise would be
  109. * flattened by the caller's await, blocking on turn/end before the caller
  110. * can act mid-turn (the cancel scenario's whole point).
  111. */
  112. async function sendPrompt(timeoutMs?: number): Promise<{ settled: ReturnType<WebScaffold['whenTurnSettled']> }> {
  113. const input = page.locator('textarea').first()
  114. await input.waitFor({ timeout: 10_000 })
  115. const settled = scaffold!.whenTurnSettled(timeoutMs)
  116. await input.fill(PROMPT)
  117. await input.press('Enter')
  118. return { settled }
  119. }
  120. it.skipIf(MODE !== 'record')('records the base fixture live through the composer', async () => {
  121. await launch()
  122. onTestFailed(() => saveFailureShot(page, 'web-e2e-interactions-record'))
  123. const { settled } = await sendPrompt(180_000)
  124. const sessionId = await settled
  125. await recordFixture(scaffold!, sessionId, FIXTURE)
  126. }, 200_000)
  127. it.skipIf(MODE === 'record')('matches the canonical persisted session', async () => {
  128. await launch()
  129. const { settled } = await sendPrompt(30_000)
  130. await settled
  131. })
  132. it.skipIf(MODE === 'record')('cancels a hung stream deterministically via the readyFile marker', async () => {
  133. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
  134. let marker = ''
  135. await launch((sidecarHome) => {
  136. marker = join(sidecarHome, '.hang-ready')
  137. return { patches: [{ at: 0, entry: { kind: 'hang', readyFile: marker } }] }
  138. })
  139. onTestFailed(() => saveFailureShot(page, 'web-e2e-cancel'))
  140. const { settled } = await sendPrompt()
  141. // The marker IS the synchronization: the stream is provably parked in the
  142. // hang (prefix chunks delivered to the loop) before the stop click.
  143. await expect.poll(() => existsSync(marker), { timeout: 15_000 }).toBe(true)
  144. await expect.poll(
  145. () => page.getByRole('status').filter({ hasText: 'Deep diving...' }).isVisible(),
  146. { timeout: 10_000 },
  147. ).toBe(true)
  148. const loadingSnapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
  149. await compareOrRefreshGolden(LOADING_EXPECTED, loadingSnapshot, MODE)
  150. const input = page.locator('textarea').first()
  151. await input.fill(RUNNING_DRAFT)
  152. const send = page.getByRole('button', { name: 'Send message', exact: true })
  153. await send.waitFor({ timeout: 10_000 })
  154. expect(await page.getByRole('button', { name: 'Stop generating', exact: true }).count()).toBe(0)
  155. const runningDraftSnapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
  156. await compareOrRefreshGolden(RUNNING_DRAFT_EXPECTED, runningDraftSnapshot, MODE)
  157. await send.click()
  158. await expect.poll(() => input.inputValue(), { timeout: 10_000 }).toBe('')
  159. const queuedRow = page.locator('[data-queue-dock]').getByRole('listitem').filter({ hasText: RUNNING_DRAFT })
  160. await queuedRow.waitFor({ timeout: 10_000 })
  161. await page.getByRole('button', { name: 'Stop generating', exact: true }).waitFor({ timeout: 10_000 })
  162. await queuedRow.getByRole('button', { name: 'Remove queued message' }).click()
  163. await expect.poll(() => queuedRow.count(), { timeout: 10_000 }).toBe(0)
  164. await page.getByRole('button', { name: 'Stop generating' }).click()
  165. await settled
  166. expect(turnEndReasons(sessionEvents).at(-1)).toBe('aborted')
  167. // Composer recovered; no streaming node lingers. The host settled first
  168. // (awaited above), but the abort frame reaches the browser over SSE — the
  169. // frozen-partial swap is eventually consistent, so poll rather than count.
  170. await expect.poll(() => page.locator('textarea').first().isEnabled(), { timeout: 10_000 }).toBe(true)
  171. await expect.poll(() => page.locator('[data-streaming="true"]').count(), { timeout: 10_000 }).toBe(0)
  172. // Golden of the aborted end-state: the prompt bubble plus the frozen
  173. // partial ('partial' is the hang entry's replayed prefix) and no more.
  174. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
  175. await compareOrRefreshGolden(CANCEL_EXPECTED, snapshot, MODE)
  176. expect(tripwire.pageErrors).toEqual([])
  177. expect(tripwire.warnings).toEqual([])
  178. }, 120_000)
  179. it.skipIf(MODE === 'record')('surfaces a non-retryable AUTH failure without retrying', async () => {
  180. await launch(() => ({
  181. patches: [{ at: 0, entry: { kind: 'throw', chunks: [], message: AUTH_PROVIDER_MESSAGE, code: 'AUTH' } }],
  182. }))
  183. onTestFailed(() => saveFailureShot(page, 'web-e2e-error-auth'))
  184. const { settled } = await sendPrompt()
  185. await settled
  186. expect(turnEndReasons(sessionEvents).at(-1)).toBe('error')
  187. // AUTH is outside llm-retry's retryable set: no retry record.
  188. expect(sessionEvents.filter(e => e.type === 'llm/retry').length).toBe(0)
  189. await expect.poll(() => page.locator('textarea').first().isEnabled(), { timeout: 10_000 }).toBe(true)
  190. expect(await page.locator('[data-streaming="true"]').count()).toBe(0)
  191. const errorStatus = page.getByRole('status').filter({ hasText: 'This turn failed' })
  192. await errorStatus.waitFor({ timeout: 10_000 })
  193. expect(await errorStatus.textContent()).toContain('API key is invalid')
  194. expect(await errorStatus.textContent()).toContain('AUTH')
  195. expect(await page.locator('body').textContent()).not.toContain('sk-preview-secret')
  196. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
  197. await compareOrRefreshGolden(ERROR_EXPECTED, snapshot, MODE)
  198. await page.getByRole('tab', { name: 'Trajectory' }).click()
  199. const requestMarker = page.locator('tr[data-request-only="true"]').last()
  200. .getByRole('button', { name: /Request #/ })
  201. await requestMarker.click()
  202. await page.getByText('API key is invalid', { exact: true }).waitFor({ timeout: 10_000 })
  203. expect(await page.locator('body').textContent()).not.toContain('sk-preview-secret')
  204. expect(tripwire.pageErrors).toEqual([])
  205. expect(tripwire.warnings).toEqual([])
  206. }, 120_000)
  207. it.skipIf(MODE === 'record')('keeps a terminal request marker inside the trajectory table', async () => {
  208. await launch(() => ({
  209. patches: [{ at: 0, entry: { kind: 'throw', chunks: [], message: AUTH_PROVIDER_MESSAGE, code: 'AUTH' } }],
  210. }))
  211. const { settled } = await sendPrompt()
  212. await settled
  213. await page.getByRole('tab', { name: 'Trajectory' }).click()
  214. // The boundary marker row itself is a 0-height hairline except at the
  215. // table tail; the marker button is absolutely positioned and stays
  216. // visible, so wait on it directly.
  217. const tailRequest = page.locator('tr[data-request-only="true"]').last()
  218. const requestMarker = tailRequest.getByRole('button', { name: /Request #/ })
  219. await requestMarker.waitFor({ timeout: 10_000 })
  220. const markerWithinTable = await requestMarker.evaluate((element) => {
  221. const marker = element.getBoundingClientRect()
  222. const table = element.closest('table')?.getBoundingClientRect()
  223. if (table === undefined) throw new Error('request marker has no table')
  224. return marker.bottom <= table.bottom
  225. })
  226. expect(markerWithinTable).toBe(true)
  227. expect(tripwire.pageErrors).toEqual([])
  228. expect(tripwire.warnings).toEqual([])
  229. }, 120_000)
  230. it.skipIf(MODE === 'record')('recovers a transient SERVER failure through llm-retry and completes', async () => {
  231. const derived = deriveReplayScript(parseSessionLog(await readFile(FIXTURE, 'utf8')))
  232. expect(derived).toHaveLength(1)
  233. await launch(() => ({
  234. patches: [
  235. { at: 0, entry: { kind: 'throw', chunks: [], message: 'upstream 503', code: 'SERVER' } },
  236. // Append the fixture's own success as the retry attempt — single-
  237. // sourced from the recording, never copied into a committed sidecar.
  238. { at: 1, entry: derived[0]! },
  239. ],
  240. }))
  241. onTestFailed(() => saveFailureShot(page, 'web-e2e-retry'))
  242. // llm-retry backs off ~500ms before the second attempt.
  243. const { settled } = await sendPrompt(60_000)
  244. await settled
  245. expect(turnEndReasons(sessionEvents).at(-1)).toBe('completed')
  246. // The durable retry record proves the second attempt (request/header logs
  247. // only on change, so attempt count is invisible there).
  248. expect(sessionEvents.filter(e => e.type === 'llm/retry').length).toBeGreaterThanOrEqual(1)
  249. await expect.poll(() => page.getByText('event sourcing', { exact: false }).count(), { timeout: 10_000 }).toBeGreaterThan(0)
  250. // Golden of the recovered end-state: the discarded partial stays absent,
  251. // while the settled retry row remains as durable recovery context.
  252. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
  253. await compareOrRefreshGolden(RETRY_EXPECTED, snapshot, MODE)
  254. expect(tripwire.pageErrors).toEqual([])
  255. expect(tripwire.warnings).toEqual([])
  256. }, 120_000)
  257. it.skipIf(MODE === 'record')('surfaces the terminal turn error after transient retries exhaust', async () => {
  258. // A whole-script replacement: three throw entries cover the first request
  259. // plus both budgeted retries (patches cannot reach past the one-call
  260. // derived script). The scenario-owned policy keeps exhaustion fast and
  261. // jitter-free instead of walking the shared default's five backed-off
  262. // attempts.
  263. const failure: ReplayEntry = { kind: 'throw', chunks: [], message: 'upstream 503', code: 'SERVER' }
  264. await launch(
  265. () => [failure, failure, failure],
  266. { mode: 'normal', maxRetries: 2, retryableCodes: ['SERVER'], backoff: { initialDelayMs: 25, maxDelayMs: 50, jitterRatio: 0 } },
  267. )
  268. onTestFailed(() => saveFailureShot(page, 'web-e2e-retry-exhausted'))
  269. const { settled } = await sendPrompt(60_000)
  270. await settled
  271. expect(turnEndReasons(sessionEvents).at(-1)).toBe('error')
  272. expect(sessionEvents.filter(e => e.type === 'llm/retry').length).toBe(2)
  273. await expect.poll(() => page.locator('textarea').first().isEnabled(), { timeout: 10_000 }).toBe(true)
  274. expect(await page.locator('[data-streaming="true"]').count()).toBe(0)
  275. // The terminal error row must render even though the turn owns a retry
  276. // chain: exhausted recovery shares the failing turn, so suppressing the
  277. // row by retry history would leave the failure invisible.
  278. const errorStatus = page.getByRole('status').filter({ hasText: 'This turn failed' })
  279. await errorStatus.waitFor({ timeout: 10_000 })
  280. expect(await errorStatus.textContent()).toContain('upstream 503')
  281. expect(await errorStatus.textContent()).toContain('SERVER')
  282. // The settled retry chain stays alongside the terminal row as recovery
  283. // context; the golden pins both.
  284. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
  285. await compareOrRefreshGolden(RETRY_EXHAUSTED_EXPECTED, snapshot, MODE)
  286. expect(tripwire.pageErrors).toEqual([])
  287. expect(tripwire.warnings).toEqual([])
  288. }, 120_000)
  289. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  290. await assertFixtureInventory(SNAPSHOT_DIR, [
  291. 'session.jsonl', 'cancel.expected.md', 'loading.expected.md', 'running-draft.expected.md',
  292. 'error-auth.expected.md', 'retry.expected.md', 'retry-exhausted.expected.md',
  293. ])
  294. })
  295. })