code-mode-fixture.snapshot.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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, details-panel resolution of a sub-callId, 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 and resolves a sub-row through the details panel', 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. // Sub-row click → details panel resolves the sub-callId with FULL output.
  159. const nest = document.querySelector('[data-subcalls]')
  160. if (nest === null) throw new Error('sub-call nest missing')
  161. const bashRow = nest.querySelector('[data-sample="bash-global"]')
  162. if (bashRow === null) throw new Error('bash sample sub-row missing')
  163. fireEvent.click(bashRow)
  164. const details = await screen.findByText('Input')
  165. const panel = details.closest('[class*="root"]')
  166. if (panel === null) throw new Error('details panel missing')
  167. expect({
  168. title: visibleText(within(panel as HTMLElement).getByText('bash')),
  169. inputEchoesArgs: visibleText(panel).includes('ls notes'),
  170. outputComplete: visibleText(panel).includes('demo.txt new-demo.txt')
  171. || visibleText(panel).includes('demo.txt\nnew-demo.txt')
  172. || (panel.textContent ?? '').includes('demo.txt\nnew-demo.txt'),
  173. }).toMatchInlineSnapshot(`
  174. {
  175. "inputEchoesArgs": true,
  176. "outputComplete": true,
  177. "title": "bash",
  178. }
  179. `)
  180. })
  181. it('trajectory and waterfall surface the run_code sub-calls with real timing', async () => {
  182. boot()
  183. await openFixtureSession()
  184. // Switch to the trajectory tab (same slot ring the chat view registers in).
  185. fireEvent.click(await screen.findByRole('tab', { name: 'Trajectory' }))
  186. await waitFor(() => {
  187. expect(document.querySelector('[data-kind="subtool"]')).not.toBeNull()
  188. }, { timeout: 10_000 })
  189. const subCells = [...document.querySelectorAll('[data-kind="subtool"]')]
  190. expect({
  191. // Three Sub cells nested under the run_code Tool cell, in dispatch order,
  192. // each with a real +N.Ns own-duration off the start/settle pair (the
  193. // fixture spaces every event 800ms apart — never the em dash).
  194. subCells: subCells.map(cell => visibleText(cell)),
  195. }).toMatchInlineSnapshot(`
  196. {
  197. "subCells": [
  198. "#51Subbash · {"command":"ls notes","description":"List notes"}+0.8s",
  199. "#52Subread · {"path":"notes/demo.txt"}+0.8s",
  200. "#53Subread · {"path":"notes/missing.txt"}+0.8s",
  201. ],
  202. }
  203. `)
  204. // Waterfall: each sub-call draws a measured lane scaled into the parent
  205. // turn's dispatch window.
  206. fireEvent.click(screen.getByRole('tab', { name: 'Waterfall' }))
  207. await waitFor(() => {
  208. expect(document.querySelector('[data-subspan]')).not.toBeNull()
  209. }, { timeout: 10_000 })
  210. const lanes = [...document.querySelectorAll('[data-subspan]')]
  211. expect({
  212. lanes: lanes.map(lane => ({
  213. label: visibleText(lane.querySelector('[class*="subTag"]') ?? lane),
  214. title: lane.querySelector('[data-timing]')?.getAttribute('title'),
  215. timing: lane.querySelector('[data-timing]')?.getAttribute('data-timing'),
  216. })),
  217. }).toMatchInlineSnapshot(`
  218. {
  219. "lanes": [
  220. {
  221. "label": "bash",
  222. "timing": "measured",
  223. "title": "bash · 0.80s",
  224. },
  225. {
  226. "label": "read",
  227. "timing": "measured",
  228. "title": "read · 0.80s",
  229. },
  230. {
  231. "label": "read",
  232. "timing": "measured",
  233. "title": "read · 0.80s",
  234. },
  235. ],
  236. }
  237. `)
  238. })