client-apply.client.spec.ts 7.5 KB

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