session-projections.host.spec.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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 { mkdtemp, readFile, rm } from 'node:fs/promises'
  11. import { tmpdir } from 'node:os'
  12. import { join } from 'node:path'
  13. import { Context } from '@deepseek-ai/cordis'
  14. import { z } from 'zod'
  15. import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent'
  16. import { AttachmentStore } from '@deepseek-ai/dsh-attachment'
  17. import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-presets'
  18. import type { Agent } from '@deepseek-ai/dsh-agent'
  19. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  20. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  21. import type { Session } from '@deepseek-ai/dsh-session'
  22. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  23. import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
  24. import SessionProjectionCache, { projectionCacheDomainSpec } from '@deepseek-ai/dsh-session-projection-cache'
  25. import Storage from '@deepseek-ai/dsh-storage'
  26. import * as StorageDomain from '@deepseek-ai/dsh-storage-domain'
  27. import * as StorageJson from '@deepseek-ai/dsh-storage-json'
  28. import type { SessionControlFrame, SessionFollowFrame } from '@deepseek-ai/dsh-api-session-controller/types'
  29. import { createSessionTestRemote, type TestSessionRemote } from './test-remote.ts'
  30. declare module '@deepseek-ai/dsh-session-projection/types' {
  31. interface SessionProjectionStateMap {
  32. 'test/last-user': LastUserState
  33. 'test/internal-count': number
  34. 'test/private-prompt': string | null
  35. }
  36. interface SessionProjectionMap {
  37. 'test/last-user': { text: string } | null
  38. }
  39. }
  40. function request<P>(payload: P): P {
  41. return payload
  42. }
  43. function page(
  44. remote: TestSessionRemote,
  45. request: { sessionId: SessionId; throughSeq: number; beforeSeq?: number; maxMessages?: number },
  46. ) {
  47. return remote.page({
  48. address: { kind: 'session', sessionId: request.sessionId },
  49. throughSeq: request.throughSeq,
  50. ...(request.beforeSeq === undefined ? {} : { beforeSeq: request.beforeSeq }),
  51. ...(request.maxMessages === undefined ? {} : { maxMessages: request.maxMessages }),
  52. })
  53. }
  54. /** Read and close one snapshot-first follow generation. */
  55. async function opening(
  56. remote: TestSessionRemote,
  57. sessionId: SessionId,
  58. maxMessages?: number,
  59. ): Promise<Extract<SessionFollowFrame, { type: 'snapshot' }>> {
  60. const abort = new AbortController()
  61. const iterator = remote.follow({
  62. address: { kind: 'session', sessionId },
  63. ...(maxMessages === undefined ? {} : { maxMessages }),
  64. }, abort.signal)[Symbol.asyncIterator]()
  65. const first = await iterator.next()
  66. abort.abort()
  67. await iterator.return?.()
  68. if (first.done || first.value.type !== 'snapshot') throw new Error('follow did not open with a snapshot')
  69. return first.value
  70. }
  71. /** Whole-value unit folding the latest user/message text; null before the first. */
  72. type LastUserState = { text: string } | null
  73. const lastUserUnit = () => ({
  74. key: 'test/last-user',
  75. stateSchema: z.union([z.object({ text: z.string() }), z.null()]),
  76. init: () => null,
  77. apply: (state, event) => (event.type === 'user/message'
  78. ? { text: (event.data.content[0] as { text?: string }).text ?? '' }
  79. : state),
  80. wire: {
  81. viewSchema: z.union([z.object({ text: z.string() }), z.null()]),
  82. view: state => state,
  83. },
  84. stateVersion: 1,
  85. }) satisfies ProjectionDefinition<'test/last-user', LastUserState>
  86. const internalCountUnit = () => ({
  87. key: 'test/internal-count',
  88. stateSchema: z.number().int().nonnegative(),
  89. init: () => 0,
  90. apply: (state: number) => state + 1,
  91. stateVersion: 1,
  92. }) satisfies ProjectionDefinition<'test/internal-count', number>
  93. const privatePromptUnit = () => ({
  94. key: 'test/private-prompt',
  95. stateSchema: z.string().nullable(),
  96. init: () => null,
  97. apply: (state, event) => (event.type === 'user/message'
  98. ? (event.data.content[0] as { text?: string }).text ?? ''
  99. : state),
  100. stateVersion: 1,
  101. }) satisfies ProjectionDefinition<'test/private-prompt', string | null>
  102. async function harness(withRegistry: boolean): Promise<{ ctx: Context; session: Session }> {
  103. const ctx = new Context()
  104. await ctx.plugin(SessionStore)
  105. await ctx.plugin(AgentRegistry)
  106. if (withRegistry) await ctx.plugin(SessionProjectionRegistry)
  107. const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } })
  108. // The gateway reads both the session and durable inbox baseline.
  109. ctx.agents.register({ id: session.id, session, inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), status: 'idle', ctx } as Agent)
  110. return { ctx, session }
  111. }
  112. /** Append `count` user messages so the log has paginable message boundaries. */
  113. function seedMessages(session: Session, count: number): void {
  114. for (let i = 0; i < count; i++) {
  115. session.append('user/message', createUserMessage({
  116. content: [{ type: 'text', text: `m${i}` }],
  117. source: { kind: 'user' },
  118. }), { surfaceOp: 'append' })
  119. }
  120. }
  121. const remote = (ctx: Context) => createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  122. describe('session.history projections block', () => {
  123. it('tracks pending and used model selections across repeated request headers', async () => {
  124. const { ctx, session } = await harness(true)
  125. remote(ctx)
  126. await new Promise(resolve => setTimeout(resolve, 0))
  127. const selected = { provider: 'p', model: 'next' }
  128. session.append('model/selection', selected)
  129. session.append('model/selection', selected)
  130. session.append('request/header', {
  131. header: { config: { provider: 'p', model: 'used' } }, reason: 'initial',
  132. })
  133. session.append('request/header', {
  134. header: { config: { provider: 'p', model: 'used' } }, reason: 'initial',
  135. })
  136. expect(ctx.sessionProjections.snapshot(session).values.modelSelection).toEqual({
  137. lastUsed: { provider: 'p', model: 'used' },
  138. next: selected,
  139. })
  140. session.append('request/header', {
  141. header: { config: selected }, reason: 'initial',
  142. })
  143. expect(ctx.sessionProjections.snapshot(session).values.modelSelection).toEqual({
  144. lastUsed: selected,
  145. next: selected,
  146. })
  147. })
  148. it('serves the unit value on the tail page with asOfSeq = last event seq', async () => {
  149. const { ctx, session } = await harness(true)
  150. ctx.sessionProjections.register(lastUserUnit())
  151. seedMessages(session, 3)
  152. const snapshot = await opening(remote(ctx), session.id)
  153. const { records, projections } = snapshot
  154. expect(projections.asOfSeq).toBe(session.seq - 1)
  155. expect(projections.values['test/last-user']).toEqual({ text: 'm2' })
  156. // asOfSeq IS the window tail: the last served event carries it.
  157. const last = records.at(-1)
  158. expect(last?.event.seq).toBe(projections.asOfSeq)
  159. })
  160. it('returns a complete current replacement cut on each follow generation', async () => {
  161. const { ctx, session } = await harness(true)
  162. ctx.sessionProjections.register(lastUserUnit())
  163. seedMessages(session, 2)
  164. const snapshot = await opening(remote(ctx), session.id)
  165. expect(snapshot.records.map(record => record.event.seq)).toEqual([0, 1])
  166. expect(snapshot.projections.asOfSeq).toBe(1)
  167. expect(snapshot.projections.values).toEqual(
  168. expect.objectContaining({ 'test/last-user': { text: 'm1' } }),
  169. )
  170. })
  171. it('projects an empty log at cursor -1', async () => {
  172. const { ctx, session } = await harness(true)
  173. ctx.sessionProjections.register(lastUserUnit())
  174. const snapshot = await opening(remote(ctx), session.id)
  175. expect(snapshot.records).toEqual([])
  176. expect(snapshot.projections.asOfSeq).toBe(-1)
  177. expect(snapshot.projections.values).toEqual(
  178. expect.objectContaining({ 'test/last-user': null }),
  179. )
  180. })
  181. it('publishes the attachments imageLimits as a constant unit while both seams are composed', async () => {
  182. const { ctx, session } = await harness(true)
  183. const limits = {
  184. maxImageBytes: 5 * 1024 * 1024,
  185. maxImagesPerMessage: 20,
  186. maxMessageImageBytes: 100 * 1024 * 1024,
  187. maxImagePixels: 40_000_000,
  188. maxImageDimension: 2000,
  189. mediaTypes: ['image/png'] as const,
  190. }
  191. await ctx.plugin(class extends AttachmentStore {
  192. readonly imageLimits = limits
  193. validateImage(): Promise<void> { return Promise.resolve() }
  194. saveImage(): Promise<never> { return Promise.reject(new Error('unused')) }
  195. readImage(): Promise<never> { return Promise.reject(new Error('unused')) }
  196. })
  197. const gateway = remote(ctx)
  198. await new Promise(resolve => setTimeout(resolve, 0))
  199. seedMessages(session, 2)
  200. const snapshot = await opening(gateway, session.id)
  201. expect(snapshot.projections.values['imageLimits']).toEqual(limits)
  202. // Constant unit: appending events must never broadcast an imageLimits projection.
  203. await new Promise(resolve => setTimeout(resolve, 0))
  204. const abort = new AbortController()
  205. const iterator = gateway.control(abort.signal)[Symbol.asyncIterator]()
  206. await iterator.next()
  207. const next = iterator.next()
  208. seedMessages(session, 1)
  209. await new Promise(resolve => setTimeout(resolve, 0))
  210. await expect(next).resolves.toMatchObject({
  211. done: false,
  212. value: { type: 'projection', key: 'sessionListMetadata' },
  213. })
  214. const extra = iterator.next()
  215. const quiet = Symbol('quiet')
  216. expect(await Promise.race([
  217. extra,
  218. new Promise<typeof quiet>(resolve => setTimeout(() => { resolve(quiet) }, 0)),
  219. ])).toBe(quiet)
  220. abort.abort()
  221. await expect(extra).resolves.toEqual({ done: true, value: undefined })
  222. })
  223. it('leaves the imageLimits key absent while no attachment service is composed', async () => {
  224. const { ctx, session } = await harness(true)
  225. seedMessages(session, 1)
  226. const snapshot = await opening(remote(ctx), session.id)
  227. expect('imageLimits' in snapshot.projections.values).toBe(false)
  228. })
  229. it('never carries the block on loadOlder pages (beforeSeq present)', async () => {
  230. const { ctx, session } = await harness(true)
  231. ctx.sessionProjections.register(lastUserUnit())
  232. seedMessages(session, 5)
  233. const older = await page(remote(ctx), request({
  234. sessionId: session.id, throughSeq: session.seq - 1, beforeSeq: 3, maxMessages: 2,
  235. }))
  236. expect(older.ok).toBe(true)
  237. if (!older.ok) throw new Error('unreachable')
  238. expect('projections' in older.value).toBe(false)
  239. })
  240. it('serves no block when the composition has no projection registry', async () => {
  241. const { ctx, session } = await harness(false)
  242. seedMessages(session, 2)
  243. const response = await page(remote(ctx), request({ sessionId: session.id, throughSeq: session.seq - 1 }))
  244. expect(response.ok).toBe(true)
  245. if (!response.ok) throw new Error('unreachable')
  246. expect('projections' in response.value).toBe(false)
  247. })
  248. it('never exposes a host-only unit through history, listing, or push frames', async () => {
  249. const { ctx, session } = await harness(true)
  250. ctx.sessionProjections.register(internalCountUnit())
  251. const proxy = remote(ctx)
  252. await new Promise(resolve => setTimeout(resolve, 0))
  253. const abort = new AbortController()
  254. const iterator = proxy.control(abort.signal)[Symbol.asyncIterator]()
  255. const baseline = await iterator.next()
  256. if (baseline.done || baseline.value.type !== 'baseline') {
  257. throw new Error('control stream ended before its baseline')
  258. }
  259. expect('test/internal-count' in (baseline.value.value.projections[session.id]?.values ?? {}))
  260. .toBe(false)
  261. seedMessages(session, 1)
  262. const changed = await iterator.next()
  263. expect(changed).toMatchObject({
  264. done: false,
  265. value: { type: 'projection', key: 'sessionListMetadata' },
  266. })
  267. abort.abort()
  268. await iterator.return?.()
  269. const history = await opening(proxy, session.id)
  270. expect('test/internal-count' in history.projections.values).toBe(false)
  271. const listing = await proxy.list(request({}))
  272. if (!listing.ok) throw new Error('listing failed')
  273. const row = listing.value.items.find(item => item.sessionId === session.id)
  274. expect('test/internal-count' in (row?.projections?.values ?? {})).toBe(false)
  275. })
  276. it('drops a disposed registration from subsequent tail pages (empty block, key absent)', async () => {
  277. const { ctx, session } = await harness(true)
  278. const dispose = ctx.sessionProjections.register(lastUserUnit())
  279. seedMessages(session, 1)
  280. const proxy = remote(ctx)
  281. const before = await opening(proxy, session.id)
  282. expect(before.projections.values['test/last-user']).toEqual({ text: 'm0' })
  283. dispose()
  284. const after = await opening(proxy, session.id)
  285. // The registry stays mounted; only the disposed key leaves while the
  286. // gateway-owned Session-list unit remains.
  287. expect(after.projections.asOfSeq).toBe(session.seq - 1)
  288. expect('test/last-user' in after.projections.values).toBe(false)
  289. expect(after.projections.values.sessionListMetadata).toEqual({
  290. blank: true,
  291. lastPromptAt: session.events.at(-1)?.time,
  292. })
  293. })
  294. it('removes the gateway-owned Session-list unit when the gateway fiber unloads', async () => {
  295. const { ctx, session } = await harness(true)
  296. expect('sessionListMetadata' in ctx.sessionProjections.snapshot(session).values).toBe(false)
  297. const fiber = ctx.plugin(Object.assign((gatewayCtx: Context) => {
  298. createSessionTestRemote(gatewayCtx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  299. }, { inject: ['sessions', 'agents', 'sessionProjections'] }))
  300. await fiber.await()
  301. await vi.waitFor(() => {
  302. expect(ctx.sessionProjections.snapshot(session).values.sessionListMetadata)
  303. .toEqual({ blank: true, lastPromptAt: null })
  304. })
  305. await fiber.dispose()
  306. expect('sessionListMetadata' in ctx.sessionProjections.snapshot(session).values).toBe(false)
  307. })
  308. })
  309. describe('session.list projections column', () => {
  310. it('serves every already-materialized wire value from the live registry without folding', async () => {
  311. const { ctx, session } = await harness(true)
  312. ctx.sessionProjections.register(lastUserUnit())
  313. const gateway = remote(ctx)
  314. await new Promise(resolve => setTimeout(resolve, 0))
  315. session.append('turn/start', { turn: 1 })
  316. seedMessages(session, 1)
  317. const response = await gateway.list(request({}))
  318. if (!response.ok) throw new Error('unreachable')
  319. const row = response.value.items.find(item => item.sessionId === session.id)
  320. expect(row?.projections?.values['test/last-user']).toEqual({ text: 'm0' })
  321. expect(row?.projections?.values.sessionListMetadata).toEqual({
  322. blank: false,
  323. lastPromptAt: session.events.at(-1)?.time,
  324. })
  325. expect(row?.projections?.asOfSeq).toBe(session.seq - 1)
  326. })
  327. it('lists the latest preset selected by a blank Session instead of its creation preset', async () => {
  328. const { ctx } = await harness(true)
  329. const session = ctx.sessions.create(SessionId('preset-list'), {
  330. meta: { cwd: '/workspace', agentPreset: 'standard' },
  331. })
  332. ctx.sessionProjections.register(agentPresetProjectionDefinition)
  333. const gateway = remote(ctx)
  334. await new Promise(resolve => setTimeout(resolve, 0))
  335. session.append('agent-preset/selected', { agentPreset: 'minimal' })
  336. const response = await gateway.list(request({}))
  337. if (!response.ok) throw new Error('unreachable')
  338. const row = response.value.items.find(item => item.sessionId === session.id)
  339. expect(row?.projections?.values.agentPreset).toBe('minimal')
  340. })
  341. it('omits an unmaterialized live projection instead of folding history for listing', async () => {
  342. const { ctx, session } = await harness(true)
  343. seedMessages(session, 1)
  344. const unit = lastUserUnit()
  345. const apply = vi.fn(unit.apply)
  346. ctx.sessionProjections.register({ ...unit, apply })
  347. const response = await remote(ctx).list(request({}))
  348. if (!response.ok) throw new Error('unreachable')
  349. const row = response.value.items.find(item => item.sessionId === session.id)
  350. expect(row).toBeDefined()
  351. expect('test/last-user' in (row?.projections?.values ?? {})).toBe(false)
  352. expect(apply).not.toHaveBeenCalled()
  353. })
  354. it('omits the column entirely when no registry is mounted', async () => {
  355. const { ctx, session } = await harness(false)
  356. seedMessages(session, 1)
  357. const response = await remote(ctx).list(request({}))
  358. if (!response.ok) throw new Error('unreachable')
  359. const row = response.value.items.find(item => item.sessionId === session.id)
  360. expect(row).toBeDefined()
  361. expect(row !== undefined && 'projections' in row).toBe(false)
  362. })
  363. it('serves every available cold projection hint from the cache with zero log loads', async () => {
  364. const { ctx } = await harness(true)
  365. const coldId = SessionId('session-cold-listing')
  366. const load = () => { throw new Error('list must not load event logs') }
  367. ctx.provide('sessionPersistence', {
  368. list: async () => [{ version: 0, id: coldId, createdAt: 5, cwd: '/tmp' }],
  369. locate: () => undefined,
  370. load,
  371. inspect: load,
  372. readFrom: load,
  373. } as never)
  374. ctx.provide('sessionProjectionCache', {
  375. // The carrier hands the listed header through as the identity witness.
  376. cachedSnapshot: (meta: { id: unknown; createdAt: number }) =>
  377. (meta.id === coldId && meta.createdAt === 5
  378. ? {
  379. asOfSeq: 7,
  380. values: {
  381. 'test/last-user': { text: 'cached' },
  382. sessionListMetadata: { blank: false, lastPromptAt: 6 },
  383. title: 'Cached title',
  384. },
  385. }
  386. : undefined),
  387. } as never)
  388. const response = await remote(ctx).list(request({}))
  389. if (!response.ok) throw new Error('unreachable')
  390. const row = response.value.items.find(item => item.sessionId === coldId)
  391. expect(row?.running).toBe(false)
  392. expect(row?.projections).toEqual({
  393. asOfSeq: 7,
  394. values: {
  395. 'test/last-user': { text: 'cached' },
  396. sessionListMetadata: { blank: false, lastPromptAt: 6 },
  397. title: 'Cached title',
  398. },
  399. })
  400. })
  401. it('keeps persisted host-only state out of a cold session.list response', async () => {
  402. const root = await mkdtemp(join(tmpdir(), 'dsh-api-projcache-'))
  403. const ctx = new Context()
  404. try {
  405. await ctx.plugin(Storage)
  406. await ctx.plugin(StorageJson, { root })
  407. await ctx.plugin(StorageDomain, { backend: 'json' })
  408. await ctx.plugin(SessionStore)
  409. await ctx.plugin(AgentRegistry)
  410. await ctx.plugin(SessionProjectionRegistry)
  411. ctx.sessionProjections.register(privatePromptUnit())
  412. await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 100, writeIntervalMs: 60_000 })
  413. const gateway = remote(ctx)
  414. await new Promise(resolve => setTimeout(resolve, 0))
  415. const id = SessionId('session-cold-host-state')
  416. const secret = 'private prompt text from the cache'
  417. let session: Session | undefined
  418. const owner = await ctx.plugin(Object.assign((sessionCtx: Context) => {
  419. session = sessionCtx.sessions.create(id, { meta: { createdAt: 5, cwd: '/workspace' } })
  420. }, { inject: ['sessions'] }))
  421. if (session === undefined) throw new Error('session was not created')
  422. session.append('turn/start', { turn: 1 })
  423. session.append('user/message', createUserMessage({
  424. content: [{ type: 'text', text: secret }],
  425. source: { kind: 'user' },
  426. }), { surfaceOp: 'append' })
  427. await ctx.sessionProjectionCache.write(session)
  428. const stored = await readFile(
  429. join(root, projectionCacheDomainSpec.name, 'sessions', `${id}.json`),
  430. 'utf8',
  431. )
  432. expect(stored).toContain(secret)
  433. const header = session.header
  434. await owner.dispose()
  435. expect(ctx.sessions.get(id)).toBeUndefined()
  436. ctx.provide('sessionPersistence', {
  437. list: async () => [header],
  438. locate: () => undefined,
  439. } as never)
  440. const response = await gateway.list(request({}))
  441. if (!response.ok) throw new Error('unreachable')
  442. const row = response.value.items.find(item => item.sessionId === id)
  443. expect(row?.projections?.values.sessionListMetadata).toMatchObject({ blank: false })
  444. expect('test/private-prompt' in (row?.projections?.values ?? {})).toBe(false)
  445. expect(JSON.stringify(row)).not.toContain(secret)
  446. } finally {
  447. await ctx.fiber.dispose()
  448. await rm(root, { recursive: true, force: true })
  449. }
  450. })
  451. it('cold rows without a cache plugin (or without a stored row) just lack the column', async () => {
  452. const { ctx } = await harness(true)
  453. const coldId = SessionId('session-cold-uncached')
  454. ctx.provide('sessionPersistence', {
  455. list: async () => [{ version: 0, id: coldId, createdAt: 5, cwd: '/tmp' }],
  456. locate: () => undefined,
  457. } as never)
  458. const response = await remote(ctx).list(request({}))
  459. if (!response.ok) throw new Error('unreachable')
  460. const row = response.value.items.find(item => item.sessionId === coldId)
  461. expect(row).toBeDefined()
  462. expect(row !== undefined && 'projections' in row).toBe(false)
  463. })
  464. it('a throwing column read degrades that row, never the listing', async () => {
  465. const { ctx, session } = await harness(true)
  466. ctx.sessionProjections.register({
  467. ...lastUserUnit(),
  468. wire: {
  469. viewSchema: z.union([z.object({ text: z.string() }), z.null()]),
  470. view: () => { throw new Error('unit exploded') },
  471. },
  472. })
  473. seedMessages(session, 1)
  474. const response = await remote(ctx).list(request({}))
  475. if (!response.ok) throw new Error('unreachable')
  476. const row = response.value.items.find(item => item.sessionId === session.id)
  477. expect(row).toBeDefined()
  478. expect(row !== undefined && 'projections' in row).toBe(false)
  479. })
  480. })
  481. describe('Session control projection frames', () => {
  482. /** Drain frames until `count` projection replacements arrive. */
  483. async function collect(
  484. iterable: AsyncIterable<SessionControlFrame>,
  485. count: number,
  486. abort: AbortController,
  487. ): Promise<SessionControlFrame[]> {
  488. const frames: SessionControlFrame[] = []
  489. for await (const frame of iterable) {
  490. frames.push(frame)
  491. if (frames.filter(candidate => candidate.type === 'projection').length >= count) abort.abort()
  492. }
  493. return frames
  494. }
  495. it('broadcasts a frame per changed unit with the causing seq, and none for same-reference applies', async () => {
  496. const { ctx, session } = await harness(true)
  497. ctx.sessionProjections.register(lastUserUnit())
  498. const proxy = remote(ctx)
  499. // The controller's onChanged subscription lives in an inject child whose
  500. // fiber activates asynchronously; yield until it lands before appending.
  501. await new Promise(resolve => setTimeout(resolve, 0))
  502. const abort = new AbortController()
  503. const stream = proxy.control(abort.signal)
  504. const collected = collect(stream, 5, abort)
  505. const now = vi.spyOn(Date, 'now').mockReturnValue(100)
  506. seedMessages(session, 1)
  507. now.mockReturnValue(200)
  508. session.append('turn/start', { turn: 1 })
  509. now.mockReturnValue(300)
  510. seedMessages(session, 1)
  511. now.mockRestore()
  512. const frames = await collected
  513. const pushes = frames.filter(
  514. (f): f is Extract<SessionControlFrame, { type: 'projection' }> =>
  515. f.type === 'projection' && f.key === 'test/last-user',
  516. )
  517. expect(pushes).toEqual([
  518. { type: 'projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 0 },
  519. { type: 'projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 2 },
  520. ])
  521. expect(frames.filter(
  522. (f): f is Extract<SessionControlFrame, { type: 'projection' }> =>
  523. f.type === 'projection' && f.key === 'sessionListMetadata',
  524. )).toEqual([
  525. { type: 'projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: true, lastPromptAt: 100 }, seq: 0 },
  526. { type: 'projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: false, lastPromptAt: 100 }, seq: 1 },
  527. { type: 'projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: false, lastPromptAt: 300 }, seq: 2 },
  528. ])
  529. // Frame seq aligns with the tail block's asOfSeq vocabulary (higher-seq-wins compatible).
  530. const tail = await opening(proxy, session.id)
  531. expect(tail.projections.asOfSeq).toBe(pushes.at(-1)?.seq)
  532. })
  533. })