steering.e2e.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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 the Session control 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; 50 ms supplies test-only headroom,
  30. // while larger values lengthen all three replay scenarios linearly.
  31. const REPLAY_PACE_MS = 50
  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. // Empty-draft flush scenario: an override-only fixture. The whole-script
  35. // replacement answers both model calls of a FRESH session (no recorded
  36. // session.jsonl exists — call 0 keeps the turn open with a question-tool
  37. // call, call 1 is the reply after both steerings drain).
  38. const STEER_ALL_DIR = fileURLToPath(new URL('./snapshots/steer-all', import.meta.url))
  39. const STEER_ALL_FIXTURE = join(STEER_ALL_DIR, 'session.jsonl')
  40. const STEER_ALL_OVERRIDE = join(STEER_ALL_DIR, 'replay.override.json')
  41. const STEER_ALL_MID = join(STEER_ALL_DIR, 'mid-steer.expected.md')
  42. const STEER_ALL_SETTLED = join(STEER_ALL_DIR, 'settled.expected.md')
  43. const STEER_ONE = 'Interjection: include the word BANANA in your final reply.'
  44. const STEER_TWO = 'Interjection: include the word ORANGE in your final reply.'
  45. /** Concatenated assistant text deltas — the model-visible reply body. */
  46. function assistantText(events: SessionEvent[]): string {
  47. return events
  48. .filter(e => e.type === 'assistant/chunk')
  49. .map((e) => {
  50. const chunk = (e as SessionEvent & { data: { chunk: { type: string; text?: string } } }).data.chunk
  51. return chunk.type === 'text-delta' ? chunk.text ?? '' : ''
  52. })
  53. .join('')
  54. }
  55. /** Claimed user messages whose payload contains the exact scenario text. */
  56. function claimedMessages(events: readonly SessionEvent[], text: string): SessionEvent<'user/message'>[] {
  57. return events.filter((event): event is SessionEvent<'user/message'> =>
  58. event.type === 'user/message' && JSON.stringify(event.data.content).includes(text))
  59. }
  60. describe('web e2e: mid-turn steering lands durably and visibly', () => {
  61. let scaffold: WebScaffold
  62. let browser: Browser
  63. let page: Page
  64. let tripwire: ReturnType<typeof watchConsole>
  65. const sessionEvents: SessionEvent[] = []
  66. beforeAll(async () => {
  67. scaffold = await launchWebScaffold(MODE === 'record'
  68. ? {}
  69. : { replayFixture: FIXTURE, paceMs: REPLAY_PACE_MS })
  70. scaffold.ctx.on('session/event', (_session, event) => { sessionEvents.push(event) })
  71. browser = await chromium.launch()
  72. page = await newEnglishPage(browser)
  73. tripwire = watchConsole(page)
  74. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  75. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  76. // Fresh world: connect a Workspace so the composer scenarios start live.
  77. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  78. }, 120_000)
  79. afterAll(async () => {
  80. await browser?.close()
  81. await scaffold?.close()
  82. })
  83. it('strictly steers one queued row; the interjection is logged, rendered, and obeyed', async () => {
  84. onTestFailed(() => saveFailureShot(page, 'web-e2e-steering'))
  85. if (MODE !== 'record') {
  86. // The steer lands as a durable user/message, so the inventory holds
  87. // both the opening prompt and the later same-turn steer.
  88. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT, STEER])
  89. }
  90. const input = page.locator('textarea').first()
  91. await input.waitFor({ timeout: 10_000 })
  92. const settled = scaffold.whenTurnSettled(MODE === 'record' ? 180_000 : 30_000)
  93. await input.fill(PROMPT)
  94. await input.press('Enter')
  95. // Enter remains the Queue gesture. The row action then atomically moves
  96. // this exact occurrence into the current turn's steering outbox.
  97. await input.fill(STEER)
  98. await input.press('Enter')
  99. const queuedRow = page.getByRole('listitem').filter({ hasText: STEER })
  100. await queuedRow.waitFor({ timeout: 10_000 })
  101. const steerButton = queuedRow.getByRole('button', { name: 'Steer queued message' })
  102. await expect.poll(() => steerButton.isEnabled(), { timeout: 10_000 }).toBe(true)
  103. await steerButton.click({ timeout: 10_000 })
  104. const pendingSteering = page.locator('[data-pending-steering]').filter({ hasText: STEER })
  105. // A timeout while the Queue row remains means strict steer lost to a
  106. // closing window (`steer-unavailable`); inspect replay pacing first.
  107. await pendingSteering.waitFor({ timeout: 10_000 })
  108. // The blocked composer keeps steering pending long enough to observe the
  109. // Host-authoritative mirror before the loop admits it durably.
  110. const composer = page.locator('[data-question-key]')
  111. await composer.waitFor({ timeout: MODE === 'record' ? 120_000 : 30_000 })
  112. if (MODE !== 'record') {
  113. expect(await page.getByText(STEER, { exact: true }).count()).toBe(1)
  114. expect(await pendingSteering.count()).toBe(1)
  115. expect(await page.getByRole('button', { name: 'Edit queued message' }).count()).toBe(0)
  116. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  117. await compareOrRefreshGolden(MID_EXPECTED, snapshot, MODE)
  118. }
  119. // Answer the composer; the tool result closes the step, the loop drains
  120. // the steer as user/message, and the steered continuation runs the
  121. // final model call.
  122. await composer.getByRole('radio', { name: 'Yes' }).click()
  123. await composer.getByRole('radio', { name: 'Yes' }).press('Enter')
  124. await settled
  125. if (MODE === 'record') {
  126. const sessionId = await settled
  127. await recordFixture(scaffold, sessionId, FIXTURE)
  128. // Fixture honesty: a recording where the live model ignored the steer
  129. // would replay as a vacuous scenario — reject it and re-record instead.
  130. const recorded = parseSessionLog(await readFile(FIXTURE, 'utf8'))
  131. expect(claimedMessages(recorded, STEER)).toHaveLength(1)
  132. expect(assistantText(recorded)).toContain('BANANA')
  133. return
  134. }
  135. // Durable: exactly one claimed user/message carrying the steering text.
  136. const steerEvents = claimedMessages(sessionEvents, STEER)
  137. expect(steerEvents).toHaveLength(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. expect(await pendingSteering.count()).toBe(0)
  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: steer text between the question round trip and the
  149. // 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. })
  159. describe('web e2e: composer shortcut steers directly', () => {
  160. let scaffold: WebScaffold
  161. let browser: Browser
  162. let page: Page
  163. let tripwire: ReturnType<typeof watchConsole>
  164. const sessionEvents: SessionEvent[] = []
  165. beforeAll(async () => {
  166. scaffold = await launchWebScaffold({ replayFixture: FIXTURE, paceMs: REPLAY_PACE_MS })
  167. scaffold.ctx.on('session/event', (_session, event) => { sessionEvents.push(event) })
  168. browser = await chromium.launch()
  169. page = await newEnglishPage(browser)
  170. tripwire = watchConsole(page)
  171. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  172. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  173. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  174. }, 120_000)
  175. afterAll(async () => {
  176. await browser?.close()
  177. await scaffold?.close()
  178. })
  179. it.skipIf(MODE === 'record')('uses Cmd+Enter without creating a Queue row', async () => {
  180. onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-steering'))
  181. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT, STEER])
  182. const input = page.locator('textarea').first()
  183. await input.waitFor({ timeout: 10_000 })
  184. const settled = scaffold.whenTurnSettled(30_000)
  185. await input.fill(PROMPT)
  186. await input.press('Enter')
  187. await page.getByRole('button', { name: 'Stop generating' }).waitFor({ timeout: 10_000 })
  188. await input.fill(STEER)
  189. await input.press('Meta+Enter')
  190. await expect.poll(() => input.inputValue(), { timeout: 5_000 }).toBe('')
  191. expect(await page.locator('[data-queue-dock]').count()).toBe(0)
  192. const composer = page.locator('[data-question-key]')
  193. await composer.waitFor({ timeout: 30_000 })
  194. const pendingSteering = page.locator('[data-pending-steering]').filter({ hasText: STEER })
  195. await pendingSteering.waitFor({ timeout: 10_000 })
  196. await composer.getByRole('radio', { name: 'Yes' }).click()
  197. await composer.getByRole('radio', { name: 'Yes' }).press('Enter')
  198. await settled
  199. const steerEvents = claimedMessages(sessionEvents, STEER)
  200. expect(steerEvents).toHaveLength(1)
  201. await expect.poll(() => page.getByText(STEER, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  202. expect(await pendingSteering.count()).toBe(0)
  203. await expect.poll(() => page.getByText('BANANA', { exact: false }).count(), { timeout: 10_000 })
  204. .toBeGreaterThanOrEqual(2)
  205. expect(tripwire.pageErrors).toEqual([])
  206. expect(tripwire.warnings).toEqual([])
  207. }, 90_000)
  208. })
  209. describe('web e2e: composer shortcut follows the swapped busy behavior', () => {
  210. let scaffold: WebScaffold
  211. let browser: Browser
  212. let page: Page
  213. let tripwire: ReturnType<typeof watchConsole>
  214. const sessionEvents: SessionEvent[] = []
  215. beforeAll(async () => {
  216. scaffold = await launchWebScaffold({ replayFixture: FIXTURE, paceMs: REPLAY_PACE_MS })
  217. scaffold.ctx.on('session/event', (_session, event) => { sessionEvents.push(event) })
  218. browser = await chromium.launch()
  219. page = await newEnglishPage(browser)
  220. tripwire = watchConsole(page)
  221. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  222. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  223. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  224. }, 120_000)
  225. afterAll(async () => {
  226. await browser?.close()
  227. await scaffold?.close()
  228. })
  229. it.skipIf(MODE === 'record')('queues Cmd+Enter when plain Enter is configured to Steer', async () => {
  230. onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-swapped-shortcut'))
  231. await page.getByRole('button', { name: 'Settings', exact: true }).click()
  232. const dialog = page.getByRole('dialog', { name: 'Settings' })
  233. await dialog.getByRole('button', { name: 'Queue' }).click()
  234. await page.getByRole('menuitem', { name: 'Steer' }).click()
  235. await dialog.getByRole('button', { name: 'Steer' }).waitFor({ timeout: 10_000 })
  236. await page.keyboard.press('Escape')
  237. const input = page.locator('textarea').first()
  238. const settled = scaffold.whenTurnSettled(30_000)
  239. await input.fill(PROMPT)
  240. await input.press('Enter')
  241. await page.getByRole('button', { name: 'Stop generating' }).waitFor({ timeout: 10_000 })
  242. const queuedText = 'Queued by the complementary Cmd+Enter shortcut.'
  243. await input.fill(queuedText)
  244. await input.press('Meta+Enter')
  245. const queuedRow = page.locator('[data-queue-dock]').getByRole('listitem').filter({ hasText: queuedText })
  246. await queuedRow.getByText(queuedText, { exact: true }).waitFor({ timeout: 10_000 })
  247. expect(await page.locator('[data-pending-steering]').filter({ hasText: queuedText }).count()).toBe(0)
  248. expect(claimedMessages(sessionEvents, queuedText)).toHaveLength(0)
  249. // Remove the asserted Queue row, then finish the recorded question turn
  250. // so replay teardown still proves that every fixture call was consumed.
  251. await queuedRow.getByRole('button', { name: 'Remove queued message' }).click()
  252. const composer = page.locator('[data-question-key]')
  253. await composer.waitFor({ timeout: 30_000 })
  254. await composer.getByRole('radio', { name: 'Yes' }).click()
  255. await composer.getByRole('radio', { name: 'Yes' }).press('Enter')
  256. await settled
  257. expect(tripwire.pageErrors).toEqual([])
  258. expect(tripwire.warnings).toEqual([])
  259. }, 90_000)
  260. })
  261. describe('web e2e: empty-draft Cmd+Enter steers the whole queue', () => {
  262. let scaffold: WebScaffold
  263. let browser: Browser
  264. let page: Page
  265. let tripwire: ReturnType<typeof watchConsole>
  266. const sessionEvents: SessionEvent[] = []
  267. beforeAll(async () => {
  268. // The scenario boots a fresh session against the override-only fixture;
  269. // the replay.override.json sidecar replaces the derived script, so the
  270. // (deliberately absent) session.jsonl is never read.
  271. scaffold = await launchWebScaffold({
  272. replayFixture: STEER_ALL_FIXTURE,
  273. replayOverride: STEER_ALL_OVERRIDE,
  274. paceMs: REPLAY_PACE_MS,
  275. })
  276. scaffold.ctx.on('session/event', (_session, event) => { sessionEvents.push(event) })
  277. browser = await chromium.launch()
  278. page = await newEnglishPage(browser)
  279. tripwire = watchConsole(page)
  280. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  281. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  282. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  283. await page.getByText('Standard mode', { exact: true }).waitFor({ timeout: 10_000 })
  284. }, 120_000)
  285. afterAll(async () => {
  286. await browser?.close()
  287. await scaffold?.close()
  288. })
  289. it.skipIf(MODE === 'record')('queues two messages, then flushes both with an empty-draft Cmd+Enter', async () => {
  290. onTestFailed(() => saveFailureShot(page, 'web-e2e-steer-all'))
  291. const input = page.locator('textarea').first()
  292. await input.waitFor({ timeout: 10_000 })
  293. const settled = scaffold.whenTurnSettled(30_000)
  294. // Call 0 streams a question-tool call; the fills must land inside the
  295. // first replay window, before the question composer replaces the textarea.
  296. await input.fill(PROMPT)
  297. await input.press('Enter')
  298. await input.fill(STEER_ONE)
  299. await input.press('Enter')
  300. await input.fill(STEER_TWO)
  301. await input.press('Enter')
  302. const dock = page.locator('[data-queue-dock]')
  303. // Both messages queued: the two-row dock shows a collapsed count header,
  304. // and Playwright text matching skips the hidden rows — expand the list,
  305. // then assert each row's content.
  306. await dock.getByText('2 queued messages').waitFor({ timeout: 10_000 })
  307. await dock.getByRole('button').click()
  308. await dock.getByText(STEER_ONE, { exact: true }).waitFor({ timeout: 10_000 })
  309. await dock.getByText(STEER_TWO, { exact: true }).waitFor({ timeout: 10_000 })
  310. expect(await page.locator('[data-pending-steering]').count()).toBe(0)
  311. // Empty draft + Cmd+Enter: both queued rows steer in FIFO order, the dock
  312. // empties, and the pending steering renders at the conversation tail.
  313. await input.press('Meta+Enter')
  314. await expect.poll(
  315. () => page.locator('[data-pending-steering]').filter({ hasText: /BANANA|ORANGE/ }).count(),
  316. { timeout: 10_000 },
  317. ).toBe(2)
  318. expect(await page.locator('[data-queue-dock]').count()).toBe(0)
  319. // The reasoning row streams independently of the steering handoff. Wait
  320. // for the block to settle so the mid snapshot does not race its transient
  321. // visually-hidden Running label while the question keeps the turn open.
  322. await page.locator('[data-variant="think"][data-state="ok"]').first().waitFor({ timeout: 10_000 })
  323. const mid = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  324. await compareOrRefreshGolden(STEER_ALL_MID, mid, MODE)
  325. // Answer the question; the step closes, the loop drains both steerings
  326. // into one next-step request, and the final reply obeys both markers.
  327. const composer = page.locator('[data-question-key]')
  328. await composer.waitFor({ timeout: 30_000 })
  329. await composer.getByRole('radio', { name: 'Yes' }).click()
  330. await composer.getByRole('radio', { name: 'Yes' }).press('Enter')
  331. await settled
  332. const first = claimedMessages(sessionEvents, STEER_ONE)
  333. const second = claimedMessages(sessionEvents, STEER_TWO)
  334. expect(first).toHaveLength(1)
  335. expect(second).toHaveLength(1)
  336. expect(assistantText(sessionEvents)).toContain('BANANA')
  337. expect(assistantText(sessionEvents)).toContain('ORANGE')
  338. await expect.poll(() => page.getByText(STEER_ONE, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  339. await expect.poll(() => page.getByText(STEER_TWO, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  340. expect(await page.locator('[data-pending-steering]').count()).toBe(0)
  341. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  342. await compareOrRefreshGolden(STEER_ALL_SETTLED, snapshot, MODE)
  343. expect(tripwire.pageErrors).toEqual([])
  344. expect(tripwire.warnings).toEqual([])
  345. }, 200_000)
  346. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  347. await assertFixtureInventory(STEER_ALL_DIR, [
  348. 'replay.override.json', 'mid-steer.expected.md', 'settled.expected.md',
  349. ])
  350. })
  351. })