session-projections.host.spec.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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 = new Context()
  220. ownedContexts.add(ctx)
  221. await mountAgentLoopTestDependencies(ctx)
  222. await mountAgentLoopTestHarness(ctx)
  223. const coldId = SessionId('cold-persisted-queue')
  224. const meta: SessionHeader = { version: SESSION_FORMAT_VERSION, id: coldId, createdAt: 1, cwd: '/tmp', isSeeded: false }
  225. const message = createUserMessage({
  226. content: [{ type: 'text', text: 'survive process restart' }],
  227. source: { kind: 'user' },
  228. })
  229. const events: SessionEvent[] = [{
  230. type: 'agent/inbox/spliced',
  231. seq: SessionSeq(0),
  232. time: 2,
  233. data: { target: 'next-turn', start: 0, inserted: [message] },
  234. }]
  235. ctx.provide('sessionPersistence', testSessionPersistence(ctx, {
  236. list: () => Promise.resolve([meta]),
  237. inspect: () => Promise.resolve({ meta, events, inheritedEventCount: SessionLogOffset(0) }),
  238. }) as never)
  239. const snapshot = await opening(remote(ctx), coldId)
  240. expect(snapshot.projections.values.inbox).toEqual({
  241. 'next-turn': [message],
  242. 'next-step': [],
  243. })
  244. expect(ctx.agents.get(coldId)).toBeUndefined()
  245. expect(ctx.sessions.get(coldId)).toBeUndefined()
  246. })
  247. it('removes claimed steering from the pending Inbox projection immediately', async () => {
  248. const { ctx, session, claim } = await harness(true)
  249. const proxy = remote(ctx)
  250. const message = createUserMessage({
  251. content: [{ type: 'text', text: 'apply this now' }],
  252. source: { kind: 'user' },
  253. })
  254. const agent = ctx.agents.get(session.id)
  255. if (agent === undefined) throw new Error('missing Agent')
  256. agent.inbox.append('next-step', message)
  257. claim('next-step')
  258. const during = await opening(proxy, session.id)
  259. expect(during.projections.values.inbox).toEqual({
  260. 'next-turn': [],
  261. 'next-step': [],
  262. })
  263. session.append('user/message', message, { surfaceOp: 'append' })
  264. const settled = await opening(proxy, session.id)
  265. expect(settled.projections.values.inbox).toEqual({
  266. 'next-turn': [],
  267. 'next-step': [],
  268. })
  269. const rejected = createUserMessage({
  270. content: [{ type: 'text', text: 'reject this pre-step' }],
  271. source: { kind: 'user' },
  272. })
  273. session.append('turn/start', { turn: 1 })
  274. agent.inbox.append('next-step', rejected)
  275. claim('next-step')
  276. session.append('turn/end', { turn: 1, reason: { kind: 'blocked' } })
  277. const closed = await opening(proxy, session.id)
  278. expect(closed.projections.values.inbox).toEqual({
  279. 'next-turn': [],
  280. 'next-step': [],
  281. })
  282. })
  283. it('returns a complete current replacement cut on each follow generation', async () => {
  284. const { ctx, session } = await harness(true)
  285. ctx.sessionProjections.register(lastUserUnit())
  286. seedMessages(session, 2)
  287. const snapshot = await opening(remote(ctx), session.id)
  288. expect(snapshot.records.map(record => record.event.seq)).toEqual([0, 1])
  289. expect(snapshot.projections.asOfSeq).toBe(1)
  290. expect(snapshot.projections.values).toEqual(
  291. expect.objectContaining({ 'test/last-user': { text: 'm1' } }),
  292. )
  293. })
  294. it('projects an empty log at cursor -1', async () => {
  295. const { ctx, session } = await harness(true)
  296. ctx.sessionProjections.register(lastUserUnit())
  297. const snapshot = await opening(remote(ctx), session.id)
  298. expect(snapshot.records).toEqual([])
  299. expect(snapshot.projections.asOfSeq).toBe(-1)
  300. expect(snapshot.projections.values).toEqual(
  301. expect.objectContaining({ 'test/last-user': null }),
  302. )
  303. })
  304. it('publishes the attachments imageLimits as a constant unit while both seams are composed', async () => {
  305. const { ctx, session } = await harness(true)
  306. const limits = {
  307. maxImageBytes: 5 * 1024 * 1024,
  308. maxImagesPerMessage: 20,
  309. maxMessageImageBytes: 100 * 1024 * 1024,
  310. maxImagePixels: 40_000_000,
  311. maxImageDimension: 2000,
  312. mediaTypes: ['image/png'] as const,
  313. }
  314. await ctx.plugin(class extends AttachmentStore {
  315. readonly imageLimits = limits
  316. validateImage(): Promise<void> { return Promise.resolve() }
  317. saveImage(): Promise<never> { return Promise.reject(new Error('unused')) }
  318. readImage(): Promise<never> { return Promise.reject(new Error('unused')) }
  319. })
  320. const gateway = remote(ctx)
  321. await new Promise(resolve => setTimeout(resolve, 0))
  322. seedMessages(session, 2)
  323. const snapshot = await opening(gateway, session.id)
  324. expect(snapshot.projections.values['imageLimits']).toEqual(limits)
  325. // Constant unit: appending events must never broadcast an imageLimits projection.
  326. await new Promise(resolve => setTimeout(resolve, 0))
  327. const abort = new AbortController()
  328. const iterator = gateway.control(abort.signal)[Symbol.asyncIterator]()
  329. await iterator.next()
  330. const next = iterator.next()
  331. seedMessages(session, 1)
  332. await new Promise(resolve => setTimeout(resolve, 0))
  333. await expect(next).resolves.toMatchObject({
  334. done: false,
  335. value: { type: 'projection', key: 'sessionListMetadata' },
  336. })
  337. const extra = iterator.next()
  338. const quiet = Symbol('quiet')
  339. expect(await Promise.race([
  340. extra,
  341. new Promise<typeof quiet>(resolve => setTimeout(() => { resolve(quiet) }, 0)),
  342. ])).toBe(quiet)
  343. abort.abort()
  344. await expect(extra).resolves.toEqual({ done: true, value: undefined })
  345. })
  346. it('leaves the imageLimits key absent while no attachment service is composed', async () => {
  347. const { ctx, session } = await harness(true)
  348. seedMessages(session, 1)
  349. const snapshot = await opening(remote(ctx), session.id)
  350. expect('imageLimits' in snapshot.projections.values).toBe(false)
  351. })
  352. it('never carries the block on loadOlder pages (beforeSeq present)', async () => {
  353. const { ctx, session } = await harness(true)
  354. ctx.sessionProjections.register(lastUserUnit())
  355. seedMessages(session, 5)
  356. const older = await page(remote(ctx), request({
  357. sessionId: session.id, throughSeq: session.seq - 1, beforeSeq: 3, maxMessages: 2,
  358. }))
  359. expect(older.ok).toBe(true)
  360. if (!older.ok) throw new Error('unreachable')
  361. expect('projections' in older.value).toBe(false)
  362. })
  363. it('serves no block when the composition has no projection registry', async () => {
  364. const { ctx, session } = await harness(false)
  365. seedMessages(session, 2)
  366. const response = await page(remote(ctx), request({ sessionId: session.id, throughSeq: session.seq - 1 }))
  367. expect(response.ok).toBe(true)
  368. if (!response.ok) throw new Error('unreachable')
  369. expect('projections' in response.value).toBe(false)
  370. })
  371. it('never exposes a host-only unit through history, listing, or push frames', async () => {
  372. const { ctx, session } = await harness(true)
  373. ctx.sessionProjections.register(internalCountUnit())
  374. const proxy = remote(ctx)
  375. await new Promise(resolve => setTimeout(resolve, 0))
  376. const abort = new AbortController()
  377. const iterator = proxy.control(abort.signal)[Symbol.asyncIterator]()
  378. const baseline = await iterator.next()
  379. if (baseline.done || baseline.value.type !== 'baseline') {
  380. throw new Error('control stream ended before its baseline')
  381. }
  382. expect('test/internal-count' in (baseline.value.value.projections[session.id]?.values ?? {}))
  383. .toBe(false)
  384. seedMessages(session, 1)
  385. const changed = await iterator.next()
  386. expect(changed).toMatchObject({
  387. done: false,
  388. value: { type: 'projection', key: 'sessionListMetadata' },
  389. })
  390. abort.abort()
  391. await iterator.return?.()
  392. const history = await opening(proxy, session.id)
  393. expect('test/internal-count' in history.projections.values).toBe(false)
  394. const listing = await proxy.list(request({}))
  395. if (!listing.ok) throw new Error('listing failed')
  396. const row = listing.value.items.find(item => item.sessionId === session.id)
  397. expect('test/internal-count' in (row?.projections?.values ?? {})).toBe(false)
  398. })
  399. it('drops a disposed registration from subsequent tail pages (empty block, key absent)', async () => {
  400. const { ctx, session } = await harness(true)
  401. const dispose = ctx.sessionProjections.register(lastUserUnit())
  402. seedMessages(session, 1)
  403. const proxy = remote(ctx)
  404. const before = await opening(proxy, session.id)
  405. expect(before.projections.values['test/last-user']).toEqual({ text: 'm0' })
  406. dispose()
  407. const after = await opening(proxy, session.id)
  408. // The registry stays mounted; only the disposed key leaves while the
  409. // gateway-owned Session-list unit remains.
  410. expect(after.projections.asOfSeq).toBe(session.seq - 1)
  411. expect('test/last-user' in after.projections.values).toBe(false)
  412. expect(after.projections.values.sessionListMetadata).toEqual({
  413. blank: true,
  414. lastPromptAt: session.eventAt(SessionSeq(session.seq - 1))?.time,
  415. })
  416. })
  417. it('removes the gateway-owned Session-list unit when the gateway fiber unloads', async () => {
  418. const { ctx, session } = await harness(true)
  419. expect('sessionListMetadata' in ctx.sessionProjections.snapshot(session).values).toBe(false)
  420. const fiber = ctx.plugin(Object.assign((gatewayCtx: Context) => {
  421. createSessionTestRemote(gatewayCtx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  422. }, { inject: ['sessions', 'agents', 'sessionProjections'] }))
  423. await fiber.await()
  424. await vi.waitFor(() => {
  425. expect(ctx.sessionProjections.snapshot(session).values.sessionListMetadata)
  426. .toEqual({ blank: true, lastPromptAt: null })
  427. })
  428. await fiber.dispose()
  429. expect('sessionListMetadata' in ctx.sessionProjections.snapshot(session).values).toBe(false)
  430. })
  431. })
  432. describe('session.list projections column', () => {
  433. it('serves every already-materialized wire value from the live registry without folding', async () => {
  434. const { ctx, session } = await harness(true)
  435. ctx.sessionProjections.register(lastUserUnit())
  436. const gateway = remote(ctx)
  437. await new Promise(resolve => setTimeout(resolve, 0))
  438. session.append('turn/start', { turn: 1 })
  439. seedMessages(session, 1)
  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 === session.id)
  443. expect(row?.projections?.values['test/last-user']).toEqual({ text: 'm0' })
  444. expect(row?.projections?.values.sessionListMetadata).toEqual({
  445. blank: false,
  446. lastPromptAt: session.eventAt(SessionSeq(session.seq - 1))?.time,
  447. })
  448. expect(row?.projections?.asOfSeq).toBe(session.seq - 1)
  449. })
  450. it('lists the latest preset selected by a blank Session instead of its creation preset', async () => {
  451. const { ctx } = await harness(true)
  452. const session = ctx.sessions.create(SessionId('preset-list'), {
  453. meta: { cwd: '/workspace', agentPreset: 'standard' },
  454. })
  455. ctx.sessionProjections.register(agentPresetProjectionDefinition)
  456. const gateway = remote(ctx)
  457. await new Promise(resolve => setTimeout(resolve, 0))
  458. session.append('agent-preset/selected', { agentPreset: 'minimal' })
  459. const response = await gateway.list(request({}))
  460. if (!response.ok) throw new Error('unreachable')
  461. const row = response.value.items.find(item => item.sessionId === session.id)
  462. expect(row?.projections?.values.agentPreset).toBe('minimal')
  463. })
  464. it('omits an unmaterialized live projection instead of folding history for listing', async () => {
  465. const { ctx, session } = await harness(true)
  466. seedMessages(session, 1)
  467. const unit = lastUserUnit()
  468. const apply = vi.fn(unit.apply)
  469. ctx.sessionProjections.register({ ...unit, apply })
  470. const response = await remote(ctx).list(request({}))
  471. if (!response.ok) throw new Error('unreachable')
  472. const row = response.value.items.find(item => item.sessionId === session.id)
  473. expect(row).toBeDefined()
  474. expect('test/last-user' in (row?.projections?.values ?? {})).toBe(false)
  475. expect(apply).not.toHaveBeenCalled()
  476. })
  477. it('omits the column entirely when no registry is mounted', async () => {
  478. const { ctx, session } = await harness(false)
  479. seedMessages(session, 1)
  480. const response = await remote(ctx).list(request({}))
  481. if (!response.ok) throw new Error('unreachable')
  482. const row = response.value.items.find(item => item.sessionId === session.id)
  483. expect(row).toBeDefined()
  484. expect(row !== undefined && 'projections' in row).toBe(false)
  485. })
  486. it('serves every available cold projection hint from the cache with zero log loads', async () => {
  487. const { ctx } = await harness(true)
  488. const coldId = SessionId('session-cold-listing')
  489. const load = () => { throw new Error('list must not load event logs') }
  490. ctx.provide('sessionPersistence', testSessionPersistence(ctx, {
  491. list: async () => [{ version: SESSION_FORMAT_VERSION, id: coldId, createdAt: 5, isSeeded: false, cwd: '/tmp' }],
  492. inspect: load,
  493. open: load,
  494. }) as never)
  495. ctx.provide('sessionProjectionCache', {
  496. // The carrier hands the listed header through as the identity witness.
  497. cachedSnapshot: (meta: { id: unknown; createdAt: number }) =>
  498. (meta.id === coldId && meta.createdAt === 5
  499. ? {
  500. asOfSeq: SessionSeq(7),
  501. values: {
  502. 'test/last-user': { text: 'cached' },
  503. sessionListMetadata: { blank: false, lastPromptAt: 6 },
  504. title: 'Cached title',
  505. },
  506. }
  507. : undefined),
  508. } as never)
  509. const response = await remote(ctx).list(request({}))
  510. if (!response.ok) throw new Error('unreachable')
  511. const row = response.value.items.find(item => item.sessionId === coldId)
  512. expect(row?.running).toBe(false)
  513. expect(row?.projections).toEqual({
  514. asOfSeq: 7,
  515. values: {
  516. 'test/last-user': { text: 'cached' },
  517. sessionListMetadata: { blank: false, lastPromptAt: 6 },
  518. title: 'Cached title',
  519. },
  520. })
  521. })
  522. it('keeps persisted host-only state out of a cold session.list response', async () => {
  523. const root = await mkdtemp(join(tmpdir(), 'dsh-api-projcache-'))
  524. const ctx = new Context()
  525. try {
  526. await ctx.plugin(Storage)
  527. await ctx.plugin(StorageJson, { root })
  528. await ctx.plugin(StorageDomain, { backend: 'json' })
  529. await ctx.plugin(SessionStore)
  530. await ctx.plugin(AgentRegistry)
  531. await ctx.plugin(SessionProjectionRegistry)
  532. ctx.sessionProjections.register(privatePromptUnit())
  533. await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 100, writeIntervalMs: 60_000 })
  534. const gateway = remote(ctx)
  535. await new Promise(resolve => setTimeout(resolve, 0))
  536. const id = SessionId('session-cold-host-state')
  537. const secret = 'private prompt text from the cache'
  538. let session: Session | undefined
  539. const owner = await ctx.plugin(Object.assign((sessionCtx: Context) => {
  540. session = sessionCtx.sessions.create(id, { meta: { createdAt: 5, cwd: '/workspace' } })
  541. }, { inject: ['sessions'] }))
  542. if (session === undefined) throw new Error('session was not created')
  543. session.append('turn/start', { turn: 1 })
  544. session.append('user/message', createUserMessage({
  545. content: [{ type: 'text', text: secret }],
  546. source: { kind: 'user' },
  547. }), { surfaceOp: 'append' })
  548. await ctx.sessionProjectionCache.write(session)
  549. const stored = await readFile(
  550. join(root, projectionCacheDomainSpec.name, 'sessions', `${id}.json`),
  551. 'utf8',
  552. )
  553. expect(stored).toContain(secret)
  554. const header = session.header
  555. await owner.dispose()
  556. expect(ctx.sessions.get(id)).toBeUndefined()
  557. ctx.provide('sessionPersistence', {
  558. list: async () => [{ header, revision: 'test:cold-host-state:1' }],
  559. } as never)
  560. const response = await gateway.list(request({}))
  561. if (!response.ok) throw new Error('unreachable')
  562. const row = response.value.items.find(item => item.sessionId === id)
  563. expect(row?.projections?.values.sessionListMetadata).toMatchObject({ blank: false })
  564. expect('test/private-prompt' in (row?.projections?.values ?? {})).toBe(false)
  565. expect(JSON.stringify(row)).not.toContain(secret)
  566. } finally {
  567. await ctx.fiber.dispose()
  568. await rm(root, { recursive: true, force: true })
  569. }
  570. })
  571. it('cold rows without a cache plugin (or without a stored row) just lack the column', async () => {
  572. const { ctx } = await harness(true)
  573. const coldId = SessionId('session-cold-uncached')
  574. ctx.provide('sessionPersistence', testSessionPersistence(ctx, {
  575. list: async () => [{ version: SESSION_FORMAT_VERSION, id: coldId, createdAt: 5, isSeeded: false, cwd: '/tmp' }],
  576. }) as never)
  577. const response = await remote(ctx).list(request({}))
  578. if (!response.ok) throw new Error('unreachable')
  579. const row = response.value.items.find(item => item.sessionId === coldId)
  580. expect(row).toBeDefined()
  581. expect(row !== undefined && 'projections' in row).toBe(false)
  582. })
  583. it('a throwing column read degrades that row, never the listing', async () => {
  584. const { ctx, session } = await harness(true)
  585. ctx.sessionProjections.register({
  586. ...lastUserUnit(),
  587. wire: {
  588. viewSchema: z.union([z.object({ text: z.string() }), z.null()]),
  589. view: () => { throw new Error('unit exploded') },
  590. },
  591. })
  592. seedMessages(session, 1)
  593. const response = await remote(ctx).list(request({}))
  594. if (!response.ok) throw new Error('unreachable')
  595. const row = response.value.items.find(item => item.sessionId === session.id)
  596. expect(row).toBeDefined()
  597. expect(row !== undefined && 'projections' in row).toBe(false)
  598. })
  599. })
  600. describe('Session control projection frames', () => {
  601. /** Drain frames until `count` projection replacements arrive. */
  602. async function collect(
  603. iterable: AsyncIterable<SessionControlFrame>,
  604. count: number,
  605. abort: AbortController,
  606. ): Promise<SessionControlFrame[]> {
  607. const frames: SessionControlFrame[] = []
  608. for await (const frame of iterable) {
  609. frames.push(frame)
  610. if (frames.filter(candidate => candidate.type === 'projection').length >= count) abort.abort()
  611. }
  612. return frames
  613. }
  614. it('broadcasts changed view references with the causing seq and skips same-reference applies', async () => {
  615. const { ctx, session } = await harness(true)
  616. ctx.sessionProjections.register(lastUserUnit())
  617. const proxy = remote(ctx)
  618. // The controller's onChanged subscription lives in an inject child whose
  619. // fiber activates asynchronously; yield until it lands before appending.
  620. await new Promise(resolve => setTimeout(resolve, 0))
  621. const abort = new AbortController()
  622. const stream = proxy.control(abort.signal)
  623. const collected = collect(stream, 5, abort)
  624. const now = vi.spyOn(Date, 'now').mockReturnValue(100)
  625. seedMessages(session, 1)
  626. now.mockReturnValue(200)
  627. session.append('turn/start', { turn: 1 })
  628. now.mockReturnValue(300)
  629. // The equal payload is a new object, so Object.is still treats its view as changed.
  630. seedMessages(session, 1)
  631. now.mockRestore()
  632. const frames = await collected
  633. const pushes = frames.filter(
  634. (f): f is Extract<SessionControlFrame, { type: 'projection' }> =>
  635. f.type === 'projection' && f.key === 'test/last-user',
  636. )
  637. expect(pushes).toEqual([
  638. { type: 'projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 0 },
  639. { type: 'projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 2 },
  640. ])
  641. expect(frames.filter(
  642. (f): f is Extract<SessionControlFrame, { type: 'projection' }> =>
  643. f.type === 'projection' && f.key === 'sessionListMetadata',
  644. )).toEqual([
  645. { type: 'projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: true, lastPromptAt: 100 }, seq: 0 },
  646. { type: 'projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: false, lastPromptAt: 100 }, seq: 1 },
  647. { type: 'projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: false, lastPromptAt: 300 }, seq: 2 },
  648. ])
  649. // Frame seq aligns with the tail block's asOfSeq vocabulary (higher-seq-wins compatible).
  650. const tail = await opening(proxy, session.id)
  651. expect(tail.projections.asOfSeq).toBe(pushes.at(-1)?.seq)
  652. })
  653. })