steering.e2e.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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 user/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. /** Claimed user messages whose payload contains the exact scenario text. */
  45. function claimedMessages(events: readonly SessionEvent[], text: string): SessionEvent<'user/message'>[] {
  46. return events.filter((event): event is SessionEvent<'user/message'> =>
  47. event.type === 'user/message' && JSON.stringify(event.data.content).includes(text))
  48. }
  49. describe('web e2e: mid-turn steering lands durably and visibly', () => {
  50. let scaffold: WebScaffold
  51. let browser: Browser
  52. let page: Page
  53. let tripwire: ReturnType<typeof watchConsole>
  54. const sessionEvents: SessionEvent[] = []
  55. beforeAll(async () => {
  56. scaffold = await launchWebScaffold(MODE === 'record'
  57. ? {}
  58. : { replayFixture: FIXTURE, paceMs: REPLAY_PACE_MS })
  59. scaffold.ctx.on('session/event', (_session, event) => { sessionEvents.push(event) })
  60. browser = await chromium.launch()
  61. page = await newEnglishPage(browser)
  62. tripwire = watchConsole(page)
  63. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  64. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  65. // Fresh world: connect a Workspace so the composer scenarios start live.
  66. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  67. }, 120_000)
  68. afterAll(async () => {
  69. await browser?.close()
  70. await scaffold?.close()
  71. })
  72. it('strictly steers one queued row; the interjection is logged, rendered, and obeyed', async () => {
  73. onTestFailed(() => saveFailureShot(page, 'web-e2e-steering'))
  74. if (MODE !== 'record') {
  75. // The steer lands as a durable user/message, so the inventory holds
  76. // both the opening prompt and the later same-turn steer.
  77. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT, STEER])
  78. }
  79. const input = page.locator('textarea').first()
  80. await input.waitFor({ timeout: 10_000 })
  81. const settled = scaffold.whenTurnSettled(MODE === 'record' ? 180_000 : 30_000)
  82. await input.fill(PROMPT)
  83. await input.press('Enter')
  84. // Enter remains the Queue gesture. The row action then atomically moves
  85. // this exact occurrence into the current turn's steering outbox.
  86. await input.fill(STEER)
  87. await input.press('Enter')
  88. const queued = page.getByText(STEER, { exact: true })
  89. await queued.waitFor({ timeout: 10_000 })
  90. const queuedRow = page.getByRole('listitem').filter({ hasText: STEER })
  91. const steerButton = queuedRow.getByRole('button', { name: 'Steer queued message' })
  92. await expect.poll(() => steerButton.isEnabled(), { timeout: 10_000 }).toBe(true)
  93. await steerButton.click({ timeout: 10_000 })
  94. const pendingSteering = page.locator('[data-pending-steering]').filter({ hasText: STEER })
  95. // A timeout while the Queue row remains means strict steer lost to a
  96. // closing window (`steer-unavailable`); inspect replay pacing first.
  97. await pendingSteering.waitFor({ timeout: 10_000 })
  98. // The blocked composer keeps steering pending long enough to observe the
  99. // Host-authoritative mirror before the loop admits it durably.
  100. const composer = page.locator('[data-question-key]')
  101. await composer.waitFor({ timeout: MODE === 'record' ? 120_000 : 30_000 })
  102. if (MODE !== 'record') {
  103. expect(await page.getByText(STEER, { exact: true }).count()).toBe(1)
  104. expect(await pendingSteering.count()).toBe(1)
  105. expect(await page.getByRole('button', { name: 'Edit queued message' }).count()).toBe(0)
  106. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  107. await compareOrRefreshGolden(MID_EXPECTED, snapshot, MODE)
  108. }
  109. // Answer the composer; the tool result closes the step, the loop drains
  110. // the steer as user/message, and the steered continuation runs the
  111. // final model call.
  112. await composer.getByRole('radio', { name: 'Yes' }).click()
  113. await composer.getByRole('radio', { name: 'Yes' }).press('Enter')
  114. await settled
  115. if (MODE === 'record') {
  116. const sessionId = await settled
  117. await recordFixture(scaffold, sessionId, FIXTURE)
  118. // Fixture honesty: a recording where the live model ignored the steer
  119. // would replay as a vacuous scenario — reject it and re-record instead.
  120. const recorded = parseSessionLog(await readFile(FIXTURE, 'utf8'))
  121. expect(claimedMessages(recorded, STEER)).toHaveLength(1)
  122. expect(assistantText(recorded)).toContain('BANANA')
  123. return
  124. }
  125. // Durable: exactly one claimed user/message carrying the steering text.
  126. const steerEvents = claimedMessages(sessionEvents, STEER)
  127. expect(steerEvents).toHaveLength(1)
  128. expect(JSON.stringify(steerEvents[0])).toContain('BANANA')
  129. const turnEnds = sessionEvents.filter(e => e.type === 'turn/end')
  130. expect(turnEnds).toHaveLength(1)
  131. expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed')
  132. // Visible: the plain steering bubble plus the reply that obeys it
  133. // (steer text + final reply each contain the marker word).
  134. await expect.poll(() => page.getByText(STEER, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  135. expect(await pendingSteering.count()).toBe(0)
  136. await expect.poll(() => page.getByText('BANANA', { exact: false }).count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(2)
  137. expect(await page.locator('[data-question-key]').count()).toBe(0)
  138. // Settled golden: steer text between the question round trip and the
  139. // obeying reply, composer takeover gone.
  140. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  141. await compareOrRefreshGolden(SETTLED_EXPECTED, snapshot, MODE)
  142. expect(tripwire.pageErrors).toEqual([])
  143. expect(tripwire.warnings).toEqual([])
  144. }, 200_000)
  145. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  146. await assertFixtureInventory(SNAPSHOT_DIR, ['session.jsonl', 'mid-steer.expected.md', 'settled.expected.md'])
  147. })
  148. })
  149. describe('web e2e: composer shortcut steers directly', () => {
  150. let scaffold: WebScaffold
  151. let browser: Browser
  152. let page: Page
  153. let tripwire: ReturnType<typeof watchConsole>
  154. const sessionEvents: SessionEvent[] = []
  155. beforeAll(async () => {
  156. scaffold = await launchWebScaffold({ replayFixture: FIXTURE, paceMs: REPLAY_PACE_MS })
  157. scaffold.ctx.on('session/event', (_session, event) => { sessionEvents.push(event) })
  158. browser = await chromium.launch()
  159. page = await newEnglishPage(browser)
  160. tripwire = watchConsole(page)
  161. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  162. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  163. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  164. }, 120_000)
  165. afterAll(async () => {
  166. await browser?.close()
  167. await scaffold?.close()
  168. })
  169. it.skipIf(MODE === 'record')('uses Cmd+Enter without creating a Queue row', async () => {
  170. onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-steering'))
  171. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT, STEER])
  172. const input = page.locator('textarea').first()
  173. await input.waitFor({ timeout: 10_000 })
  174. const settled = scaffold.whenTurnSettled(30_000)
  175. await input.fill(PROMPT)
  176. await input.press('Enter')
  177. await page.getByRole('button', { name: 'Stop generating' }).waitFor({ timeout: 10_000 })
  178. await input.fill(STEER)
  179. await input.press('Meta+Enter')
  180. await expect.poll(() => input.inputValue(), { timeout: 5_000 }).toBe('')
  181. expect(await page.locator('[data-queue-dock]').count()).toBe(0)
  182. const composer = page.locator('[data-question-key]')
  183. await composer.waitFor({ timeout: 30_000 })
  184. const pendingSteering = page.locator('[data-pending-steering]').filter({ hasText: STEER })
  185. await pendingSteering.waitFor({ timeout: 10_000 })
  186. await composer.getByRole('radio', { name: 'Yes' }).click()
  187. await composer.getByRole('radio', { name: 'Yes' }).press('Enter')
  188. await settled
  189. const steerEvents = claimedMessages(sessionEvents, STEER)
  190. expect(steerEvents).toHaveLength(1)
  191. await expect.poll(() => page.getByText(STEER, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  192. expect(await pendingSteering.count()).toBe(0)
  193. await expect.poll(() => page.getByText('BANANA', { exact: false }).count(), { timeout: 10_000 })
  194. .toBeGreaterThanOrEqual(2)
  195. expect(tripwire.pageErrors).toEqual([])
  196. expect(tripwire.warnings).toEqual([])
  197. }, 90_000)
  198. })
  199. describe('web e2e: composer shortcut follows the swapped busy behavior', () => {
  200. let scaffold: WebScaffold
  201. let browser: Browser
  202. let page: Page
  203. let tripwire: ReturnType<typeof watchConsole>
  204. const sessionEvents: SessionEvent[] = []
  205. beforeAll(async () => {
  206. scaffold = await launchWebScaffold({ replayFixture: FIXTURE, paceMs: REPLAY_PACE_MS })
  207. scaffold.ctx.on('session/event', (_session, event) => { sessionEvents.push(event) })
  208. browser = await chromium.launch()
  209. page = await newEnglishPage(browser)
  210. tripwire = watchConsole(page)
  211. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  212. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  213. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  214. }, 120_000)
  215. afterAll(async () => {
  216. await browser?.close()
  217. await scaffold?.close()
  218. })
  219. it.skipIf(MODE === 'record')('queues Cmd+Enter when plain Enter is configured to Steer', async () => {
  220. onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-swapped-shortcut'))
  221. await page.getByRole('button', { name: 'Settings', exact: true }).click()
  222. const dialog = page.getByRole('dialog', { name: 'Settings' })
  223. await dialog.getByRole('button', { name: 'Queue' }).click()
  224. await page.getByRole('menuitem', { name: 'Steer' }).click()
  225. await dialog.getByRole('button', { name: 'Steer' }).waitFor({ timeout: 10_000 })
  226. await page.keyboard.press('Escape')
  227. const input = page.locator('textarea').first()
  228. const settled = scaffold.whenTurnSettled(30_000)
  229. await input.fill(PROMPT)
  230. await input.press('Enter')
  231. await page.getByRole('button', { name: 'Stop generating' }).waitFor({ timeout: 10_000 })
  232. const queuedText = 'Queued by the complementary Cmd+Enter shortcut.'
  233. await input.fill(queuedText)
  234. await input.press('Meta+Enter')
  235. const queuedRow = page.locator('[data-queue-dock]').getByRole('listitem').filter({ hasText: queuedText })
  236. await queuedRow.getByText(queuedText, { exact: true }).waitFor({ timeout: 10_000 })
  237. expect(await page.locator('[data-pending-steering]').filter({ hasText: queuedText }).count()).toBe(0)
  238. expect(claimedMessages(sessionEvents, queuedText)).toHaveLength(0)
  239. // Remove the asserted Queue row, then finish the recorded question turn
  240. // so replay teardown still proves that every fixture call was consumed.
  241. await queuedRow.getByRole('button', { name: 'Remove queued message' }).click()
  242. const composer = page.locator('[data-question-key]')
  243. await composer.waitFor({ timeout: 30_000 })
  244. await composer.getByRole('radio', { name: 'Yes' }).click()
  245. await composer.getByRole('radio', { name: 'Yes' }).press('Enter')
  246. await settled
  247. expect(tripwire.pageErrors).toEqual([])
  248. expect(tripwire.warnings).toEqual([])
  249. }, 90_000)
  250. })