steering.e2e.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. // 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 queued = page.getByText(STEER, { exact: true })
  100. await queued.waitFor({ timeout: 10_000 })
  101. const queuedRow = page.getByRole('listitem').filter({ hasText: STEER })
  102. const steerButton = queuedRow.getByRole('button', { name: 'Steer queued message' })
  103. await expect.poll(() => steerButton.isEnabled(), { timeout: 10_000 }).toBe(true)
  104. await steerButton.click({ timeout: 10_000 })
  105. const pendingSteering = page.locator('[data-pending-steering]').filter({ hasText: STEER })
  106. // A timeout while the Queue row remains means strict steer lost to a
  107. // closing window (`steer-unavailable`); inspect replay pacing first.
  108. await pendingSteering.waitFor({ timeout: 10_000 })
  109. // The blocked composer keeps steering pending long enough to observe the
  110. // Host-authoritative mirror before the loop admits it durably.
  111. const composer = page.locator('[data-question-key]')
  112. await composer.waitFor({ timeout: MODE === 'record' ? 120_000 : 30_000 })
  113. if (MODE !== 'record') {
  114. expect(await page.getByText(STEER, { exact: true }).count()).toBe(1)
  115. expect(await pendingSteering.count()).toBe(1)
  116. expect(await page.getByRole('button', { name: 'Edit queued message' }).count()).toBe(0)
  117. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  118. await compareOrRefreshGolden(MID_EXPECTED, snapshot, MODE)
  119. }
  120. // Answer the composer; the tool result closes the step, the loop drains
  121. // the steer as user/message, and the steered continuation runs the
  122. // final model call.
  123. await composer.getByRole('radio', { name: 'Yes' }).click()
  124. await composer.getByRole('radio', { name: 'Yes' }).press('Enter')
  125. await settled
  126. if (MODE === 'record') {
  127. const sessionId = await settled
  128. await recordFixture(scaffold, sessionId, FIXTURE)
  129. // Fixture honesty: a recording where the live model ignored the steer
  130. // would replay as a vacuous scenario — reject it and re-record instead.
  131. const recorded = parseSessionLog(await readFile(FIXTURE, 'utf8'))
  132. expect(claimedMessages(recorded, STEER)).toHaveLength(1)
  133. expect(assistantText(recorded)).toContain('BANANA')
  134. return
  135. }
  136. // Durable: exactly one claimed user/message carrying the steering text.
  137. const steerEvents = claimedMessages(sessionEvents, STEER)
  138. expect(steerEvents).toHaveLength(1)
  139. expect(JSON.stringify(steerEvents[0])).toContain('BANANA')
  140. const turnEnds = sessionEvents.filter(e => e.type === 'turn/end')
  141. expect(turnEnds).toHaveLength(1)
  142. expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed')
  143. // Visible: the plain steering bubble plus the reply that obeys it
  144. // (steer text + final reply each contain the marker word).
  145. await expect.poll(() => page.getByText(STEER, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  146. expect(await pendingSteering.count()).toBe(0)
  147. await expect.poll(() => page.getByText('BANANA', { exact: false }).count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(2)
  148. expect(await page.locator('[data-question-key]').count()).toBe(0)
  149. // Settled golden: steer text between the question round trip and the
  150. // obeying reply, composer takeover gone.
  151. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  152. await compareOrRefreshGolden(SETTLED_EXPECTED, snapshot, MODE)
  153. expect(tripwire.pageErrors).toEqual([])
  154. expect(tripwire.warnings).toEqual([])
  155. }, 200_000)
  156. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  157. await assertFixtureInventory(SNAPSHOT_DIR, ['session.jsonl', 'mid-steer.expected.md', 'settled.expected.md'])
  158. })
  159. })
  160. describe('web e2e: composer shortcut steers directly', () => {
  161. let scaffold: WebScaffold
  162. let browser: Browser
  163. let page: Page
  164. let tripwire: ReturnType<typeof watchConsole>
  165. const sessionEvents: SessionEvent[] = []
  166. beforeAll(async () => {
  167. scaffold = await launchWebScaffold({ replayFixture: FIXTURE, paceMs: REPLAY_PACE_MS })
  168. scaffold.ctx.on('session/event', (_session, event) => { sessionEvents.push(event) })
  169. browser = await chromium.launch()
  170. page = await newEnglishPage(browser)
  171. tripwire = watchConsole(page)
  172. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  173. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  174. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  175. }, 120_000)
  176. afterAll(async () => {
  177. await browser?.close()
  178. await scaffold?.close()
  179. })
  180. it.skipIf(MODE === 'record')('uses Cmd+Enter without creating a Queue row', async () => {
  181. onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-steering'))
  182. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT, STEER])
  183. const input = page.locator('textarea').first()
  184. await input.waitFor({ timeout: 10_000 })
  185. const settled = scaffold.whenTurnSettled(30_000)
  186. await input.fill(PROMPT)
  187. await input.press('Enter')
  188. await page.getByRole('button', { name: 'Stop generating' }).waitFor({ timeout: 10_000 })
  189. await input.fill(STEER)
  190. await input.press('Meta+Enter')
  191. await expect.poll(() => input.inputValue(), { timeout: 5_000 }).toBe('')
  192. expect(await page.locator('[data-queue-dock]').count()).toBe(0)
  193. const composer = page.locator('[data-question-key]')
  194. await composer.waitFor({ timeout: 30_000 })
  195. const pendingSteering = page.locator('[data-pending-steering]').filter({ hasText: STEER })
  196. await pendingSteering.waitFor({ timeout: 10_000 })
  197. await composer.getByRole('radio', { name: 'Yes' }).click()
  198. await composer.getByRole('radio', { name: 'Yes' }).press('Enter')
  199. await settled
  200. const steerEvents = claimedMessages(sessionEvents, STEER)
  201. expect(steerEvents).toHaveLength(1)
  202. await expect.poll(() => page.getByText(STEER, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  203. expect(await pendingSteering.count()).toBe(0)
  204. await expect.poll(() => page.getByText('BANANA', { exact: false }).count(), { timeout: 10_000 })
  205. .toBeGreaterThanOrEqual(2)
  206. expect(tripwire.pageErrors).toEqual([])
  207. expect(tripwire.warnings).toEqual([])
  208. }, 90_000)
  209. })
  210. describe('web e2e: composer shortcut follows the swapped busy behavior', () => {
  211. let scaffold: WebScaffold
  212. let browser: Browser
  213. let page: Page
  214. let tripwire: ReturnType<typeof watchConsole>
  215. const sessionEvents: SessionEvent[] = []
  216. beforeAll(async () => {
  217. scaffold = await launchWebScaffold({ replayFixture: FIXTURE, paceMs: REPLAY_PACE_MS })
  218. scaffold.ctx.on('session/event', (_session, event) => { sessionEvents.push(event) })
  219. browser = await chromium.launch()
  220. page = await newEnglishPage(browser)
  221. tripwire = watchConsole(page)
  222. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  223. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  224. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  225. }, 120_000)
  226. afterAll(async () => {
  227. await browser?.close()
  228. await scaffold?.close()
  229. })
  230. it.skipIf(MODE === 'record')('queues Cmd+Enter when plain Enter is configured to Steer', async () => {
  231. onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-swapped-shortcut'))
  232. await page.getByRole('button', { name: 'Settings', exact: true }).click()
  233. const dialog = page.getByRole('dialog', { name: 'Settings' })
  234. await dialog.getByRole('button', { name: 'Queue' }).click()
  235. await page.getByRole('menuitem', { name: 'Steer' }).click()
  236. await dialog.getByRole('button', { name: 'Steer' }).waitFor({ timeout: 10_000 })
  237. await page.keyboard.press('Escape')
  238. const input = page.locator('textarea').first()
  239. const settled = scaffold.whenTurnSettled(30_000)
  240. await input.fill(PROMPT)
  241. await input.press('Enter')
  242. await page.getByRole('button', { name: 'Stop generating' }).waitFor({ timeout: 10_000 })
  243. const queuedText = 'Queued by the complementary Cmd+Enter shortcut.'
  244. await input.fill(queuedText)
  245. await input.press('Meta+Enter')
  246. const queuedRow = page.locator('[data-queue-dock]').getByRole('listitem').filter({ hasText: queuedText })
  247. await queuedRow.getByText(queuedText, { exact: true }).waitFor({ timeout: 10_000 })
  248. expect(await page.locator('[data-pending-steering]').filter({ hasText: queuedText }).count()).toBe(0)
  249. expect(claimedMessages(sessionEvents, queuedText)).toHaveLength(0)
  250. // Remove the asserted Queue row, then finish the recorded question turn
  251. // so replay teardown still proves that every fixture call was consumed.
  252. await queuedRow.getByRole('button', { name: 'Remove queued message' }).click()
  253. const composer = page.locator('[data-question-key]')
  254. await composer.waitFor({ timeout: 30_000 })
  255. await composer.getByRole('radio', { name: 'Yes' }).click()
  256. await composer.getByRole('radio', { name: 'Yes' }).press('Enter')
  257. await settled
  258. expect(tripwire.pageErrors).toEqual([])
  259. expect(tripwire.warnings).toEqual([])
  260. }, 90_000)
  261. })
  262. describe('web e2e: empty-draft Cmd+Enter steers the whole queue', () => {
  263. let scaffold: WebScaffold
  264. let browser: Browser
  265. let page: Page
  266. let tripwire: ReturnType<typeof watchConsole>
  267. const sessionEvents: SessionEvent[] = []
  268. beforeAll(async () => {
  269. // The scenario boots a fresh session against the override-only fixture;
  270. // the replay.override.json sidecar replaces the derived script, so the
  271. // (deliberately absent) session.jsonl is never read.
  272. scaffold = await launchWebScaffold({
  273. replayFixture: STEER_ALL_FIXTURE,
  274. replayOverride: STEER_ALL_OVERRIDE,
  275. paceMs: REPLAY_PACE_MS,
  276. })
  277. scaffold.ctx.on('session/event', (_session, event) => { sessionEvents.push(event) })
  278. browser = await chromium.launch()
  279. page = await newEnglishPage(browser)
  280. tripwire = watchConsole(page)
  281. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  282. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  283. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  284. await page.getByText('Standard mode', { exact: true }).waitFor({ timeout: 10_000 })
  285. }, 120_000)
  286. afterAll(async () => {
  287. await browser?.close()
  288. await scaffold?.close()
  289. })
  290. it.skipIf(MODE === 'record')('queues two messages, then flushes both with an empty-draft Cmd+Enter', async () => {
  291. onTestFailed(() => saveFailureShot(page, 'web-e2e-steer-all'))
  292. const input = page.locator('textarea').first()
  293. await input.waitFor({ timeout: 10_000 })
  294. const settled = scaffold.whenTurnSettled(30_000)
  295. // Call 0 streams a question-tool call; the fills must land inside the
  296. // first replay window, before the question composer replaces the textarea.
  297. await input.fill(PROMPT)
  298. await input.press('Enter')
  299. await input.fill(STEER_ONE)
  300. await input.press('Enter')
  301. await input.fill(STEER_TWO)
  302. await input.press('Enter')
  303. const dock = page.locator('[data-queue-dock]')
  304. // Both messages queued: the two-row dock shows a collapsed count header,
  305. // and Playwright text matching skips the hidden rows — expand the list,
  306. // then assert each row's content.
  307. await dock.getByText('2 queued messages').waitFor({ timeout: 10_000 })
  308. await dock.getByRole('button').click()
  309. await dock.getByText(STEER_ONE, { exact: true }).waitFor({ timeout: 10_000 })
  310. await dock.getByText(STEER_TWO, { exact: true }).waitFor({ timeout: 10_000 })
  311. expect(await page.locator('[data-pending-steering]').count()).toBe(0)
  312. // Empty draft + Cmd+Enter: both queued rows steer in FIFO order, the dock
  313. // empties, and the pending steering renders at the conversation tail.
  314. await input.press('Meta+Enter')
  315. await expect.poll(
  316. () => page.locator('[data-pending-steering]').filter({ hasText: /BANANA|ORANGE/ }).count(),
  317. { timeout: 10_000 },
  318. ).toBe(2)
  319. expect(await page.locator('[data-queue-dock]').count()).toBe(0)
  320. // The reasoning row streams independently of the steering handoff. Wait
  321. // for the block to settle so the mid snapshot does not race its transient
  322. // visually-hidden Running label while the question keeps the turn open.
  323. await page.locator('[data-variant="think"][data-state="ok"]').first().waitFor({ timeout: 10_000 })
  324. const mid = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  325. await compareOrRefreshGolden(STEER_ALL_MID, mid, MODE)
  326. // Answer the question; the step closes, the loop drains both steerings
  327. // into one next-step request, and the final reply obeys both markers.
  328. const composer = page.locator('[data-question-key]')
  329. await composer.waitFor({ timeout: 30_000 })
  330. await composer.getByRole('radio', { name: 'Yes' }).click()
  331. await composer.getByRole('radio', { name: 'Yes' }).press('Enter')
  332. await settled
  333. const first = claimedMessages(sessionEvents, STEER_ONE)
  334. const second = claimedMessages(sessionEvents, STEER_TWO)
  335. expect(first).toHaveLength(1)
  336. expect(second).toHaveLength(1)
  337. expect(assistantText(sessionEvents)).toContain('BANANA')
  338. expect(assistantText(sessionEvents)).toContain('ORANGE')
  339. await expect.poll(() => page.getByText(STEER_ONE, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  340. await expect.poll(() => page.getByText(STEER_TWO, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  341. expect(await page.locator('[data-pending-steering]').count()).toBe(0)
  342. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  343. await compareOrRefreshGolden(STEER_ALL_SETTLED, snapshot, MODE)
  344. expect(tripwire.pageErrors).toEqual([])
  345. expect(tripwire.warnings).toEqual([])
  346. }, 200_000)
  347. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  348. await assertFixtureInventory(STEER_ALL_DIR, [
  349. 'replay.override.json', 'mid-steer.expected.md', 'settled.expected.md',
  350. ])
  351. })
  352. })