client-apply.client.spec.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. import { Context } from '@deepseek-ai/cordis'
  2. import type { Fiber } from '@deepseek-ai/cordis'
  3. import type {
  4. ConnectionGeneration,
  5. ConnectionHandle,
  6. } from '@deepseek-ai/dsh-client-connection/client'
  7. import {
  8. RemoteStreamCarrierError,
  9. RemoteStream,
  10. type RemoteStreamOptions,
  11. } from '@deepseek-ai/dsh-api-gateway/client'
  12. import type { SessionId } from '@deepseek-ai/dsh-session/types'
  13. import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
  14. import { afterEach, describe, expect, it, vi } from 'vitest'
  15. import * as SessionClient from '../src/client/index.ts'
  16. import { ClientSessions } from '../src/client/sessions/service.ts'
  17. import { FakeApiClient, fakeRemote } from './fake-api.client.ts'
  18. const GENERATION: ConnectionGeneration = { id: 1, host: { home: '/home/fixture' } }
  19. const sid = (value: string): SessionId => value as SessionId
  20. type RemoteListener = (...args: never[]) => void
  21. interface Bench {
  22. readonly ctx: Context
  23. readonly api: FakeApiClient
  24. readonly fiber: Fiber
  25. readonly sessions: ClientSessions
  26. dispatch(event: string, ...args: unknown[]): void
  27. publishGeneration(generation: ConnectionGeneration | undefined): void
  28. }
  29. const contexts = new Set<Context>()
  30. afterEach(async () => {
  31. vi.restoreAllMocks()
  32. await Promise.all([...contexts].map(async (ctx) => { await ctx.fiber.dispose() }))
  33. contexts.clear()
  34. })
  35. async function mount(initialGeneration?: ConnectionGeneration): Promise<Bench> {
  36. const ctx = new Context()
  37. contexts.add(ctx)
  38. await ctx.plugin(TypertRegistry)
  39. const api = new FakeApiClient()
  40. const remote = fakeRemote(api)
  41. const listeners = new Map<string, Set<RemoteListener>>()
  42. const generationListeners = new Set<() => void>()
  43. let generation = initialGeneration
  44. const connection: ConnectionHandle = {
  45. isLoopback: true,
  46. generation: {
  47. getSnapshot: () => generation,
  48. subscribe: (listener) => {
  49. generationListeners.add(listener)
  50. return () => { generationListeners.delete(listener) }
  51. },
  52. },
  53. state: { getSnapshot: () => 'connected' as const, subscribe: () => () => {} },
  54. rpc: {
  55. call: () => Promise.reject(new Error('unexpected generic RPC call')),
  56. },
  57. reconnect: () => {},
  58. registerGenerationSource: () => () => {},
  59. start: () => ({ stop: () => {} }),
  60. }
  61. ctx.reflect.provide('connection', connection)
  62. ctx.reflect.provide('fileUpload', {
  63. available: true,
  64. post: () => Promise.reject(new Error('unexpected file upload')),
  65. })
  66. ctx.reflect.provide('remote', {
  67. ...remote,
  68. $stream: <Item>(options: RemoteStreamOptions<Item>) => (
  69. new RemoteStream(connection, options)
  70. ),
  71. get $host() {
  72. return { home: generation?.host.home, isLoopback: connection.isLoopback }
  73. },
  74. $on: (event: string, listener: RemoteListener) => {
  75. const eventListeners = listeners.get(event) ?? new Set<RemoteListener>()
  76. eventListeners.add(listener)
  77. listeners.set(event, eventListeners)
  78. return () => { eventListeners.delete(listener) }
  79. },
  80. })
  81. ctx.reflect.provide('remote.commands', remote.commands)
  82. ctx.reflect.provide('remote.session', remote.session)
  83. ctx.reflect.provide('remote.subagents', remote.subagents)
  84. const fiber = ctx.plugin(SessionClient)
  85. await fiber
  86. const sessions = ctx.sessions as ClientSessions
  87. return {
  88. ctx,
  89. api,
  90. fiber,
  91. sessions,
  92. dispatch: (event, ...args) => {
  93. for (const listener of listeners.get(event) ?? []) listener(...args as never[])
  94. },
  95. publishGeneration: (next) => {
  96. generation = next
  97. for (const listener of [...generationListeners]) listener()
  98. },
  99. }
  100. }
  101. async function flush(): Promise<void> {
  102. for (let index = 0; index < 12; index++) await Promise.resolve()
  103. }
  104. describe('Session Controller Client apply', () => {
  105. it('routes Session Remote Events and connection generations into the object layer', async () => {
  106. const connected = vi.spyOn(ClientSessions.prototype, 'handleConnected')
  107. const error = vi.spyOn(ClientSessions.prototype, 'handleSessionError')
  108. const bench = await mount()
  109. expect(connected).not.toHaveBeenCalled()
  110. bench.dispatch('api-session/added', {
  111. sessionId: sid('session-1'),
  112. updatedAt: 1,
  113. running: false,
  114. blank: true,
  115. })
  116. await flush()
  117. expect(bench.sessions.list.getSnapshot().byId[sid('session-1')]).toMatchObject({
  118. running: false,
  119. updatedAt: 1,
  120. })
  121. bench.dispatch('api-session/status', sid('session-1'), true)
  122. bench.dispatch('api-session/activity', sid('session-1'), 9)
  123. bench.dispatch('api-session/error', sid('session-1'), 'agent failed')
  124. await flush()
  125. expect(bench.sessions.list.getSnapshot().byId[sid('session-1')]).toMatchObject({
  126. running: true,
  127. updatedAt: 9,
  128. })
  129. expect(error).toHaveBeenCalledWith(sid('session-1'), 'agent failed')
  130. bench.dispatch('api-session/removed', sid('session-1'))
  131. await flush()
  132. expect(bench.sessions.list.getSnapshot().byId[sid('session-1')]).toBeUndefined()
  133. bench.ctx.emit('connection/reset')
  134. expect(connected).toHaveBeenCalledOnce()
  135. })
  136. it('accepts the control baseline, retries a carrier generation, and reports terminal protocol failure', async () => {
  137. const accept = vi.spyOn(ClientSessions.prototype, 'handleControlFrame')
  138. const logged = vi.spyOn(console, 'error').mockImplementation(() => {})
  139. const bench = await mount(GENERATION)
  140. await flush()
  141. expect(accept).toHaveBeenCalledWith({
  142. type: 'baseline',
  143. value: { queues: {}, jobs: {}, projections: {} },
  144. })
  145. bench.api.failStreams(new RemoteStreamCarrierError('generation lost'))
  146. await flush()
  147. expect(accept.mock.calls.filter(([frame]) => frame.type === 'baseline')).toHaveLength(2)
  148. bench.api.pushControl({ type: 'baseline', value: bench.api.controlBaseline } as never)
  149. await vi.waitFor(() => {
  150. expect(logged).toHaveBeenCalledWith(
  151. '[session-controller] control stream failed:',
  152. expect.objectContaining({ message: 'session control stream emitted more than one opening snapshot' }),
  153. )
  154. })
  155. })
  156. it('materializes Host-addressed Agent scopes before the Session list arrives', async () => {
  157. const bench = await mount()
  158. const adapter = bench.ctx.typert.contexts.getClient('agent')
  159. const first = adapter?.resolve(sid('agent-early'))
  160. expect(first).toBeDefined()
  161. expect(bench.sessions.scopeOf(first as Context)).toBe(sid('agent-early'))
  162. expect(adapter?.resolve(sid('agent-early'))).toBe(first)
  163. })
  164. it('projects Agent Context identity in both directions and withdraws the adapter on disposal', async () => {
  165. const bench = await mount(GENERATION)
  166. await flush()
  167. expect(bench.sessions.list.getSnapshot().phase).toBe('ready')
  168. bench.dispatch('api-session/added', {
  169. sessionId: sid('agent-1'),
  170. updatedAt: 1,
  171. running: false,
  172. blank: true,
  173. })
  174. await flush()
  175. const scoped = bench.sessions.scope(sid('agent-1'))
  176. const adapter = bench.ctx.typert.contexts.getClient('agent')
  177. expect(scoped).toBeDefined()
  178. expect(adapter?.identity(bench.ctx)).toBeUndefined()
  179. expect(adapter?.identity(scoped!)).toBe(sid('agent-1'))
  180. expect(adapter?.resolve(sid('agent-1'))).toBe(scoped)
  181. await bench.fiber.dispose()
  182. expect(bench.ctx.typert.contexts.getClient('agent')).toBeUndefined()
  183. })
  184. it('waits for a Host generation before retrying the control stream', async () => {
  185. const accept = vi.spyOn(ClientSessions.prototype, 'handleControlFrame')
  186. const bench = await mount()
  187. await flush()
  188. expect(accept.mock.calls.filter(([frame]) => frame.type === 'baseline')).toHaveLength(1)
  189. bench.api.failStreams(new RemoteStreamCarrierError('offline'))
  190. await flush()
  191. expect(accept.mock.calls.filter(([frame]) => frame.type === 'baseline')).toHaveLength(1)
  192. bench.publishGeneration(GENERATION)
  193. await flush()
  194. expect(accept.mock.calls.filter(([frame]) => frame.type === 'baseline')).toHaveLength(2)
  195. })
  196. })