session-projections.host.spec.ts 29 KB

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