produced-files.e2e.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. // Web e2e scenario: the single-line produced-files summary a finished turn
  2. // ends with. Cold-seeds ten writes (zero model calls), then verifies the real
  3. // assembled lane adapts from a coarse width budget and offers no folder
  4. // handoff: chips open in the right Sidebar's text preview, which has no
  5. // directory form, so the row shows nothing rather than a dead button.
  6. import { fileURLToPath } from 'node:url'
  7. import type { Browser, Page } from 'playwright'
  8. import { chromium } from 'playwright'
  9. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  10. import { ToolCallId, createAssistantMessage, createToolResultMessage, createUserMessage } from '@deepseek-ai/dsh-llm'
  11. import { SESSION_FORMAT_VERSION, Session, SessionId } from '@deepseek-ai/dsh-session'
  12. import type {} from '@deepseek-ai/dsh-session-title'
  13. import {
  14. launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
  15. } from './scaffold.ts'
  16. import { newEnglishPage, saveFailureShot } from './support.ts'
  17. const MODE = webSnapshotMode()
  18. const OVERLAY = fileURLToPath(new URL('./produced-files.overlay.yml', import.meta.url))
  19. const SEED_ID = 'produced-files-web-e2e'
  20. const DONE = 'PRODUCED_FILES_DONE'
  21. /** Ten varied names exercise estimated prefix selection and CSS shrinking. */
  22. const PRODUCED = [
  23. '关于我.md',
  24. 'index.html',
  25. 'long-generated-experience-specification-for-produced-files-overflow.md',
  26. 'styles.css',
  27. 'app.ts',
  28. 'schema.json',
  29. 'README.md',
  30. 'preview.svg',
  31. 'notes.txt',
  32. 'manifest.yaml',
  33. ] as const
  34. /** Build one settled turn whose successful write calls carry ten locations. */
  35. function producedFixture(): string {
  36. const session = Session.create(SessionId('produced-files-source'))
  37. const eventTimeOrigin = new Date().setHours(12, 0, 0, 0)
  38. session.append('turn/start', { turn: 1 })
  39. const user = session.append('user/message', createUserMessage({
  40. content: [{ type: 'text', text: 'Create the site files.' }],
  41. source: { kind: 'user' },
  42. }), { surfaceOp: 'append' })
  43. session.append('session/title', {
  44. title: 'Produced files overflow', messageSeqs: [user.seq], source: { kind: 'fallback' },
  45. })
  46. session.append('step/start', { turn: 1, step: 1 })
  47. const calls = PRODUCED.map((path, index) => ({
  48. path,
  49. callId: ToolCallId(`produced-files-${String(index)}`),
  50. args: JSON.stringify({ file_path: path, content: `content of ${path}\n` }),
  51. }))
  52. session.append('assistant/message', {
  53. stream: [],
  54. turn: 1,
  55. step: 1,
  56. message: createAssistantMessage({
  57. content: calls.map(call => ({
  58. type: 'tool-call' as const,
  59. id: call.callId,
  60. name: 'write',
  61. arguments: call.args,
  62. })),
  63. source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  64. }),
  65. }, { surfaceOp: 'append' })
  66. for (const call of calls) {
  67. const source = session.append('tool/call', {
  68. turn: 1, step: 1, callId: call.callId, name: 'write', arguments: call.args,
  69. })
  70. session.append('tool/result', {
  71. turn: 1,
  72. step: 1,
  73. message: createToolResultMessage({
  74. callId: call.callId,
  75. content: [{ type: 'text', text: `Created ${call.path}` }],
  76. isError: false,
  77. }),
  78. }, { surfaceOp: 'append', sourceEventSeqs: [source.seq] })
  79. }
  80. session.append('step/end', { turn: 1, step: 1 })
  81. session.append('step/start', { turn: 1, step: 2 })
  82. session.append('assistant/message', {
  83. stream: [],
  84. turn: 1,
  85. step: 2,
  86. message: createAssistantMessage({
  87. content: [{ type: 'text', text: `Created the site.\n\n${DONE}` }],
  88. source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  89. }),
  90. }, { surfaceOp: 'append' })
  91. session.append('step/end', { turn: 1, step: 2 })
  92. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  93. return [
  94. JSON.stringify({
  95. type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}',
  96. createdAt: 0, cwd: '{{cwd}}', isSeeded: false, delegationDepth: 0,
  97. }),
  98. ...session.snapshotEvents().map(event => JSON.stringify({
  99. ...event, time: eventTimeOrigin + event.seq * 1_000,
  100. })),
  101. '',
  102. ].join('\n')
  103. }
  104. describe('web e2e: a finished turn ends with the files it produced', () => {
  105. let scaffold: WebScaffold
  106. let browser: Browser
  107. let page: Page
  108. let tripwire: ReturnType<typeof watchConsole>
  109. beforeAll(async () => {
  110. scaffold = await launchWebScaffold({ extraOverlayPath: OVERLAY })
  111. await seedSession(scaffold, producedFixture(), SEED_ID)
  112. browser = await chromium.launch()
  113. page = await newEnglishPage(browser)
  114. // Keep the responsive sidebar available while selecting the cold seed;
  115. // the assertion itself narrows the conversation after navigation.
  116. await page.setViewportSize({ width: 1800, height: 900 })
  117. tripwire = watchConsole(page)
  118. await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  119. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  120. }, 120_000)
  121. afterAll(async () => {
  122. await browser?.close()
  123. await scaffold?.close()
  124. })
  125. it.skipIf(MODE === 'record')('adapts a ten-file summary without leaving one line', async () => {
  126. onTestFailed(() => saveFailureShot(page, 'web-e2e-produced-files'))
  127. const groupRow = page.locator('[role="treeitem"]').first()
  128. await groupRow.waitFor({ timeout: 15_000 })
  129. if (await groupRow.getAttribute('aria-expanded') !== 'true') await groupRow.click()
  130. const sessionRow = page.locator('[role="treeitem"]').nth(1)
  131. await sessionRow.waitFor({ timeout: 10_000 })
  132. await sessionRow.click()
  133. await expect.poll(() => page.getByText(DONE, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  134. const row = page.locator('[data-produced-files-row]')
  135. await row.waitFor({ timeout: 15_000 })
  136. const chips = row.getByRole('button')
  137. await expect.poll(() => chips.count()).toBe(6)
  138. await expect.poll(() => row.getByText('+ 4 files', { exact: true }).isVisible()).toBe(true)
  139. await page.setViewportSize({ width: 750, height: 900 })
  140. await page.evaluate(async () => { await document.fonts.ready })
  141. await page.waitForFunction(() => {
  142. const frame = document.querySelector('[data-sidebar-collapsed][data-rightbar-collapsed]')
  143. if (frame === null) return false
  144. const tracks = getComputedStyle(frame).gridTemplateColumns.split(' ').map(Number.parseFloat)
  145. // The responsive sidebar's settled collapsed track is 56px.
  146. return tracks[0] === 56 && tracks.at(-1) === 0
  147. && frame.getAnimations().every(animation =>
  148. animation.playState === 'finished' || animation.playState === 'idle')
  149. }, undefined, { timeout: 10_000 })
  150. await expect.poll(() => chips.count()).toBe(4)
  151. const laneWidth = await row.evaluate(element => element.clientWidth)
  152. // Keep font-metric differences away from the 479px and 583px container-query edges.
  153. expect(laneWidth).toBeGreaterThan(503)
  154. expect(laneWidth).toBeLessThan(559)
  155. expect(await chips.nth(0).innerText()).toBe('关于我.md')
  156. expect(await chips.nth(1).innerText()).toBe('index.html')
  157. expect(await chips.nth(3).innerText()).toBe('styles.css')
  158. await expect.poll(() => row.getByText('+ 6 files', { exact: true }).isVisible()).toBe(true)
  159. // Chips open in the right Sidebar's text preview, and a directory is not
  160. // something that preview can show, so the row offers no folder action.
  161. expect(await page.getByRole('button', { name: /folder/i }).count()).toBe(0)
  162. expect(await page.getByText('Files changed', { exact: true }).count()).toBe(1)
  163. const turnSpacing = await page.evaluate((done) => {
  164. const requiredElement = <T extends Element>(value: T | null | undefined, name: string): T => {
  165. if (value === null || value === undefined) throw new Error(`produced-file layout is missing ${name}`)
  166. return value
  167. }
  168. const answer = requiredElement(
  169. [...document.querySelectorAll<HTMLElement>('[data-chat-flow-kind="assistant-step"]')]
  170. .find(element => element.textContent?.includes(done)),
  171. 'final answer',
  172. )
  173. const producedRow = requiredElement(
  174. document.querySelector<HTMLElement>('[data-produced-files-row]'),
  175. 'produced row',
  176. )
  177. const producedRoot = requiredElement(producedRow.parentElement?.parentElement, 'produced root')
  178. const turnTail = requiredElement(producedRoot.closest<HTMLElement>('[data-turn-tail]'), 'turn tail')
  179. const actions = requiredElement(
  180. turnTail.querySelector<HTMLButtonElement>('button[aria-label="Copy"]')?.parentElement,
  181. 'action row',
  182. )
  183. const answerRect = answer.getBoundingClientRect()
  184. const producedRect = producedRoot.getBoundingClientRect()
  185. const actionsRect = actions.getBoundingClientRect()
  186. return {
  187. answerToProduced: producedRect.top - answerRect.bottom,
  188. producedToActions: actionsRect.top - producedRect.bottom,
  189. }
  190. }, DONE)
  191. expect(turnSpacing.answerToProduced).toBeCloseTo(20, 1)
  192. expect(turnSpacing.producedToActions).toBeCloseTo(20, 1)
  193. const tops = await row.locator(':scope > *:visible').evaluateAll(elements =>
  194. elements.map(element => element.getBoundingClientRect().top))
  195. expect(new Set(tops.map(top => Math.round(top))).size).toBe(1)
  196. const geometry = await row.evaluate(element => ({
  197. clientWidth: element.clientWidth, scrollWidth: element.scrollWidth,
  198. }))
  199. expect(geometry.scrollWidth).toBeLessThanOrEqual(geometry.clientWidth)
  200. expect(tripwire.pageErrors).toEqual([])
  201. expect(tripwire.warnings).toEqual([])
  202. }, 90_000)
  203. })