code-mode-fixture.snapshot.ts 10 KB

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