live-interactions.e2e.ts 18 KB

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