code-mode-fixture.snapshot.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. // @vitest-environment jsdom
  2. // Code Mode fixture snapshot over the BUILT client graph (the workspace-flow
  3. // idiom: real bundles via AppWebEntry, keyless FixtureApiClient transport).
  4. // Opens the fixture history session and pins the run_code turn's rendering:
  5. // the code-variant parent row titled by the model-authored description, its
  6. // three always-visible nested sub-rows (bash through the sample registration,
  7. // read through GenericToolCard, the failing read wearing the error state),
  8. // the expanded program body, inert bash / file-link sub-row gestures, and
  9. // the trajectory/waterfall tabs' sub-call cells and timing lanes.
  10. import { readFileSync } from 'node:fs'
  11. import { join } from 'node:path'
  12. import { act, cleanup, fireEvent, screen, waitFor, within } from '@testing-library/react'
  13. import { afterEach, beforeEach, expect, it, vi } from 'vitest'
  14. import type { WebBootEntry } from '@deepseek-ai/dsh-client-modules/client'
  15. import { AppWebEntry } from '@deepseek-ai/dsh-client-web'
  16. const PLUGINS: readonly (WebBootEntry & { dir: string })[] = [
  17. { id: '@deepseek-ai/dsh-client-connection', dir: 'connection', url: '/plugins/connection.js', rev: 'fx', inject: [], immediately: true },
  18. { id: '@deepseek-ai/dsh-client-runtime', dir: 'runtime', url: '/plugins/runtime.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-connection'], immediately: true },
  19. { id: '@deepseek-ai/dsh-client-ui-theme', dir: 'ui-theme', url: '/plugins/ui-theme.js', rev: 'fx', inject: [], immediately: true },
  20. { id: '@deepseek-ai/dsh-client-locale', dir: 'locale', url: '/plugins/locale.js', rev: 'fx', inject: [], immediately: true },
  21. { id: '@deepseek-ai/dsh-client-ui-layout', dir: 'ui-layout', url: '/plugins/ui-layout.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-runtime'] },
  22. { id: '@deepseek-ai/dsh-client-ui-sidebar', dir: 'ui-sidebar', url: '/plugins/ui-sidebar.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] },
  23. { id: '@deepseek-ai/dsh-client-ui-conversation', dir: 'ui-conversation', url: '/plugins/ui-conversation.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] },
  24. {
  25. id: '@deepseek-ai/dsh-client-ui-workspace',
  26. dir: 'ui-workspace',
  27. url: '/plugins/ui-workspace.js',
  28. rev: 'fx',
  29. inject: [
  30. '@deepseek-ai/dsh-client-runtime',
  31. '@deepseek-ai/dsh-client-ui-conversation',
  32. '@deepseek-ai/dsh-client-ui-sidebar',
  33. ],
  34. },
  35. { id: '@deepseek-ai/dsh-client-ui-trajectory', dir: 'ui-trajectory', url: '/plugins/ui-trajectory.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-conversation'] },
  36. ]
  37. const bundles = new Map(PLUGINS.map(plugin => [
  38. plugin.url,
  39. readFileSync(join(process.cwd(), 'packages/client', plugin.dir, 'lib/client.js'), 'utf8'),
  40. ]))
  41. interface FixtureWindow extends Window {
  42. __DSH_BOOT__?: { rev: string; entries: WebBootEntry[] }
  43. __ModuleLoader__?: unknown
  44. }
  45. class ResizeObserverStub {
  46. observe(): void {}
  47. disconnect(): void {}
  48. unobserve(): void {}
  49. }
  50. const win = window as FixtureWindow
  51. let unmount: (() => void) | undefined
  52. beforeEach(() => {
  53. localStorage.clear()
  54. document.title = 'DeepSeek Harness'
  55. vi.stubGlobal('ResizeObserver', ResizeObserverStub)
  56. vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>
  57. setTimeout(() => { callback(0) }, 0) as unknown as number)
  58. vi.stubGlobal('cancelAnimationFrame', (id: number) => { clearTimeout(id) })
  59. })
  60. afterEach(() => {
  61. act(() => { unmount?.() })
  62. unmount = undefined
  63. cleanup()
  64. delete win.__DSH_BOOT__
  65. delete win.__ModuleLoader__
  66. delete (globalThis as Record<string, unknown>).__fxTiming
  67. document.body.innerHTML = ''
  68. document.head.querySelectorAll('style[data-plugin]').forEach((style) => { style.remove() })
  69. document.title = ''
  70. history.replaceState(null, '', '/')
  71. vi.unstubAllGlobals()
  72. })
  73. /** Boot the complete built client graph against the populated fixture branch. */
  74. function boot(): void {
  75. history.replaceState(null, '', '/?fixture')
  76. const root = document.createElement('div')
  77. root.id = 'root'
  78. document.body.appendChild(root)
  79. win.__DSH_BOOT__ = { rev: 'fx', entries: PLUGINS.map(({ dir: _dir, ...plugin }) => plugin) }
  80. act(() => {
  81. const entry = new AppWebEntry(root, {
  82. fetchBundle: (url) => {
  83. const code = bundles.get(url)
  84. return code === undefined ? Promise.reject(new Error(`missing built bundle ${url}`)) : Promise.resolve(code)
  85. },
  86. executeBundle: (code) => { (0, eval)(code) },
  87. })
  88. void entry.run()
  89. unmount = () => { entry.dispose() }
  90. })
  91. }
  92. /** Collapse decorative whitespace while preserving the text a user sees. */
  93. function visibleText(element: Element): string {
  94. return (element.textContent ?? '').replace(/\s+/g, ' ').trim()
  95. }
  96. /** Open the fixture history session (the alpha log carrying the run_code turn) and scroll to its tail. */
  97. async function openFixtureSession(): Promise<void> {
  98. const tree = await screen.findByRole('tree', { name: 'Sessions' }, { timeout: 10_000 })
  99. const group = within(tree).getByText('4 sessions').closest<HTMLElement>('[role="treeitem"]')
  100. if (group === null) throw new Error('fixture Workspace group missing')
  101. if (group.getAttribute('aria-expanded') === 'false') {
  102. fireEvent.click(within(group).getByText('fixture'))
  103. await waitFor(() => {
  104. expect(within(tree).getByText('4 sessions').closest('[role="treeitem"]')?.getAttribute('aria-expanded')).toBe('true')
  105. })
  106. }
  107. const session = await within(tree).findByText('Fixture 历史会话')
  108. fireEvent.click(session)
  109. await waitFor(() => {
  110. expect(document.querySelector('[data-variant="code"]')).not.toBeNull()
  111. }, { timeout: 10_000 })
  112. }
  113. it('renders the fixture run_code turn: code parent row, nested sub-rows, error state', async () => {
  114. boot()
  115. await openFixtureSession()
  116. const codeRoot = document.querySelector('[data-variant="code"]')
  117. if (codeRoot === null) throw new Error('code-variant row missing')
  118. const nest = codeRoot.closest('[class*="callRow"]')?.querySelector('[data-subcalls]')
  119. if (nest === undefined || nest === null) throw new Error('sub-call nest missing under the code row')
  120. expect({
  121. parentRow: visibleText(codeRoot),
  122. // The three sub-rows in dispatch order: bash rides the sample plugin's
  123. // keyed registration (the same one a native top-level bash row uses),
  124. // both reads ride GenericToolCard.
  125. bashSample: nest.querySelector('[data-sample="bash-global"]') !== null,
  126. subRows: [...nest.querySelectorAll(':scope > *')].map(visibleText),
  127. errorSubRow: nest.querySelector('[data-state="error"]') !== null,
  128. }).toMatchInlineSnapshot(`
  129. {
  130. "bashSample": true,
  131. "errorSubRow": true,
  132. "parentRow": "CodeRead the notes files and summarize",
  133. "subRows": [
  134. "BashList notes",
  135. "Readnotes/demo.txt",
  136. "Readnotes/missing.txt",
  137. ],
  138. }
  139. `)
  140. })
  141. it('expands the code row into the program body; sub-row clicks do not open details', async () => {
  142. boot()
  143. await openFixtureSession()
  144. // Expand: the leading control reveals the program (shiki-tokenized: the
  145. // text splits into styled spans inside one <pre class="shiki"> tree).
  146. const codeRoot = document.querySelector('[data-variant="code"]')
  147. if (codeRoot === null) throw new Error('code-variant row missing')
  148. const toggle = codeRoot.querySelector('button[aria-expanded]')
  149. if (toggle === null) throw new Error('code row expand control missing')
  150. fireEvent.click(toggle)
  151. await waitFor(() => {
  152. // Scope to THIS row: the markdown fixture turn also renders shiki pres.
  153. const pre = codeRoot.querySelector('pre.shiki')
  154. if (pre === null || !(pre.textContent ?? '').includes('const listing = await tools.bash')) {
  155. throw new Error('highlighted program body missing under the code row')
  156. }
  157. })
  158. // Tool rows no longer drive the details panel: bash is inert, file paths
  159. // are host-open links (fixture openPath is a no-op success).
  160. const nest = document.querySelector('[data-subcalls]')
  161. if (nest === null) throw new Error('sub-call nest missing')
  162. const bashRow = nest.querySelector('[data-sample="bash-global"]')
  163. if (bashRow === null) throw new Error('bash sample sub-row missing')
  164. const fileLink = nest.querySelector('button')
  165. if (fileLink === null) throw new Error('file-path summary link missing on a read sub-row')
  166. const frame = document.querySelector('[data-details-collapsed]')
  167. if (frame === null) throw new Error('app frame missing')
  168. expect(frame.getAttribute('data-details-collapsed')).toBe('true')
  169. fireEvent.click(bashRow)
  170. expect(frame.getAttribute('data-details-collapsed')).toBe('true')
  171. fireEvent.click(fileLink)
  172. expect(frame.getAttribute('data-details-collapsed')).toBe('true')
  173. expect({
  174. fileLink: visibleText(fileLink),
  175. detailsCollapsed: frame.getAttribute('data-details-collapsed'),
  176. }).toMatchInlineSnapshot(`
  177. {
  178. "detailsCollapsed": "true",
  179. "fileLink": "notes/demo.txt",
  180. }
  181. `)
  182. })
  183. it('trajectory and waterfall surface the run_code sub-calls with real timing', async () => {
  184. boot()
  185. await openFixtureSession()
  186. // Switch to the trajectory tab (same slot ring the chat view registers in).
  187. fireEvent.click(await screen.findByRole('tab', { name: 'Trajectory' }))
  188. await waitFor(() => {
  189. expect(document.querySelector('[data-kind="subtool"]')).not.toBeNull()
  190. }, { timeout: 10_000 })
  191. const subCells = [...document.querySelectorAll('[data-kind="subtool"]')]
  192. expect({
  193. // Three Sub cells nested under the run_code Tool cell, in dispatch order,
  194. // each with a real +N.Ns own-duration off the start/settle pair (the
  195. // fixture spaces every event 800ms apart — never the em dash).
  196. subCells: subCells.map(cell => visibleText(cell)),
  197. }).toMatchInlineSnapshot(`
  198. {
  199. "subCells": [
  200. "#51Subbash · {"command":"ls notes","description":"List notes"}+0.8s",
  201. "#52Subread · {"path":"notes/demo.txt"}+0.8s",
  202. "#53Subread · {"path":"notes/missing.txt"}+0.8s",
  203. ],
  204. }
  205. `)
  206. // Waterfall: each sub-call draws a measured lane scaled into the parent
  207. // turn's dispatch window.
  208. fireEvent.click(screen.getByRole('tab', { name: 'Waterfall' }))
  209. await waitFor(() => {
  210. expect(document.querySelector('[data-subspan]')).not.toBeNull()
  211. }, { timeout: 10_000 })
  212. const lanes = [...document.querySelectorAll('[data-subspan]')]
  213. expect({
  214. lanes: lanes.map(lane => ({
  215. label: visibleText(lane.querySelector('[class*="subTag"]') ?? lane),
  216. title: lane.querySelector('[data-timing]')?.getAttribute('title'),
  217. timing: lane.querySelector('[data-timing]')?.getAttribute('data-timing'),
  218. })),
  219. }).toMatchInlineSnapshot(`
  220. {
  221. "lanes": [
  222. {
  223. "label": "bash",
  224. "timing": "measured",
  225. "title": "bash · 0.80s",
  226. },
  227. {
  228. "label": "read",
  229. "timing": "measured",
  230. "title": "read · 0.80s",
  231. },
  232. {
  233. "label": "read",
  234. "timing": "measured",
  235. "title": "read · 0.80s",
  236. },
  237. ],
  238. }
  239. `)
  240. })