search-card.snapshot.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. // @vitest-environment jsdom
  2. // Assembled search-card snapshot: boots the real built `packages/client/*/lib/
  3. // client.js` bundles through AppWebEntry's ModuleLoader path against the keyless
  4. // FixtureApiClient transport (no API key, no model round), opens the fixture
  5. // session, and pins the search card the `grep` turn (fixture turn 66) renders in
  6. // the assembled application. The built-boot smoke proves the graph boots but
  7. // carries no behavior assertions by contract; this is the assembled-output check
  8. // that a broken SearchRow registration or a dropped card would fail — the
  9. // per-package suites bench over src and cannot see the bundled wiring.
  10. //
  11. // Keyless and deterministic: the fixture is the fake server, so the grep turn's
  12. // matches, its truncation summary, and its head/tail cap are fixed in the
  13. // fixture, not harvested from a live model. The recovery-footer arm is a pure
  14. // derivation over the result view, pinned at every render site by the
  15. // ui-conversation suite; here the fixture turn exercises the assembled card
  16. // shape and its cap.
  17. import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
  18. import { dirname, join } from 'node:path'
  19. import { act, cleanup, fireEvent, screen, waitFor, within } from '@testing-library/react'
  20. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  21. import type { WebBootEntry } from '@deepseek-ai/dsh-client-modules/client'
  22. import { AppWebEntry } from '@deepseek-ai/dsh-client-web'
  23. const EXPECTED = join(process.cwd(), 'apps/web/tests/snapshots/search-card/grep-card.expected.txt')
  24. const refreshing = process.env.DSH_SNAPSHOT === 'record' || process.env.DSH_SNAPSHOT === 'refresh'
  25. const PLUGINS: readonly (WebBootEntry & { dir: string })[] = [
  26. { id: '@deepseek-ai/dsh-client-connection', dir: 'connection', url: '/plugins/connection.js', rev: 'fx', inject: [], immediately: true },
  27. { id: '@deepseek-ai/dsh-client-runtime', dir: 'runtime', url: '/plugins/runtime.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-connection'], immediately: true },
  28. { id: '@deepseek-ai/dsh-client-ui-theme', dir: 'ui-theme', url: '/plugins/ui-theme.js', rev: 'fx', inject: [], immediately: true },
  29. { id: '@deepseek-ai/dsh-client-locale', dir: 'locale', url: '/plugins/locale.js', rev: 'fx', inject: [], immediately: true },
  30. { id: '@deepseek-ai/dsh-client-ui-layout', dir: 'ui-layout', url: '/plugins/ui-layout.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-runtime'] },
  31. { id: '@deepseek-ai/dsh-client-ui-sidebar', dir: 'ui-sidebar', url: '/plugins/ui-sidebar.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] },
  32. { id: '@deepseek-ai/dsh-client-ui-conversation', dir: 'ui-conversation', url: '/plugins/ui-conversation.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] },
  33. {
  34. id: '@deepseek-ai/dsh-client-ui-workspace',
  35. dir: 'ui-workspace',
  36. url: '/plugins/ui-workspace.js',
  37. rev: 'fx',
  38. inject: [
  39. '@deepseek-ai/dsh-client-runtime',
  40. '@deepseek-ai/dsh-client-ui-conversation',
  41. '@deepseek-ai/dsh-client-ui-sidebar',
  42. ],
  43. },
  44. { id: '@deepseek-ai/dsh-client-ui-trajectory', dir: 'ui-trajectory', url: '/plugins/ui-trajectory.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-conversation'] },
  45. ]
  46. const bundles = new Map(PLUGINS.map(plugin => [
  47. plugin.url,
  48. readFileSync(join(process.cwd(), 'packages/client', plugin.dir, 'lib/client.js'), 'utf8'),
  49. ]))
  50. interface FixtureWindow extends Window {
  51. __DSH_BOOT__?: { rev: string; entries: WebBootEntry[] }
  52. __ModuleLoader__?: unknown
  53. }
  54. class ResizeObserverStub {
  55. observe(): void {}
  56. disconnect(): void {}
  57. unobserve(): void {}
  58. }
  59. const win = window as FixtureWindow
  60. let unmount: (() => void) | undefined
  61. /** Normalize a rendered search card to a stable text shape: the kind, the banner
  62. * summary, each file header (path + count), each visible match line, the expand
  63. * control label, and the recovery footer. CSS-module class names carry a
  64. * per-build hash in one of two schemes — ui-primitives emits `_<name>_<hash>`
  65. * (name bounded by underscores), ui-conversation emits `<hash>_<name>` (name at
  66. * the end). `hasClass` matches a module class by its logical name under either,
  67. * without matching a longer name that contains it (`line` must not hit
  68. * `lineNumber`). */
  69. function hasClass(el: Element, name: string): boolean {
  70. return [...el.classList].some(cls => cls === name || cls.endsWith(`_${name}`) || cls.startsWith(`_${name}_`) || cls.includes(`_${name}_`))
  71. }
  72. function cardShape(root: Element): string {
  73. const card = root.querySelector('[data-search]')
  74. if (card === null) return '<no search card>'
  75. const pick = (from: Element, name: string): Element[] =>
  76. [...from.querySelectorAll('*')].filter(el => hasClass(el, name))
  77. const lines: string[] = [`kind=${card.getAttribute('data-search')}`]
  78. const summary = pick(card, 'summary')[0]?.textContent?.trim()
  79. if (summary !== undefined && summary !== '') lines.push(`summary=${summary}`)
  80. for (const header of pick(card, 'fileHeader')) lines.push(`file=${header.textContent?.trim() ?? ''}`)
  81. for (const row of pick(card, 'line')) lines.push(`line=${row.textContent?.trim() ?? ''}`)
  82. const expand = pick(card, 'expand')[0]?.textContent?.trim()
  83. if (expand !== undefined && expand !== '') lines.push(`expand=${expand}`)
  84. const recovery = pick(root, 'searchRecovery')[0]?.textContent?.trim()
  85. if (recovery !== undefined && recovery !== '') lines.push(`recovery=${recovery}`)
  86. return lines.join('\n')
  87. }
  88. beforeEach(() => {
  89. localStorage.clear()
  90. // English pinned before boot so the sidebar's role/text locators stay
  91. // deterministic (the built-boot smoke's convention).
  92. localStorage.setItem('dsh.locale', 'en')
  93. document.title = 'DeepSeek Harness'
  94. vi.stubGlobal('ResizeObserver', ResizeObserverStub)
  95. vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>
  96. setTimeout(() => { callback(0) }, 0) as unknown as number)
  97. vi.stubGlobal('cancelAnimationFrame', (id: number) => { clearTimeout(id) })
  98. })
  99. afterEach(() => {
  100. act(() => { unmount?.() })
  101. unmount = undefined
  102. cleanup()
  103. delete win.__DSH_BOOT__
  104. delete win.__ModuleLoader__
  105. document.body.innerHTML = ''
  106. document.head.querySelectorAll('style[data-plugin]').forEach((style) => { style.remove() })
  107. document.title = ''
  108. history.replaceState(null, '', '/')
  109. vi.unstubAllGlobals()
  110. })
  111. describe('assembled search card', () => {
  112. it('renders the grep card, its truncation summary, and its capped head/tail slice from the built bundles', async () => {
  113. history.replaceState(null, '', '/?fixture')
  114. const root = document.createElement('div')
  115. root.id = 'root'
  116. document.body.appendChild(root)
  117. win.__DSH_BOOT__ = { rev: 'fx', entries: PLUGINS.map(({ dir: _dir, ...plugin }) => plugin) }
  118. act(() => {
  119. const entry = new AppWebEntry(root, {
  120. loadBundle: async (url) => {
  121. const code = bundles.get(url)
  122. if (code === undefined) throw new Error(`missing built bundle ${url}`)
  123. ;(0, eval)(code)
  124. },
  125. })
  126. void entry.run()
  127. unmount = () => { entry.dispose() }
  128. })
  129. const tree = await screen.findByRole('tree', { name: 'Sessions' }, { timeout: 10_000 })
  130. fireEvent.click(await within(tree).findByText('Fixture 历史会话'))
  131. // Wait for chat content to reach the fixture's later turns (the bash sample
  132. // is turn 65, the grep card turn 66).
  133. await waitFor(() => {
  134. expect(document.querySelector('[data-sample="bash"]')).not.toBeNull()
  135. }, { timeout: 10_000 })
  136. // The grep turn's keyed SearchRow composes ToolRow: the card is collapsed
  137. // by default, so wait for the summary row, then expand it to reach the card.
  138. await waitFor(() => {
  139. const tools = [...document.querySelectorAll('[data-tool]')].map(el => el.getAttribute('data-tool'))
  140. expect(tools, `tools present: ${tools.join(', ')}`).toContain('grep')
  141. }, { timeout: 10_000 })
  142. // `data-tool` sits on the ToolRow root; the collapsed row is the expand
  143. // toggle. Click it so the card and its recovery footer mount, then shape the
  144. // whole row (the card lives inside ToolRow's body wrapper).
  145. const grepRow = document.querySelector('[data-tool="grep"]')!
  146. act(() => { fireEvent.click(grepRow.querySelector('[data-expandable]') ?? grepRow) })
  147. await waitFor(() => {
  148. expect(grepRow.querySelector('[data-search]')).not.toBeNull()
  149. }, { timeout: 10_000 })
  150. const shape = cardShape(grepRow)
  151. if (refreshing) {
  152. mkdirSync(dirname(EXPECTED), { recursive: true })
  153. writeFileSync(EXPECTED, shape)
  154. }
  155. await expect(shape).toMatchFileSnapshot(EXPECTED)
  156. })
  157. })