workspace-flow.snapshot.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 a new workspace → name dialog. */
  124. async function createWorkspaceViaPicker(name: string): Promise<void> {
  125. fireEvent.click(workspaceChip())
  126. fireEvent.click(await screen.findByRole('menuitem', { name: 'Create a new workspace' }))
  127. const dialog = await screen.findByRole('dialog', { name: 'Create a new workspace' })
  128. fireEvent.change(within(dialog).getByRole('textbox', { name: 'New workspace name' }), {
  129. target: { value: name },
  130. })
  131. fireEvent.click(within(dialog).getByRole('button', { name: 'Create workspace' }))
  132. }
  133. /** Pick an existing Workspace row from the chip menu. */
  134. async function pickWorkspace(title: string): Promise<void> {
  135. fireEvent.click(workspaceChip())
  136. fireEvent.click(await screen.findByRole('menuitem', { name: title }))
  137. }
  138. it('locks the composer in the New Session view state until a Workspace is chosen', async () => {
  139. boot('?fixture=empty')
  140. const composer = await findLockedComposer()
  141. const tree = screen.getByRole('tree', { name: 'Sessions' })
  142. expect({
  143. headline: visibleText(screen.getByText("Let's start building")),
  144. chip: visibleText(workspaceChip()),
  145. composerDisabled: composer.disabled,
  146. sendDisabled: screen.getByRole<HTMLButtonElement>('button', { name: 'Send message' }).disabled,
  147. sidebar: visibleText(tree),
  148. }).toMatchInlineSnapshot(`
  149. {
  150. "chip": "New Workspace",
  151. "composerDisabled": true,
  152. "headline": "Let's start building",
  153. "sendDisabled": true,
  154. "sidebar": "No sessions yet",
  155. }
  156. `)
  157. })
  158. it('selects the recent Workspace and opens its blank Session on first load', async () => {
  159. boot('?fixture')
  160. const composer = await findHeroComposer()
  161. const tree = screen.getByRole('tree', { name: 'Sessions' })
  162. await waitFor(() => { expect(within(tree).getByText('4 sessions')).toBeDefined() }, { timeout: 10_000 })
  163. expect({
  164. chip: visibleText(workspaceChip()),
  165. composerDisabled: composer.disabled,
  166. blankRow: within(tree).getByText('New Session').textContent,
  167. }).toMatchInlineSnapshot(`
  168. {
  169. "blankRow": "New Session",
  170. "chip": "fixture",
  171. "composerDisabled": false,
  172. }
  173. `)
  174. })
  175. it('creating a Workspace materializes and lists its selected blank Session', async () => {
  176. boot('?fixture=empty')
  177. await findLockedComposer()
  178. await createWorkspaceViaPicker('nova')
  179. // The pick connected the workspace: full Session+Agent exists, composer live.
  180. const composer = await findHeroComposer()
  181. const tree = screen.getByRole('tree', { name: 'Sessions' })
  182. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() })
  183. expect(within(tree).getByText('New Session')).toBeDefined()
  184. const group = within(tree).getByText('1 session').closest('[role="treeitem"]')
  185. if (group === null) throw new Error('created Workspace projection missing')
  186. expect({
  187. composerDisabled: composer.disabled,
  188. chip: visibleText(workspaceChip()),
  189. workspace: visibleText(group),
  190. }).toMatchInlineSnapshot(`
  191. {
  192. "chip": "nova",
  193. "composerDisabled": false,
  194. "workspace": "nova1 session",
  195. }
  196. `)
  197. })
  198. it('New Session reuses the Workspace blank session and converts the single visible row', async () => {
  199. boot('?fixture=empty')
  200. await findLockedComposer()
  201. await createWorkspaceViaPicker('nova')
  202. await findHeroComposer()
  203. const tree = screen.getByRole('tree', { name: 'Sessions' })
  204. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() }, { timeout: 10_000 })
  205. // New Session resolves through the recent Workspace and reuses its blank
  206. // session in place: no locked interlude, no second entity.
  207. fireEvent.click(screen.getByRole('button', { name: 'New session' }))
  208. const composer = await findHeroComposer()
  209. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() }, { timeout: 10_000 })
  210. setComposerText(composer, 'first light')
  211. fireEvent.keyDown(composer, { key: 'Enter' })
  212. // Conversion: the accepted prompt flips blank without adding a second row.
  213. await screen.findByText('first light', { exact: true }, { timeout: 10_000 })
  214. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() }, { timeout: 10_000 })
  215. const group = within(tree).getByText('1 session').closest('[role="treeitem"]')
  216. if (group === null) throw new Error('converted Session projection missing')
  217. expect({
  218. workspace: visibleText(group),
  219. promptVisible: screen.getByText('first light', { exact: true }).textContent,
  220. }).toMatchInlineSnapshot(`
  221. {
  222. "promptVisible": "first light",
  223. "workspace": "nova1 session",
  224. }
  225. `)
  226. })
  227. it('a failed Workspace attach recovers by reusing the published blank session', async () => {
  228. boot('?fixture&fixtureAttach=fail')
  229. // The rejected startup connect surfaces the locked view state first: the
  230. // failure leaves no client-side transaction state to unwind.
  231. await findLockedComposer()
  232. // The host published the session before rejecting attachment (blank, with
  233. // the workspace cwd), so the next connect — retry or manual pick — reuses
  234. // it instead of minting a duplicate, and the hero opens on it.
  235. await pickWorkspace('fixture')
  236. const composer = await findHeroComposer()
  237. const tree = screen.getByRole('tree', { name: 'Sessions' })
  238. const group = within(tree).getByText('3 sessions').closest('[role="treeitem"]')
  239. if (group === null) throw new Error('fixture Workspace projection missing')
  240. expect({
  241. headline: visibleText(screen.getByText("Let's start building")),
  242. composerDisabled: composer.disabled,
  243. chip: visibleText(workspaceChip()),
  244. workspace: visibleText(group),
  245. }).toMatchInlineSnapshot(`
  246. {
  247. "chip": "fixture",
  248. "composerDisabled": false,
  249. "headline": "Let's start building",
  250. "workspace": "fixture3 sessions",
  251. }
  252. `)
  253. })
  254. it('a rejected first prompt keeps the session blank and the draft in the machine', async () => {
  255. boot('?fixture=empty&fixturePrompt=reject')
  256. await findLockedComposer()
  257. await createWorkspaceViaPicker('nova')
  258. const composer = await findHeroComposer()
  259. setComposerText(composer, 'do not lose this')
  260. fireEvent.click(screen.getByRole('button', { name: 'Send message' }))
  261. const alert = await screen.findByRole('alert', {}, { timeout: 10_000 })
  262. // Failure restore rides the machine (no pendingPrompt transaction): the
  263. // draft returns to the same resident textarea one render later. The
  264. // attempt flips the composer out of the hero (engaging = retry chrome),
  265. // but acceptance never happened: the session row stays New Session.
  266. const retained = await screen.findByDisplayValue('do not lose this')
  267. const tree = screen.getByRole('tree', { name: 'Sessions' })
  268. const group = within(tree).getByText('1 session').closest('[role="treeitem"]')
  269. if (group === null) throw new Error('rejected-send Workspace projection missing')
  270. expect({
  271. error: visibleText(alert),
  272. prompt: (retained as HTMLTextAreaElement).value,
  273. blankRow: within(tree).getByText('New Session').textContent,
  274. workspace: visibleText(group),
  275. }).toMatchInlineSnapshot(`
  276. {
  277. "blankRow": "New Session",
  278. "error": "fixture: prompt rejected before acceptance (agent-busy)",
  279. "prompt": "do not lose this",
  280. "workspace": "nova1 session",
  281. }
  282. `)
  283. })
  284. it('switching Workspace before the first message carries the draft to the new blank session', async () => {
  285. boot('?fixture')
  286. const composer = await findHeroComposer()
  287. setComposerText(composer, 'carry me')
  288. // Switch = session switch: the new workspace's blank session takes over,
  289. // the typed draft moves machine-to-machine, the old blank stays hidden.
  290. await createWorkspaceViaPicker('nova')
  291. await waitFor(() => { expect(visibleText(workspaceChip())).toBe('nova') }, { timeout: 10_000 })
  292. const carried = await screen.findByDisplayValue('carry me')
  293. const tree = screen.getByRole('tree', { name: 'Sessions' })
  294. const fixtureGroup = within(tree).getByText('3 sessions').closest('[role="treeitem"]')
  295. const novaGroup = within(tree).getByText('1 session').closest('[role="treeitem"]')
  296. if (fixtureGroup === null || novaGroup === null) throw new Error('Workspace projections missing after switch')
  297. expect({
  298. chip: visibleText(workspaceChip()),
  299. prompt: (carried as HTMLTextAreaElement).value,
  300. fixtureWorkspace: visibleText(fixtureGroup),
  301. novaWorkspace: visibleText(novaGroup),
  302. }).toMatchInlineSnapshot(`
  303. {
  304. "chip": "nova",
  305. "fixtureWorkspace": "fixture3 sessions",
  306. "novaWorkspace": "nova1 session",
  307. "prompt": "carry me",
  308. }
  309. `)
  310. })