1
0

client-flow.spec.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. // @vitest-environment jsdom
  2. import { Context } from 'cordis'
  3. import { describe, expect, it, vi } from 'vitest'
  4. import { act, cleanup, render } from '@testing-library/react'
  5. import { afterEach } from 'vitest'
  6. import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
  7. import type { DirectoryFlowOwnerProps } from '@deepseek-ai/dsh-client-ui-workspace/client'
  8. import { apply, inject } from '../src/client/index.ts'
  9. import { NativeDirectoryFlow } from '../src/client/flow.ts'
  10. afterEach(cleanup)
  11. const HOLES = ['conversation.hero.workspace.directoryFlow', 'sidebar.workspaces.directoryFlow'] as const
  12. async function bench() {
  13. const ctx = new Context()
  14. await ctx.plugin(SlotsService).await()
  15. const pickDirectory = vi.fn(async (): Promise<string | null> => '/tmp/picked')
  16. ctx.provide('workspaces', { pickDirectory } as never)
  17. const slots = ctx.get('slots') as SlotsService
  18. const declare = () => slots.register({
  19. name: 'root',
  20. children: Object.fromEntries(HOLES.map(name => [name, { kind: 'single', scope: 'root' }])),
  21. } as never, () => null)
  22. return { ctx, slots, pickDirectory, declare }
  23. }
  24. function owner(overrides: Partial<DirectoryFlowOwnerProps> = {}): DirectoryFlowOwnerProps {
  25. return {
  26. open: true, busy: false,
  27. onPicked: vi.fn(), onCancel: vi.fn(), onError: vi.fn(),
  28. ...overrides,
  29. }
  30. }
  31. describe('directory-picker-native client half', () => {
  32. it('declares the services it drives', () => {
  33. expect(inject).toEqual(['slots', 'workspaces'])
  34. })
  35. it('fills both directory-flow holes for declarations before or after apply, and leaves with its fiber', async () => {
  36. const before = await bench()
  37. before.declare()
  38. const fiber = before.ctx.plugin({ inject: [...inject], apply })
  39. await fiber.await()
  40. for (const hole of HOLES) expect(before.slots.entries(hole)).toHaveLength(1)
  41. // Registry-contribution disposal proof: the fiber going down empties the holes.
  42. await fiber.dispose()
  43. for (const hole of HOLES) expect(before.slots.entries(hole)).toHaveLength(0)
  44. const after = await bench()
  45. await after.ctx.plugin({ inject: [...inject], apply }).await()
  46. for (const hole of HOLES) expect(after.slots.entries(hole)).toHaveLength(0)
  47. after.declare()
  48. await Promise.resolve()
  49. for (const hole of HOLES) expect(after.slots.entries(hole)).toHaveLength(1)
  50. })
  51. it('rolls back wholesale and reports loudly when a rival provider wins after deferred activation', async () => {
  52. const b = await bench()
  53. const rejections: unknown[] = []
  54. const onUnhandled = (reason: unknown): void => { rejections.push(reason) }
  55. // queueMicrotask throws surface as uncaughtException, not a rejection.
  56. process.on('unhandledRejection', onUnhandled)
  57. process.on('uncaughtException', onUnhandled)
  58. try {
  59. // This provider activates BEFORE any hole exists: both deferrals wait.
  60. // (Duplicate rows of the SAME package converge silently — the deferral
  61. // skips a hole its own component already occupies; the conflict needs
  62. // a rival provider.)
  63. await b.ctx.plugin({ inject: [...inject], apply }).await()
  64. b.declare()
  65. // A rival occupies both holes ahead of the pending microtask flush.
  66. b.slots.register({ name: HOLES[0] } as never, () => null)
  67. b.slots.register({ name: HOLES[1] } as never, () => null)
  68. await new Promise(resolve => setTimeout(resolve, 20))
  69. // The rival keeps both holes; this provider rolled back wholesale and
  70. // surfaced the conflict on the fail-loud channel — no partial mix.
  71. for (const hole of HOLES) expect(b.slots.entries(hole)).toHaveLength(1)
  72. expect(rejections.map(String).join('\n')).toContain('already has a registration')
  73. // Non-Error conflicts wrap before the loud rethrow (same channel).
  74. const c = await bench()
  75. await c.ctx.plugin({ inject: [...inject], apply }).await()
  76. const original = c.slots.register.bind(c.slots)
  77. const slotsAny = c.slots as { register: typeof original }
  78. slotsAny.register = ((options: never, component: never) => {
  79. if ((options as { name?: string }).name === HOLES[0]) throw 'string conflict'
  80. return original(options, component)
  81. }) as typeof original
  82. c.declare()
  83. await new Promise(resolve => setTimeout(resolve, 20))
  84. expect(rejections.map(String).join('\n')).toContain('string conflict')
  85. } finally {
  86. process.off('unhandledRejection', onUnhandled)
  87. process.off('uncaughtException', onUnhandled)
  88. }
  89. })
  90. it('rolls back the first deferral when the second hole is already occupied', async () => {
  91. const b = await bench()
  92. b.declare()
  93. // Foreign occupant in the SECOND registered hole: the pair construction
  94. // throws after the first deferral installed its subscription.
  95. b.slots.register({ name: HOLES[1] } as never, () => null)
  96. const rejections: unknown[] = []
  97. const onUnhandled = (reason: unknown): void => { rejections.push(reason) }
  98. process.on('unhandledRejection', onUnhandled)
  99. try {
  100. const fiber = b.ctx.plugin({ inject: [...inject], apply })
  101. await expect(fiber.await()).rejects.toThrow(/already has a registration/)
  102. // A leaked first deferral would now race this probe registration and
  103. // throw from its orphaned subscription against the HERO hole; the
  104. // rollback leaves only the activation failure itself (cordis re-raises
  105. // the apply throw as a late rejection — installFailLoud's contract).
  106. const disposeProbe = b.slots.register({ name: HOLES[0] } as never, () => null)
  107. await new Promise(resolve => setTimeout(resolve, 20))
  108. expect(rejections.map(String).filter(text => text.includes(HOLES[0]))).toEqual([])
  109. disposeProbe()
  110. } finally {
  111. process.off('unhandledRejection', onUnhandled)
  112. }
  113. })
  114. it('rejects a second flow occupant at load (single-kind hole)', async () => {
  115. const b = await bench()
  116. b.declare()
  117. await b.ctx.plugin({ inject: [...inject], apply }).await()
  118. expect(() => b.slots.register({ name: HOLES[0] } as never, () => null))
  119. .toThrow(/already has a registration/)
  120. })
  121. it('drives the injected pick through the hole entry and reports the picked path', async () => {
  122. const b = await bench()
  123. b.declare()
  124. await b.ctx.plugin({ inject: [...inject], apply }).await()
  125. const entry = b.slots.entries(HOLES[0])[0]!
  126. const injected = (entry.inject as () => { pick: () => Promise<string | null> })()
  127. await expect(injected.pick()).resolves.toBe('/tmp/picked')
  128. expect(b.pickDirectory).toHaveBeenCalledOnce()
  129. })
  130. it('runs one pick per open edge and reports the path to the latest onPicked', async () => {
  131. let resolve!: (path: string | null) => void
  132. const pick = vi.fn(() => new Promise<string | null>((settle) => { resolve = settle }))
  133. const first = owner()
  134. const view = render(<NativeDirectoryFlow {...first} pick={pick} />)
  135. expect(pick).toHaveBeenCalledOnce()
  136. // Re-renders while open (busy flips, handler identity changes) must not relaunch the chooser.
  137. const second = owner()
  138. view.rerender(<NativeDirectoryFlow {...second} busy pick={pick} />)
  139. expect(pick).toHaveBeenCalledOnce()
  140. // Even a fresh injected face (re-registration re-runs the inject factory)
  141. // must not relaunch while the same request is still open.
  142. const replacedPick = vi.fn(() => new Promise<string | null>(() => {}))
  143. view.rerender(<NativeDirectoryFlow {...second} busy pick={replacedPick} />)
  144. expect(replacedPick).not.toHaveBeenCalled()
  145. await act(async () => { resolve('/tmp/project') })
  146. expect(second.onPicked).toHaveBeenCalledWith('/tmp/project')
  147. expect(first.onPicked).not.toHaveBeenCalled()
  148. })
  149. it('discards a settlement that lands after the flow unmounted', async () => {
  150. let resolve!: (path: string | null) => void
  151. const pick = vi.fn(() => new Promise<string | null>((settle) => { resolve = settle }))
  152. const props = owner()
  153. const view = render(<NativeDirectoryFlow {...props} pick={pick} />)
  154. expect(pick).toHaveBeenCalledOnce()
  155. view.unmount()
  156. // The dead instance must neither adopt nor error; the owner's callbacks
  157. // stay untouched by the orphaned chooser's answer.
  158. await act(async () => { resolve('/tmp/late') })
  159. expect(props.onPicked).not.toHaveBeenCalled()
  160. expect(props.onCancel).not.toHaveBeenCalled()
  161. expect(props.onError).not.toHaveBeenCalled()
  162. // The failure arm is discarded the same way.
  163. let reject!: (reason: unknown) => void
  164. const failing = vi.fn(() => new Promise<string | null>((_settle, rejectPick) => { reject = rejectPick }))
  165. const late = owner()
  166. const failingView = render(<NativeDirectoryFlow {...late} pick={failing} />)
  167. failingView.unmount()
  168. await act(async () => { reject(new Error('too late')) })
  169. expect(late.onError).not.toHaveBeenCalled()
  170. })
  171. it('reports null as cancellation and re-arms after the owner withdraws open', async () => {
  172. const pick = vi.fn(async () => null as string | null)
  173. const props = owner()
  174. const view = render(<NativeDirectoryFlow {...props} pick={pick} />)
  175. await act(async () => {})
  176. expect(props.onCancel).toHaveBeenCalledOnce()
  177. expect(props.onPicked).not.toHaveBeenCalled()
  178. // Withdraw and reopen: a fresh request runs a fresh pick.
  179. view.rerender(<NativeDirectoryFlow {...props} open={false} pick={pick} />)
  180. view.rerender(<NativeDirectoryFlow {...props} pick={pick} />)
  181. await act(async () => {})
  182. expect(pick).toHaveBeenCalledTimes(2)
  183. })
  184. it('folds pick failures into onError messages', async () => {
  185. const props = owner()
  186. render(<NativeDirectoryFlow {...props} pick={vi.fn(async () => { throw new Error('no chooser installed') })} />)
  187. await act(async () => {})
  188. expect(props.onError).toHaveBeenCalledWith('no chooser installed')
  189. const nonError = owner()
  190. render(<NativeDirectoryFlow {...nonError} pick={vi.fn(async () => { throw 'denied' })} />)
  191. await act(async () => {})
  192. expect(nonError.onError).toHaveBeenCalledWith('denied')
  193. })
  194. it('renders nothing while closed and while open', () => {
  195. const closed = render(<NativeDirectoryFlow {...owner({ open: false })} pick={vi.fn(async () => null)} />)
  196. expect(closed.container.innerHTML).toBe('')
  197. const opened = render(<NativeDirectoryFlow {...owner()} pick={vi.fn(async () => null)} />)
  198. expect(opened.container.innerHTML).toBe('')
  199. })
  200. })