session-projections.host.spec.ts 20 KB

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