steering.e2e.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. // Web e2e scenario: mid-turn steering, end to end. The composer locks while a
  2. // turn runs, so the product UI has no steering gesture yet — the steer is
  3. // POSTed from the page itself over the same same-origin /api transport the
  4. // client uses (TODO(web-steer-composer): drive this through a composer
  5. // gesture once one exists). Everything downstream is product: the gateway
  6. // routes mode:'steer' to Agent.steer, the loop drains it at the step
  7. // boundary into a durable steering/message event, the SSE mux pushes it, and
  8. // the transcript renders the badged interjection bubble. The question
  9. // composer supplies the deterministic mid-turn window: while ask_user_question
  10. // blocks, the turn is provably running, so record and replay perform the
  11. // identical steer-then-answer sequence with zero timing dependence — and the
  12. // recorded final reply proves the steer reached the MODEL (it obeys an
  13. // instruction that only the steering message carries).
  14. import { readFile } from 'node:fs/promises'
  15. import { fileURLToPath } from 'node:url'
  16. import { join } from 'node:path'
  17. import type { Browser, Page } from 'playwright'
  18. import { chromium } from 'playwright'
  19. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  20. import { parseSessionLog } 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/steering', import.meta.url))
  28. const FIXTURE = join(SNAPSHOT_DIR, 'session.jsonl')
  29. // Two goldens for the two distinct states this interaction produces: the
  30. // mid-turn moment (steer ACCEPTED but deliberately invisible — the loop
  31. // drains steering at the step boundary, so no interjection bubble exists
  32. // while the question still blocks the step) and the settled transcript
  33. // (badged bubble in place, final reply obeying it). The pair pins the
  34. // timing semantics visually: if the client ever starts rendering pending
  35. // steers eagerly, the mid-steer golden flips first.
  36. const MID_EXPECTED = join(SNAPSHOT_DIR, 'mid-steer.expected.md')
  37. const SETTLED_EXPECTED = join(SNAPSHOT_DIR, 'settled.expected.md')
  38. const MODE = webSnapshotMode()
  39. 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.'
  40. const STEER = 'Interjection: include the word BANANA in your final reply.'
  41. /** Concatenated assistant text deltas — the model-visible reply body. */
  42. function assistantText(events: SessionEvent[]): string {
  43. return events
  44. .filter(e => e.type === 'assistant/chunk')
  45. .map((e) => {
  46. const chunk = (e as SessionEvent & { data: { chunk: { type: string; text?: string } } }).data.chunk
  47. return chunk.type === 'text-delta' ? chunk.text ?? '' : ''
  48. })
  49. .join('')
  50. }
  51. describe('web e2e: mid-turn steering lands durably and visibly', () => {
  52. let scaffold: WebScaffold
  53. let browser: Browser
  54. let page: Page
  55. let tripwire: ReturnType<typeof watchConsole>
  56. let liveSessionId: string | undefined
  57. const sessionEvents: SessionEvent[] = []
  58. beforeAll(async () => {
  59. scaffold = await launchWebScaffold(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 })
  60. scaffold.ctx.on('session/event', (session, event) => {
  61. liveSessionId ??= session.id
  62. sessionEvents.push(event)
  63. })
  64. browser = await chromium.launch()
  65. page = await browser.newPage({ viewport: { width: 1680, height: 1000 } })
  66. tripwire = watchConsole(page)
  67. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  68. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  69. // Fresh world: connect a Workspace so the composer scenarios start live.
  70. await connectFreshWorkspace(page)
  71. }, 120_000)
  72. afterAll(async () => {
  73. await browser?.close()
  74. await scaffold?.close()
  75. })
  76. it('steers during the blocked step; the interjection is logged, rendered, and obeyed', async () => {
  77. onTestFailed(() => saveFailureShot(page, 'web-e2e-steering'))
  78. if (MODE !== 'record') {
  79. // The steer must NOT be a user/message — it lands as steering/message.
  80. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
  81. }
  82. const input = page.locator('textarea').first()
  83. await input.waitFor({ timeout: 10_000 })
  84. const settled = scaffold.whenTurnSettled(MODE === 'record' ? 180_000 : 30_000)
  85. await input.fill(PROMPT)
  86. await input.press('Enter')
  87. // The blocked composer is the mid-turn barrier: its presence proves the
  88. // ask_user_question step is executing, i.e. the turn is running NOW.
  89. const composer = page.locator('[data-question-key]')
  90. await composer.waitFor({ timeout: MODE === 'record' ? 120_000 : 30_000 })
  91. // Steer through the real wire from the page (same envelope + endpoint the
  92. // web client's session.prompt uses). accepted:true is the transport proof.
  93. expect(liveSessionId).toBeDefined()
  94. const reply = await page.evaluate(async ({ sessionId, text }) => {
  95. const response = await fetch('/api/session.prompt', {
  96. method: 'POST',
  97. headers: { 'content-type': 'application/json' },
  98. body: JSON.stringify({
  99. type: 'client-request',
  100. rpcId: crypto.randomUUID(),
  101. method: 'session.prompt',
  102. payload: { sessionId, mode: 'steer', content: [{ type: 'text', text }] },
  103. }),
  104. })
  105. return await response.json() as { result?: { ok?: boolean } }
  106. }, { sessionId: liveSessionId!, text: STEER })
  107. expect(reply.result?.ok).toBe(true)
  108. if (MODE !== 'record') {
  109. // Mid-turn golden: the ACCEPTED steer is durable in the inbox but the
  110. // loop drains steering only at the step boundary, so no steering/message
  111. // exists yet and no interjection bubble renders — the composer still
  112. // blocks, alone. The DOM is stable here (no further SSE frames can
  113. // arrive until the question is answered), making this state capturable.
  114. expect(await page.getByText('插话').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 badged interjection bubble plus the reply that obeys it
  143. // (steer text + final reply each contain the marker word).
  144. await expect.poll(() => page.getByText('插话').count(), { timeout: 15_000 }).toBe(1)
  145. await expect.poll(() => page.getByText('Interjection:', { exact: false }).count(), { timeout: 10_000 }).toBe(1)
  146. await expect.poll(() => page.getByText('BANANA', { exact: false }).count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(2)
  147. expect(await page.locator('[data-question-key]').count()).toBe(0)
  148. // Settled golden: badge + interjection between the question round trip
  149. // and the obeying reply, composer takeover gone.
  150. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  151. await compareOrRefreshGolden(SETTLED_EXPECTED, snapshot, MODE)
  152. expect(tripwire.pageErrors).toEqual([])
  153. expect(tripwire.warnings).toEqual([])
  154. }, 200_000)
  155. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  156. await assertFixtureInventory(SNAPSHOT_DIR, ['session.jsonl', 'mid-steer.expected.md', 'settled.expected.md'])
  157. })
  158. })