steering.e2e.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. // Web e2e scenarios for both steering entry points: QueueDock strictly
  2. // transfers one queued occurrence, while the complementary composer gestures
  3. // choose Queue or Steer. The question tool supplies a deterministic pending-
  4. // steering snapshot before the step can drain.
  5. import { readFile } from 'node:fs/promises'
  6. import { fileURLToPath } from 'node:url'
  7. import { join } from 'node:path'
  8. import type { Browser, Page } from 'playwright'
  9. import { chromium } from 'playwright'
  10. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  11. import { parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
  12. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  13. import {
  14. assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
  15. launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
  16. } from './scaffold.ts'
  17. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  18. const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/steering', import.meta.url))
  19. const FIXTURE = join(SNAPSHOT_DIR, 'session.jsonl')
  20. // Two goldens pin the transient Host projection and its durable handoff: the
  21. // mid-turn state renders accepted steering from session/queue while the
  22. // question blocks admission, then the settled state renders the same message
  23. // from steering/message beside the reply that obeys it.
  24. const MID_EXPECTED = join(SNAPSHOT_DIR, 'mid-steer.expected.md')
  25. const SETTLED_EXPECTED = join(SNAPSHOT_DIR, 'settled.expected.md')
  26. const MODE = webSnapshotMode()
  27. // The question composer replaces the textarea, so fill → Queue row → Steer
  28. // must finish inside the first replay chunk window. At 15 ms that window is
  29. // shorter than Playwright's round trips; 100 ms supplies test-only headroom,
  30. // while larger values lengthen all three replay scenarios linearly.
  31. const REPLAY_PACE_MS = 100
  32. 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.'
  33. const STEER = 'Interjection: include the word BANANA in your final reply.'
  34. /** Concatenated assistant text deltas — the model-visible reply body. */
  35. function assistantText(events: SessionEvent[]): string {
  36. return events
  37. .filter(e => e.type === 'assistant/chunk')
  38. .map((e) => {
  39. const chunk = (e as SessionEvent & { data: { chunk: { type: string; text?: string } } }).data.chunk
  40. return chunk.type === 'text-delta' ? chunk.text ?? '' : ''
  41. })
  42. .join('')
  43. }
  44. describe('web e2e: mid-turn steering lands durably and visibly', () => {
  45. let scaffold: WebScaffold
  46. let browser: Browser
  47. let page: Page
  48. let tripwire: ReturnType<typeof watchConsole>
  49. const sessionEvents: SessionEvent[] = []
  50. beforeAll(async () => {
  51. scaffold = await launchWebScaffold(MODE === 'record'
  52. ? {}
  53. : { replayFixture: FIXTURE, paceMs: REPLAY_PACE_MS })
  54. scaffold.ctx.on('session/event', (_session, event) => { sessionEvents.push(event) })
  55. browser = await chromium.launch()
  56. page = await newEnglishPage(browser)
  57. tripwire = watchConsole(page)
  58. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  59. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  60. // Fresh world: connect a Workspace so the composer scenarios start live.
  61. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  62. }, 120_000)
  63. afterAll(async () => {
  64. await browser?.close()
  65. await scaffold?.close()
  66. })
  67. it('strictly steers one queued row; the interjection is logged, rendered, and obeyed', async () => {
  68. onTestFailed(() => saveFailureShot(page, 'web-e2e-steering'))
  69. if (MODE !== 'record') {
  70. // The steer must NOT be a user/message — it lands as steering/message.
  71. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
  72. }
  73. const input = page.locator('textarea').first()
  74. await input.waitFor({ timeout: 10_000 })
  75. const settled = scaffold.whenTurnSettled(MODE === 'record' ? 180_000 : 30_000)
  76. await input.fill(PROMPT)
  77. await input.press('Enter')
  78. // Enter remains the Queue gesture. The row action then atomically moves
  79. // this exact occurrence into the current turn's steering outbox.
  80. await input.fill(STEER)
  81. await input.press('Enter')
  82. const queued = page.getByText(STEER, { exact: true })
  83. await queued.waitFor({ timeout: 10_000 })
  84. const queuedRow = page.getByRole('listitem').filter({ hasText: STEER })
  85. const steerButton = queuedRow.getByRole('button', { name: 'Steer queued message' })
  86. await expect.poll(() => steerButton.isEnabled(), { timeout: 10_000 }).toBe(true)
  87. await steerButton.click({ timeout: 10_000 })
  88. const pendingSteering = page.locator('[data-pending-steering]').filter({ hasText: STEER })
  89. // A timeout while the Queue row remains means strict steer lost to a
  90. // closing window (`steer-unavailable`); inspect replay pacing first.
  91. await pendingSteering.waitFor({ timeout: 10_000 })
  92. // The blocked composer keeps steering pending long enough to observe the
  93. // Host-authoritative mirror before the loop admits it durably.
  94. const composer = page.locator('[data-question-key]')
  95. await composer.waitFor({ timeout: MODE === 'record' ? 120_000 : 30_000 })
  96. if (MODE !== 'record') {
  97. expect(await page.getByText(STEER, { exact: true }).count()).toBe(1)
  98. expect(await pendingSteering.count()).toBe(1)
  99. expect(await page.getByRole('button', { name: 'Edit queued message' }).count()).toBe(0)
  100. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  101. await compareOrRefreshGolden(MID_EXPECTED, snapshot, MODE)
  102. }
  103. // Answer the composer; the tool result closes the step, the loop drains
  104. // the steer as steering/message, and the steered continuation runs the
  105. // final model call.
  106. await composer.getByRole('radio', { name: 'Yes' }).click()
  107. await composer.getByRole('radio', { name: 'Yes' }).press('Enter')
  108. await settled
  109. if (MODE === 'record') {
  110. const sessionId = await settled
  111. await recordFixture(scaffold, sessionId, FIXTURE)
  112. // Fixture honesty: a recording where the live model ignored the steer
  113. // would replay as a vacuous scenario — reject it and re-record instead.
  114. const recorded = parseSessionLog(await readFile(FIXTURE, 'utf8'))
  115. expect(recorded.filter(e => e.type === 'steering/message')).toHaveLength(1)
  116. expect(assistantText(recorded)).toContain('BANANA')
  117. return
  118. }
  119. // Durable: exactly one steering/message, inside turn 1, carrying the text.
  120. const steerEvents = sessionEvents.filter(e => e.type === 'steering/message')
  121. expect(steerEvents).toHaveLength(1)
  122. expect((steerEvents[0] as SessionEvent & { data: { turn: number } }).data.turn).toBe(1)
  123. expect(JSON.stringify(steerEvents[0])).toContain('BANANA')
  124. const turnEnds = sessionEvents.filter(e => e.type === 'turn/end')
  125. expect(turnEnds).toHaveLength(1)
  126. expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed')
  127. // Visible: the plain steering bubble plus the reply that obeys it
  128. // (steer text + final reply each contain the marker word).
  129. await expect.poll(() => page.getByText(STEER, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  130. expect(await pendingSteering.count()).toBe(0)
  131. await expect.poll(() => page.getByText('BANANA', { exact: false }).count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(2)
  132. expect(await page.locator('[data-question-key]').count()).toBe(0)
  133. // Settled golden: steer text between the question round trip and the
  134. // obeying reply, composer takeover gone.
  135. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  136. await compareOrRefreshGolden(SETTLED_EXPECTED, snapshot, MODE)
  137. expect(tripwire.pageErrors).toEqual([])
  138. expect(tripwire.warnings).toEqual([])
  139. }, 200_000)
  140. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  141. await assertFixtureInventory(SNAPSHOT_DIR, ['session.jsonl', 'mid-steer.expected.md', 'settled.expected.md'])
  142. })
  143. })
  144. describe('web e2e: composer shortcut steers directly', () => {
  145. let scaffold: WebScaffold
  146. let browser: Browser
  147. let page: Page
  148. let tripwire: ReturnType<typeof watchConsole>
  149. const sessionEvents: SessionEvent[] = []
  150. beforeAll(async () => {
  151. scaffold = await launchWebScaffold({ replayFixture: FIXTURE, paceMs: REPLAY_PACE_MS })
  152. scaffold.ctx.on('session/event', (_session, event) => { sessionEvents.push(event) })
  153. browser = await chromium.launch()
  154. page = await newEnglishPage(browser)
  155. tripwire = watchConsole(page)
  156. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  157. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  158. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  159. }, 120_000)
  160. afterAll(async () => {
  161. await browser?.close()
  162. await scaffold?.close()
  163. })
  164. it.skipIf(MODE === 'record')('uses Cmd+Enter without creating a Queue row', async () => {
  165. onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-steering'))
  166. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
  167. const input = page.locator('textarea').first()
  168. await input.waitFor({ timeout: 10_000 })
  169. const settled = scaffold.whenTurnSettled(30_000)
  170. await input.fill(PROMPT)
  171. await input.press('Enter')
  172. await page.getByRole('button', { name: 'Stop generating' }).waitFor({ timeout: 10_000 })
  173. await input.fill(STEER)
  174. await input.press('Meta+Enter')
  175. await expect.poll(() => input.inputValue(), { timeout: 5_000 }).toBe('')
  176. expect(await page.locator('[data-queue-dock]').count()).toBe(0)
  177. const composer = page.locator('[data-question-key]')
  178. await composer.waitFor({ timeout: 30_000 })
  179. const pendingSteering = page.locator('[data-pending-steering]').filter({ hasText: STEER })
  180. await pendingSteering.waitFor({ timeout: 10_000 })
  181. await composer.getByRole('radio', { name: 'Yes' }).click()
  182. await composer.getByRole('radio', { name: 'Yes' }).press('Enter')
  183. await settled
  184. const steerEvents = sessionEvents.filter(event => event.type === 'steering/message')
  185. expect(steerEvents).toHaveLength(1)
  186. expect((steerEvents[0] as SessionEvent & { data: { turn: number } }).data.turn).toBe(1)
  187. await expect.poll(() => page.getByText(STEER, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  188. expect(await pendingSteering.count()).toBe(0)
  189. await expect.poll(() => page.getByText('BANANA', { exact: false }).count(), { timeout: 10_000 })
  190. .toBeGreaterThanOrEqual(2)
  191. expect(tripwire.pageErrors).toEqual([])
  192. expect(tripwire.warnings).toEqual([])
  193. }, 90_000)
  194. })
  195. describe('web e2e: composer shortcut follows the swapped busy behavior', () => {
  196. let scaffold: WebScaffold
  197. let browser: Browser
  198. let page: Page
  199. let tripwire: ReturnType<typeof watchConsole>
  200. const sessionEvents: SessionEvent[] = []
  201. beforeAll(async () => {
  202. scaffold = await launchWebScaffold({ replayFixture: FIXTURE, paceMs: REPLAY_PACE_MS })
  203. scaffold.ctx.on('session/event', (_session, event) => { sessionEvents.push(event) })
  204. browser = await chromium.launch()
  205. page = await newEnglishPage(browser)
  206. tripwire = watchConsole(page)
  207. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  208. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  209. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  210. }, 120_000)
  211. afterAll(async () => {
  212. await browser?.close()
  213. await scaffold?.close()
  214. })
  215. it.skipIf(MODE === 'record')('queues Cmd+Enter when plain Enter is configured to Steer', async () => {
  216. onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-swapped-shortcut'))
  217. await page.getByRole('button', { name: 'Settings', exact: true }).click()
  218. const dialog = page.getByRole('dialog', { name: 'Settings' })
  219. await dialog.getByRole('button', { name: 'Queue' }).click()
  220. await page.getByRole('menuitem', { name: 'Steer' }).click()
  221. await dialog.getByRole('button', { name: 'Steer' }).waitFor({ timeout: 10_000 })
  222. await page.keyboard.press('Escape')
  223. const input = page.locator('textarea').first()
  224. const settled = scaffold.whenTurnSettled(30_000)
  225. await input.fill(PROMPT)
  226. await input.press('Enter')
  227. await page.getByRole('button', { name: 'Stop generating' }).waitFor({ timeout: 10_000 })
  228. const queuedText = 'Queued by the complementary Cmd+Enter shortcut.'
  229. await input.fill(queuedText)
  230. await input.press('Meta+Enter')
  231. const queuedRow = page.locator('[data-queue-dock]').getByRole('listitem').filter({ hasText: queuedText })
  232. await queuedRow.getByText(queuedText, { exact: true }).waitFor({ timeout: 10_000 })
  233. expect(await page.locator('[data-pending-steering]').filter({ hasText: queuedText }).count()).toBe(0)
  234. expect(sessionEvents.filter(event => event.type === 'steering/message')).toHaveLength(0)
  235. // Remove the asserted Queue row, then finish the recorded question turn
  236. // so replay teardown still proves that every fixture call was consumed.
  237. await queuedRow.getByRole('button', { name: 'Remove queued message' }).click()
  238. const composer = page.locator('[data-question-key]')
  239. await composer.waitFor({ timeout: 30_000 })
  240. await composer.getByRole('radio', { name: 'Yes' }).click()
  241. await composer.getByRole('radio', { name: 'Yes' }).press('Enter')
  242. await settled
  243. expect(tripwire.pageErrors).toEqual([])
  244. expect(tripwire.warnings).toEqual([])
  245. }, 90_000)
  246. })