session-projections.host.spec.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. /**
  2. * Session Controller projection paths: 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 through the control stream.
  8. */
  9. import { describe, expect, it, vi } from 'vitest'
  10. import { Context } from '@deepseek-ai/cordis'
  11. import { z } from 'zod'
  12. import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent'
  13. import { AttachmentStore } from '@deepseek-ai/dsh-attachment'
  14. import type { Agent } from '@deepseek-ai/dsh-agent'
  15. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  16. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  17. import type { Session } from '@deepseek-ai/dsh-session'
  18. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  19. import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
  20. import UserQuestionService from '@deepseek-ai/dsh-user-questions'
  21. import { SessionControlController } from '@deepseek-ai/dsh-api-session-controller/src/control.ts'
  22. import type { SessionControlFrame } from '@deepseek-ai/dsh-api-session-controller/types'
  23. import { createSessionTestRemote, type TestSessionRemote } from './test-remote.ts'
  24. declare module '@deepseek-ai/dsh-session-projection/types' {
  25. interface SessionProjectionStateMap {
  26. 'test/last-user': LastUserState
  27. 'test/internal-count': number
  28. }
  29. interface SessionProjectionMap {
  30. 'test/last-user': { text: string } | null
  31. }
  32. }
  33. function request<P>(payload: P): P {
  34. return payload
  35. }
  36. function page(
  37. remote: TestSessionRemote,
  38. request: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number },
  39. ) {
  40. return remote.page({
  41. address: { kind: 'session', sessionId: request.sessionId },
  42. ...(request.beforeSeq === undefined ? {} : { beforeSeq: request.beforeSeq }),
  43. ...(request.maxMessages === undefined ? {} : { maxMessages: request.maxMessages }),
  44. })
  45. }
  46. /** Whole-value unit folding the latest user/message text; null before the first. */
  47. type LastUserState = { text: string } | null
  48. const lastUserUnit = () => ({
  49. key: 'test/last-user',
  50. stateSchema: z.union([z.object({ text: z.string() }), z.null()]),
  51. init: () => null,
  52. apply: (state, event) => (event.type === 'user/message'
  53. ? { text: (event.data.content[0] as { text?: string }).text ?? '' }
  54. : state),
  55. wire: {
  56. viewSchema: z.union([z.object({ text: z.string() }), z.null()]),
  57. view: state => state,
  58. },
  59. stateVersion: 1,
  60. }) satisfies ProjectionDefinition<'test/last-user', LastUserState>
  61. const internalCountUnit = () => ({
  62. key: 'test/internal-count',
  63. stateSchema: z.number().int().nonnegative(),
  64. init: () => 0,
  65. apply: (state: number) => state + 1,
  66. stateVersion: 1,
  67. }) satisfies ProjectionDefinition<'test/internal-count', number>
  68. async function harness(withRegistry: boolean): Promise<{ ctx: Context; session: Session }> {
  69. const ctx = new Context()
  70. await ctx.plugin(SessionStore)
  71. await ctx.plugin(UserQuestionService)
  72. await ctx.plugin(AgentRegistry)
  73. if (withRegistry) await ctx.plugin(SessionProjectionRegistry)
  74. const session = ctx.sessions.create()
  75. // The gateway reads both the session and durable inbox baseline.
  76. ctx.agents.register({ id: session.id, session, inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), status: 'idle', ctx } as Agent)
  77. return { ctx, session }
  78. }
  79. /** Append `count` user messages so the log has paginable message boundaries. */
  80. function seedMessages(session: Session, count: number): void {
  81. for (let i = 0; i < count; i++) {
  82. session.append('user/message', createUserMessage({
  83. content: [{ type: 'text', text: `m${i}` }],
  84. source: { kind: 'user' },
  85. }), { surfaceOp: 'append' })
  86. }
  87. }
  88. const remote = (ctx: Context) => createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  89. describe('session.history projections block', () => {
  90. it('serves the unit value on the tail page with asOfSeq = last event seq', async () => {
  91. const { ctx, session } = await harness(true)
  92. ctx.sessionProjections.register(lastUserUnit())
  93. seedMessages(session, 3)
  94. const response = await page(remote(ctx), request({ sessionId: session.id }))
  95. expect(response.ok).toBe(true)
  96. if (!response.ok) throw new Error('unreachable')
  97. const { events, projections } = response.value
  98. expect(projections).toBeDefined()
  99. expect(projections?.asOfSeq).toBe(session.seq - 1)
  100. expect(projections?.values['test/last-user']).toEqual({ text: 'm2' })
  101. // asOfSeq IS the window tail: the last served event carries it.
  102. expect(events.at(-1)?.event.seq).toBe(projections?.asOfSeq)
  103. })
  104. it('publishes the attachments imageLimits as a constant unit while both seams are composed', async () => {
  105. const { ctx, session } = await harness(true)
  106. const limits = {
  107. maxImageBytes: 5 * 1024 * 1024,
  108. maxImagesPerMessage: 20,
  109. maxMessageImageBytes: 100 * 1024 * 1024,
  110. maxImagePixels: 40_000_000,
  111. maxImageDimension: 2000,
  112. mediaTypes: ['image/png'] as const,
  113. }
  114. await ctx.plugin(class extends AttachmentStore {
  115. readonly imageLimits = limits
  116. validateImage(): Promise<void> { return Promise.resolve() }
  117. saveImage(): Promise<never> { return Promise.reject(new Error('unused')) }
  118. readImage(): Promise<never> { return Promise.reject(new Error('unused')) }
  119. })
  120. const gateway = remote(ctx)
  121. seedMessages(session, 2)
  122. const response = await page(gateway, request({ sessionId: session.id }))
  123. if (!response.ok) throw new Error('history failed')
  124. expect(response.value.projections?.values['imageLimits']).toEqual(limits)
  125. // Constant unit: appending events must never broadcast an imageLimits projection.
  126. await new Promise(resolve => setTimeout(resolve, 0))
  127. const abort = new AbortController()
  128. const iterator = gateway.control(abort.signal)[Symbol.asyncIterator]()
  129. await iterator.next()
  130. const next = iterator.next()
  131. seedMessages(session, 1)
  132. await new Promise(resolve => setTimeout(resolve, 0))
  133. await expect(next).resolves.toMatchObject({
  134. done: false,
  135. value: { type: 'projection', key: 'sessionListMetadata' },
  136. })
  137. const extra = iterator.next()
  138. const quiet = Symbol('quiet')
  139. expect(await Promise.race([
  140. extra,
  141. new Promise<typeof quiet>(resolve => setTimeout(() => { resolve(quiet) }, 0)),
  142. ])).toBe(quiet)
  143. abort.abort()
  144. await expect(extra).resolves.toEqual({ done: true, value: undefined })
  145. })
  146. it('leaves the imageLimits key absent while no attachment service is composed', async () => {
  147. const { ctx, session } = await harness(true)
  148. seedMessages(session, 1)
  149. const response = await page(remote(ctx), request({ sessionId: session.id }))
  150. if (!response.ok) throw new Error('history failed')
  151. expect(response.value.projections).toBeDefined()
  152. expect('imageLimits' in (response.value.projections?.values ?? {})).toBe(false)
  153. })
  154. it('never carries the block on loadOlder pages (beforeSeq present)', async () => {
  155. const { ctx, session } = await harness(true)
  156. ctx.sessionProjections.register(lastUserUnit())
  157. seedMessages(session, 5)
  158. const older = await page(remote(ctx), request({ sessionId: session.id, beforeSeq: 3, maxMessages: 2 }))
  159. expect(older.ok).toBe(true)
  160. if (!older.ok) throw new Error('unreachable')
  161. expect('projections' in older.value).toBe(false)
  162. })
  163. it('serves no block when the composition has no projection registry', async () => {
  164. const { ctx, session } = await harness(false)
  165. seedMessages(session, 2)
  166. const response = await page(remote(ctx), request({ sessionId: session.id }))
  167. expect(response.ok).toBe(true)
  168. if (!response.ok) throw new Error('unreachable')
  169. expect('projections' in response.value).toBe(false)
  170. })
  171. it('never exposes a host-only unit through history, listing, or push frames', async () => {
  172. const { ctx, session } = await harness(true)
  173. ctx.sessionProjections.register(internalCountUnit())
  174. const proxy = remote(ctx)
  175. await new Promise(resolve => setTimeout(resolve, 0))
  176. const abort = new AbortController()
  177. const iterator = proxy.control(abort.signal)[Symbol.asyncIterator]()
  178. const baseline = await iterator.next()
  179. if (baseline.done || baseline.value.type !== 'baseline') {
  180. throw new Error('control stream ended before its baseline')
  181. }
  182. expect('test/internal-count' in (baseline.value.value.projections[session.id]?.values ?? {}))
  183. .toBe(false)
  184. seedMessages(session, 1)
  185. const changed = await iterator.next()
  186. expect(changed).toMatchObject({
  187. done: false,
  188. value: { type: 'projection', key: 'sessionListMetadata' },
  189. })
  190. abort.abort()
  191. await iterator.return?.()
  192. const history = await page(proxy, request({ sessionId: session.id }))
  193. if (!history.ok) throw new Error('history failed')
  194. expect('test/internal-count' in (history.value.projections?.values ?? {})).toBe(false)
  195. const listing = await proxy.list(request({}))
  196. if (!listing.ok) throw new Error('listing failed')
  197. const row = listing.value.items.find(item => item.sessionId === session.id)
  198. expect('test/internal-count' in (row?.projections?.values ?? {})).toBe(false)
  199. })
  200. it('drops a disposed registration from subsequent tail pages (empty block, key absent)', async () => {
  201. const { ctx, session } = await harness(true)
  202. const dispose = ctx.sessionProjections.register(lastUserUnit())
  203. seedMessages(session, 1)
  204. const proxy = remote(ctx)
  205. const before = await page(proxy, request({ sessionId: session.id }))
  206. if (!before.ok) throw new Error('unreachable')
  207. expect(before.value.projections?.values['test/last-user']).toEqual({ text: 'm0' })
  208. dispose()
  209. const after = await page(proxy, request({ sessionId: session.id }))
  210. if (!after.ok) throw new Error('unreachable')
  211. // The registry stays mounted; only the disposed key leaves while the
  212. // gateway-owned Session-list unit remains.
  213. expect(after.value.projections?.asOfSeq).toBe(session.seq - 1)
  214. expect('test/last-user' in (after.value.projections?.values ?? {})).toBe(false)
  215. expect(after.value.projections?.values.sessionListMetadata).toEqual({
  216. blank: true,
  217. lastPromptAt: session.events.at(-1)?.time,
  218. })
  219. })
  220. it('removes the gateway-owned Session-list unit when the gateway fiber unloads', async () => {
  221. const { ctx, session } = await harness(true)
  222. expect('sessionListMetadata' in ctx.sessionProjections.snapshot(session).values).toBe(false)
  223. const fiber = ctx.plugin(Object.assign((gatewayCtx: Context) => {
  224. createSessionTestRemote(gatewayCtx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  225. }, { inject: ['sessions', 'agents', 'userQuestions', 'sessionProjections'] }))
  226. await fiber.await()
  227. await vi.waitFor(() => {
  228. expect(ctx.sessionProjections.snapshot(session).values.sessionListMetadata)
  229. .toEqual({ blank: true, lastPromptAt: null })
  230. })
  231. await fiber.dispose()
  232. expect('sessionListMetadata' in ctx.sessionProjections.snapshot(session).values).toBe(false)
  233. })
  234. })
  235. describe('session.list projections column', () => {
  236. it('serves attached rows from the live registry cut, watermarked for client seeding', async () => {
  237. const { ctx, session } = await harness(true)
  238. ctx.sessionProjections.register(lastUserUnit())
  239. const gateway = remote(ctx)
  240. await new Promise(resolve => setTimeout(resolve, 0))
  241. session.append('turn/start', { turn: 1 })
  242. seedMessages(session, 1)
  243. const response = await gateway.list(request({}))
  244. if (!response.ok) throw new Error('unreachable')
  245. const row = response.value.items.find(item => item.sessionId === session.id)
  246. expect(row?.projections?.values['test/last-user']).toEqual({ text: 'm0' })
  247. expect(row?.projections?.values.sessionListMetadata).toEqual({
  248. blank: false,
  249. lastPromptAt: session.events.at(-1)?.time,
  250. })
  251. expect(row?.projections?.asOfSeq).toBe(session.seq - 1)
  252. })
  253. it('omits the column entirely when no registry is mounted', async () => {
  254. const { ctx, session } = await harness(false)
  255. seedMessages(session, 1)
  256. const response = await remote(ctx).list(request({}))
  257. if (!response.ok) throw new Error('unreachable')
  258. const row = response.value.items.find(item => item.sessionId === session.id)
  259. expect(row).toBeDefined()
  260. expect(row !== undefined && 'projections' in row).toBe(false)
  261. })
  262. it('serves cold rows from the persisted projection cache with zero log loads', async () => {
  263. const { ctx } = await harness(true)
  264. const coldId = SessionId('session-cold-listing')
  265. const load = () => { throw new Error('list must not load event logs') }
  266. ctx.provide('sessionPersistence', {
  267. list: async () => [{ version: 0, id: coldId, createdAt: 5, cwd: '/tmp' }],
  268. locate: () => undefined,
  269. load,
  270. inspect: load,
  271. readFrom: load,
  272. } as never)
  273. ctx.provide('sessionProjectionCache', {
  274. // The carrier hands the listed header through as the identity witness.
  275. cachedSnapshot: (meta: { id: unknown; createdAt: number }) =>
  276. (meta.id === coldId && meta.createdAt === 5
  277. ? { asOfSeq: 7, values: { 'test/last-user': { text: 'cached' } } }
  278. : undefined),
  279. } as never)
  280. const response = await remote(ctx).list(request({}))
  281. if (!response.ok) throw new Error('unreachable')
  282. const row = response.value.items.find(item => item.sessionId === coldId)
  283. expect(row?.running).toBe(false)
  284. expect(row?.projections).toEqual({ asOfSeq: 7, values: { 'test/last-user': { text: 'cached' } } })
  285. })
  286. it('cold rows without a cache plugin (or without a stored row) just lack the column', async () => {
  287. const { ctx } = await harness(true)
  288. const coldId = SessionId('session-cold-uncached')
  289. ctx.provide('sessionPersistence', {
  290. list: async () => [{ version: 0, id: coldId, createdAt: 5, cwd: '/tmp' }],
  291. locate: () => undefined,
  292. } as never)
  293. const response = await remote(ctx).list(request({}))
  294. if (!response.ok) throw new Error('unreachable')
  295. const row = response.value.items.find(item => item.sessionId === coldId)
  296. expect(row).toBeDefined()
  297. expect(row !== undefined && 'projections' in row).toBe(false)
  298. })
  299. it('a throwing column read degrades that row, never the listing', async () => {
  300. const { ctx, session } = await harness(true)
  301. ctx.sessionProjections.register({
  302. ...lastUserUnit(),
  303. wire: {
  304. viewSchema: z.union([z.object({ text: z.string() }), z.null()]),
  305. view: () => { throw new Error('unit exploded') },
  306. },
  307. })
  308. seedMessages(session, 1)
  309. const response = await remote(ctx).list(request({}))
  310. if (!response.ok) throw new Error('unreachable')
  311. const row = response.value.items.find(item => item.sessionId === session.id)
  312. expect(row).toBeDefined()
  313. expect(row !== undefined && 'projections' in row).toBe(false)
  314. })
  315. })
  316. describe('Session control projection frames', () => {
  317. /** Drain frames until `count` projection replacements arrive. */
  318. async function collect(
  319. iterable: AsyncIterable<SessionControlFrame>,
  320. count: number,
  321. abort: AbortController,
  322. ): Promise<SessionControlFrame[]> {
  323. const frames: SessionControlFrame[] = []
  324. for await (const frame of iterable) {
  325. frames.push(frame)
  326. if (frames.filter(candidate => candidate.type === 'projection').length >= count) abort.abort()
  327. }
  328. return frames
  329. }
  330. it('broadcasts a frame per changed unit with the causing seq, and none for same-reference applies', async () => {
  331. const { ctx, session } = await harness(true)
  332. ctx.sessionProjections.register(lastUserUnit())
  333. const proxy = remote(ctx)
  334. // The controller's onChanged subscription lives in an inject child whose
  335. // fiber activates asynchronously; yield until it lands before appending.
  336. await new Promise(resolve => setTimeout(resolve, 0))
  337. const abort = new AbortController()
  338. const stream = proxy.control(abort.signal)
  339. const collected = collect(stream, 5, abort)
  340. const now = vi.spyOn(Date, 'now').mockReturnValue(100)
  341. seedMessages(session, 1)
  342. now.mockReturnValue(200)
  343. session.append('turn/start', { turn: 1 })
  344. now.mockReturnValue(300)
  345. seedMessages(session, 1)
  346. now.mockRestore()
  347. const frames = await collected
  348. const pushes = frames.filter(
  349. (f): f is Extract<SessionControlFrame, { type: 'projection' }> =>
  350. f.type === 'projection' && f.key === 'test/last-user',
  351. )
  352. expect(pushes).toEqual([
  353. { type: 'projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 0 },
  354. { type: 'projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 2 },
  355. ])
  356. expect(frames.filter(
  357. (f): f is Extract<SessionControlFrame, { type: 'projection' }> =>
  358. f.type === 'projection' && f.key === 'sessionListMetadata',
  359. )).toEqual([
  360. { type: 'projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: true, lastPromptAt: 100 }, seq: 0 },
  361. { type: 'projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: false, lastPromptAt: 100 }, seq: 1 },
  362. { type: 'projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: false, lastPromptAt: 300 }, seq: 2 },
  363. ])
  364. // Frame seq aligns with the tail block's asOfSeq vocabulary (higher-seq-wins compatible).
  365. const tail = await page(proxy, request({ sessionId: session.id }))
  366. if (!tail.ok) throw new Error('unreachable')
  367. expect(tail.value.projections?.asOfSeq).toBe(pushes.at(-1)?.seq)
  368. })
  369. it('emits no projection frames when the composition has no registry', async () => {
  370. const { ctx, session } = await harness(false)
  371. const control = new SessionControlController(ctx)
  372. const abort = new AbortController()
  373. const iterator = control.control(abort.signal)[Symbol.asyncIterator]()
  374. const baseline = await iterator.next()
  375. const next = iterator.next()
  376. seedMessages(session, 2)
  377. await new Promise(resolve => setTimeout(resolve, 0))
  378. abort.abort()
  379. if (baseline.done) throw new Error('Control stream ended before its baseline')
  380. expect(baseline.value.type).toBe('baseline')
  381. await expect(next).resolves.toEqual({ done: true, value: undefined })
  382. })
  383. })