assembly-test-client.client.spec.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. // @vitest-environment jsdom
  2. /**
  3. * TestClient over the web profile's roster read from its bundles: production
  4. * `bootClient` over in-process modules, every Remote call answered by a
  5. * `RemoteMock` installed as the Connection carrier, mount, HMR-style reload,
  6. * unload, and fail-loud teardown.
  7. */
  8. import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
  9. import { RemoteMock, ok, openStream } from '@deepseek-ai/dsh-remote-mock'
  10. import { describe, expect, it, onTestFinished, vi } from 'vitest'
  11. import type { AssemblyPlan, TestClientOptions } from '../src/assembly/index.ts'
  12. import { ClientRoster, TestClient, remoteDefaultResponses, webApp } from '../src/assembly/index.ts'
  13. /** The Gateway client and what it injects: the Typert registry and the Connection. */
  14. const API_ROSTER = webApp.closure(['@deepseek-ai/dsh-api-gateway'])
  15. const SIDEBAR = '@deepseek-ai/dsh-client-ui-sidebar'
  16. /** Declared by ui-sidebar, whose SlotMap merge is outside this package's compilation face. */
  17. const SIDEBAR_SETTINGS = 'sidebar.settings' as never
  18. const BRAND = '@deepseek-ai/dsh-client-ui-brand-official'
  19. const globals = globalThis as { __DSH_TRANSPORT__?: unknown; EventSource?: unknown; ResizeObserver?: unknown }
  20. /** The whole roster's first boot pays the cold module transform of every plugin package. */
  21. const COLD_BOOT_TIMEOUT_MS = 60_000
  22. async function started(plan: AssemblyPlan, options?: TestClientOptions): Promise<TestClient> {
  23. const mock = RemoteMock.create().load(remoteDefaultResponses)
  24. const client = await TestClient.start(plan, mock, options)
  25. onTestFinished(() => client.dispose())
  26. return client
  27. }
  28. describe('TestClient (jsdom)', () => {
  29. it('boots the whole web-app roster, connects, mounts, and disposes with nothing unmatched', async () => {
  30. const mock = RemoteMock.create().load(remoteDefaultResponses)
  31. const client = await TestClient.start({ roster: webApp }, mock, { mount: true })
  32. expect(client.connection.state.getSnapshot()).toBe('connected')
  33. expect(mock.log.streams('$events')).toHaveLength(1)
  34. const container = client.container!
  35. expect(document.body.contains(container)).toBe(true)
  36. expect(container.childElementCount).toBeGreaterThan(0)
  37. expect(globals.__DSH_TRANSPORT__).toBeDefined()
  38. expect(globals.EventSource).toBeDefined()
  39. expect(globals.ResizeObserver).toBeDefined()
  40. await client.dispose()
  41. expect(document.body.contains(container)).toBe(false)
  42. expect(globals.__DSH_TRANSPORT__).toBeUndefined()
  43. expect(globals.EventSource).toBeUndefined()
  44. expect(globals.ResizeObserver).toBeUndefined()
  45. await client.dispose()
  46. }, COLD_BOOT_TIMEOUT_MS)
  47. it('leaves a pre-existing global alone and removes only the shims it installed', async () => {
  48. const existing = { existing: true }
  49. vi.stubGlobal('ResizeObserver', existing)
  50. onTestFinished(() => { vi.unstubAllGlobals() })
  51. const client = await started({ roster: API_ROSTER })
  52. expect(globals.ResizeObserver).toBe(existing)
  53. expect(globals.EventSource).toBeDefined()
  54. await client.dispose()
  55. expect(globals.ResizeObserver).toBe(existing)
  56. expect(globals.EventSource).toBeUndefined()
  57. })
  58. it('boots overlapping clients one at a time onto their own mocks and keeps the shared globals until the last dispose', async () => {
  59. const mockA = RemoteMock.create().load(remoteDefaultResponses).unary('session/rename', ok({ title: 'a', seq: 1 }))
  60. const mockB = RemoteMock.create().load(remoteDefaultResponses).unary('session/rename', ok({ title: 'b', seq: 1 }))
  61. const [a, b] = await Promise.all([
  62. TestClient.start({ roster: API_ROSTER }, mockA),
  63. TestClient.start({ roster: API_ROSTER }, mockB),
  64. ])
  65. onTestFinished(() => b.dispose())
  66. const rename = async (client: TestClient): Promise<unknown> =>
  67. (client.ctx as unknown as { remote: { session: { rename(request: unknown): Promise<unknown> } } }).remote.session.rename({ sessionId: 's', title: 't' })
  68. await expect(rename(a)).resolves.toEqual({ ok: true, value: { title: 'a', seq: 1 } })
  69. await expect(rename(b)).resolves.toEqual({ ok: true, value: { title: 'b', seq: 1 } })
  70. expect(mockA.log.calls('session/rename')).toHaveLength(1)
  71. expect(mockB.log.calls('session/rename')).toHaveLength(1)
  72. // A rebuilt connection row reads its own mock even after another client installed the transport last.
  73. await a.reload('@deepseek-ai/dsh-client-connection')
  74. await vi.waitFor(() => { expect(a.connection.state.getSnapshot()).toBe('connected') })
  75. await expect(rename(a)).resolves.toEqual({ ok: true, value: { title: 'a', seq: 1 } })
  76. expect(mockA.log.calls('session/rename')).toHaveLength(2)
  77. expect(mockB.log.calls('session/rename')).toHaveLength(1)
  78. await a.dispose()
  79. expect(globals.__DSH_TRANSPORT__).toBeDefined()
  80. expect(globals.EventSource).toBeDefined()
  81. await b.dispose()
  82. expect(globals.__DSH_TRANSPORT__).toBeUndefined()
  83. expect(globals.EventSource).toBeUndefined()
  84. })
  85. it('boots the api subset without a mount and exposes the typed Remote', async () => {
  86. const client = await started({ roster: API_ROSTER })
  87. expect(client.container).toBeUndefined()
  88. expect(client.ctx.remote.session).toBeDefined()
  89. expect(client.connection.state.getSnapshot()).toBe('connected')
  90. })
  91. it('refuses to mount a roster that provides no uiRenderer instead of returning an empty container', async () => {
  92. const before = document.body.childElementCount
  93. await expect(TestClient.start({ roster: API_ROSTER }, RemoteMock.create().load(remoteDefaultResponses), { mount: true }))
  94. .rejects.toThrow('mount requested, but the roster provides no `uiRenderer`')
  95. expect(document.body.childElementCount).toBe(before)
  96. expect(globals.__DSH_TRANSPORT__).toBeUndefined()
  97. })
  98. it('creates no mount element when the roster cannot be loaded', async () => {
  99. const roster = ClientRoster.of([{ name: '@deepseek-ai/dsh-client-test-runtime-missing', inject: [], immediately: true }])
  100. const before = document.body.childElementCount
  101. await expect(TestClient.start({ roster }, RemoteMock.create(), { mount: true })).rejects.toThrow()
  102. expect(document.body.childElementCount).toBe(before)
  103. expect(globals.__DSH_TRANSPORT__).toBeUndefined()
  104. })
  105. it('mounts into a caller-supplied element and leaves it in place on dispose', async () => {
  106. const host = document.createElement('main')
  107. document.body.appendChild(host)
  108. const mock = RemoteMock.create().load(remoteDefaultResponses)
  109. const client = await TestClient.start({ roster: webApp }, mock, { mount: host })
  110. expect(client.container).toBe(host)
  111. expect(host.childElementCount).toBeGreaterThan(0)
  112. await client.dispose()
  113. expect(document.body.contains(host)).toBe(true)
  114. host.remove()
  115. })
  116. it('boots with a provided row in place of the real plugin', async () => {
  117. const apply = vi.fn()
  118. const client = await started({ roster: webApp, provide: { [BRAND]: { apply } } }, { mount: true })
  119. expect(apply).toHaveBeenCalledOnce()
  120. expect([...client.ctx.loader.entries()].some(entry => entry.options.name === BRAND)).toBe(true)
  121. })
  122. it('reload rebuilds the declaring entry; unload collapses it', async () => {
  123. const client = await started({ roster: webApp }, { mount: true })
  124. expect(client.ctx.slots.entries(SIDEBAR_SETTINGS)).toHaveLength(1)
  125. await client.reload(SIDEBAR)
  126. await client.flush()
  127. expect(client.ctx.slots.entries(SIDEBAR_SETTINGS)).toHaveLength(1)
  128. await client.unload(SIDEBAR)
  129. await client.flush()
  130. expect(client.ctx.slots.entries(SIDEBAR_SETTINGS)).toHaveLength(0)
  131. await expect(client.reload(SIDEBAR)).rejects.toThrow(`no Loader entry named ${SIDEBAR}`)
  132. })
  133. it('fails loud by teardown at the latest when a boot-time endpoint has no fixture', async () => {
  134. const mock = RemoteMock.create()
  135. const run = TestClient.start({ roster: webApp }, mock, { mount: true }).then(client => client.dispose())
  136. await expect(run).rejects.toThrow(/session\/control|workspace\/follow|session\/list|settings\/describe/)
  137. })
  138. it('waits through a carrier flap for the connection to become ready', async () => {
  139. let opens = 0
  140. const mock = RemoteMock.create().load(remoteDefaultResponses).stream('$events', (_args, stream) => {
  141. opens += 1
  142. const first = opens === 1
  143. setTimeout(() => {
  144. if (first) stream.fail(new Error('flap'))
  145. // Branded on the Gateway side; the test mints a plain string.
  146. else stream.push({ type: 'ready', clientId: 'reconnected' as never, host: { home: '/home/mock' } })
  147. }, 20)
  148. })
  149. const client = await TestClient.start({ roster: API_ROSTER }, mock)
  150. onTestFinished(() => client.dispose())
  151. expect(client.connection.state.getSnapshot()).toBe('connected')
  152. expect(mock.log.streams('$events')).toHaveLength(2)
  153. })
  154. it('reports the log when the connection never becomes ready', async () => {
  155. // No fixtures: workspace-controller's follow has no rule, so the proxy dispatches it as a unary call the mock
  156. // logs as unmatched, while $events never sends ready.
  157. const roster = webApp.closure(['@deepseek-ai/dsh-api-workspace-controller'])
  158. const mock = RemoteMock.create().stream('$events', openStream([]))
  159. await expect(TestClient.start({ roster }, mock, { connectTimeoutMs: 300 }))
  160. .rejects.toThrow(/connection state is \S+ after 300ms; unmatched: \[unary workspace\/follow\]; streams: \[.*\$events \(open\).*\]/)
  161. expect(globals.__DSH_TRANSPORT__).toBeUndefined()
  162. expect(globals.EventSource).toBeUndefined()
  163. })
  164. })