workspace-flow.snapshot.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. // @vitest-environment jsdom
  2. import { readFileSync } from 'node:fs'
  3. import { join } from 'node:path'
  4. import { act, cleanup, fireEvent, screen, waitFor, within } from '@testing-library/react'
  5. import { afterEach, beforeEach, expect, it, vi } from 'vitest'
  6. import type { WebBootEntry } from '@deepseek-ai/dsh-client-modules/client'
  7. import { AppWebEntry } from '@deepseek-ai/dsh-client-web'
  8. const PLUGINS: readonly (WebBootEntry & { dir: string })[] = [
  9. { id: '@deepseek-ai/dsh-client-connection', dir: 'connection', url: '/plugins/connection.js', rev: 'fx', inject: [], immediately: true },
  10. { id: '@deepseek-ai/dsh-client-runtime', dir: 'runtime', url: '/plugins/runtime.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-connection'], immediately: true },
  11. { id: '@deepseek-ai/dsh-client-ui-theme', dir: 'ui-theme', url: '/plugins/ui-theme.js', rev: 'fx', inject: [], immediately: true },
  12. { id: '@deepseek-ai/dsh-client-locale', dir: 'locale', url: '/plugins/locale.js', rev: 'fx', inject: [], immediately: true },
  13. { id: '@deepseek-ai/dsh-client-ui-layout', dir: 'ui-layout', url: '/plugins/ui-layout.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-runtime'] },
  14. { id: '@deepseek-ai/dsh-client-ui-sidebar', dir: 'ui-sidebar', url: '/plugins/ui-sidebar.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] },
  15. { id: '@deepseek-ai/dsh-client-ui-settings', dir: 'ui-settings', url: '/plugins/ui-settings.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-sidebar'] },
  16. { id: '@deepseek-ai/dsh-client-ui-settings-general', dir: 'ui-settings-general', url: '/plugins/ui-settings-general.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-settings', '@deepseek-ai/dsh-client-locale'] },
  17. { id: '@deepseek-ai/dsh-client-ui-models', dir: 'ui-models', url: '/plugins/ui-models.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-settings'] },
  18. { id: '@deepseek-ai/dsh-client-ui-conversation', dir: 'ui-conversation', url: '/plugins/ui-conversation.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] },
  19. {
  20. id: '@deepseek-ai/dsh-client-ui-workspace',
  21. dir: 'ui-workspace',
  22. url: '/plugins/ui-workspace.js',
  23. rev: 'fx',
  24. inject: [
  25. '@deepseek-ai/dsh-client-runtime',
  26. '@deepseek-ai/dsh-client-ui-conversation',
  27. '@deepseek-ai/dsh-client-ui-sidebar',
  28. ],
  29. },
  30. { id: '@deepseek-ai/dsh-client-ui-trajectory', dir: 'ui-trajectory', url: '/plugins/ui-trajectory.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-conversation'] },
  31. ]
  32. const bundles = new Map(PLUGINS.map(plugin => [
  33. plugin.url,
  34. readFileSync(join(process.cwd(), 'packages/client', plugin.dir, 'lib/client.js'), 'utf8'),
  35. ]))
  36. interface FixtureWindow extends Window {
  37. __DSH_BOOT__?: { rev: string; entries: WebBootEntry[] }
  38. __ModuleLoader__?: unknown
  39. }
  40. class ResizeObserverStub {
  41. observe(): void {}
  42. disconnect(): void {}
  43. unobserve(): void {}
  44. }
  45. const win = window as FixtureWindow
  46. let unmount: (() => void) | undefined
  47. beforeEach(() => {
  48. localStorage.clear()
  49. document.title = 'DeepSeek Harness'
  50. vi.stubGlobal('ResizeObserver', ResizeObserverStub)
  51. vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>
  52. setTimeout(() => { callback(0) }, 0) as unknown as number)
  53. vi.stubGlobal('cancelAnimationFrame', (id: number) => { clearTimeout(id) })
  54. })
  55. afterEach(() => {
  56. act(() => { unmount?.() })
  57. unmount = undefined
  58. cleanup()
  59. delete win.__DSH_BOOT__
  60. delete win.__ModuleLoader__
  61. delete (globalThis as Record<string, unknown>).__fxTiming
  62. document.body.innerHTML = ''
  63. document.head.querySelectorAll('style[data-plugin]').forEach((style) => { style.remove() })
  64. document.title = ''
  65. history.replaceState(null, '', '/')
  66. vi.unstubAllGlobals()
  67. })
  68. /** Boot the complete built client graph against one keyless fixture branch. */
  69. function boot(search: string): void {
  70. history.replaceState(null, '', `/${search}`)
  71. const root = document.createElement('div')
  72. root.id = 'root'
  73. document.body.appendChild(root)
  74. win.__DSH_BOOT__ = { rev: 'fx', entries: PLUGINS.map(({ dir: _dir, ...plugin }) => plugin) }
  75. act(() => {
  76. const entry = new AppWebEntry(root, {
  77. fetchBundle: (url) => {
  78. const code = bundles.get(url)
  79. return code === undefined ? Promise.reject(new Error(`missing built bundle ${url}`)) : Promise.resolve(code)
  80. },
  81. executeBundle: (code) => { (0, eval)(code) },
  82. })
  83. void entry.run()
  84. unmount = () => { entry.dispose() }
  85. })
  86. }
  87. /** Recreate the built client graph while preserving browser-persistent state. */
  88. function refresh(search: string): void {
  89. act(() => { unmount?.() })
  90. unmount = undefined
  91. cleanup()
  92. delete win.__DSH_BOOT__
  93. delete win.__ModuleLoader__
  94. delete (globalThis as Record<string, unknown>).__fxTiming
  95. document.body.innerHTML = ''
  96. document.head.querySelectorAll('style[data-plugin]').forEach((style) => { style.remove() })
  97. boot(search)
  98. }
  99. /** Collapse decorative whitespace while preserving the text a user sees. */
  100. function visibleText(element: Element): string {
  101. return (element.textContent ?? '').replace(/\s+/g, ' ').trim()
  102. }
  103. /** Identify the interactive Workspace chip by its menu contract. */
  104. function workspaceChip(): HTMLElement {
  105. const chip = screen.getAllByRole('button', { name: 'Choose workspace' })
  106. .find(element => element.getAttribute('aria-haspopup') === 'menu')
  107. if (chip === undefined) throw new Error('Workspace chip missing')
  108. return chip
  109. }
  110. /** Edit the runtime-owned controlled input and assert the same-tick echo:
  111. * a deferred echo makes React roll the textarea back mid-IME-composition,
  112. * committing partial keystrokes (e.g. Pinyin "nihao" leaking as "nnini h…"). */
  113. function setComposerText(composer: HTMLElement, value: string): void {
  114. fireEvent.change(composer, { target: { value } })
  115. expect((composer as HTMLTextAreaElement).value).toBe(value)
  116. }
  117. it('starts a writable page-local draft without inventing a sidebar Workspace', async () => {
  118. boot('?fixture=empty')
  119. const composer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 })
  120. const tree = screen.getByRole('tree', { name: 'Sessions' })
  121. setComposerText(composer, 'keep this local')
  122. expect({
  123. headline: visibleText(screen.getByText("Let's start building")),
  124. workspaceDraft: visibleText(workspaceChip()),
  125. sidebar: visibleText(tree),
  126. composerDisabled: (composer as HTMLTextAreaElement).disabled,
  127. prompt: (composer as HTMLTextAreaElement).value,
  128. }).toMatchInlineSnapshot(`
  129. {
  130. "composerDisabled": false,
  131. "headline": "Let's start building",
  132. "prompt": "keep this local",
  133. "sidebar": "No sessions yet",
  134. "workspaceDraft": "workspace",
  135. }
  136. `)
  137. })
  138. it('creates a real empty Workspace immediately and focuses its Session draft', async () => {
  139. boot('?fixture=empty')
  140. await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 })
  141. const workspaceSection = screen.getByText('Workspaces').parentElement
  142. if (workspaceSection === null) throw new Error('Workspace section missing')
  143. fireEvent.click(within(workspaceSection).getByRole('button', { name: 'Create workspace' }))
  144. fireEvent.click(await screen.findByRole('menuitem', { name: 'Create workspace' }))
  145. fireEvent.click(await screen.findByRole('menuitem', { name: 'Create a new workspace' }))
  146. const dialog = await screen.findByRole('dialog', { name: 'Create a new workspace' })
  147. fireEvent.change(within(dialog).getByRole('textbox', { name: 'New workspace name' }), {
  148. target: { value: 'nova' },
  149. })
  150. fireEvent.click(within(dialog).getByRole('button', { name: 'Create workspace' }))
  151. const tree = await screen.findByRole('tree', { name: 'Sessions' })
  152. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() })
  153. const group = within(tree).getByText('1 session').closest('[role="treeitem"]')
  154. const draft = within(tree).getByText('New session').closest('[role="treeitem"]')
  155. if (group === null || draft === null) throw new Error('created Workspace projection missing')
  156. expect({
  157. workspace: visibleText(group),
  158. draft: visibleText(draft),
  159. draftSelected: draft.getAttribute('aria-selected'),
  160. composerWorkspace: visibleText(workspaceChip()),
  161. }).toMatchInlineSnapshot(`
  162. {
  163. "composerWorkspace": "nova",
  164. "draft": "New session",
  165. "draftSelected": "true",
  166. "workspace": "nova1 session",
  167. }
  168. `)
  169. })
  170. it('drops the page-local draft on refresh while retaining real Workspaces and Sessions', async () => {
  171. boot('?fixture')
  172. const composer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 })
  173. const tree = screen.getByRole('tree', { name: 'Sessions' })
  174. setComposerText(composer, 'discard this page-local draft')
  175. const beforeGroup = within(tree).getByText('4 sessions').closest('[role="treeitem"]')
  176. if (beforeGroup === null) throw new Error('fixture Workspace projection missing before refresh')
  177. const before = {
  178. workspace: visibleText(beforeGroup),
  179. draft: visibleText(within(tree).getByText('New session')),
  180. prompt: (composer as HTMLTextAreaElement).value,
  181. }
  182. refresh('?fixture')
  183. const refreshedComposer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 })
  184. const refreshedTree = screen.getByRole('tree', { name: 'Sessions' })
  185. const afterGroup = within(refreshedTree).getByText('4 sessions').closest('[role="treeitem"]')
  186. if (afterGroup === null) throw new Error('fixture Workspace projection missing after refresh')
  187. expect({
  188. before,
  189. after: {
  190. workspace: visibleText(afterGroup),
  191. replacementDraft: visibleText(within(refreshedTree).getByText('New session')),
  192. prompt: (refreshedComposer as HTMLTextAreaElement).value,
  193. },
  194. }).toMatchInlineSnapshot(`
  195. {
  196. "after": {
  197. "prompt": "",
  198. "replacementDraft": "New session",
  199. "workspace": "fixture4 sessions",
  200. },
  201. "before": {
  202. "draft": "New session",
  203. "prompt": "discard this page-local draft",
  204. "workspace": "fixture4 sessions",
  205. },
  206. }
  207. `)
  208. })
  209. it('keeps a published Session with only cwd membership evidence in Ungrouped', async () => {
  210. boot('?fixture&fixtureAttach=fail')
  211. const composer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 })
  212. setComposerText(composer, 'keep this cwd-only session')
  213. fireEvent.click(screen.getByRole('button', { name: 'Send message' }))
  214. const tree = screen.getByRole('tree', { name: 'Sessions' })
  215. await waitFor(() => { expect(within(tree).getByText('Ungrouped')).toBeDefined() }, { timeout: 10_000 })
  216. const workspaceGroup = within(tree).getByText('3 sessions').closest('[role="treeitem"]')
  217. const ungroupedGroup = within(tree).getByText('1 session').closest('[role="treeitem"]')
  218. const ungroupedSection = ungroupedGroup?.parentElement
  219. if (workspaceGroup === null || ungroupedGroup === null || ungroupedSection === null || ungroupedSection === undefined) {
  220. throw new Error('Workspace or Ungrouped projection missing')
  221. }
  222. const session = within(ungroupedSection).getByRole('treeitem', { selected: true })
  223. const retained = screen.getByDisplayValue('keep this cwd-only session')
  224. expect({
  225. workspace: visibleText(workspaceGroup),
  226. ungrouped: visibleText(ungroupedGroup),
  227. session: within(session).getByText('fixture', { exact: true }).textContent,
  228. sessionSelected: session.getAttribute('aria-selected'),
  229. prompt: (retained as HTMLTextAreaElement).value,
  230. }).toMatchInlineSnapshot(`
  231. {
  232. "prompt": "keep this cwd-only session",
  233. "session": "fixture",
  234. "sessionSelected": "true",
  235. "ungrouped": "Ungrouped1 session",
  236. "workspace": "fixture3 sessions",
  237. }
  238. `)
  239. })
  240. it('materializes the automatic Workspace and Session on the first successful send', async () => {
  241. boot('?fixture=empty')
  242. const composer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 })
  243. setComposerText(composer, 'build a lighthouse')
  244. fireEvent.click(screen.getByRole('button', { name: 'Send message' }))
  245. const tree = screen.getByRole('tree', { name: 'Sessions' })
  246. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() }, { timeout: 10_000 })
  247. await screen.findByText('build a lighthouse', { exact: true }, { timeout: 10_000 })
  248. const group = within(tree).getByText('1 session').closest('[role="treeitem"]')
  249. const session = within(tree).getByRole('treeitem', { selected: true })
  250. if (group === null) throw new Error('materialized Workspace projection missing')
  251. expect({
  252. workspace: visibleText(group),
  253. session: within(session).getByText('workspace', { exact: true }).textContent,
  254. sessionSelected: session.getAttribute('aria-selected'),
  255. promptVisible: screen.getByText('build a lighthouse', { exact: true }).textContent,
  256. }).toMatchInlineSnapshot(`
  257. {
  258. "promptVisible": "build a lighthouse",
  259. "session": "workspace",
  260. "sessionSelected": "true",
  261. "workspace": "workspace1 session",
  262. }
  263. `)
  264. })
  265. it('keeps the published Workspace, Session, and unsent prompt after rejection', async () => {
  266. boot('?fixture=empty&fixturePrompt=reject')
  267. const composer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 })
  268. setComposerText(composer, 'do not lose this')
  269. fireEvent.click(screen.getByRole('button', { name: 'Send message' }))
  270. const alert = await screen.findByRole('alert', {}, { timeout: 10_000 })
  271. const retained = screen.getByDisplayValue('do not lose this')
  272. const tree = screen.getByRole('tree', { name: 'Sessions' })
  273. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() })
  274. const group = within(tree).getByText('1 session').closest('[role="treeitem"]')
  275. const session = within(tree).getByRole('treeitem', { selected: true })
  276. if (group === null) throw new Error('rejected-send Workspace projection missing')
  277. expect({
  278. workspace: visibleText(group),
  279. session: within(session).getByText('workspace', { exact: true }).textContent,
  280. error: visibleText(alert),
  281. prompt: (retained as HTMLTextAreaElement).value,
  282. }).toMatchInlineSnapshot(`
  283. {
  284. "error": "Message send failed: agent-busy: fixture: prompt rejected before acceptance",
  285. "prompt": "do not lose this",
  286. "session": "workspace",
  287. "workspace": "workspace1 session",
  288. }
  289. `)
  290. })