client-apply.spec.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. /**
  2. * Runtime plugin browser-half apply: slots + object services mounting over the
  3. * connection handle, stream-loop sink wiring into the object layer, and the
  4. * fiber-scoped loop teardown.
  5. */
  6. import { Context } from '@deepseek-ai/cordis'
  7. import { describe, expect, it, vi } from 'vitest'
  8. import type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client'
  9. import type { ConnectionSinks } from '@deepseek-ai/dsh-client-connection/client'
  10. import { SESSION_SEARCH_RESULT_LIMIT } from '@deepseek-ai/dsh-host-apiproxy/api'
  11. import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
  12. import * as RuntimeClient from '../src/client/index.ts'
  13. import type { ConversationNodeDefinition } from '../src/client/contract/conversation.ts'
  14. import { Session } from '../src/client/sessions/session.ts'
  15. import type { SessionsService } from '../src/client/sessions/service.ts'
  16. import type { WorkspacesService } from '../src/client/workspaces/service.ts'
  17. import { FakeApiClient, ok } from './fake-api.ts'
  18. interface Bench {
  19. ctx: Context
  20. api: FakeApiClient
  21. sinks: ConnectionSinks | undefined
  22. stopped: number
  23. }
  24. async function mount(): Promise<Bench> {
  25. const ctx = new Context()
  26. await ctx.plugin(TypertRegistry)
  27. const api = new FakeApiClient()
  28. const bench: Bench = { ctx, api, sinks: undefined, stopped: 0 }
  29. const handle: ConnectionHandle = {
  30. api,
  31. isLoopback: true,
  32. rpc: {
  33. call: () => Promise.reject(new Error('unexpected generic RPC call')),
  34. },
  35. start: (sinks) => {
  36. bench.sinks = sinks
  37. return { stop: () => { bench.stopped += 1 } }
  38. },
  39. }
  40. ctx.reflect.provide('connection', handle)
  41. ctx.reflect.provide('remote', {})
  42. await ctx.plugin(RuntimeClient).await()
  43. return bench
  44. }
  45. async function flushMicrotasks(): Promise<void> {
  46. for (let i = 0; i < 12; i++) await Promise.resolve()
  47. }
  48. describe('runtime client apply', () => {
  49. it('mounts slots, Sessions, and Workspaces and fans host frames into both managers', async () => {
  50. const bench = await mount()
  51. expect(bench.ctx.get('slots') !== undefined).toBe(true)
  52. // The built-in 'root' declaration ships with this package's SlotsService
  53. // (the SlotMap 'root' merge lives here).
  54. expect(bench.ctx.slots.spec('root')).toEqual({ kind: 'single', scope: 'root' })
  55. const sessions = bench.ctx.get('sessions')
  56. const workspaces = bench.ctx.get('workspaces')
  57. expect(sessions !== undefined).toBe(true)
  58. expect(workspaces !== undefined).toBe(true)
  59. // The bound the wire schema enforces, not a per-connection negotiation.
  60. expect((sessions as SessionsService).searchResultLimit).toBe(SESSION_SEARCH_RESULT_LIMIT)
  61. if (workspaces === undefined) throw new Error('WorkspacesService missing after runtime apply')
  62. expect(bench.sinks).toBeDefined()
  63. // Frame sinks reach the object layer: a host session-added lands in the list store.
  64. bench.sinks?.onHostEnvelope?.({
  65. rpcId: 'r1' as never,
  66. payload: { type: 'host/session-added', blank: true, sessionId: 's-new' } as never,
  67. })
  68. await Promise.resolve()
  69. expect((sessions as { list: { getSnapshot(): { ids: string[] } } }).list.getSnapshot().ids).toContain('s-new')
  70. bench.sinks?.onHostEnvelope?.({
  71. rpcId: 'r-workspace' as never,
  72. payload: {
  73. type: 'host/workspace-changed',
  74. workspace: {
  75. workspaceId: 'w-new', path: '/w/new', title: 'new', sessionIds: [],
  76. createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
  77. },
  78. } as never,
  79. })
  80. await Promise.resolve()
  81. expect(workspaces.list.getSnapshot().items[0]?.workspaceId).toBe('w-new')
  82. // Mux sink and onConnected route without throwing (manager semantics own the behavior).
  83. bench.sinks?.onMuxEnvelope?.({ rpcId: 'r2' as never, payload: { type: 'stream/error', message: 'x' } as never })
  84. bench.sinks?.onConnected?.()
  85. })
  86. it('selects the recent Workspace once when the first baselines have no current session', async () => {
  87. const bench = await mount()
  88. bench.api.onWorkspaceList = () => Promise.resolve(ok({
  89. items: [{
  90. workspaceId: 'w-recent', path: '/w/recent', title: 'recent', sessionIds: [],
  91. createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
  92. }] as never[],
  93. }))
  94. bench.api.onList = () => Promise.resolve(ok({ items: [] }))
  95. bench.sinks?.onConnected?.()
  96. await flushMicrotasks()
  97. const sessions = bench.ctx.get('sessions') as SessionsService
  98. const workspaces = bench.ctx.get('workspaces') as WorkspacesService
  99. expect(bench.api.callsOf('session.create')).toEqual([{ workspaceId: 'w-recent' }])
  100. expect(sessions.list.getSnapshot().current).toBe('fk-new')
  101. sessions.clear()
  102. await workspaces.refresh()
  103. await flushMicrotasks()
  104. expect(sessions.list.getSnapshot().current).toBeUndefined()
  105. expect(bench.api.callsOf('session.create')).toHaveLength(1)
  106. })
  107. it('wires registry changes into resident Sessions during the runtime apply pass', async () => {
  108. const bench = await mount()
  109. const sessions = bench.ctx.get('sessions') as SessionsService
  110. bench.sinks?.onHostEnvelope?.({
  111. rpcId: 'r-registry' as never,
  112. payload: { type: 'host/session-added', blank: true, sessionId: 's-registry' } as never,
  113. })
  114. await flushMicrotasks()
  115. expect(sessions.binding('s-registry' as never)).toBeDefined()
  116. const rebuild = vi.spyOn(Session.prototype, 'rebuildConversationRegistry')
  117. const definition: ConversationNodeDefinition<null> = {
  118. kind: 'registry-probe',
  119. match: () => null,
  120. start: () => null,
  121. update: context => context.state,
  122. buildViewNode: () => null,
  123. }
  124. bench.ctx.conversationEvents.register(definition)
  125. await flushMicrotasks()
  126. expect(rebuild).toHaveBeenCalledOnce()
  127. rebuild.mockRestore()
  128. })
  129. it('stops the stream loop when the plugin fiber unloads', async () => {
  130. const bench = await mount()
  131. const fiber = [...bench.ctx.registry.values()].find(f => f.name?.includes('client'))
  132. // Dispose the whole tree: the ctx.effect teardown must call loop.stop exactly once.
  133. await bench.ctx.fiber.dispose()
  134. expect(bench.stopped).toBe(1)
  135. void fiber
  136. })
  137. })