question-composer.e2e.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. // Web e2e scenario: the resident question composer. The shipped composition
  2. // already exposes ask_user_question (the ui-question row's node half mounts
  3. // the tool), so a recorded turn where the model asks blocks mid-turn on the
  4. // real userInteraction seam: the composer renders in the browser, the test
  5. // answers through it, and the turn completes with the answer in the log.
  6. // Replay is fully deterministic — the question content arrives from replayed
  7. // chunks, the composer wait is real, and the answer click is the test's own
  8. // gesture (the ONE place a drive step legitimately reacts to model content:
  9. // the turn cannot complete without it, in record and replay alike).
  10. import { readFile } from 'node:fs/promises'
  11. import { fileURLToPath } from 'node:url'
  12. import { join } from 'node:path'
  13. import type { Browser, Page } from 'playwright'
  14. import { chromium } from 'playwright'
  15. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  16. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  17. import {
  18. assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
  19. launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
  20. } from './scaffold.ts'
  21. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  22. const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/question-composer', import.meta.url))
  23. const FIXTURE = join(SNAPSHOT_DIR, 'session.jsonl')
  24. const UI_EXPECTED = join(SNAPSHOT_DIR, 'ui.expected.md')
  25. const COMPOSED_EXPECTED = join(SNAPSHOT_DIR, 'composed.expected.md')
  26. // Final golden: the answered transcript — the question resolved into its tool
  27. // round trip and the final reply, the state the composer goldens cannot see.
  28. const ANSWERED_EXPECTED = join(SNAPSHOT_DIR, 'answered.expected.md')
  29. const MODE = webSnapshotMode()
  30. // The options carry long descriptions on purpose: the squeeze assertion below
  31. // needs option copy that WRAPS, which is the only shape that reproduces a
  32. // collapsed row painting its copy outside its own box.
  33. const PROMPT = 'Use the ask_user_question tool to ask me exactly one multi-select question with id "color", question "Which color do you prefer?", header "Pick one", and two options: label "Blue" with description "A cool recessive hue that reads as calm and trustworthy in long reading sessions and dense dashboards.", and label "Green" with description "A restful mid-spectrum hue with the highest perceived brightness, easiest on the eye over long sessions." Set multi_select to true. After I answer, reply with the single word DONE and stop.'
  34. describe('web e2e: resident question composer round trip', () => {
  35. let scaffold: WebScaffold
  36. let browser: Browser
  37. let page: Page
  38. let tripwire: ReturnType<typeof watchConsole>
  39. const sessionEvents: SessionEvent[] = []
  40. beforeAll(async () => {
  41. scaffold = await launchWebScaffold(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 })
  42. scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
  43. browser = await chromium.launch()
  44. page = await newEnglishPage(browser)
  45. tripwire = watchConsole(page)
  46. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  47. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  48. // Fresh world: connect a Workspace so the composer scenarios start live.
  49. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  50. }, 120_000)
  51. afterAll(async () => {
  52. await browser?.close()
  53. await scaffold?.close()
  54. })
  55. it('asks through the composer, answers, and completes with the answer logged', async () => {
  56. onTestFailed(() => saveFailureShot(page, 'web-e2e-question'))
  57. if (MODE !== 'record') {
  58. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
  59. }
  60. const input = page.locator('textarea').first()
  61. await input.waitFor({ timeout: 10_000 })
  62. const settled = scaffold.whenTurnSettled(MODE === 'record' ? 180_000 : 30_000)
  63. await input.fill(PROMPT)
  64. await input.press('Enter')
  65. // The composer takes over the input area while the tool blocks. Its
  66. // presence is a STABLE waiting state (not a transient): it stays until
  67. // answered, so a plain waitFor is race-free.
  68. const composer = page.locator('[data-question-key]')
  69. await composer.waitFor({ timeout: MODE === 'record' ? 120_000 : 30_000 })
  70. await expect.poll(() => composer.getByText('Which color do you prefer?').count(), { timeout: 10_000 }).toBeGreaterThan(0)
  71. if (MODE !== 'record') {
  72. // This golden owns the stable question surface; the answered-state
  73. // golden below owns the resulting transcript.
  74. const snapshot = await captureStableAria(page, '[data-question-key]', scaffold.workspaceCwd)
  75. await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
  76. }
  77. // Squeezed card: the option rows are the capped card's scroll content, so
  78. // shrinking the seat must push overflow into the option list, never
  79. // collapse a row below the height its own copy needs — a collapsed row
  80. // paints its centered copy outside the row box, over the title and the
  81. // neighbouring rows. Measured on the live composer at seat heights that
  82. // force the cap, then restored for the answer gesture below. Replay only:
  83. // record mode must reach the recording write below, not abort on layout.
  84. if (MODE !== 'record') {
  85. const original = page.viewportSize() ?? { width: 1680, height: 1000 }
  86. for (const height of [520, 440, 380]) {
  87. await page.setViewportSize({ width: 900, height })
  88. const squeeze = await composer.evaluate((card) => {
  89. // Role/ARIA selectors, not the CSS-module class names: the built
  90. // client hashes those.
  91. const rows = [...card.querySelectorAll<HTMLElement>(
  92. '[role="radio"], [role="checkbox"], [aria-expanded]',
  93. )]
  94. const spill = rows.map(row => Math.max(...[...row.children].map((child) => {
  95. const box = row.getBoundingClientRect()
  96. const inner = child.getBoundingClientRect()
  97. return Math.max(box.top - inner.top, inner.bottom - box.bottom)
  98. })))
  99. const list = card.querySelector<HTMLElement>('[data-question-scroll]')
  100. return {
  101. rows: rows.length,
  102. spill: Math.max(...spill),
  103. // Wrapped copy is the shape that overflows a collapsed row, and a
  104. // scrolling list proves the seat is genuinely capped. Without both,
  105. // the spill assertion would hold vacuously.
  106. wrappedRows: rows.filter(row => row.getBoundingClientRect().height > 42).length,
  107. scrolls: list === null ? false : list.scrollHeight > list.clientHeight,
  108. }
  109. })
  110. expect(squeeze.rows).toBeGreaterThan(0)
  111. expect(squeeze.wrappedRows).toBeGreaterThan(0)
  112. expect(squeeze.scrolls).toBe(true)
  113. // Sub-pixel tolerance: every row's copy stays inside its border box.
  114. expect(squeeze.spill).toBeLessThan(0.6)
  115. }
  116. await page.setViewportSize(original)
  117. }
  118. const blue = composer.getByRole('checkbox', { name: 'Blue' })
  119. await blue.click()
  120. const custom = composer.getByRole('textbox')
  121. await custom.fill('Include accessibility notes')
  122. expect(await blue.getAttribute('aria-checked')).toBe('true')
  123. expect(await custom.inputValue()).toBe('Include accessibility notes')
  124. if (MODE !== 'record') {
  125. const snapshot = await captureStableAria(page, '[data-question-key]', scaffold.workspaceCwd)
  126. await compareOrRefreshGolden(COMPOSED_EXPECTED, snapshot, MODE)
  127. }
  128. await custom.press('Enter')
  129. const sessionId = await settled
  130. if (MODE === 'record') {
  131. await recordFixture(scaffold, sessionId, FIXTURE)
  132. return
  133. }
  134. // World state: the tool result carries the chosen answer, and DONE lands.
  135. const results = sessionEvents.filter(e => e.type === 'tool/result')
  136. const answerText = results.flatMap(event => event.data.message.content.flatMap(block =>
  137. block.type === 'tool-result'
  138. ? block.content.filter(item => item.type === 'text').map(item => item.text)
  139. : [],
  140. )).at(-1)
  141. expect(JSON.parse(answerText ?? '')).toEqual({
  142. answers: [{ id: 'color', selected: ['Blue'], custom: 'Include accessibility notes' }],
  143. })
  144. await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
  145. // Composer gone; regular input restored.
  146. expect(await page.locator('[data-question-key]').count()).toBe(0)
  147. await expect.poll(() => page.locator('textarea').first().isEnabled(), { timeout: 10_000 }).toBe(true)
  148. // Golden of the answered transcript: the ask_user_question round trip
  149. // rendered as history (question tool row + DONE), composer takeover gone.
  150. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  151. await compareOrRefreshGolden(ANSWERED_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, [
  157. 'session.jsonl',
  158. 'ui.expected.md',
  159. 'composed.expected.md',
  160. 'answered.expected.md',
  161. ])
  162. })
  163. })