question-composer.e2e.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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, 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. // Second golden: the answered transcript — the question resolved into its
  26. // tool round trip and the final reply, the state the waiting golden cannot see.
  27. const ANSWERED_EXPECTED = join(SNAPSHOT_DIR, 'answered.expected.md')
  28. const MODE = webSnapshotMode()
  29. // The options carry long descriptions on purpose: the squeeze assertion below
  30. // needs option copy that WRAPS, which is the only shape that reproduces a
  31. // collapsed row painting its copy outside its own box.
  32. const PROMPT = 'Use the ask_user_question tool to ask me exactly one 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." After I answer, reply with the single word DONE and stop.'
  33. describe('web e2e: resident question composer round trip', () => {
  34. let scaffold: WebScaffold
  35. let browser: Browser
  36. let page: Page
  37. let tripwire: ReturnType<typeof watchConsole>
  38. const sessionEvents: SessionEvent[] = []
  39. beforeAll(async () => {
  40. scaffold = await launchWebScaffold(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 })
  41. scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
  42. browser = await chromium.launch()
  43. page = await browser.newPage({ viewport: { width: 1680, height: 1000 } })
  44. tripwire = watchConsole(page)
  45. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  46. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  47. // Fresh world: connect a Workspace so the composer scenarios start live.
  48. await connectFreshWorkspace(page)
  49. }, 120_000)
  50. afterAll(async () => {
  51. await browser?.close()
  52. await scaffold?.close()
  53. })
  54. it('asks through the composer, answers, and completes with the answer logged', async () => {
  55. onTestFailed(() => saveFailureShot(page, 'web-e2e-question'))
  56. if (MODE !== 'record') {
  57. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
  58. }
  59. const input = page.locator('textarea').first()
  60. await input.waitFor({ timeout: 10_000 })
  61. const settled = scaffold.whenTurnSettled(MODE === 'record' ? 180_000 : 30_000)
  62. await input.fill(PROMPT)
  63. await input.press('Enter')
  64. // The composer takes over the input area while the tool blocks. Its
  65. // presence is a STABLE waiting state (not a transient): it stays until
  66. // answered, so a plain waitFor is race-free.
  67. const composer = page.locator('[data-question-key]')
  68. await composer.waitFor({ timeout: MODE === 'record' ? 120_000 : 30_000 })
  69. await expect.poll(() => composer.getByText('Which color do you prefer?').count(), { timeout: 10_000 }).toBeGreaterThan(0)
  70. if (MODE !== 'record') {
  71. // This golden owns the stable question surface; the answered-state
  72. // golden below owns the resulting transcript.
  73. const snapshot = await captureStableAria(page, '[data-question-key]', scaffold.workspaceCwd)
  74. await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
  75. }
  76. // Squeezed card: the option rows are the capped card's scroll content, so
  77. // shrinking the seat must push overflow into the option list, never
  78. // collapse a row below the height its own copy needs — a collapsed row
  79. // paints its centered copy outside the row box, over the title and the
  80. // neighbouring rows. Measured on the live composer at seat heights that
  81. // force the cap, then restored for the answer gesture below. Replay only:
  82. // record mode must reach the recording write below, not abort on layout.
  83. if (MODE !== 'record') {
  84. const original = page.viewportSize() ?? { width: 1680, height: 1000 }
  85. for (const height of [520, 440, 380]) {
  86. await page.setViewportSize({ width: 900, height })
  87. const squeeze = await composer.evaluate((card) => {
  88. // Role/ARIA selectors, not the CSS-module class names: the built
  89. // client hashes those.
  90. const rows = [...card.querySelectorAll<HTMLElement>(
  91. '[role="radio"], [role="checkbox"], [aria-expanded]',
  92. )]
  93. const spill = rows.map(row => Math.max(...[...row.children].map((child) => {
  94. const box = row.getBoundingClientRect()
  95. const inner = child.getBoundingClientRect()
  96. return Math.max(box.top - inner.top, inner.bottom - box.bottom)
  97. })))
  98. const list = rows[0]?.parentElement ?? null
  99. return {
  100. rows: rows.length,
  101. spill: Math.max(...spill),
  102. // Wrapped copy is the shape that overflows a collapsed row, and a
  103. // scrolling list proves the seat is genuinely capped. Without both,
  104. // the spill assertion would hold vacuously.
  105. wrappedRows: rows.filter(row => row.getBoundingClientRect().height > 42).length,
  106. scrolls: list === null ? false : list.scrollHeight > list.clientHeight,
  107. }
  108. })
  109. expect(squeeze.rows).toBeGreaterThan(0)
  110. expect(squeeze.wrappedRows).toBeGreaterThan(0)
  111. expect(squeeze.scrolls).toBe(true)
  112. // Sub-pixel tolerance: every row's copy stays inside its border box.
  113. expect(squeeze.spill).toBeLessThan(0.6)
  114. }
  115. await page.setViewportSize(original)
  116. }
  117. await composer.getByRole('radio', { name: 'Blue' }).click()
  118. // Submit: Enter on the focused option (the composer's documented submit).
  119. await composer.getByRole('radio', { name: 'Blue' }).press('Enter')
  120. const sessionId = await settled
  121. if (MODE === 'record') {
  122. await recordFixture(scaffold, sessionId, FIXTURE)
  123. return
  124. }
  125. // World state: the tool result carries the chosen answer, and DONE lands.
  126. const results = sessionEvents.filter(e => e.type === 'tool/result')
  127. expect(JSON.stringify(results.at(-1))).toContain('Blue')
  128. await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
  129. // Composer gone; regular input restored.
  130. expect(await page.locator('[data-question-key]').count()).toBe(0)
  131. await expect.poll(() => page.locator('textarea').first().isEnabled(), { timeout: 10_000 }).toBe(true)
  132. // Golden of the answered transcript: the ask_user_question round trip
  133. // rendered as history (question tool row + DONE), composer takeover gone.
  134. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  135. await compareOrRefreshGolden(ANSWERED_EXPECTED, snapshot, MODE)
  136. expect(tripwire.pageErrors).toEqual([])
  137. expect(tripwire.warnings).toEqual([])
  138. }, 200_000)
  139. it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
  140. await assertFixtureInventory(SNAPSHOT_DIR, ['session.jsonl', 'ui.expected.md', 'answered.expected.md'])
  141. })
  142. })