workspace-flow.snapshot.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. // @vitest-environment jsdom
  2. // Assembled keyless snapshots of the New Session flow under the agent-parity
  3. // model: startup auto-connects the recent Workspace's blank session when one
  4. // exists; without any Workspace the composer is locked in the pure view
  5. // state until one is chosen. Picking one materializes the full Session+Agent
  6. // (reuse-or-create of the workspace's blank session), the first ACCEPTED
  7. // prompt flips blank and surfaces the session in lists, and failures leave
  8. // no client-side transaction state: a failed attach keeps the view state
  9. // locked, a rejected prompt keeps the session blank with the draft restored.
  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-settings', dir: 'ui-settings', url: '/plugins/ui-settings.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-sidebar'] },
  24. { 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'] },
  25. { id: '@deepseek-ai/dsh-client-ui-models', dir: 'ui-models', url: '/plugins/ui-models.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-settings'] },
  26. { id: '@deepseek-ai/dsh-client-ui-conversation', dir: 'ui-conversation', url: '/plugins/ui-conversation.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] },
  27. {
  28. id: '@deepseek-ai/dsh-client-ui-workspace',
  29. dir: 'ui-workspace',
  30. url: '/plugins/ui-workspace.js',
  31. rev: 'fx',
  32. inject: [
  33. '@deepseek-ai/dsh-client-runtime',
  34. '@deepseek-ai/dsh-client-ui-conversation',
  35. '@deepseek-ai/dsh-client-ui-sidebar',
  36. ],
  37. },
  38. { id: '@deepseek-ai/dsh-client-ui-trajectory', dir: 'ui-trajectory', url: '/plugins/ui-trajectory.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-conversation'] },
  39. ]
  40. const bundles = new Map(PLUGINS.map(plugin => [
  41. plugin.url,
  42. readFileSync(join(process.cwd(), 'packages/client', plugin.dir, 'lib/client.js'), 'utf8'),
  43. ]))
  44. interface FixtureWindow extends Window {
  45. __DSH_BOOT__?: { rev: string; entries: WebBootEntry[] }
  46. __ModuleLoader__?: unknown
  47. }
  48. class ResizeObserverStub {
  49. observe(): void {}
  50. disconnect(): void {}
  51. unobserve(): void {}
  52. }
  53. const win = window as FixtureWindow
  54. let unmount: (() => void) | undefined
  55. beforeEach(() => {
  56. localStorage.clear()
  57. document.title = 'DeepSeek Harness'
  58. vi.stubGlobal('ResizeObserver', ResizeObserverStub)
  59. vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>
  60. setTimeout(() => { callback(0) }, 0) as unknown as number)
  61. vi.stubGlobal('cancelAnimationFrame', (id: number) => { clearTimeout(id) })
  62. })
  63. afterEach(() => {
  64. act(() => { unmount?.() })
  65. unmount = undefined
  66. cleanup()
  67. delete win.__DSH_BOOT__
  68. delete win.__ModuleLoader__
  69. delete (globalThis as Record<string, unknown>).__fxTiming
  70. document.body.innerHTML = ''
  71. document.head.querySelectorAll('style[data-plugin]').forEach((style) => { style.remove() })
  72. document.title = ''
  73. history.replaceState(null, '', '/')
  74. vi.unstubAllGlobals()
  75. })
  76. /** Boot the complete built client graph against one keyless fixture branch. */
  77. function boot(search: string): void {
  78. history.replaceState(null, '', `/${search}`)
  79. const root = document.createElement('div')
  80. root.id = 'root'
  81. document.body.appendChild(root)
  82. win.__DSH_BOOT__ = { rev: 'fx', entries: PLUGINS.map(({ dir: _dir, ...plugin }) => plugin) }
  83. act(() => {
  84. const entry = new AppWebEntry(root, {
  85. fetchBundle: (url) => {
  86. const code = bundles.get(url)
  87. return code === undefined ? Promise.reject(new Error(`missing built bundle ${url}`)) : Promise.resolve(code)
  88. },
  89. executeBundle: (code) => { (0, eval)(code) },
  90. })
  91. void entry.run()
  92. unmount = () => { entry.dispose() }
  93. })
  94. }
  95. /** Collapse decorative whitespace while preserving the text a user sees. */
  96. function visibleText(element: Element): string {
  97. return (element.textContent ?? '').replace(/\s+/g, ' ').trim()
  98. }
  99. /** Identify the interactive Workspace chip (view state or blank-session hero) by its menu contract. */
  100. function workspaceChip(): HTMLElement {
  101. const chip = screen.getAllByRole('button', { name: 'Choose workspace' })
  102. .find(element => element.getAttribute('aria-haspopup') === 'menu')
  103. if (chip === undefined) throw new Error('Workspace chip missing')
  104. return chip
  105. }
  106. /** The locked view-state composer (no session yet). */
  107. async function findLockedComposer(): Promise<HTMLTextAreaElement> {
  108. return await screen.findByPlaceholderText(
  109. 'Choose a workspace to start', {}, { timeout: 10_000 },
  110. )
  111. }
  112. /** The live blank-session hero composer (session materialized). */
  113. async function findHeroComposer(): Promise<HTMLTextAreaElement> {
  114. return await screen.findByPlaceholderText(
  115. 'Describe what you want to build', {}, { timeout: 10_000 },
  116. )
  117. }
  118. /** Edit the machine-owned controlled input and assert the same-tick echo. */
  119. function setComposerText(composer: HTMLElement, value: string): void {
  120. fireEvent.change(composer, { target: { value } })
  121. expect((composer as HTMLTextAreaElement).value).toBe(value)
  122. }
  123. /** Drive the picker's create flow: chip → Create workspace → name dialog. */
  124. async function createWorkspaceViaPicker(name: string): Promise<void> {
  125. fireEvent.click(workspaceChip())
  126. fireEvent.click(await screen.findByRole('menuitem', { name: 'Create workspace' }))
  127. fireEvent.click(await screen.findByRole('menuitem', { name: 'Create a new workspace' }))
  128. const dialog = await screen.findByRole('dialog', { name: 'Create a new workspace' })
  129. fireEvent.change(within(dialog).getByRole('textbox', { name: 'New workspace name' }), {
  130. target: { value: name },
  131. })
  132. fireEvent.click(within(dialog).getByRole('button', { name: 'Create workspace' }))
  133. }
  134. /** Pick an existing Workspace row from the chip menu. */
  135. async function pickWorkspace(title: string): Promise<void> {
  136. fireEvent.click(workspaceChip())
  137. fireEvent.click(await screen.findByRole('menuitem', { name: title }))
  138. }
  139. it('locks the composer in the New Session view state until a Workspace is chosen', async () => {
  140. boot('?fixture=empty')
  141. const composer = await findLockedComposer()
  142. const tree = screen.getByRole('tree', { name: 'Sessions' })
  143. expect({
  144. headline: visibleText(screen.getByText("Let's start building")),
  145. chip: visibleText(workspaceChip()),
  146. composerDisabled: composer.disabled,
  147. sendDisabled: screen.getByRole<HTMLButtonElement>('button', { name: 'Send message' }).disabled,
  148. sidebar: visibleText(tree),
  149. }).toMatchInlineSnapshot(`
  150. {
  151. "chip": "New Workspace",
  152. "composerDisabled": true,
  153. "headline": "Let's start building",
  154. "sendDisabled": true,
  155. "sidebar": "No sessions yet",
  156. }
  157. `)
  158. })
  159. it('selects the recent Workspace and opens its blank Session on first load', async () => {
  160. boot('?fixture')
  161. const composer = await findHeroComposer()
  162. const tree = screen.getByRole('tree', { name: 'Sessions' })
  163. await waitFor(() => { expect(within(tree).getByText('4 sessions')).toBeDefined() }, { timeout: 10_000 })
  164. expect({
  165. chip: visibleText(workspaceChip()),
  166. composerDisabled: composer.disabled,
  167. blankRow: within(tree).getByText('New Session').textContent,
  168. }).toMatchInlineSnapshot(`
  169. {
  170. "blankRow": "New Session",
  171. "chip": "fixture",
  172. "composerDisabled": false,
  173. }
  174. `)
  175. })
  176. it('creating a Workspace materializes and lists its selected blank Session', async () => {
  177. boot('?fixture=empty')
  178. await findLockedComposer()
  179. await createWorkspaceViaPicker('nova')
  180. // The pick connected the workspace: full Session+Agent exists, composer live.
  181. const composer = await findHeroComposer()
  182. const tree = screen.getByRole('tree', { name: 'Sessions' })
  183. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() })
  184. expect(within(tree).getByText('New Session')).toBeDefined()
  185. const group = within(tree).getByText('1 session').closest('[role="treeitem"]')
  186. if (group === null) throw new Error('created Workspace projection missing')
  187. expect({
  188. composerDisabled: composer.disabled,
  189. chip: visibleText(workspaceChip()),
  190. workspace: visibleText(group),
  191. }).toMatchInlineSnapshot(`
  192. {
  193. "chip": "nova",
  194. "composerDisabled": false,
  195. "workspace": "nova1 session",
  196. }
  197. `)
  198. })
  199. it('New Session reuses the Workspace blank session and converts the single visible row', async () => {
  200. boot('?fixture=empty')
  201. await findLockedComposer()
  202. await createWorkspaceViaPicker('nova')
  203. await findHeroComposer()
  204. const tree = screen.getByRole('tree', { name: 'Sessions' })
  205. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() }, { timeout: 10_000 })
  206. // New Session resolves through the recent Workspace and reuses its blank
  207. // session in place: no locked interlude, no second entity.
  208. fireEvent.click(screen.getByRole('button', { name: 'New session' }))
  209. const composer = await findHeroComposer()
  210. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() }, { timeout: 10_000 })
  211. setComposerText(composer, 'first light')
  212. fireEvent.keyDown(composer, { key: 'Enter' })
  213. // Conversion: the accepted prompt flips blank without adding a second row.
  214. await screen.findByText('first light', { exact: true }, { timeout: 10_000 })
  215. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() }, { timeout: 10_000 })
  216. const group = within(tree).getByText('1 session').closest('[role="treeitem"]')
  217. if (group === null) throw new Error('converted Session projection missing')
  218. expect({
  219. workspace: visibleText(group),
  220. promptVisible: screen.getByText('first light', { exact: true }).textContent,
  221. }).toMatchInlineSnapshot(`
  222. {
  223. "promptVisible": "first light",
  224. "workspace": "nova1 session",
  225. }
  226. `)
  227. })
  228. it('a failed Workspace attach recovers by reusing the published blank session', async () => {
  229. boot('?fixture&fixtureAttach=fail')
  230. // The rejected startup connect surfaces the locked view state first: the
  231. // failure leaves no client-side transaction state to unwind.
  232. await findLockedComposer()
  233. // The host published the session before rejecting attachment (blank, with
  234. // the workspace cwd), so the next connect — retry or manual pick — reuses
  235. // it instead of minting a duplicate, and the hero opens on it.
  236. await pickWorkspace('fixture')
  237. const composer = await findHeroComposer()
  238. const tree = screen.getByRole('tree', { name: 'Sessions' })
  239. const group = within(tree).getByText('3 sessions').closest('[role="treeitem"]')
  240. if (group === null) throw new Error('fixture Workspace projection missing')
  241. expect({
  242. headline: visibleText(screen.getByText("Let's start building")),
  243. composerDisabled: composer.disabled,
  244. chip: visibleText(workspaceChip()),
  245. workspace: visibleText(group),
  246. }).toMatchInlineSnapshot(`
  247. {
  248. "chip": "fixture",
  249. "composerDisabled": false,
  250. "headline": "Let's start building",
  251. "workspace": "fixture3 sessions",
  252. }
  253. `)
  254. })
  255. it('a rejected first prompt keeps the session blank and the draft in the machine', async () => {
  256. boot('?fixture=empty&fixturePrompt=reject')
  257. await findLockedComposer()
  258. await createWorkspaceViaPicker('nova')
  259. const composer = await findHeroComposer()
  260. setComposerText(composer, 'do not lose this')
  261. fireEvent.click(screen.getByRole('button', { name: 'Send message' }))
  262. const alert = await screen.findByRole('alert', {}, { timeout: 10_000 })
  263. // Failure restore rides the machine (no pendingPrompt transaction): the
  264. // draft returns to the same resident textarea one render later. The
  265. // attempt flips the composer out of the hero (engaging = retry chrome),
  266. // but acceptance never happened: the session row stays New Session.
  267. const retained = await screen.findByDisplayValue('do not lose this')
  268. const tree = screen.getByRole('tree', { name: 'Sessions' })
  269. const group = within(tree).getByText('1 session').closest('[role="treeitem"]')
  270. if (group === null) throw new Error('rejected-send Workspace projection missing')
  271. expect({
  272. error: visibleText(alert),
  273. prompt: (retained as HTMLTextAreaElement).value,
  274. blankRow: within(tree).getByText('New Session').textContent,
  275. workspace: visibleText(group),
  276. }).toMatchInlineSnapshot(`
  277. {
  278. "blankRow": "New Session",
  279. "error": "fixture: prompt rejected before acceptance (agent-busy)",
  280. "prompt": "do not lose this",
  281. "workspace": "nova1 session",
  282. }
  283. `)
  284. })
  285. it('switching Workspace before the first message carries the draft to the new blank session', async () => {
  286. boot('?fixture')
  287. const composer = await findHeroComposer()
  288. setComposerText(composer, 'carry me')
  289. // Switch = session switch: the new workspace's blank session takes over,
  290. // the typed draft moves machine-to-machine, the old blank stays hidden.
  291. await createWorkspaceViaPicker('nova')
  292. await waitFor(() => { expect(visibleText(workspaceChip())).toBe('nova') }, { timeout: 10_000 })
  293. const carried = await screen.findByDisplayValue('carry me')
  294. const tree = screen.getByRole('tree', { name: 'Sessions' })
  295. const fixtureGroup = within(tree).getByText('3 sessions').closest('[role="treeitem"]')
  296. const novaGroup = within(tree).getByText('1 session').closest('[role="treeitem"]')
  297. if (fixtureGroup === null || novaGroup === null) throw new Error('Workspace projections missing after switch')
  298. expect({
  299. chip: visibleText(workspaceChip()),
  300. prompt: (carried as HTMLTextAreaElement).value,
  301. fixtureWorkspace: visibleText(fixtureGroup),
  302. novaWorkspace: visibleText(novaGroup),
  303. }).toMatchInlineSnapshot(`
  304. {
  305. "chip": "nova",
  306. "fixtureWorkspace": "fixture3 sessions",
  307. "novaWorkspace": "nova1 session",
  308. "prompt": "carry me",
  309. }
  310. `)
  311. })