apply.client.spec.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import { Context } from '@deepseek-ai/cordis'
  2. import { describe, expect, it, vi } from 'vitest'
  3. import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
  4. import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
  5. import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
  6. import { apply, inject } from '@deepseek-ai/dsh-client-ui-workspace/client'
  7. import type { WorkspaceBrowserInjected, WorkspacePickerInjected } from '@deepseek-ai/dsh-client-ui-workspace/client'
  8. import { WorkspaceBrowser } from '../src/client/rows/WorkspaceBrowser.tsx'
  9. import { WorkspacePicker } from '../src/client/WorkspacePicker.tsx'
  10. import { apply as hostApply } from '../src/index.ts'
  11. import type { SessionReference } from '@deepseek-ai/dsh-api-session-controller/client'
  12. async function bench() {
  13. const ctx = new Context()
  14. await ctx.plugin(SlotRegistry).await()
  15. const create = vi.fn(async (input: { name: string } | { path: string }) => ({
  16. workspaceId: 'ws-new' as never,
  17. path: 'name' in input ? `/projects/${input.name}` : input.path,
  18. title: 'new', sessionIds: [], createdAt: '0', updatedAt: '0',
  19. }))
  20. const rename = vi.fn(async () => ({}))
  21. const selectPanel = vi.fn()
  22. ctx.provide('layout', { selectPanel, beginNavigation: () => new AbortController().signal })
  23. const search = vi.fn(async () => ({
  24. ok: true as const,
  25. value: { items: [{ sessionId: 'session' as never, snippet: 'match' }], hasMore: false },
  26. }))
  27. const renameSession = vi.fn(async (title: string) => ({ ok: true, value: { title, seq: 1 } }))
  28. const binding = vi.fn((_id: string) => ({ session: { rename: renameSession } }))
  29. const retain = vi.fn((target: string) => {
  30. const resolved = binding(target)
  31. const release = vi.fn()
  32. return {
  33. sessionId: target,
  34. binding: resolved,
  35. ready: Promise.resolve(resolved),
  36. release,
  37. [Symbol.dispose]: release,
  38. } as unknown as SessionReference
  39. })
  40. const using = vi.fn(async (
  41. target: string,
  42. _options: unknown,
  43. operation: (reference: SessionReference) => unknown,
  44. ) => await operation(retain(target)))
  45. const fork = vi.fn(async () => 'forked' as never)
  46. const subscribe = () => () => {}
  47. ctx.provide('workspaces', {
  48. list: {
  49. getSnapshot: () => ({
  50. items: [], archivedSessionIds: [], state: 'idle', phase: 'ready', error: null,
  51. }),
  52. subscribe,
  53. },
  54. create,
  55. rename,
  56. delete: vi.fn(async () => undefined),
  57. insertBefore: vi.fn(async () => undefined),
  58. archiveSession: vi.fn(async () => undefined),
  59. insertSessionBefore: vi.fn(async () => ({})),
  60. } as never)
  61. ctx.provide('sessions', {
  62. list: {
  63. getSnapshot: () => ({
  64. ids: [], byId: {}, current: undefined, phase: 'ready',
  65. subagentsByParent: {}, jobsBySession: {}, currentAddress: undefined,
  66. }),
  67. subscribe,
  68. },
  69. create: vi.fn(async () => 'created' as never),
  70. retain,
  71. using,
  72. search,
  73. searchResultLimit: 20,
  74. binding,
  75. subagentAddress: vi.fn(() => undefined),
  76. refreshSubagents: vi.fn(() => Promise.resolve()),
  77. fork,
  78. } as never)
  79. const pickDirectory = vi.fn(() => Promise.resolve({ ok: true as const, value: '/projects/picked' }))
  80. const directoryPicker = { pick: pickDirectory }
  81. Object.assign(new TestRemote(ctx), { directoryPicker })
  82. ctx.provide('remote.directoryPicker', directoryPicker as never)
  83. const locale = new LocaleRuntime(ctx)
  84. // These specs assert the shipped Chinese copy. There is no jsdom `window`
  85. // in this lane, so browser-language detection never runs and the locale
  86. // comes from FALLBACK_LOCALE (en): state the asserted locale explicitly.
  87. locale.setLocale('zh')
  88. ctx.provide('locale', locale)
  89. return {
  90. ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename,
  91. retain, using, selectPanel, search, renameSession, binding, fork, pickDirectory,
  92. }
  93. }
  94. type HoleName = 'sidebar.workspaces' | 'conversation.hero.workspace' | 'conversation.empty.workspace'
  95. /** Declare any subset of the holes with a single root registration ('root' is a single slot). */
  96. function declare(slots: SlotRegistry, ...names: HoleName[]): () => void {
  97. const children = Object.fromEntries(names.map(name => [name, { kind: 'single', scope: 'root' }]))
  98. return slots.register({ name: 'root', children } as never, () => null)
  99. }
  100. describe('ui-workspace apply', () => {
  101. it('keeps the host Loader entry inert', () => {
  102. expect(hostApply).not.toThrow()
  103. })
  104. it('declares the services it drives', () => {
  105. expect(inject).toEqual([
  106. 'slots', 'sessions', 'workspaces', 'locale', 'remote', 'remote.directoryPicker', 'layout',
  107. ])
  108. })
  109. it('registers browser and pickers for declarations arriving before or after apply', async () => {
  110. const before = await bench()
  111. declare(before.slots, 'sidebar.workspaces')
  112. await before.ctx.plugin({ inject: [...inject], apply }).await()
  113. expect(before.slots.entries('sidebar.workspaces')[0]!.component).toBe(WorkspaceBrowser)
  114. // Copy rides the standard locale seat: the entry declares the namespace
  115. // and apply registered both dictionaries.
  116. expect(before.slots.entries('sidebar.workspaces')[0]!.locale).toBe('workspace')
  117. expect(before.locale.bind('workspace')('session.new')).toBe('新会话')
  118. const after = await bench()
  119. await after.ctx.plugin({ inject: [...inject], apply }).await()
  120. declare(after.slots, 'conversation.hero.workspace', 'conversation.empty.workspace')
  121. await Promise.resolve()
  122. expect(after.slots.entries('conversation.hero.workspace')[0]!.component).toBe(WorkspacePicker)
  123. // expect(after.slots.entries('conversation.empty.workspace')[0]!.component).toBe(WorkspacePicker)
  124. })
  125. it('routes browser actions and picker creation to the services', async () => {
  126. const b = await bench()
  127. declare(b.slots, 'sidebar.workspaces', 'conversation.hero.workspace')
  128. await b.ctx.plugin({ inject: [...inject], apply }).await()
  129. const startSession = vi.spyOn(b.ctx.uiWorkspace, 'startSession').mockImplementation(() => undefined)
  130. const browser = (b.slots.entries('sidebar.workspaces')[0]!.inject as () => WorkspaceBrowserInjected)()
  131. // Both arms delegate to the shared Session navigation action.
  132. browser.startSession('ws' as never)
  133. expect(startSession).toHaveBeenCalledWith('ws')
  134. browser.startSession()
  135. expect(startSession).toHaveBeenLastCalledWith(undefined)
  136. browser.open('session' as never)
  137. expect(b.retain).toHaveBeenCalledWith('session', { source: 'mainView' })
  138. const signal = new AbortController().signal
  139. await expect(browser.searchSessions('match', signal)).resolves.toEqual({
  140. items: [{ sessionId: 'session', snippet: 'match' }],
  141. hasMore: false,
  142. })
  143. expect(b.search).toHaveBeenCalledWith('match', signal)
  144. expect(browser.searchResultLimit).toBe(20)
  145. await browser.renameSession('session' as never, 'renamed session')
  146. expect(b.using).toHaveBeenCalledWith(
  147. 'session', { source: 'workspaceOperation' }, expect.any(Function),
  148. )
  149. expect(b.renameSession).toHaveBeenCalledWith('renamed session')
  150. browser.forkSession('session' as never)
  151. await vi.waitFor(() => {
  152. expect(b.retain).toHaveBeenCalledWith('forked', { source: 'mainView' })
  153. })
  154. expect(b.fork).toHaveBeenCalledWith({ sessionId: 'session', increaseTitle: true })
  155. await browser.renameWorkspace('ws' as never, 'renamed')
  156. expect(b.rename).toHaveBeenCalledWith('ws', 'renamed')
  157. await browser.createWorkspace({ path: '/tmp/browser-project' })
  158. expect(b.create).toHaveBeenCalledWith({ path: '/tmp/browser-project' })
  159. const picker = (b.slots.entries('conversation.hero.workspace')[0]!.inject as () => WorkspacePickerInjected)()
  160. await picker.createWorkspace({ path: '/tmp/project' })
  161. expect(b.create).toHaveBeenCalledWith({ path: '/tmp/project' })
  162. })
  163. it('declares the two directory-flow holes and reports their occupancy per surface', async () => {
  164. const b = await bench()
  165. declare(b.slots, 'sidebar.workspaces', 'conversation.hero.workspace')
  166. await b.ctx.plugin({ inject: [...inject], apply }).await()
  167. // Registration declared the child holes (declaration = render authorization).
  168. expect(b.slots.spec('sidebar.workspaces.directoryFlow')).toMatchObject({ kind: 'single' })
  169. expect(b.slots.spec('conversation.hero.workspace.directoryFlow')).toMatchObject({ kind: 'single' })
  170. const browser = (b.slots.entries('sidebar.workspaces')[0]!.inject as () => WorkspaceBrowserInjected)()
  171. const picker = (b.slots.entries('conversation.hero.workspace')[0]!.inject as () => WorkspacePickerInjected)()
  172. expect(browser.hooks.directoryFlow.getSnapshot()).toBe(false)
  173. expect(browser.hooks.hostInfo.getSnapshot()).toMatchObject({ home: undefined })
  174. expect(picker.hooks.directoryFlow.getSnapshot()).toBe(false)
  175. // A flow occupant flips exactly its own surface, and the source notifies.
  176. const notified = vi.fn()
  177. const unsubscribe = browser.hooks.directoryFlow.subscribe(notified)
  178. const dispose = b.slots.register({ name: 'sidebar.workspaces.directoryFlow' } as never, () => null)
  179. expect(browser.hooks.directoryFlow.getSnapshot()).toBe(true)
  180. expect(picker.hooks.directoryFlow.getSnapshot()).toBe(false)
  181. await Promise.resolve()
  182. expect(notified).toHaveBeenCalled()
  183. dispose()
  184. expect(browser.hooks.directoryFlow.getSnapshot()).toBe(false)
  185. unsubscribe()
  186. })
  187. it('rejects the browser search callback on a Session Controller business error', async () => {
  188. const b = await bench()
  189. b.search.mockImplementationOnce(async () => ({
  190. ok: false,
  191. error: new RemoteError('gateway/internal', 'index unavailable', {}),
  192. }) as never)
  193. declare(b.slots, 'sidebar.workspaces')
  194. await b.ctx.plugin({ inject: [...inject], apply }).await()
  195. const browser = (b.slots.entries('sidebar.workspaces')[0]!.inject as () => WorkspaceBrowserInjected)()
  196. await expect(browser.searchSessions('needle', new AbortController().signal))
  197. .rejects.toThrow('index unavailable')
  198. })
  199. it('unregisters every entry on teardown', async () => {
  200. const b = await bench()
  201. declare(b.slots, 'sidebar.workspaces', 'conversation.hero.workspace', 'conversation.empty.workspace')
  202. const fiber = b.ctx.plugin({ inject: [...inject], apply })
  203. await fiber.await()
  204. await fiber.dispose()
  205. expect(b.slots.entries('sidebar.workspaces')).toHaveLength(0)
  206. expect(b.slots.entries('conversation.hero.workspace')).toHaveLength(0)
  207. // expect(b.slots.entries('conversation.empty.workspace')).toHaveLength(0)
  208. })
  209. })