client-apply.client.spec.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. rpc: {
  54. call: () => Promise.reject(new Error('unexpected generic RPC call')),
  55. },
  56. registerGenerationSource: () => () => {},
  57. start: () => ({ stop: () => {} }),
  58. }
  59. ctx.reflect.provide('remote', {
  60. ...remote,
  61. $stream: <Item>(options: RemoteStreamOptions<Item>) => (
  62. new RemoteStream(connection, options)
  63. ),
  64. get $host() {
  65. return { home: generation?.host.home, isLoopback: connection.isLoopback }
  66. },
  67. $on: (event: string, listener: RemoteListener) => {
  68. const eventListeners = listeners.get(event) ?? new Set<RemoteListener>()
  69. eventListeners.add(listener)
  70. listeners.set(event, eventListeners)
  71. return () => { eventListeners.delete(listener) }
  72. },
  73. })
  74. ctx.reflect.provide('remote.commands', remote.commands)
  75. ctx.reflect.provide('remote.session', remote.session)
  76. ctx.reflect.provide('remote.subagents', remote.subagents)
  77. const fiber = ctx.plugin(SessionClient)
  78. await fiber
  79. const sessions = ctx.sessions as ClientSessions
  80. return {
  81. ctx,
  82. api,
  83. fiber,
  84. sessions,
  85. dispatch: (event, ...args) => {
  86. for (const listener of listeners.get(event) ?? []) listener(...args as never[])
  87. },
  88. publishGeneration: (next) => {
  89. generation = next
  90. for (const listener of [...generationListeners]) listener()
  91. },
  92. }
  93. }
  94. async function flush(): Promise<void> {
  95. for (let index = 0; index < 12; index++) await Promise.resolve()
  96. }
  97. describe('Session Controller Client apply', () => {
  98. it('routes Session Remote Events and connection generations into the object layer', async () => {
  99. const connected = vi.spyOn(ClientSessions.prototype, 'handleConnected')
  100. const error = vi.spyOn(ClientSessions.prototype, 'handleSessionError')
  101. const bench = await mount()
  102. expect(connected).not.toHaveBeenCalled()
  103. bench.dispatch('api-session/added', {
  104. sessionId: sid('session-1'),
  105. updatedAt: 1,
  106. running: false,
  107. blank: true,
  108. })
  109. await flush()
  110. expect(bench.sessions.list.getSnapshot().byId[sid('session-1')]).toMatchObject({
  111. running: false,
  112. updatedAt: 1,
  113. })
  114. bench.dispatch('api-session/status', sid('session-1'), true)
  115. bench.dispatch('api-session/activity', sid('session-1'), 9)
  116. bench.dispatch('api-session/error', sid('session-1'), 'agent failed')
  117. await flush()
  118. expect(bench.sessions.list.getSnapshot().byId[sid('session-1')]).toMatchObject({
  119. running: true,
  120. updatedAt: 9,
  121. })
  122. expect(error).toHaveBeenCalledWith(sid('session-1'), 'agent failed')
  123. bench.dispatch('api-session/removed', sid('session-1'))
  124. await flush()
  125. expect(bench.sessions.list.getSnapshot().byId[sid('session-1')]).toBeUndefined()
  126. bench.ctx.emit('connection/reset')
  127. expect(connected).toHaveBeenCalledOnce()
  128. })
  129. it('accepts the control baseline, retries a carrier generation, and reports terminal protocol failure', async () => {
  130. const accept = vi.spyOn(ClientSessions.prototype, 'handleControlFrame')
  131. const logged = vi.spyOn(console, 'error').mockImplementation(() => {})
  132. const bench = await mount(GENERATION)
  133. await flush()
  134. expect(accept).toHaveBeenCalledWith({
  135. type: 'baseline',
  136. value: { queues: {}, jobs: {}, projections: {} },
  137. })
  138. bench.api.failStreams(new RemoteStreamCarrierError('generation lost'))
  139. await flush()
  140. expect(accept.mock.calls.filter(([frame]) => frame.type === 'baseline')).toHaveLength(2)
  141. bench.api.pushControl({ type: 'baseline', value: bench.api.controlBaseline } as never)
  142. await vi.waitFor(() => {
  143. expect(logged).toHaveBeenCalledWith(
  144. '[session-controller] control stream failed:',
  145. expect.objectContaining({ message: 'session control stream emitted more than one opening snapshot' }),
  146. )
  147. })
  148. })
  149. it('materializes Host-addressed Agent scopes before the Session list arrives', async () => {
  150. const bench = await mount()
  151. const adapter = bench.ctx.typert.contexts.getClient('agent')
  152. const first = adapter?.resolve(sid('agent-early'))
  153. expect(first).toBeDefined()
  154. expect(bench.sessions.scopeOf(first as Context)).toBe(sid('agent-early'))
  155. expect(adapter?.resolve(sid('agent-early'))).toBe(first)
  156. })
  157. it('projects Agent Context identity in both directions and withdraws the adapter on disposal', async () => {
  158. const bench = await mount(GENERATION)
  159. await flush()
  160. expect(bench.sessions.list.getSnapshot().phase).toBe('ready')
  161. bench.dispatch('api-session/added', {
  162. sessionId: sid('agent-1'),
  163. updatedAt: 1,
  164. running: false,
  165. blank: true,
  166. })
  167. await flush()
  168. const scoped = bench.sessions.scope(sid('agent-1'))
  169. const adapter = bench.ctx.typert.contexts.getClient('agent')
  170. expect(scoped).toBeDefined()
  171. expect(adapter?.identity(bench.ctx)).toBeUndefined()
  172. expect(adapter?.identity(scoped!)).toBe(sid('agent-1'))
  173. expect(adapter?.resolve(sid('agent-1'))).toBe(scoped)
  174. await bench.fiber.dispose()
  175. expect(bench.ctx.typert.contexts.getClient('agent')).toBeUndefined()
  176. })
  177. it('waits for a Host generation before retrying the control stream', async () => {
  178. const accept = vi.spyOn(ClientSessions.prototype, 'handleControlFrame')
  179. const bench = await mount()
  180. await flush()
  181. expect(accept.mock.calls.filter(([frame]) => frame.type === 'baseline')).toHaveLength(1)
  182. bench.api.failStreams(new RemoteStreamCarrierError('offline'))
  183. await flush()
  184. expect(accept.mock.calls.filter(([frame]) => frame.type === 'baseline')).toHaveLength(1)
  185. bench.publishGeneration(GENERATION)
  186. await flush()
  187. expect(accept.mock.calls.filter(([frame]) => frame.type === 'baseline')).toHaveLength(2)
  188. })
  189. })