live-interactions.e2e.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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.v2.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. await page.locator('[data-streaming="true"]')
  152. .getByText('partial', { exact: true })
  153. .waitFor({ timeout: 30_000 })
  154. const loadingSnapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
  155. await compareOrRefreshGolden(LOADING_EXPECTED, loadingSnapshot, MODE)
  156. const input = page.locator('[data-composer-input]').first()
  157. await input.fill(RUNNING_DRAFT)
  158. const send = page.getByRole('button', { name: 'Send message', exact: true })
  159. await send.waitFor({ timeout: 10_000 })
  160. expect(await page.getByRole('button', { name: 'Stop generating', exact: true }).count()).toBe(0)
  161. const runningDraftSnapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
  162. await compareOrRefreshGolden(RUNNING_DRAFT_EXPECTED, runningDraftSnapshot, MODE)
  163. await send.click()
  164. await expect.poll(() => input.textContent(), { timeout: 10_000 }).toBe('')
  165. const queuedRow = page.locator('[data-queue-dock]').getByRole('listitem').filter({ hasText: RUNNING_DRAFT })
  166. await queuedRow.waitFor({ timeout: 10_000 })
  167. await page.getByRole('button', { name: 'Stop generating', exact: true }).waitFor({ timeout: 10_000 })
  168. await queuedRow.getByRole('button', { name: 'Remove queued message' }).click()
  169. await expect.poll(() => queuedRow.count(), { timeout: 10_000 }).toBe(0)
  170. await page.getByRole('button', { name: 'Stop generating' }).click()
  171. await settled
  172. expect(turnEndReasons(sessionEvents).at(-1)).toBe('aborted')
  173. // Composer recovered; no streaming node lingers. The host settled first
  174. // (awaited above), but the abort frame reaches the browser over SSE — the
  175. // frozen-partial swap is eventually consistent, so poll rather than count.
  176. await expect.poll(() => page.locator('[data-composer-input]').first().isEnabled(), { timeout: 10_000 }).toBe(true)
  177. await expect.poll(() => page.locator('[data-streaming="true"]').count(), { timeout: 10_000 }).toBe(0)
  178. // Golden of the aborted end-state: the prompt bubble plus the frozen
  179. // partial ('partial' is the hang entry's replayed prefix) and no more.
  180. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
  181. await compareOrRefreshGolden(CANCEL_EXPECTED, snapshot, MODE)
  182. const expanded = await captureExpandedTurnProcessAria(
  183. page,
  184. '[class*="centerCol"]',
  185. scaffold!.workspaceCwd,
  186. )
  187. await compareOrRefreshGolden(CANCEL_EXPANDED_EXPECTED, expanded, MODE)
  188. expect(tripwire.pageErrors).toEqual([])
  189. expect(tripwire.warnings).toEqual([])
  190. }, 120_000)
  191. it.skipIf(MODE === 'record')('surfaces a non-retryable AUTH failure without retrying', async () => {
  192. await launch(() => ({
  193. patches: [{ at: 0, entry: { kind: 'throw', chunks: [], message: AUTH_PROVIDER_MESSAGE, code: 'AUTH' } }],
  194. }))
  195. onTestFailed(() => saveFailureShot(page, 'web-e2e-error-auth'))
  196. const { settled } = await sendPrompt()
  197. await settled
  198. expect(turnEndReasons(sessionEvents).at(-1)).toBe('error')
  199. // AUTH is outside llm-retry's retryable set: no retry record.
  200. expect(sessionEvents.filter(e => e.type === 'llm/retry').length).toBe(0)
  201. await expect.poll(() => page.locator('[data-composer-input]').first().isEnabled(), { timeout: 10_000 }).toBe(true)
  202. expect(await page.locator('[data-streaming="true"]').count()).toBe(0)
  203. const errorStatus = page.getByRole('status').filter({ hasText: 'This turn failed' })
  204. await errorStatus.waitFor({ timeout: 10_000 })
  205. expect(await errorStatus.textContent()).toContain('API key is invalid')
  206. expect(await errorStatus.textContent()).toContain('AUTH')
  207. expect(await page.locator('body').textContent()).not.toContain('sk-preview-secret')
  208. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
  209. await compareOrRefreshGolden(ERROR_EXPECTED, snapshot, MODE)
  210. await page.getByRole('tab', { name: 'Trajectory' }).click()
  211. const requestMarker = page.locator('tr[data-request-only="true"]').last()
  212. .getByRole('button', { name: /Request #/ })
  213. await requestMarker.click()
  214. await page.getByText('API key is invalid', { exact: true }).waitFor({ timeout: 10_000 })
  215. expect(await page.locator('body').textContent()).not.toContain('sk-preview-secret')
  216. expect(tripwire.pageErrors).toEqual([])
  217. expect(tripwire.warnings).toEqual([])
  218. }, 120_000)
  219. it.skipIf(MODE === 'record')('keeps a terminal request marker inside the trajectory table', async () => {
  220. await launch(() => ({
  221. patches: [{ at: 0, entry: { kind: 'throw', chunks: [], message: AUTH_PROVIDER_MESSAGE, code: 'AUTH' } }],
  222. }))
  223. const { settled } = await sendPrompt()
  224. await settled
  225. await page.getByRole('tab', { name: 'Trajectory' }).click()
  226. // The boundary marker row itself is a 0-height hairline except at the
  227. // table tail; the marker button is absolutely positioned and stays
  228. // visible, so wait on it directly.
  229. const tailRequest = page.locator('tr[data-request-only="true"]').last()
  230. const requestMarker = tailRequest.getByRole('button', { name: /Request #/ })
  231. await requestMarker.waitFor({ timeout: 10_000 })
  232. const markerWithinTable = await requestMarker.evaluate((element) => {
  233. const marker = element.getBoundingClientRect()
  234. const table = element.closest('table')?.getBoundingClientRect()
  235. if (table === undefined) throw new Error('request marker has no table')
  236. return marker.bottom <= table.bottom
  237. })
  238. expect(markerWithinTable).toBe(true)
  239. expect(tripwire.pageErrors).toEqual([])
  240. expect(tripwire.warnings).toEqual([])
  241. }, 120_000)
  242. it.skipIf(MODE === 'record')('recovers a transient SERVER failure through llm-retry and completes', async () => {
  243. const derived = deriveReplayScript(parseSessionLog(await readFile(FIXTURE, 'utf8')))
  244. expect(derived).toHaveLength(1)
  245. await launch(() => ({
  246. patches: [
  247. { at: 0, entry: { kind: 'throw', chunks: [], message: 'upstream 503', code: 'SERVER' } },
  248. // Append the fixture's own success as the retry attempt — single-
  249. // sourced from the recording, never copied into a committed sidecar.
  250. { at: 1, entry: derived[0]! },
  251. ],
  252. }))
  253. onTestFailed(() => saveFailureShot(page, 'web-e2e-retry'))
  254. // llm-retry backs off ~500ms before the second attempt.
  255. const { settled } = await sendPrompt(60_000)
  256. await settled
  257. expect(turnEndReasons(sessionEvents).at(-1)).toBe('completed')
  258. // The durable retry record proves the second attempt (request/header logs
  259. // only on change, so attempt count is invisible there).
  260. expect(sessionEvents.filter(e => e.type === 'llm/retry').length).toBeGreaterThanOrEqual(1)
  261. await expect.poll(() => page.getByText('event sourcing', { exact: false }).count(), { timeout: 10_000 }).toBeGreaterThan(0)
  262. // Golden of the recovered end-state: the discarded partial stays absent,
  263. // while the settled retry row remains as durable recovery context.
  264. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
  265. await compareOrRefreshGolden(RETRY_EXPECTED, snapshot, MODE)
  266. const expanded = await captureExpandedTurnProcessAria(
  267. page,
  268. '[class*="centerCol"]',
  269. scaffold!.workspaceCwd,
  270. )
  271. await compareOrRefreshGolden(RETRY_EXPANDED_EXPECTED, expanded, MODE)
  272. expect(tripwire.pageErrors).toEqual([])
  273. expect(tripwire.warnings).toEqual([])
  274. }, 120_000)
  275. it.skipIf(MODE === 'record')('surfaces the terminal turn error after transient retries exhaust', async () => {
  276. // A whole-script replacement: three throw entries cover the first request
  277. // plus both budgeted retries (patches cannot reach past the one-call
  278. // derived script). The scenario-owned policy keeps exhaustion fast and
  279. // jitter-free instead of walking the shared default's five backed-off
  280. // attempts.
  281. const failure: ReplayEntry = { kind: 'throw', chunks: [], message: 'upstream 503', code: 'SERVER' }
  282. await launch(
  283. () => [failure, failure, failure],
  284. { mode: 'normal', maxRetries: 2, retryableCodes: ['SERVER'], backoff: { initialDelayMs: 25, maxDelayMs: 50, jitterRatio: 0 } },
  285. )
  286. onTestFailed(() => saveFailureShot(page, 'web-e2e-retry-exhausted'))
  287. const { settled } = await sendPrompt(60_000)
  288. await settled
  289. expect(turnEndReasons(sessionEvents).at(-1)).toBe('error')
  290. expect(sessionEvents.filter(e => e.type === 'llm/retry').length).toBe(2)
  291. await expect.poll(() => page.locator('[data-composer-input]').first().isEnabled(), { timeout: 10_000 }).toBe(true)
  292. expect(await page.locator('[data-streaming="true"]').count()).toBe(0)
  293. // The terminal error row must render even though the turn owns a retry
  294. // chain: exhausted recovery shares the failing turn, so suppressing the
  295. // row by retry history would leave the failure invisible.
  296. const errorStatus = page.getByRole('status').filter({ hasText: 'This turn failed' })
  297. await errorStatus.waitFor({ timeout: 10_000 })
  298. expect(await errorStatus.textContent()).toContain('upstream 503')
  299. expect(await errorStatus.textContent()).toContain('SERVER')
  300. // The settled retry chain stays alongside the terminal row as recovery
  301. // context; the golden pins both.
  302. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
  303. await compareOrRefreshGolden(RETRY_EXHAUSTED_EXPECTED, snapshot, MODE)
  304. expect(tripwire.pageErrors).toEqual([])
  305. expect(tripwire.warnings).toEqual([])
  306. }, 120_000)
  307. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  308. await assertFixtureInventory(SNAPSHOT_DIR, [
  309. 'session.v2.jsonl', 'cancel.expected.md', 'cancel-expanded.expected.md',
  310. 'loading.expected.md', 'running-draft.expected.md', 'error-auth.expected.md',
  311. 'retry.expected.md', 'retry-expanded.expected.md', 'retry-exhausted.expected.md',
  312. ])
  313. })
  314. })