workspace-flow.snapshot.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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": "Choose 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. const newSessionButton = screen.getAllByRole('button', { name: 'New session' })
  208. .find(button => visibleText(button) === 'New Session')
  209. if (newSessionButton === undefined) throw new Error('New Session button missing')
  210. fireEvent.click(newSessionButton)
  211. const composer = await findHeroComposer()
  212. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() }, { timeout: 10_000 })
  213. setComposerText(composer, 'first light')
  214. fireEvent.keyDown(composer, { key: 'Enter' })
  215. // Conversion: the accepted prompt flips blank without adding a second row.
  216. await screen.findByText('first light', { exact: true }, { timeout: 10_000 })
  217. await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() }, { timeout: 10_000 })
  218. const group = within(tree).getByText('1 session').closest('[role="treeitem"]')
  219. if (group === null) throw new Error('converted Session projection missing')
  220. expect({
  221. workspace: visibleText(group),
  222. promptVisible: screen.getByText('first light', { exact: true }).textContent,
  223. }).toMatchInlineSnapshot(`
  224. {
  225. "promptVisible": "first light",
  226. "workspace": "nova1 session",
  227. }
  228. `)
  229. })
  230. it('a failed Workspace attach recovers by reusing the published blank session', async () => {
  231. boot('?fixture&fixtureAttach=fail')
  232. // The rejected startup connect surfaces the locked view state first: the
  233. // failure leaves no client-side transaction state to unwind.
  234. await findLockedComposer()
  235. // The host published the session before rejecting attachment (blank, with
  236. // the workspace cwd), so the next connect — retry or manual pick — reuses
  237. // it instead of minting a duplicate, and the hero opens on it.
  238. await pickWorkspace('fixture')
  239. const composer = await findHeroComposer()
  240. const tree = screen.getByRole('tree', { name: 'Sessions' })
  241. const group = within(tree).getByText('3 sessions').closest('[role="treeitem"]')
  242. if (group === null) throw new Error('fixture Workspace projection missing')
  243. expect({
  244. headline: visibleText(screen.getByText("Let's start building")),
  245. composerDisabled: composer.disabled,
  246. chip: visibleText(workspaceChip()),
  247. workspace: visibleText(group),
  248. }).toMatchInlineSnapshot(`
  249. {
  250. "chip": "fixture",
  251. "composerDisabled": false,
  252. "headline": "Let's start building",
  253. "workspace": "fixture3 sessions",
  254. }
  255. `)
  256. })
  257. it('a rejected first prompt keeps the session blank and the draft in the machine', async () => {
  258. boot('?fixture=empty&fixturePrompt=reject')
  259. await findLockedComposer()
  260. await createWorkspaceViaPicker('nova')
  261. const composer = await findHeroComposer()
  262. setComposerText(composer, 'do not lose this')
  263. fireEvent.click(screen.getByRole('button', { name: 'Send message' }))
  264. const alert = await screen.findByRole('alert', {}, { timeout: 10_000 })
  265. // Failure restore rides the machine (no pendingPrompt transaction): the
  266. // draft returns to the same resident textarea one render later. The
  267. // attempt flips the composer out of the hero (engaging = retry chrome),
  268. // but acceptance never happened: the session row stays New Session.
  269. const retained = await screen.findByDisplayValue('do not lose this')
  270. const tree = screen.getByRole('tree', { name: 'Sessions' })
  271. const group = within(tree).getByText('1 session').closest('[role="treeitem"]')
  272. if (group === null) throw new Error('rejected-send Workspace projection missing')
  273. expect({
  274. error: visibleText(alert),
  275. prompt: (retained as HTMLTextAreaElement).value,
  276. blankRow: within(tree).getByText('New Session').textContent,
  277. workspace: visibleText(group),
  278. }).toMatchInlineSnapshot(`
  279. {
  280. "blankRow": "New Session",
  281. "error": "fixture: prompt rejected before acceptance (agent-busy)",
  282. "prompt": "do not lose this",
  283. "workspace": "nova1 session",
  284. }
  285. `)
  286. })
  287. it('switching Workspace before the first message carries the draft to the new blank session', async () => {
  288. boot('?fixture')
  289. const composer = await findHeroComposer()
  290. setComposerText(composer, 'carry me')
  291. // Switch = session switch: the new workspace's blank session takes over,
  292. // the typed draft moves machine-to-machine, the old blank stays hidden.
  293. await createWorkspaceViaPicker('nova')
  294. await waitFor(() => { expect(visibleText(workspaceChip())).toBe('nova') }, { timeout: 10_000 })
  295. const carried = await screen.findByDisplayValue('carry me')
  296. const tree = screen.getByRole('tree', { name: 'Sessions' })
  297. const fixtureGroup = within(tree).getByText('3 sessions').closest('[role="treeitem"]')
  298. const novaGroup = within(tree).getByText('1 session').closest('[role="treeitem"]')
  299. if (fixtureGroup === null || novaGroup === null) throw new Error('Workspace projections missing after switch')
  300. expect({
  301. chip: visibleText(workspaceChip()),
  302. prompt: (carried as HTMLTextAreaElement).value,
  303. fixtureWorkspace: visibleText(fixtureGroup),
  304. novaWorkspace: visibleText(novaGroup),
  305. }).toMatchInlineSnapshot(`
  306. {
  307. "chip": "nova",
  308. "fixtureWorkspace": "fixture3 sessions",
  309. "novaWorkspace": "nova1 session",
  310. "prompt": "carry me",
  311. }
  312. `)
  313. })