api-proxy-projections.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /**
  2. * Projection carrier paths of the host ApiProxy: the history tail page's
  3. * projections block reads the registry's watermark snapshot (asOfSeq = last
  4. * event seq, one consistent cut); loadOlder pages never carry the block; a
  5. * composition without the registry serves histories without it; a disposed
  6. * registration's key leaves subsequent responses; and every unit change is
  7. * pushed to mux consumers as a session/projection frame minted here.
  8. */
  9. import { describe, expect, it } from 'vitest'
  10. import { Context } from 'cordis'
  11. import { z } from 'zod'
  12. import AgentRegistry from '@deepseek-ai/dsh-agent'
  13. import type { Agent } from '@deepseek-ai/dsh-agent'
  14. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  15. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  16. import type { Session } from '@deepseek-ai/dsh-session'
  17. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  18. import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
  19. import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
  20. import type { MuxFrame, RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api'
  21. import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
  22. import { createApiProxy } from '@deepseek-ai/dsh-host-apiproxy'
  23. declare module '@deepseek-ai/dsh-session-projection/types' {
  24. interface SessionProjectionMap {
  25. 'test/last-user': { text: string } | null
  26. }
  27. }
  28. let nextRpc = 1
  29. function request<P>(payload: P): RpcRequest<P> {
  30. return { rpcId: RpcId(`proj-${String(nextRpc++)}`), payload }
  31. }
  32. /** Whole-value unit folding the latest user/message text; null before the first. */
  33. type LastUserState = { text: string } | null
  34. const lastUserUnit = (): ProjectionDefinition<'test/last-user', LastUserState> => ({
  35. key: 'test/last-user',
  36. schema: z.union([z.object({ text: z.string() }), z.null()]),
  37. init: () => null,
  38. apply: (state, event) => (event.type === 'user/message'
  39. ? { text: (event.data.content[0] as { text?: string }).text ?? '' }
  40. : state),
  41. view: state => state,
  42. stateVersion: 1,
  43. })
  44. async function harness(withRegistry: boolean): Promise<{ ctx: Context; session: Session }> {
  45. const ctx = new Context()
  46. await ctx.plugin(SessionStore)
  47. await ctx.plugin(UserInteractionService)
  48. await ctx.plugin(AgentRegistry)
  49. if (withRegistry) await ctx.plugin(SessionProjectionRegistry)
  50. const session = ctx.sessions.create()
  51. // history resolves the agent first; a live structural stub is enough (only
  52. // .session is read on this path).
  53. ctx.agents.register({ id: session.id, session, status: 'idle', ctx } as Agent)
  54. return { ctx, session }
  55. }
  56. /** Append `count` user messages so the log has paginable message boundaries. */
  57. function seedMessages(session: Session, count: number): void {
  58. for (let i = 0; i < count; i++) {
  59. session.append('user/message', createUserMessage({
  60. content: [{ type: 'text', text: `m${i}` }],
  61. source: { kind: 'user' },
  62. }), { surfaceOp: 'append' })
  63. }
  64. }
  65. const api = (ctx: Context) => createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
  66. describe('session.history projections block', () => {
  67. it('serves the unit value on the tail page with asOfSeq = last event seq', async () => {
  68. const { ctx, session } = await harness(true)
  69. ctx.sessionProjections.register(lastUserUnit())
  70. seedMessages(session, 3)
  71. const response = await api(ctx).sessions.history(request({ sessionId: session.id }))
  72. expect(response.result.ok).toBe(true)
  73. if (!response.result.ok) throw new Error('unreachable')
  74. const { events, projections } = response.result.value
  75. expect(projections).toBeDefined()
  76. expect(projections?.asOfSeq).toBe(session.seq - 1)
  77. expect(projections?.values['test/last-user']).toEqual({ text: 'm2' })
  78. // asOfSeq IS the window tail: the last served event carries it.
  79. expect(events.at(-1)?.event.seq).toBe(projections?.asOfSeq)
  80. })
  81. it('never carries the block on loadOlder pages (beforeSeq present)', async () => {
  82. const { ctx, session } = await harness(true)
  83. ctx.sessionProjections.register(lastUserUnit())
  84. seedMessages(session, 5)
  85. const older = await api(ctx).sessions.history(request({ sessionId: session.id, beforeSeq: 3, maxMessages: 2 }))
  86. expect(older.result.ok).toBe(true)
  87. if (!older.result.ok) throw new Error('unreachable')
  88. expect('projections' in older.result.value).toBe(false)
  89. })
  90. it('serves no block when the composition has no projection registry', async () => {
  91. const { ctx, session } = await harness(false)
  92. seedMessages(session, 2)
  93. const response = await api(ctx).sessions.history(request({ sessionId: session.id }))
  94. expect(response.result.ok).toBe(true)
  95. if (!response.result.ok) throw new Error('unreachable')
  96. expect('projections' in response.result.value).toBe(false)
  97. })
  98. it('drops a disposed registration from subsequent tail pages (empty block, key absent)', async () => {
  99. const { ctx, session } = await harness(true)
  100. const dispose = ctx.sessionProjections.register(lastUserUnit())
  101. seedMessages(session, 1)
  102. const proxy = api(ctx)
  103. const before = await proxy.sessions.history(request({ sessionId: session.id }))
  104. if (!before.result.ok) throw new Error('unreachable')
  105. expect(before.result.value.projections?.values['test/last-user']).toEqual({ text: 'm0' })
  106. dispose()
  107. const after = await proxy.sessions.history(request({ sessionId: session.id }))
  108. if (!after.result.ok) throw new Error('unreachable')
  109. // The registry is still mounted, so the block itself stays (asOfSeq cut
  110. // with zero keys); the disposed key reads as capability absence.
  111. expect(after.result.value.projections?.asOfSeq).toBe(session.seq - 1)
  112. expect(after.result.value.projections?.values).toEqual({})
  113. })
  114. })
  115. describe('session.list projections column', () => {
  116. it('serves attached rows from the live registry cut, watermarked for client seeding', async () => {
  117. const { ctx, session } = await harness(true)
  118. ctx.sessionProjections.register(lastUserUnit())
  119. seedMessages(session, 1)
  120. const response = await api(ctx).sessions.list(request({}))
  121. if (!response.result.ok) throw new Error('unreachable')
  122. const row = response.result.value.items.find(item => item.sessionId === session.id)
  123. expect(row?.projections?.values['test/last-user']).toEqual({ text: 'm0' })
  124. expect(row?.projections?.asOfSeq).toBe(session.seq - 1)
  125. })
  126. it('omits the column entirely when no registry is mounted', async () => {
  127. const { ctx, session } = await harness(false)
  128. seedMessages(session, 1)
  129. const response = await api(ctx).sessions.list(request({}))
  130. if (!response.result.ok) throw new Error('unreachable')
  131. const row = response.result.value.items.find(item => item.sessionId === session.id)
  132. expect(row).toBeDefined()
  133. expect(row !== undefined && 'projections' in row).toBe(false)
  134. })
  135. it('serves cold rows from the persisted projection cache with zero log loads', async () => {
  136. const { ctx } = await harness(true)
  137. const coldId = SessionId('session-cold-listing')
  138. const load = () => { throw new Error('list must not load event logs') }
  139. ctx.provide('sessionPersistence', {
  140. list: async () => [{ version: 0, id: coldId, createdAt: 5, cwd: '/tmp' }],
  141. locate: () => undefined,
  142. load,
  143. inspect: load,
  144. readFrom: load,
  145. } as never)
  146. ctx.provide('sessionProjectionCache', {
  147. // The carrier hands the listed header through as the identity witness.
  148. cachedSnapshot: (meta: { id: unknown; createdAt: number }) =>
  149. (meta.id === coldId && meta.createdAt === 5
  150. ? { asOfSeq: 7, values: { 'test/last-user': { text: 'cached' } } }
  151. : undefined),
  152. } as never)
  153. const response = await api(ctx).sessions.list(request({}))
  154. if (!response.result.ok) throw new Error('unreachable')
  155. const row = response.result.value.items.find(item => item.sessionId === coldId)
  156. expect(row?.running).toBe(false)
  157. expect(row?.projections).toEqual({ asOfSeq: 7, values: { 'test/last-user': { text: 'cached' } } })
  158. })
  159. it('cold rows without a cache plugin (or without a stored row) just lack the column', async () => {
  160. const { ctx } = await harness(true)
  161. const coldId = SessionId('session-cold-uncached')
  162. ctx.provide('sessionPersistence', {
  163. list: async () => [{ version: 0, id: coldId, createdAt: 5, cwd: '/tmp' }],
  164. locate: () => undefined,
  165. } as never)
  166. const response = await api(ctx).sessions.list(request({}))
  167. if (!response.result.ok) throw new Error('unreachable')
  168. const row = response.result.value.items.find(item => item.sessionId === coldId)
  169. expect(row).toBeDefined()
  170. expect(row !== undefined && 'projections' in row).toBe(false)
  171. })
  172. it('a throwing column read degrades that row, never the listing', async () => {
  173. const { ctx, session } = await harness(true)
  174. ctx.sessionProjections.register({
  175. ...lastUserUnit(),
  176. view: () => { throw new Error('unit exploded') },
  177. })
  178. seedMessages(session, 1)
  179. const response = await api(ctx).sessions.list(request({}))
  180. if (!response.result.ok) throw new Error('unreachable')
  181. const row = response.result.value.items.find(item => item.sessionId === session.id)
  182. expect(row).toBeDefined()
  183. expect(row !== undefined && 'projections' in row).toBe(false)
  184. })
  185. })
  186. describe('session/projection push frame', () => {
  187. /** Drain frames until `count` session/projection frames arrived. */
  188. async function collect(iterable: AsyncIterable<RpcRequest<MuxFrame>>, count: number, abort: AbortController): Promise<MuxFrame[]> {
  189. const frames: MuxFrame[] = []
  190. for await (const envelope of iterable) {
  191. frames.push(envelope.payload)
  192. if (frames.filter(f => f.type === 'session/projection').length >= count) abort.abort()
  193. }
  194. return frames
  195. }
  196. it('broadcasts a frame per changed unit with the causing seq, and none for same-reference applies', async () => {
  197. const { ctx, session } = await harness(true)
  198. ctx.sessionProjections.register(lastUserUnit())
  199. const proxy = api(ctx)
  200. // The gateway's onChanged subscription lives in an inject child whose
  201. // fiber activates asynchronously; yield until it lands before appending.
  202. await new Promise(resolve => setTimeout(resolve, 0))
  203. const abort = new AbortController()
  204. const stream = proxy.events.mux({ rpcId: RpcId('t-proj-mux'), payload: {} }, abort.signal)
  205. const collected = collect(stream, 2, abort)
  206. seedMessages(session, 1)
  207. // Same-reference apply: turn/start does not concern the unit — no frame.
  208. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  209. seedMessages(session, 1)
  210. const frames = await collected
  211. const pushes = frames.filter(
  212. (f): f is Extract<MuxFrame, { type: 'session/projection' }> => f.type === 'session/projection',
  213. )
  214. expect(pushes).toEqual([
  215. { type: 'session/projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 0 },
  216. { type: 'session/projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 2 },
  217. ])
  218. // Frame seq aligns with the tail block's asOfSeq vocabulary (higher-seq-wins compatible).
  219. const tail = await proxy.sessions.history(request({ sessionId: session.id }))
  220. if (!tail.result.ok) throw new Error('unreachable')
  221. expect(tail.result.value.projections?.asOfSeq).toBe(pushes.at(-1)?.seq)
  222. })
  223. it('emits no projection frames when the composition has no registry', async () => {
  224. const { ctx, session } = await harness(false)
  225. const proxy = api(ctx)
  226. const abort = new AbortController()
  227. const stream = proxy.events.mux({ rpcId: RpcId('t-noproj-mux'), payload: {} }, abort.signal)
  228. const frames: MuxFrame[] = []
  229. const drained = (async () => {
  230. for await (const envelope of stream) {
  231. frames.push(envelope.payload)
  232. if (frames.filter(f => f.type === 'session/event').length >= 2) abort.abort()
  233. }
  234. })()
  235. seedMessages(session, 2)
  236. await drained
  237. expect(frames.some(f => f.type === 'session/projection')).toBe(false)
  238. })
  239. })