steering.e2e.ts 20 KB

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