steering.e2e.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. // Web e2e scenario: mid-turn steering over the host wire. The Web UI has no
  2. // steer entry, so the steer is POSTed from the page over the same
  3. // same-origin /api transport the client uses. Everything downstream is
  4. // product: the gateway routes mode:'steer' to Agent.steer, the loop drains
  5. // it at the step boundary into a durable steering/message event, the SSE mux
  6. // pushes it, and the transcript shows the text as a plain bubble (no
  7. // interjection chrome). The question composer supplies the deterministic
  8. // mid-turn window: while ask_user_question blocks, the turn is provably
  9. // running, so record and replay perform the identical steer-then-answer
  10. // sequence with zero timing dependence — and the recorded final reply proves
  11. // the steer reached the MODEL (it obeys an instruction that only the
  12. // steering message carries).
  13. import { readFile } from 'node:fs/promises'
  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 { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  19. import { parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
  20. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  21. import {
  22. assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
  23. launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
  24. } from './scaffold.ts'
  25. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  26. const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/steering', import.meta.url))
  27. const FIXTURE = join(SNAPSHOT_DIR, 'session.jsonl')
  28. // Two goldens for the two distinct states this interaction produces: the
  29. // mid-turn moment (steer ACCEPTED but deliberately invisible — the loop
  30. // drains steering at the step boundary, so no steering text exists while
  31. // the question still blocks the step) and the settled transcript (plain
  32. // bubble in place, final reply obeying it). The pair pins the timing
  33. // semantics visually: if the client ever starts rendering pending steers
  34. // eagerly, the mid-steer golden flips first.
  35. const MID_EXPECTED = join(SNAPSHOT_DIR, 'mid-steer.expected.md')
  36. const SETTLED_EXPECTED = join(SNAPSHOT_DIR, 'settled.expected.md')
  37. const MODE = webSnapshotMode()
  38. const PROMPT = 'Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop.'
  39. const STEER = 'Interjection: include the word BANANA in your final reply.'
  40. /** Concatenated assistant text deltas — the model-visible reply body. */
  41. function assistantText(events: SessionEvent[]): string {
  42. return events
  43. .filter(e => e.type === 'assistant/chunk')
  44. .map((e) => {
  45. const chunk = (e as SessionEvent & { data: { chunk: { type: string; text?: string } } }).data.chunk
  46. return chunk.type === 'text-delta' ? chunk.text ?? '' : ''
  47. })
  48. .join('')
  49. }
  50. describe('web e2e: mid-turn steering lands durably and visibly', () => {
  51. let scaffold: WebScaffold
  52. let browser: Browser
  53. let page: Page
  54. let tripwire: ReturnType<typeof watchConsole>
  55. let liveSessionId: string | undefined
  56. const sessionEvents: SessionEvent[] = []
  57. beforeAll(async () => {
  58. scaffold = await launchWebScaffold(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 })
  59. scaffold.ctx.on('session/event', (session, event) => {
  60. liveSessionId ??= session.id
  61. sessionEvents.push(event)
  62. })
  63. browser = await chromium.launch()
  64. page = await newEnglishPage(browser)
  65. tripwire = watchConsole(page)
  66. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  67. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  68. // Fresh world: connect a Workspace so the composer scenarios start live.
  69. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  70. }, 120_000)
  71. afterAll(async () => {
  72. await browser?.close()
  73. await scaffold?.close()
  74. })
  75. it('steers during the blocked step; the message is logged, rendered, and obeyed', async () => {
  76. onTestFailed(() => saveFailureShot(page, 'web-e2e-steering'))
  77. if (MODE !== 'record') {
  78. // The steer must NOT be a user/message — it lands as steering/message.
  79. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
  80. }
  81. const input = page.locator('textarea').first()
  82. await input.waitFor({ timeout: 10_000 })
  83. const settled = scaffold.whenTurnSettled(MODE === 'record' ? 180_000 : 30_000)
  84. await input.fill(PROMPT)
  85. await input.press('Enter')
  86. // The blocked composer is the mid-turn barrier: its presence proves the
  87. // ask_user_question step is executing, i.e. the turn is running NOW.
  88. const composer = page.locator('[data-question-key]')
  89. await composer.waitFor({ timeout: MODE === 'record' ? 120_000 : 30_000 })
  90. // Steer through the real wire from the page (same envelope + endpoint the
  91. // web client's session.prompt uses). accepted:true is the transport proof.
  92. expect(liveSessionId).toBeDefined()
  93. const reply = await page.evaluate(async ({ sessionId, text }) => {
  94. const response = await fetch('/api/session.prompt', {
  95. method: 'POST',
  96. headers: { 'content-type': 'application/json' },
  97. body: JSON.stringify({
  98. type: 'client-request',
  99. rpcId: crypto.randomUUID(),
  100. method: 'session.prompt',
  101. payload: { sessionId, mode: 'steer', content: [{ type: 'text', text }] },
  102. }),
  103. })
  104. return await response.json() as { result?: { ok?: boolean } }
  105. }, { sessionId: liveSessionId!, text: STEER })
  106. expect(reply.result?.ok).toBe(true)
  107. if (MODE !== 'record') {
  108. // Mid-turn golden: the ACCEPTED steer is durable in the inbox but the
  109. // loop drains steering only at the step boundary, so no steering/message
  110. // exists yet and no steer text renders — the composer still blocks,
  111. // alone. The DOM is stable here (no further SSE frames can arrive until
  112. // the question is answered), making this state capturable.
  113. expect(await page.getByText(STEER, { exact: true }).count()).toBe(0)
  114. expect(await page.getByRole('button', { name: 'Edit queued message' }).count()).toBe(0)
  115. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  116. await compareOrRefreshGolden(MID_EXPECTED, snapshot, MODE)
  117. }
  118. // Answer the composer; the tool result closes the step, the loop drains
  119. // the steer as steering/message, and the steered continuation runs the
  120. // final model call.
  121. await composer.getByRole('radio', { name: 'Yes' }).click()
  122. await composer.getByRole('radio', { name: 'Yes' }).press('Enter')
  123. await settled
  124. if (MODE === 'record') {
  125. const sessionId = await settled
  126. await recordFixture(scaffold, sessionId, FIXTURE)
  127. // Fixture honesty: a recording where the live model ignored the steer
  128. // would replay as a vacuous scenario — reject it and re-record instead.
  129. const recorded = parseSessionLog(await readFile(FIXTURE, 'utf8'))
  130. expect(recorded.filter(e => e.type === 'steering/message')).toHaveLength(1)
  131. expect(assistantText(recorded)).toContain('BANANA')
  132. return
  133. }
  134. // Durable: exactly one steering/message, inside turn 1, carrying the text.
  135. const steerEvents = sessionEvents.filter(e => e.type === 'steering/message')
  136. expect(steerEvents).toHaveLength(1)
  137. expect((steerEvents[0] as SessionEvent & { data: { turn: number } }).data.turn).toBe(1)
  138. expect(JSON.stringify(steerEvents[0])).toContain('BANANA')
  139. const turnEnds = sessionEvents.filter(e => e.type === 'turn/end')
  140. expect(turnEnds).toHaveLength(1)
  141. expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed')
  142. // Visible: the plain steering bubble plus the reply that obeys it
  143. // (steer text + final reply each contain the marker word).
  144. await expect.poll(() => page.getByText(STEER, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  145. await expect.poll(() => page.getByText('BANANA', { exact: false }).count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(2)
  146. expect(await page.locator('[data-question-key]').count()).toBe(0)
  147. // Settled golden: steer text between the question round trip and the
  148. // obeying reply, composer takeover gone.
  149. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  150. await compareOrRefreshGolden(SETTLED_EXPECTED, snapshot, MODE)
  151. expect(tripwire.pageErrors).toEqual([])
  152. expect(tripwire.warnings).toEqual([])
  153. }, 200_000)
  154. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  155. await assertFixtureInventory(SNAPSHOT_DIR, ['session.jsonl', 'mid-steer.expected.md', 'settled.expected.md'])
  156. })
  157. })