api-proxy-projections.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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, { Inbox } 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. // The gateway reads both the session and durable inbox baseline.
  52. ctx.agents.register({ id: session.id, session, inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), status: 'idle', ctx } as Agent)
  53. return { ctx, session }
  54. }
  55. /** Append `count` user messages so the log has paginable message boundaries. */
  56. function seedMessages(session: Session, count: number): void {
  57. for (let i = 0; i < count; i++) {
  58. session.append('user/message', createUserMessage({
  59. content: [{ type: 'text', text: `m${i}` }],
  60. source: { kind: 'user' },
  61. }), { surfaceOp: 'append' })
  62. }
  63. }
  64. const api = (ctx: Context) => createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
  65. describe('session.history projections block', () => {
  66. it('serves the unit value on the tail page with asOfSeq = last event seq', async () => {
  67. const { ctx, session } = await harness(true)
  68. ctx.sessionProjections.register(lastUserUnit())
  69. seedMessages(session, 3)
  70. const response = await api(ctx).sessions.history(request({ sessionId: session.id }))
  71. expect(response.result.ok).toBe(true)
  72. if (!response.result.ok) throw new Error('unreachable')
  73. const { events, projections } = response.result.value
  74. expect(projections).toBeDefined()
  75. expect(projections?.asOfSeq).toBe(session.seq - 1)
  76. expect(projections?.values['test/last-user']).toEqual({ text: 'm2' })
  77. // asOfSeq IS the window tail: the last served event carries it.
  78. expect(events.at(-1)?.event.seq).toBe(projections?.asOfSeq)
  79. })
  80. it('never carries the block on loadOlder pages (beforeSeq present)', async () => {
  81. const { ctx, session } = await harness(true)
  82. ctx.sessionProjections.register(lastUserUnit())
  83. seedMessages(session, 5)
  84. const older = await api(ctx).sessions.history(request({ sessionId: session.id, beforeSeq: 3, maxMessages: 2 }))
  85. expect(older.result.ok).toBe(true)
  86. if (!older.result.ok) throw new Error('unreachable')
  87. expect('projections' in older.result.value).toBe(false)
  88. })
  89. it('serves no block when the composition has no projection registry', async () => {
  90. const { ctx, session } = await harness(false)
  91. seedMessages(session, 2)
  92. const response = await api(ctx).sessions.history(request({ sessionId: session.id }))
  93. expect(response.result.ok).toBe(true)
  94. if (!response.result.ok) throw new Error('unreachable')
  95. expect('projections' in response.result.value).toBe(false)
  96. })
  97. it('drops a disposed registration from subsequent tail pages (empty block, key absent)', async () => {
  98. const { ctx, session } = await harness(true)
  99. const dispose = ctx.sessionProjections.register(lastUserUnit())
  100. seedMessages(session, 1)
  101. const proxy = api(ctx)
  102. const before = await proxy.sessions.history(request({ sessionId: session.id }))
  103. if (!before.result.ok) throw new Error('unreachable')
  104. expect(before.result.value.projections?.values['test/last-user']).toEqual({ text: 'm0' })
  105. dispose()
  106. const after = await proxy.sessions.history(request({ sessionId: session.id }))
  107. if (!after.result.ok) throw new Error('unreachable')
  108. // The registry is still mounted, so the block itself stays (asOfSeq cut
  109. // with zero keys); the disposed key reads as capability absence.
  110. expect(after.result.value.projections?.asOfSeq).toBe(session.seq - 1)
  111. expect(after.result.value.projections?.values).toEqual({})
  112. })
  113. })
  114. describe('session.list projections column', () => {
  115. it('serves attached rows from the live registry cut, watermarked for client seeding', async () => {
  116. const { ctx, session } = await harness(true)
  117. ctx.sessionProjections.register(lastUserUnit())
  118. seedMessages(session, 1)
  119. const response = await api(ctx).sessions.list(request({}))
  120. if (!response.result.ok) throw new Error('unreachable')
  121. const row = response.result.value.items.find(item => item.sessionId === session.id)
  122. expect(row?.projections?.values['test/last-user']).toEqual({ text: 'm0' })
  123. expect(row?.projections?.asOfSeq).toBe(session.seq - 1)
  124. })
  125. it('omits the column entirely when no registry is mounted', async () => {
  126. const { ctx, session } = await harness(false)
  127. seedMessages(session, 1)
  128. const response = await api(ctx).sessions.list(request({}))
  129. if (!response.result.ok) throw new Error('unreachable')
  130. const row = response.result.value.items.find(item => item.sessionId === session.id)
  131. expect(row).toBeDefined()
  132. expect(row !== undefined && 'projections' in row).toBe(false)
  133. })
  134. it('serves cold rows from the persisted projection cache with zero log loads', async () => {
  135. const { ctx } = await harness(true)
  136. const coldId = SessionId('session-cold-listing')
  137. const load = () => { throw new Error('list must not load event logs') }
  138. ctx.provide('sessionPersistence', {
  139. list: async () => [{ version: 0, id: coldId, createdAt: 5, cwd: '/tmp' }],
  140. locate: () => undefined,
  141. load,
  142. inspect: load,
  143. readFrom: load,
  144. } as never)
  145. ctx.provide('sessionProjectionCache', {
  146. // The carrier hands the listed header through as the identity witness.
  147. cachedSnapshot: (meta: { id: unknown; createdAt: number }) =>
  148. (meta.id === coldId && meta.createdAt === 5
  149. ? { asOfSeq: 7, values: { 'test/last-user': { text: 'cached' } } }
  150. : undefined),
  151. } as never)
  152. const response = await api(ctx).sessions.list(request({}))
  153. if (!response.result.ok) throw new Error('unreachable')
  154. const row = response.result.value.items.find(item => item.sessionId === coldId)
  155. expect(row?.running).toBe(false)
  156. expect(row?.projections).toEqual({ asOfSeq: 7, values: { 'test/last-user': { text: 'cached' } } })
  157. })
  158. it('cold rows without a cache plugin (or without a stored row) just lack the column', async () => {
  159. const { ctx } = await harness(true)
  160. const coldId = SessionId('session-cold-uncached')
  161. ctx.provide('sessionPersistence', {
  162. list: async () => [{ version: 0, id: coldId, createdAt: 5, cwd: '/tmp' }],
  163. locate: () => undefined,
  164. } as never)
  165. const response = await api(ctx).sessions.list(request({}))
  166. if (!response.result.ok) throw new Error('unreachable')
  167. const row = response.result.value.items.find(item => item.sessionId === coldId)
  168. expect(row).toBeDefined()
  169. expect(row !== undefined && 'projections' in row).toBe(false)
  170. })
  171. it('a throwing column read degrades that row, never the listing', async () => {
  172. const { ctx, session } = await harness(true)
  173. ctx.sessionProjections.register({
  174. ...lastUserUnit(),
  175. view: () => { throw new Error('unit exploded') },
  176. })
  177. seedMessages(session, 1)
  178. const response = await api(ctx).sessions.list(request({}))
  179. if (!response.result.ok) throw new Error('unreachable')
  180. const row = response.result.value.items.find(item => item.sessionId === session.id)
  181. expect(row).toBeDefined()
  182. expect(row !== undefined && 'projections' in row).toBe(false)
  183. })
  184. })
  185. describe('session/projection push frame', () => {
  186. /** Drain frames until `count` session/projection frames arrived. */
  187. async function collect(iterable: AsyncIterable<RpcRequest<MuxFrame>>, count: number, abort: AbortController): Promise<MuxFrame[]> {
  188. const frames: MuxFrame[] = []
  189. for await (const envelope of iterable) {
  190. frames.push(envelope.payload)
  191. if (frames.filter(f => f.type === 'session/projection').length >= count) abort.abort()
  192. }
  193. return frames
  194. }
  195. it('broadcasts a frame per changed unit with the causing seq, and none for same-reference applies', async () => {
  196. const { ctx, session } = await harness(true)
  197. ctx.sessionProjections.register(lastUserUnit())
  198. const proxy = api(ctx)
  199. // The gateway's onChanged subscription lives in an inject child whose
  200. // fiber activates asynchronously; yield until it lands before appending.
  201. await new Promise(resolve => setTimeout(resolve, 0))
  202. const abort = new AbortController()
  203. const stream = proxy.events.mux({ rpcId: RpcId('t-proj-mux'), payload: {} }, abort.signal)
  204. const collected = collect(stream, 2, abort)
  205. seedMessages(session, 1)
  206. // Same-reference apply: turn/start does not concern the unit — no frame.
  207. session.append('turn/start', { turn: 1 })
  208. seedMessages(session, 1)
  209. const frames = await collected
  210. const pushes = frames.filter(
  211. (f): f is Extract<MuxFrame, { type: 'session/projection' }> => f.type === 'session/projection',
  212. )
  213. expect(pushes).toEqual([
  214. { type: 'session/projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 0 },
  215. { type: 'session/projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 2 },
  216. ])
  217. // Frame seq aligns with the tail block's asOfSeq vocabulary (higher-seq-wins compatible).
  218. const tail = await proxy.sessions.history(request({ sessionId: session.id }))
  219. if (!tail.result.ok) throw new Error('unreachable')
  220. expect(tail.result.value.projections?.asOfSeq).toBe(pushes.at(-1)?.seq)
  221. })
  222. it('emits no projection frames when the composition has no registry', async () => {
  223. const { ctx, session } = await harness(false)
  224. const proxy = api(ctx)
  225. const abort = new AbortController()
  226. const stream = proxy.events.mux({ rpcId: RpcId('t-noproj-mux'), payload: {} }, abort.signal)
  227. const frames: MuxFrame[] = []
  228. const drained = (async () => {
  229. for await (const envelope of stream) {
  230. frames.push(envelope.payload)
  231. if (frames.filter(f => f.type === 'session/event').length >= 2) abort.abort()
  232. }
  233. })()
  234. seedMessages(session, 2)
  235. await drained
  236. expect(frames.some(f => f.type === 'session/projection')).toBe(false)
  237. })
  238. })