client-apply.client.spec.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. /**
  2. * Session Controller Client apply inside the assembled client: Remote events
  3. * arriving as emit frames on the `$events` stream, the control stream over
  4. * the real Connection, and Agent Context identity through the Typert registry.
  5. */
  6. import type { Context } from '@deepseek-ai/cordis'
  7. import { RemoteStreamCarrierError } from '@deepseek-ai/dsh-api-gateway/client'
  8. import { ok, type RemoteMock } from '@deepseek-ai/dsh-remote-mock'
  9. import { createClientTest, type TestClient, webApp } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/index.ts'
  10. import type { SessionId } from '@deepseek-ai/dsh-session/types'
  11. import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
  12. import { afterEach, describe, expect, vi, type MockInstance } from 'vitest'
  13. import { ClientSessions } from '../src/client/sessions/service.ts'
  14. import type { SessionListValue } from '../src/types.ts'
  15. const SELF = '@deepseek-ai/dsh-api-session-controller'
  16. const ROSTER = webApp.closure([SELF])
  17. const it = createClientTest({ roster: ROSTER })
  18. const EVENTS = '$events'
  19. const CONTROL = 'session/control'
  20. const BASELINE = { type: 'baseline', value: { queues: {}, jobs: {}, projections: {} } }
  21. /** The first client boot pays the cold module transform of the cone. */
  22. const COLD_BOOT_TIMEOUT_MS = 60_000
  23. const sid = (value: string): SessionId => value as SessionId
  24. afterEach(() => {
  25. vi.restoreAllMocks()
  26. })
  27. async function bench(start: () => Promise<TestClient>) {
  28. const client = await start()
  29. return { client, sessions: client.ctx.sessions as ClientSessions }
  30. }
  31. /** Deliver one Remote event the way the Host forwards it: an emit frame on the `$events` stream, consumed by the client. */
  32. async function emit(mock: RemoteMock, event: string, ...args: unknown[]): Promise<void> {
  33. mock.streams.push(EVENTS, { type: 'emit', event, args })
  34. await mock.streams.drained(EVENTS)
  35. }
  36. function baselines(accept: MockInstance): number {
  37. return accept.mock.calls.filter(([frame]) => (frame as { type: string }).type === 'baseline').length
  38. }
  39. describe('Session Controller Client apply', () => {
  40. it('routes Remote events from the $events stream into the object layer and runs handleConnected once per generation', async ({ mock, start }) => {
  41. const connected = vi.spyOn(ClientSessions.prototype, 'handleConnected')
  42. const error = vi.spyOn(ClientSessions.prototype, 'handleSessionError')
  43. const { client, sessions } = await bench(start)
  44. // The first generation's `connection/reset` already ran it; apply itself saw no Host yet.
  45. await vi.waitFor(() => { expect(connected).toHaveBeenCalledOnce() })
  46. await emit(mock, 'api-session/added', { sessionId: sid('session-1'), updatedAt: 1, running: false, blank: true })
  47. await vi.waitFor(() => {
  48. expect(sessions.list.getSnapshot().byId[sid('session-1')]).toMatchObject({ running: false, updatedAt: 1 })
  49. })
  50. await emit(mock, 'api-session/status', sid('session-1'), true)
  51. await emit(mock, 'api-session/activity', sid('session-1'), 9)
  52. await emit(mock, 'api-session/error', sid('session-1'), 'agent failed')
  53. await vi.waitFor(() => {
  54. expect(sessions.list.getSnapshot().byId[sid('session-1')]).toMatchObject({ running: true, updatedAt: 9 })
  55. })
  56. expect(error).toHaveBeenCalledWith(sid('session-1'), 'agent failed')
  57. await emit(mock, 'api-session/removed', sid('session-1'))
  58. await vi.waitFor(() => { expect(sessions.list.getSnapshot().byId[sid('session-1')]).toBeUndefined() })
  59. client.connection.reconnect()
  60. await mock.streams.opened(EVENTS, 2)
  61. await vi.waitFor(() => { expect(connected).toHaveBeenCalledTimes(2) })
  62. }, COLD_BOOT_TIMEOUT_MS)
  63. it('runs handleConnected at apply when the Host is already connected, as a reload of the row does', async ({ start }) => {
  64. const connected = vi.spyOn(ClientSessions.prototype, 'handleConnected')
  65. const { client } = await bench(start)
  66. await vi.waitFor(() => { expect(connected).toHaveBeenCalledOnce() })
  67. await client.reload(SELF)
  68. expect(connected).toHaveBeenCalledTimes(2)
  69. })
  70. it('accepts the control baseline, retries a carrier loss once, and reports a second opening snapshot as a protocol failure', async ({ mock, start }) => {
  71. const accept = vi.spyOn(ClientSessions.prototype, 'handleControlFrame')
  72. const logged = vi.spyOn(console, 'error').mockImplementation(() => {})
  73. await start()
  74. await vi.waitFor(() => { expect(baselines(accept)).toBe(1) })
  75. expect(accept).toHaveBeenCalledWith(BASELINE)
  76. // One immediate retry while the Host is available reopens the stream, whose script pushes the baseline again.
  77. mock.streams.fail(CONTROL, new RemoteStreamCarrierError('generation lost'))
  78. await vi.waitFor(() => { expect(baselines(accept)).toBe(2) })
  79. expect(mock.log.streams(CONTROL)).toHaveLength(2)
  80. mock.streams.push(CONTROL, BASELINE)
  81. await vi.waitFor(() => {
  82. expect(logged).toHaveBeenCalledWith(
  83. '[session-controller] control stream failed:',
  84. expect.objectContaining({ message: 'session control stream emitted more than one opening snapshot' }),
  85. )
  86. })
  87. })
  88. it('materializes Host-addressed Agent scopes before the Session list arrives', async ({ mock, start }) => {
  89. const list = Promise.withResolvers<RemoteResult<SessionListValue>>()
  90. mock.remote.session.list.mockReturnValueOnce(list.promise)
  91. const { client, sessions } = await bench(start)
  92. const adapter = client.ctx.typert.contexts.getClient('agent')
  93. const first = adapter?.resolve(sid('agent-early'))
  94. expect(first).toBeDefined()
  95. expect(sessions.scopeOf(first as Context)).toBe(sid('agent-early'))
  96. expect(adapter?.resolve(sid('agent-early'))).toBe(first)
  97. list.resolve(ok({ items: [] }))
  98. await vi.waitFor(() => { expect(sessions.list.getSnapshot().phase).toBe('ready') })
  99. })
  100. it('projects Agent Context identity in both directions and withdraws the adapter when the row unloads', async ({ mock, start }) => {
  101. const { client, sessions } = await bench(start)
  102. await vi.waitFor(() => { expect(sessions.list.getSnapshot().phase).toBe('ready') })
  103. await emit(mock, 'api-session/added', { sessionId: sid('agent-1'), updatedAt: 1, running: false, blank: true })
  104. await vi.waitFor(() => { expect(sessions.scope(sid('agent-1'))).toBeDefined() })
  105. const scoped = sessions.scope(sid('agent-1')) as Context
  106. const adapter = client.ctx.typert.contexts.getClient('agent')
  107. expect(adapter?.identity(client.ctx)).toBeUndefined()
  108. expect(adapter?.identity(scoped)).toBe(sid('agent-1'))
  109. expect(adapter?.resolve(sid('agent-1'))).toBe(scoped)
  110. await client.unload(SELF)
  111. expect(client.ctx.typert.contexts.getClient('agent')).toBeUndefined()
  112. })
  113. it('waits for a Host generation before retrying the control stream', async ({ mock, start }) => {
  114. const accept = vi.spyOn(ClientSessions.prototype, 'handleControlFrame')
  115. const hostBack = Promise.withResolvers<undefined>()
  116. let opens = 0
  117. // The second $events generation stays unready until the test lets the Host answer.
  118. mock.stream(EVENTS, (_args, stream) => {
  119. opens += 1
  120. const ready = { type: 'ready', clientId: `mock-client-${String(opens)}`, host: { home: '/home/mock' } }
  121. if (opens === 1) stream.push(ready)
  122. else void hostBack.promise.then(() => { stream.push(ready) })
  123. })
  124. const client = await start()
  125. await vi.waitFor(() => { expect(baselines(accept)).toBe(1) })
  126. client.connection.reconnect()
  127. await mock.streams.opened(EVENTS, 2)
  128. expect(client.connection.generation.getSnapshot()).toBeUndefined()
  129. mock.streams.fail(CONTROL, new RemoteStreamCarrierError('offline'))
  130. await client.flush()
  131. expect(baselines(accept)).toBe(1)
  132. expect(mock.log.streams(CONTROL)).toHaveLength(1)
  133. hostBack.resolve(undefined)
  134. await vi.waitFor(() => { expect(baselines(accept)).toBe(2) })
  135. expect(client.connection.generation.getSnapshot()).toMatchObject({ id: 2 })
  136. })
  137. })