session-projections.host.spec.ts 27 KB

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