client-apply.spec.ts 6.3 KB

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