workspace-flow.snapshot.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. /** Wait for the runtime-owned controlled input to echo a browser edit. */
  111. async function setComposerText(composer: HTMLElement, value: string): Promise<void> {
  112. fireEvent.change(composer, { target: { value } })
  113. await waitFor(() => { expect((composer as HTMLTextAreaElement).value).toBe(value) })
  114. }
  115. it('starts a writable page-local draft without inventing a sidebar Workspace', async () => {
  116. boot('?fixture=empty')
  117. const composer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 })
  118. const tree = screen.getByRole('tree', { name: 'Sessions' })
  119. await setComposerText(composer, 'keep this local')
  120. expect({
  121. headline: visibleText(screen.getByText("Let's start building")),
  122. workspaceDraft: visibleText(workspaceChip()),
  123. sidebar: visibleText(tree),
  124. composerDisabled: (composer as HTMLTextAreaElement).disabled,
  125. prompt: (composer as HTMLTextAreaElement).value,
  126. }).toMatchInlineSnapshot(`
  127. {
  128. "composerDisabled": false,
  129. "headline": "Let's start building",
  130. "prompt": "keep this local",
  131. "sidebar": "No sessions yet",
  132. "workspaceDraft": "workspace",
  133. }
  134. `)
  135. })
  136. it('creates a real empty Workspace immediately and focuses its Session draft', async () => {
  137. boot('?fixture=empty')
  138. await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 })
  139. const workspaceSection = screen.getByText('Workspaces').parentElement
  140. if (workspaceSection === null) throw new Error('Workspace section missing')
  141. fireEvent.click(within(workspaceSection).getByRole('button', { name: 'Create workspace' }))
  142. fireEvent.click(await screen.findByRole('menuitem', { name: 'Create workspace' }))
  143. fireEvent.click(await screen.findByRole('menuitem', { name: 'Create a new workspace' }))
  144. const dialog = await screen.findByRole('dialog', { name: 'Create a new workspace' })
  145. fireEvent.change(within(dialog).getByRole('textbox', { name: 'New workspace name' }), {
  146. target: { value: 'nova' },
  147. })
  148. fireEvent.click(within(dialog).getByRole('button', { name: 'Create workspace' }))
  149. const tree = await screen.findByRole('tree', { name: 'Sessions' })
  150. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() })
  151. const group = within(tree).getByText('1 session').closest('[role="treeitem"]')
  152. const draft = within(tree).getByText('New session').closest('[role="treeitem"]')
  153. if (group === null || draft === null) throw new Error('created Workspace projection missing')
  154. expect({
  155. workspace: visibleText(group),
  156. draft: visibleText(draft),
  157. draftSelected: draft.getAttribute('aria-selected'),
  158. composerWorkspace: visibleText(workspaceChip()),
  159. }).toMatchInlineSnapshot(`
  160. {
  161. "composerWorkspace": "nova",
  162. "draft": "New session",
  163. "draftSelected": "true",
  164. "workspace": "nova1 session",
  165. }
  166. `)
  167. })
  168. it('drops the page-local draft on refresh while retaining real Workspaces and Sessions', async () => {
  169. boot('?fixture')
  170. const composer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 })
  171. const tree = screen.getByRole('tree', { name: 'Sessions' })
  172. await setComposerText(composer, 'discard this page-local draft')
  173. const beforeGroup = within(tree).getByText('4 sessions').closest('[role="treeitem"]')
  174. if (beforeGroup === null) throw new Error('fixture Workspace projection missing before refresh')
  175. const before = {
  176. workspace: visibleText(beforeGroup),
  177. draft: visibleText(within(tree).getByText('New session')),
  178. prompt: (composer as HTMLTextAreaElement).value,
  179. }
  180. refresh('?fixture')
  181. const refreshedComposer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 })
  182. const refreshedTree = screen.getByRole('tree', { name: 'Sessions' })
  183. const afterGroup = within(refreshedTree).getByText('4 sessions').closest('[role="treeitem"]')
  184. if (afterGroup === null) throw new Error('fixture Workspace projection missing after refresh')
  185. expect({
  186. before,
  187. after: {
  188. workspace: visibleText(afterGroup),
  189. replacementDraft: visibleText(within(refreshedTree).getByText('New session')),
  190. prompt: (refreshedComposer as HTMLTextAreaElement).value,
  191. },
  192. }).toMatchInlineSnapshot(`
  193. {
  194. "after": {
  195. "prompt": "",
  196. "replacementDraft": "New session",
  197. "workspace": "fixture4 sessions",
  198. },
  199. "before": {
  200. "draft": "New session",
  201. "prompt": "discard this page-local draft",
  202. "workspace": "fixture4 sessions",
  203. },
  204. }
  205. `)
  206. })
  207. it('keeps a published Session with only cwd membership evidence in Ungrouped', async () => {
  208. boot('?fixture&fixtureAttach=fail')
  209. const composer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 })
  210. await setComposerText(composer, 'keep this cwd-only session')
  211. fireEvent.click(screen.getByRole('button', { name: 'Send message' }))
  212. const tree = screen.getByRole('tree', { name: 'Sessions' })
  213. await waitFor(() => { expect(within(tree).getByText('Ungrouped')).toBeDefined() }, { timeout: 10_000 })
  214. const workspaceGroup = within(tree).getByText('3 sessions').closest('[role="treeitem"]')
  215. const ungroupedGroup = within(tree).getByText('1 session').closest('[role="treeitem"]')
  216. const ungroupedSection = ungroupedGroup?.parentElement
  217. if (workspaceGroup === null || ungroupedGroup === null || ungroupedSection === null || ungroupedSection === undefined) {
  218. throw new Error('Workspace or Ungrouped projection missing')
  219. }
  220. const session = within(ungroupedSection).getByRole('treeitem', { selected: true })
  221. const retained = screen.getByDisplayValue('keep this cwd-only session')
  222. expect({
  223. workspace: visibleText(workspaceGroup),
  224. ungrouped: visibleText(ungroupedGroup),
  225. session: within(session).getByText('fixture', { exact: true }).textContent,
  226. sessionSelected: session.getAttribute('aria-selected'),
  227. prompt: (retained as HTMLTextAreaElement).value,
  228. }).toMatchInlineSnapshot(`
  229. {
  230. "prompt": "keep this cwd-only session",
  231. "session": "fixture",
  232. "sessionSelected": "true",
  233. "ungrouped": "Ungrouped1 session",
  234. "workspace": "fixture3 sessions",
  235. }
  236. `)
  237. })
  238. it('materializes the automatic Workspace and Session on the first successful send', async () => {
  239. boot('?fixture=empty')
  240. const composer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 })
  241. await setComposerText(composer, 'build a lighthouse')
  242. fireEvent.click(screen.getByRole('button', { name: 'Send message' }))
  243. const tree = screen.getByRole('tree', { name: 'Sessions' })
  244. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() }, { timeout: 10_000 })
  245. await screen.findByText('build a lighthouse', { exact: true }, { timeout: 10_000 })
  246. const group = within(tree).getByText('1 session').closest('[role="treeitem"]')
  247. const session = within(tree).getByRole('treeitem', { selected: true })
  248. if (group === null) throw new Error('materialized Workspace projection missing')
  249. expect({
  250. workspace: visibleText(group),
  251. session: within(session).getByText('workspace', { exact: true }).textContent,
  252. sessionSelected: session.getAttribute('aria-selected'),
  253. promptVisible: screen.getByText('build a lighthouse', { exact: true }).textContent,
  254. }).toMatchInlineSnapshot(`
  255. {
  256. "promptVisible": "build a lighthouse",
  257. "session": "workspace",
  258. "sessionSelected": "true",
  259. "workspace": "workspace1 session",
  260. }
  261. `)
  262. })
  263. it('keeps the published Workspace, Session, and unsent prompt after rejection', async () => {
  264. boot('?fixture=empty&fixturePrompt=reject')
  265. const composer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 })
  266. await setComposerText(composer, 'do not lose this')
  267. fireEvent.click(screen.getByRole('button', { name: 'Send message' }))
  268. const alert = await screen.findByRole('alert', {}, { timeout: 10_000 })
  269. const retained = screen.getByDisplayValue('do not lose this')
  270. const tree = screen.getByRole('tree', { name: 'Sessions' })
  271. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() })
  272. const group = within(tree).getByText('1 session').closest('[role="treeitem"]')
  273. const session = within(tree).getByRole('treeitem', { selected: true })
  274. if (group === null) throw new Error('rejected-send Workspace projection missing')
  275. expect({
  276. workspace: visibleText(group),
  277. session: within(session).getByText('workspace', { exact: true }).textContent,
  278. error: visibleText(alert),
  279. prompt: (retained as HTMLTextAreaElement).value,
  280. }).toMatchInlineSnapshot(`
  281. {
  282. "error": "Message send failed: agent-busy: fixture: prompt rejected before acceptance",
  283. "prompt": "do not lose this",
  284. "session": "workspace",
  285. "workspace": "workspace1 session",
  286. }
  287. `)
  288. })