1
0

session.spec.ts 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { CallId } from '@deepseek-ai/dsh-llm'
  4. import SessionStore, { SESSION_FORMAT_VERSION, Session, SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
  5. import type { CreateSessionOptions, SessionEventType, SessionHeader, TodoItem } from '@deepseek-ai/dsh-session'
  6. describe('Session', () => {
  7. it('derives message history from the event log', () => {
  8. const session = new Session(SessionId('s1'))
  9. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  10. session.append('user/message', { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  11. session.append('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'hi' } })
  12. session.append('assistant/message', {
  13. turn: 1, step: 1,
  14. content: [
  15. { type: 'text', text: 'let me check' },
  16. { type: 'tool-call', id: CallId('c1'), name: 'echo', arguments: '{}' },
  17. ],
  18. }, { surfaceOp: 'append' })
  19. session.append('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'ok' }], isError: false }, { surfaceOp: 'append' })
  20. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  21. const messages = session.deriveMessages()
  22. expect(messages.map(m => m.role)).toEqual(['user', 'assistant', 'user'])
  23. // raw chunks must NOT appear in derived history
  24. expect(messages[1]!.content).toHaveLength(2)
  25. expect(messages[2]!.content[0]).toMatchObject({ type: 'tool-result', toolCallId: CallId('c1') })
  26. })
  27. it('accepts and round-trips a max-tokens turn/end reason', () => {
  28. // The max-tokens TurnEndReason variant carries no extra data, so it must
  29. // append and persist like any other reason (JSON-serializable, no fields).
  30. const session = new Session(SessionId('s1'))
  31. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  32. session.append('turn/end', { turn: 1, reason: { kind: 'max-tokens' } })
  33. const turnEnd = session.events.findLast(e => e.type === 'turn/end')!
  34. expect(turnEnd.data.reason).toEqual({ kind: 'max-tokens' })
  35. // survives a structuredClone (the persistence-serialization boundary)
  36. expect(structuredClone(turnEnd.data.reason)).toEqual({ kind: 'max-tokens' })
  37. })
  38. it('renders context and steering messages as tagged synthetic user content', () => {
  39. const session = new Session(SessionId('s2'))
  40. session.append('context/message', {
  41. content: [{ type: 'text', text: 'file changed: a.ts' }],
  42. source: { kind: 'plugin', plugin: 'watcher' },
  43. }, { surfaceOp: 'append' })
  44. session.append('steering/message', {
  45. turn: 1,
  46. content: [{ type: 'text', text: 'focus on tests' }],
  47. source: { kind: 'user' },
  48. }, { surfaceOp: 'append' })
  49. const [contextMessage, steeringMessage] = session.deriveMessages()
  50. expect(contextMessage!.role).toBe('user')
  51. expect(contextMessage!.content[0]).toMatchObject({ type: 'text', text: '<context source="plugin">' })
  52. expect(contextMessage!.content.at(-1)).toMatchObject({ type: 'text', text: '</context>' })
  53. expect(steeringMessage!.content[0]).toMatchObject({ type: 'text', text: '<steering source="user">' })
  54. })
  55. it('renders raw context without a generic envelope while preserving structured metadata', () => {
  56. const session = new Session(SessionId('s2-raw'))
  57. const meta = {
  58. kind: 'workspace-instructions',
  59. version: 1,
  60. changes: [{ action: 'set', scope: 'pkg', path: 'pkg/AGENTS.md', digest: 'abc123' }],
  61. }
  62. session.append('context/message', {
  63. content: [{ type: 'text', text: '<system-reminder>Additional instructions from: pkg/AGENTS.md</system-reminder>' }],
  64. source: { kind: 'plugin', plugin: 'workspace-context' },
  65. envelope: 'raw',
  66. meta,
  67. }, { surfaceOp: 'append' })
  68. expect(session.deriveMessages()).toEqual([{
  69. role: 'user',
  70. content: [{ type: 'text', text: '<system-reminder>Additional instructions from: pkg/AGENTS.md</system-reminder>' }],
  71. }])
  72. const event = session.events[0]
  73. expect(event?.type === 'context/message' && event.data.meta).toEqual(meta)
  74. })
  75. it('replays identically from a seeded event log', () => {
  76. const original = new Session(SessionId('s3'))
  77. original.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  78. original.append('user/message', { content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  79. original.append('assistant/message', { turn: 1, step: 1, content: [{ type: 'text', text: 'a' }] }, { surfaceOp: 'append' })
  80. original.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  81. const replayed = new Session(SessionId('s3-replay'), [...original.events])
  82. expect(replayed.deriveMessages()).toEqual(original.deriveMessages())
  83. expect(replayed.seq).toBe(original.seq)
  84. })
  85. it('isolates the log from mutation through a derived message (append-only contract)', () => {
  86. const session = new Session(SessionId('s4'))
  87. session.append('user/message', { content: [{ type: 'text', text: 'original' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  88. session.append('tool/result', {
  89. turn: 1, step: 1, callId: CallId('c1'),
  90. content: [{ type: 'text', text: 'tool out' }], isError: false,
  91. }, { surfaceOp: 'append' })
  92. const before = structuredClone(session.events)
  93. // A misbehaving consumer tries to mutate the messages it was handed.
  94. const messages = session.deriveMessages()
  95. const userBlock = messages[0]!.content[0]!
  96. expect(() => { if (userBlock.type === 'text') userBlock.text = 'HACKED' }).toThrow(TypeError)
  97. const toolBlock = messages[1]!.content[0]!
  98. expect(() => {
  99. if (toolBlock.type === 'tool-result') toolBlock.content.push({ type: 'text', text: 'injected' })
  100. }).toThrow(TypeError)
  101. expect(() => { messages[0]!.content.push({ type: 'text', text: 'extra' }) }).toThrow(TypeError)
  102. // The returned ARRAY is the caller's own snapshot, though — reordering it
  103. // is the caller's business and never reaches the cache or the log.
  104. messages.reverse()
  105. // The log is unchanged: deep-equal to the snapshot taken before mutation.
  106. expect(session.events).toEqual(before)
  107. // And a fresh derivation still reflects the original content and order.
  108. expect(session.deriveMessages()[0]!.content).toEqual([{ type: 'text', text: 'original' }])
  109. })
  110. it('rejects non-JSON-serializable event data at the source (incl. sparse arrays)', () => {
  111. const session = new Session(SessionId('s5'))
  112. const bad = (extra: unknown) => () => session.append('user/message', { content: [{ type: 'text', text: 'x' }], source: { kind: 'user' }, extra } as never, { surfaceOp: 'append' })
  113. expect(bad(1n)).toThrow(/non-JSON-serializable/)
  114. expect(bad(() => 0)).toThrow(/non-JSON-serializable/)
  115. expect(bad(Symbol('s'))).toThrow(/non-JSON-serializable/)
  116. expect(bad(new Map())).toThrow(/non-JSON-serializable/)
  117. expect(bad(undefined)).toThrow(/non-JSON-serializable/)
  118. expect(bad(Infinity)).toThrow(/non-JSON-serializable/)
  119. // A sparse array: `every` skips the hole but JSON.stringify writes it null.
  120. // Build the hole without a sparse literal or `delete` (both linted).
  121. const sparse: unknown[] = Array(3)
  122. sparse[0] = 1
  123. sparse[2] = 3 // index 1 stays a hole
  124. expect(bad(sparse)).toThrow(/non-JSON-serializable/)
  125. // A DENSE array carrying a non-serializable element is rejected too.
  126. expect(bad([1, 2n, 3])).toThrow(/non-JSON-serializable/)
  127. // A nested non-serializable value (inside a plain object) is rejected.
  128. expect(bad({ nested: { deep: () => 0 } })).toThrow(/non-JSON-serializable/)
  129. // A circular reference is rejected (the seen-set guard, not a stack blow-up).
  130. const cyclic: Record<string, unknown> = { a: 1 }
  131. cyclic['self'] = cyclic
  132. expect(bad(cyclic)).toThrow(/non-JSON-serializable/)
  133. // The rejected appends never entered the log.
  134. expect(session.events).toHaveLength(0)
  135. })
  136. it('rejects a surface-eligible append with no surfaceOp marker (runtime guard for the union-widening loophole)', () => {
  137. const session = new Session(SessionId('s5b'))
  138. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  139. // A widened SessionEventType bypasses the overload's conditional requirement,
  140. // so the runtime guard must still reject the missing surface marker.
  141. const widenedType = 'user/message' as SessionEventType
  142. expect(() => session.append(widenedType, { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }))
  143. .toThrow(/surface-eligible and requires a surfaceOp marker/)
  144. // The rejected append never entered the log (only turn/start is present).
  145. expect(session.events).toHaveLength(1)
  146. })
  147. it('accepts dense arrays and nested plain objects', () => {
  148. const session = new Session(SessionId('s6'))
  149. expect(() => session.append('user/message', { content: [{ type: 'text', text: 'x' }], source: { kind: 'user' }, extra: [1, 2, [3, { a: null, b: true }]] } as never, { surfaceOp: 'append' })).not.toThrow()
  150. expect(session.events).toHaveLength(1)
  151. })
  152. it('validates seed events: rejects a non-JSON-serializable seed', () => {
  153. // A replay/fork seed must satisfy the SAME invariant as Session.append, or
  154. // it builds a live log no backend can persist.
  155. const badSeed = [
  156. { type: 'user/message' as const, seq: 0, time: 1, data: { content: [{ type: 'text' as const, text: 'x' }], source: { kind: 'user' as const }, bad: 1n } },
  157. ] as unknown as SessionEvent[]
  158. expect(() => new Session(SessionId('seed-bad'), badSeed)).toThrow(/losslessly JSON-serializable/)
  159. })
  160. it('validates seed events: rejects a non-contiguous seq', () => {
  161. const gapSeed = [
  162. { type: 'turn/start' as const, seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message' as const, source: { kind: 'user' as const } } } },
  163. { type: 'turn/end' as const, seq: 5, time: 2, data: { turn: 1, reason: { kind: 'completed' as const } } }, // gap: expected seq 1
  164. ] as SessionEvent[]
  165. expect(() => new Session(SessionId('seed-gap'), gapSeed)).toThrow(/contiguous|seq/)
  166. })
  167. it('validates seed events: rejects a surface-eligible event missing its surfaceOp marker', () => {
  168. // A surface-eligible event (user/message) with no surfaceOp would load fine
  169. // but vanish from deriveMessages() (the surface is the sole derivation path),
  170. // so a resume/fork would silently lose history. append() forbids this at
  171. // compile time; a raw seed must be rejected at runtime to match.
  172. const markerlessSeed = [
  173. { type: 'turn/start' as const, seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message' as const, source: { kind: 'user' as const } } } },
  174. { type: 'user/message' as const, seq: 1, time: 2, data: { content: [{ type: 'text' as const, text: 'hi' }], source: { kind: 'user' as const } } },
  175. { type: 'turn/end' as const, seq: 2, time: 3, data: { turn: 1, reason: { kind: 'completed' as const } } },
  176. ] as SessionEvent[]
  177. expect(() => new Session(SessionId('seed-no-marker'), markerlessSeed)).toThrow(/requires a surfaceOp marker/)
  178. })
  179. it('accepts a well-formed contiguous serializable seed', () => {
  180. const goodSeed = [
  181. { type: 'turn/start' as const, seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message' as const, source: { kind: 'user' as const } } } },
  182. { type: 'user/message' as const, seq: 1, time: 2, data: { content: [{ type: 'text' as const, text: 'hi' }], source: { kind: 'user' as const } }, surfaceOp: 'append' as const },
  183. { type: 'turn/end' as const, seq: 2, time: 3, data: { turn: 1, reason: { kind: 'completed' as const } } },
  184. ] as SessionEvent[]
  185. const session = new Session(SessionId('seed-ok'), goodSeed)
  186. expect(session.events).toHaveLength(3)
  187. })
  188. it('reads each seed array entry once so validation and storage use the same event', () => {
  189. const accepted = {
  190. type: 'turn/start' as const,
  191. seq: 0,
  192. time: 1,
  193. data: { turn: 1, trigger: { kind: 'message' as const, source: { kind: 'user' as const } } },
  194. }
  195. const drifted = { ...accepted, seq: 99, data: { invalid: 1n } }
  196. let reads = 0
  197. const seed = new Array<SessionEvent>(1)
  198. Object.defineProperty(seed, 0, {
  199. enumerable: true,
  200. get: () => {
  201. reads += 1
  202. return reads === 1 ? accepted : drifted
  203. },
  204. })
  205. const session = new Session(SessionId('seed-entry-snapshot'), seed)
  206. expect(reads).toBe(1)
  207. expect(session.events).toEqual([accepted])
  208. })
  209. it('reads a nested seed-data getter once and stores its first JSON value', () => {
  210. let reads = 0
  211. const data = Object.defineProperty({}, 'value', {
  212. enumerable: true,
  213. get: () => {
  214. reads += 1
  215. return reads === 1 ? 'accepted' : 1n
  216. },
  217. })
  218. const seed = [{ type: 'test/unstable', seq: 0, time: 1, data }] as unknown as SessionEvent[]
  219. const session = new Session(SessionId('seed-nested-drift'), seed)
  220. expect(reads).toBe(1)
  221. expect(session.events[0]!.data).toEqual({ value: 'accepted' })
  222. })
  223. it('rejects non-JSON surface metadata in a seed event', () => {
  224. const seed = [{
  225. type: 'user/message',
  226. seq: 0,
  227. time: 1,
  228. data: { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } },
  229. surfaceOp: { op: 'replace', start: 1n, end: 2 },
  230. }] as unknown as SessionEvent[]
  231. expect(() => new Session(SessionId('seed-bad-metadata'), seed))
  232. .toThrow(/losslessly JSON-serializable/)
  233. })
  234. it('rejects exotic seed metadata before cloning can erase its prototype', () => {
  235. class ReplaceOp {
  236. readonly op = 'replace' as const
  237. readonly start = 0
  238. readonly end = 0
  239. }
  240. const seed = [{
  241. type: 'user/message',
  242. seq: 0,
  243. time: 1,
  244. data: { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } },
  245. surfaceOp: new ReplaceOp(),
  246. }] as unknown as SessionEvent[]
  247. expect(() => new Session(SessionId('seed-exotic-metadata'), seed))
  248. .toThrow(/losslessly JSON-serializable/)
  249. })
  250. it('rejects an exotic seed event shell before spreading erases its prototype', () => {
  251. class SeedEvent {
  252. readonly type = 'turn/start' as const
  253. readonly seq = 0
  254. readonly time = 1
  255. readonly data = { turn: 1, trigger: { kind: 'message' as const, source: { kind: 'user' as const } } }
  256. }
  257. const seed: SessionEvent[] = [new SeedEvent()]
  258. expect(() => new Session(SessionId('seed-exotic-shell'), seed))
  259. .toThrow(/not losslessly JSON-serializable/)
  260. })
  261. it('accepts a null-prototype seed event shell as a plain JSON record', () => {
  262. const event = Object.assign(Object.create(null) as Record<string, unknown>, {
  263. type: 'turn/start' as const,
  264. seq: 0,
  265. time: 1,
  266. data: { turn: 1, trigger: { kind: 'message' as const, source: { kind: 'user' as const } } },
  267. }) as unknown as SessionEvent
  268. const session = new Session(SessionId('seed-null-prototype'), [event])
  269. expect(session.events).toEqual([{ ...event }])
  270. })
  271. it('reads a nested seed-metadata getter once and stores its first JSON value', () => {
  272. let reads = 0
  273. const surfaceOp = Object.defineProperty({ op: 'replace', end: 0 }, 'start', {
  274. enumerable: true,
  275. get: () => {
  276. reads += 1
  277. return reads === 1 ? 0 : 1n
  278. },
  279. })
  280. const seed = [{
  281. type: 'user/message',
  282. seq: 0,
  283. time: 1,
  284. data: { content: [{ type: 'text', text: 'source' }], source: { kind: 'user' } },
  285. surfaceOp: 'append',
  286. }, {
  287. type: 'user/message',
  288. seq: 1,
  289. time: 2,
  290. data: { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } },
  291. surfaceOp,
  292. sourceEventSeqs: [0],
  293. }] as unknown as SessionEvent[]
  294. const session = new Session(SessionId('seed-unstable-metadata'), seed)
  295. const event = session.events[1]!
  296. if (event.type !== 'user/message') throw new Error('test fixture must remain a user/message')
  297. expect(reads).toBe(1)
  298. expect(event.surfaceOp).toEqual({ op: 'replace', start: 0, end: 0 })
  299. })
  300. it.each([
  301. ['an Error', new Error('validator failed'), 'validator failed'],
  302. ['a non-Error value', 'validator failed', 'invalid surface metadata'],
  303. ] as const)('adds seed context when surface validation throws %s', (_name, failure, expected) => {
  304. const originalHasOwn = Object.hasOwn
  305. const hasOwn = vi.spyOn(Object, 'hasOwn').mockImplementation((object: object, property: PropertyKey): boolean => {
  306. if ((object as Record<string, unknown>)['op'] === 'replace') throw failure
  307. return originalHasOwn(object, property)
  308. })
  309. const seed = [{
  310. type: 'user/message',
  311. seq: 0,
  312. time: 1,
  313. data: { content: [{ type: 'text', text: 'source' }], source: { kind: 'user' } },
  314. surfaceOp: 'append',
  315. }, {
  316. type: 'user/message',
  317. seq: 1,
  318. time: 2,
  319. data: { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } },
  320. surfaceOp: { op: 'replace', start: 0, end: 0 },
  321. sourceEventSeqs: [0],
  322. }] as unknown as SessionEvent[]
  323. try {
  324. expect(() => new Session(SessionId('seed-non-error-metadata-failure'), seed))
  325. .toThrow(`invalid seed event at index 1: ${expected}`)
  326. } finally {
  327. hasOwn.mockRestore()
  328. }
  329. })
  330. it('snapshots the seed: mutating the original after construction does not affect session.events', () => {
  331. const seed = [
  332. { type: 'turn/start' as const, seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message' as const, source: { kind: 'user' as const } } } },
  333. { type: 'user/message' as const, seq: 1, time: 2, data: { content: [{ type: 'text' as const, text: 'original' }], source: { kind: 'user' as const } }, surfaceOp: 'append' as const },
  334. { type: 'turn/end' as const, seq: 2, time: 3, data: { turn: 1, reason: { kind: 'completed' as const } } },
  335. ] as SessionEvent[]
  336. const session = new Session(SessionId('seed-snapshot'), seed)
  337. // Mutate the ORIGINAL seed objects after construction: a shared reference
  338. // would let this rewrite the forked log (or reintroduce non-serializable
  339. // data past validation). The snapshot must shield session.events.
  340. const um = seed[1]!
  341. ;(um.data as { content: { type: 'text'; text: string }[] }).content[0]!.text = 'HACKED'
  342. ;(um.data as Record<string, unknown>)['injected'] = 1n // would have failed validation
  343. const logged = session.events[1]!
  344. expect(logged.type === 'user/message' && (logged.data.content[0] as { text: string }).text).toBe('original')
  345. expect((logged.data as Record<string, unknown>)['injected']).toBeUndefined()
  346. })
  347. it('snapshots append data: mutating the passed object after append does not affect session.events', () => {
  348. const session = new Session(SessionId('append-snapshot'))
  349. const data = { content: [{ type: 'text' as const, text: 'original' }], source: { kind: 'user' as const } }
  350. const event = session.append('user/message', data, { surfaceOp: 'append' })
  351. // Mutate the caller's object after append returns. A shared reference would
  352. // make session.events diverge from the value that passed validation.
  353. data.content[0]!.text = 'HACKED'
  354. ;(data as Record<string, unknown>)['injected'] = 1n
  355. const logged = session.events[0]!
  356. expect(logged.type === 'user/message' && (logged.data.content[0] as { text: string }).text).toBe('original')
  357. expect((logged.data as Record<string, unknown>)['injected']).toBeUndefined()
  358. // The returned event carries the same snapshot, not the caller's input.
  359. expect((event.data.content[0] as { text: string }).text).toBe('original')
  360. })
  361. it('reads a nested append-data getter once and stores its first JSON value', () => {
  362. const session = new Session(SessionId('append-nested-drift'))
  363. let reads = 0
  364. const data = Object.defineProperty({}, 'value', {
  365. enumerable: true,
  366. get: () => {
  367. reads += 1
  368. return reads === 1 ? 'accepted' : 1n
  369. },
  370. })
  371. const event = session.append('todo/write', data as never)
  372. expect(reads).toBe(1)
  373. expect(event.data).toEqual({ value: 'accepted' })
  374. expect(session.events).toEqual([event])
  375. })
  376. it('rejects non-JSON surface metadata before appending the event', () => {
  377. const session = new Session(SessionId('append-bad-metadata'))
  378. expect(() => session.append(
  379. 'user/message',
  380. { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } },
  381. { surfaceOp: { op: 'replace', start: 1n, end: 2 } } as never,
  382. )).toThrow(/non-JSON-serializable surface metadata/)
  383. expect(session.events).toEqual([])
  384. })
  385. it('rejects exotic surface metadata before cloning can erase its prototype', () => {
  386. class ReplaceOp {
  387. readonly op = 'replace' as const
  388. readonly start = 0
  389. readonly end = 0
  390. }
  391. const session = new Session(SessionId('append-exotic-metadata'))
  392. expect(() => session.append(
  393. 'user/message',
  394. { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } },
  395. { surfaceOp: new ReplaceOp() },
  396. )).toThrow(/non-JSON-serializable surface metadata/)
  397. expect(session.events).toEqual([])
  398. })
  399. it('reads a nested append-metadata getter once and stores its first JSON value', () => {
  400. const session = new Session(SessionId('append-unstable-metadata'))
  401. const source = session.append(
  402. 'user/message',
  403. { content: [{ type: 'text', text: 'source' }], source: { kind: 'user' } },
  404. { surfaceOp: 'append' },
  405. )
  406. let reads = 0
  407. const surfaceOp = Object.defineProperty({ op: 'replace', end: 0 }, 'start', {
  408. enumerable: true,
  409. get: () => {
  410. reads += 1
  411. return reads === 1 ? 0 : 1n
  412. },
  413. })
  414. const event = session.append(
  415. 'user/message',
  416. { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } },
  417. { surfaceOp, sourceEventSeqs: [0] } as never,
  418. )
  419. expect(reads).toBe(1)
  420. expect(event.surfaceOp).toEqual({ op: 'replace', start: 0, end: 0 })
  421. expect(session.events).toEqual([source, event])
  422. })
  423. it('rejects invalid plain surface metadata shapes at append', () => {
  424. const session = new Session(SessionId('append-invalid-surface-shape'))
  425. const appendRaw = session.append.bind(session) as unknown as (
  426. type: SessionEventType,
  427. data: unknown,
  428. opts?: unknown,
  429. ) => SessionEvent
  430. const data = { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } }
  431. expect(() => appendRaw('user/message', data, { surfaceOp: 'invalid' }))
  432. .toThrow(/invalid surfaceOp/)
  433. expect(() => appendRaw('user/message', data, {
  434. surfaceOp: { op: 'replace', start: -1, end: 0 },
  435. })).toThrow(/invalid replace surfaceOp/)
  436. expect(() => appendRaw('user/message', data, {
  437. surfaceOp: 'append',
  438. sourceEventSeqs: [0, -1],
  439. })).toThrow(/non-negative safe integers/)
  440. expect(session.events).toEqual([])
  441. })
  442. it('rejects surface metadata on non-surface append and seed events', () => {
  443. const session = new Session(SessionId('non-surface-metadata'))
  444. const appendRaw = session.append.bind(session) as unknown as (
  445. type: SessionEventType,
  446. data: unknown,
  447. opts?: unknown,
  448. ) => SessionEvent
  449. expect(() => appendRaw(
  450. 'turn/start',
  451. { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
  452. { surfaceOp: 'append' },
  453. )).toThrow(/not surface-eligible and cannot carry surfaceOp/)
  454. expect(() => new Session(SessionId('non-surface-metadata-seed'), [{
  455. type: 'turn/start',
  456. seq: 0,
  457. time: 1,
  458. data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
  459. surfaceOp: 'append',
  460. } as unknown as SessionEvent])).toThrow(/invalid seed event.*not surface-eligible/)
  461. expect(session.events).toEqual([])
  462. })
  463. it('deep-freezes seeded and appended event snapshots', () => {
  464. const seeded = new Session(SessionId('seed-frozen'), [{
  465. type: 'turn/start',
  466. seq: 0,
  467. time: 1,
  468. data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
  469. }])
  470. const seededEvent = seeded.events[0]!
  471. if (seededEvent.type !== 'turn/start') throw new Error('test fixture must remain a turn/start')
  472. expect(Object.isFrozen(seededEvent)).toBe(true)
  473. expect(Object.isFrozen(seededEvent.data)).toBe(true)
  474. expect(Object.isFrozen(seededEvent.data.trigger)).toBe(true)
  475. expect(() => { seededEvent.data.turn = 99 }).toThrow(TypeError)
  476. const appended = new Session(SessionId('append-frozen'))
  477. const appendedEvent = appended.append('todo/write', {
  478. todos: [{ content: 'first', status: 'pending' }],
  479. })
  480. expect(Object.isFrozen(appendedEvent)).toBe(true)
  481. expect(Object.isFrozen(appendedEvent.data)).toBe(true)
  482. expect(Object.isFrozen(appendedEvent.data.todos)).toBe(true)
  483. expect(Object.isFrozen(appendedEvent.data.todos[0])).toBe(true)
  484. expect(() => { appendedEvent.data.todos[0]!.content = 'mutated' }).toThrow(TypeError)
  485. })
  486. it('returns cached frozen event-array snapshots that do not grow after append', () => {
  487. const session = new Session(SessionId('events-snapshot'))
  488. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  489. const before = session.events
  490. const beforeEvent = before[0]!
  491. if (beforeEvent.type !== 'turn/start') throw new Error('test fixture must remain a turn/start')
  492. expect(session.events).toBe(before)
  493. expect(Object.isFrozen(before)).toBe(true)
  494. expect(() => { (before as SessionEvent[]).push(beforeEvent) }).toThrow(TypeError)
  495. expect(() => { beforeEvent.data.turn = 99 }).toThrow(TypeError)
  496. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  497. const after = session.events
  498. expect(before).toHaveLength(1)
  499. expect(after).toHaveLength(2)
  500. expect(after).not.toBe(before)
  501. expect(session.events).toBe(after)
  502. })
  503. it('detaches and freezes an explicitly supplied session header', () => {
  504. const input = {
  505. version: SESSION_FORMAT_VERSION,
  506. id: SessionId('header-owned'),
  507. createdAt: 123,
  508. cwd: '/accepted',
  509. parentSession: SessionId('parent'),
  510. seedLength: 2,
  511. }
  512. const session = new Session(SessionId('header-owned'), undefined, input)
  513. input.cwd = '/caller-mutated'
  514. expect(session.header).toEqual({
  515. version: SESSION_FORMAT_VERSION,
  516. id: 'header-owned',
  517. createdAt: 123,
  518. cwd: '/accepted',
  519. parentSession: 'parent',
  520. seedLength: 2,
  521. })
  522. expect(session.header).not.toBe(input)
  523. expect(Object.isFrozen(session.header)).toBe(true)
  524. expect(Reflect.set(session.header, 'cwd', '/published-mutated')).toBe(false)
  525. expect(session.id).toBe('header-owned')
  526. expect(session.header.cwd).toBe('/accepted')
  527. })
  528. it('rejects an exotic, non-JSON, or mismatched supplied header', () => {
  529. class ExoticHeader implements SessionHeader {
  530. readonly version = SESSION_FORMAT_VERSION
  531. readonly id = SessionId('header-invalid')
  532. readonly createdAt = 123
  533. }
  534. expect(() => new Session(SessionId('header-invalid'), undefined, new ExoticHeader()))
  535. .toThrow(/not losslessly JSON-serializable/)
  536. expect(() => new Session(SessionId('header-invalid'), undefined, {
  537. version: SESSION_FORMAT_VERSION,
  538. id: SessionId('header-invalid'),
  539. createdAt: 123,
  540. parentSession: 1n,
  541. } as unknown as SessionHeader)).toThrow(/not losslessly JSON-serializable/)
  542. expect(() => new Session(SessionId('header-invalid'), undefined, {
  543. version: SESSION_FORMAT_VERSION,
  544. id: SessionId('other'),
  545. createdAt: 123,
  546. })).toThrow(/does not match session id/)
  547. })
  548. it('rejects invalid scalar fields in an explicitly supplied header', () => {
  549. const base = {
  550. version: SESSION_FORMAT_VERSION,
  551. id: SessionId('header-shape'),
  552. createdAt: 123,
  553. }
  554. const cases: Array<{ header: unknown; error: RegExp }> = [
  555. { header: 1, error: /not a plain JSON record/ },
  556. { header: null, error: /not a plain JSON record/ },
  557. { header: { ...base, version: 1 }, error: /header version/ },
  558. { header: { ...base, createdAt: '123' }, error: /createdAt must be a finite number/ },
  559. { header: { ...base, cwd: 1 }, error: /header cwd must be a string/ },
  560. { header: { ...base, cwd: 'relative' }, error: /header cwd must be an absolute path/ },
  561. { header: { ...base, parentSession: 1 }, error: /header parentSession must be a string/ },
  562. { header: { ...base, seedLength: '1' }, error: /seedLength must be a non-negative safe integer/ },
  563. { header: { ...base, seedLength: 0.5 }, error: /seedLength must be a non-negative safe integer/ },
  564. { header: { ...base, seedLength: -1 }, error: /seedLength must be a non-negative safe integer/ },
  565. ]
  566. for (const { header, error } of cases) {
  567. expect(() => new Session(SessionId('header-shape'), undefined, header as SessionHeader)).toThrow(error)
  568. }
  569. })
  570. it('rejects seed records with invalid fixed-envelope fields', () => {
  571. const base = {
  572. type: 'turn/start',
  573. seq: 0,
  574. time: 1,
  575. data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
  576. }
  577. const cases: unknown[] = [
  578. { ...base, extra: true },
  579. { ...base, type: 1 },
  580. { ...base, seq: '0' },
  581. { ...base, seq: 0.5 },
  582. { ...base, seq: -1 },
  583. { ...base, time: '1' },
  584. { ...base, time: 0.5 },
  585. { ...base, time: -1 },
  586. { type: base.type, seq: base.seq, time: base.time },
  587. ]
  588. for (const [index, event] of cases.entries()) {
  589. expect(() => new Session(SessionId(`bad-envelope-${index}`), [event as SessionEvent]))
  590. .toThrow(/invalid event envelope/)
  591. }
  592. })
  593. })
  594. describe('SessionStore', () => {
  595. it('creates sessions, emits session/created and session/event', async () => {
  596. const ctx = new Context()
  597. await ctx.plugin(SessionStore)
  598. const created: Session[] = []
  599. const events: [Session, SessionEvent][] = []
  600. ctx.on('session/created', session => void created.push(session))
  601. ctx.on('session/event', (session, event) => void events.push([session, event]))
  602. const session = ctx.sessions.create()
  603. expect(created).toEqual([session])
  604. // The store-owned append publication hooks are module-private. A JavaScript caller
  605. // may create an unrelated property with the old implementation's name,
  606. // but cannot suppress the durable event feed.
  607. expect(Reflect.set(session, 'onAppend', undefined)).toBe(true)
  608. session.append('user/message', { content: [{ type: 'text', text: 'x' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  609. expect(events).toHaveLength(1)
  610. expect(events[0]![0]).toBe(session)
  611. expect(events[0]![1].type).toBe('user/message')
  612. expect(ctx.sessions.get(session.id)).toBe(session)
  613. expect(ctx.sessions.list()).toEqual([session])
  614. })
  615. it('rejects duplicate ids and supports seeding', async () => {
  616. const ctx = new Context()
  617. await ctx.plugin(SessionStore)
  618. const a = ctx.sessions.create(SessionId('fixed'))
  619. expect(() => ctx.sessions.create(SessionId('fixed'))).toThrow('already exists')
  620. a.append('user/message', { content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  621. const forked = ctx.sessions.create(SessionId('fork'), { seed: [...a.events] })
  622. expect(forked.deriveMessages()).toEqual(a.deriveMessages())
  623. })
  624. it('enter() rejects a stale prepared session whose id is already live (no overwrite)', async () => {
  625. // A stale prepared object must not replace the live same-id entry; its later
  626. // detach would otherwise remove the wrong session.
  627. const ctx = new Context()
  628. await ctx.plugin(SessionStore)
  629. const stale = ctx.sessions.prepare(SessionId('racy'))
  630. const live = ctx.sessions.create(SessionId('racy'))
  631. expect(() => ctx.sessions.enter(stale)).toThrow(/already exists/)
  632. // The live session is intact and still the store entry.
  633. expect(ctx.sessions.get(SessionId('racy'))).toBe(live)
  634. })
  635. it('prepare() + enter() + announce() register a session and emit session/created', async () => {
  636. const ctx = new Context()
  637. await ctx.plugin(SessionStore)
  638. const created: Session[] = []
  639. ctx.on('session/created', session => void created.push(session))
  640. const session = ctx.sessions.prepare(SessionId('lifecycle'))
  641. // prepare alone does NOT enter the store.
  642. expect(ctx.sessions.get(SessionId('lifecycle'))).toBeUndefined()
  643. const detach = ctx.sessions.enter(session)
  644. expect(ctx.sessions.get(SessionId('lifecycle'))).toBe(session)
  645. // enter does NOT announce.
  646. expect(created).toEqual([])
  647. ctx.sessions.announce(session)
  648. expect(created).toEqual([session])
  649. // The detach disposer removes the entry + stops notification.
  650. detach()
  651. detach() // idempotent: cannot disturb a later same-id lifecycle
  652. expect(ctx.sessions.get(SessionId('lifecycle'))).toBeUndefined()
  653. })
  654. it('prevents simultaneous attachment of one session object to two stores', async () => {
  655. const firstCtx = new Context()
  656. const secondCtx = new Context()
  657. await firstCtx.plugin(SessionStore)
  658. await secondCtx.plugin(SessionStore)
  659. const session = new Session(SessionId('owned-key'))
  660. const detachFirst = firstCtx.sessions.enter(session)
  661. expect(() => secondCtx.sessions.enter(session)).toThrow(/already attached to a store/)
  662. expect(firstCtx.sessions.get(SessionId('owned-key'))).toBe(session)
  663. detachFirst()
  664. expect(firstCtx.sessions.get(SessionId('owned-key'))).toBeUndefined()
  665. const detachSecond = secondCtx.sessions.enter(session)
  666. expect(secondCtx.sessions.get(SessionId('owned-key'))).toBe(session)
  667. detachSecond()
  668. })
  669. it('rejects direct and reentrant repeat announcements to preserve one lifecycle pair', async () => {
  670. const ctx = new Context()
  671. await ctx.plugin(SessionStore)
  672. let created = 0
  673. let disposed = 0
  674. let reentrantError = ''
  675. ctx.on('session/created', (session) => {
  676. created += 1
  677. try {
  678. ctx.sessions.announce(session)
  679. } catch (error: unknown) {
  680. reentrantError = String(error)
  681. }
  682. })
  683. ctx.on('session/disposed', () => { disposed += 1 })
  684. const session = ctx.sessions.prepare(SessionId('once'))
  685. const detach = ctx.sessions.enter(session)
  686. ctx.sessions.announce(session)
  687. expect(reentrantError).toMatch(/already announced/)
  688. expect(() => { ctx.sessions.announce(session) }).toThrow(/already announced/)
  689. detach()
  690. expect({ created, disposed }).toEqual({ created: 1, disposed: 1 })
  691. })
  692. it('defers a reentrant detach until the creation dispatch unwinds', async () => {
  693. const ctx = new Context()
  694. await ctx.plugin(SessionStore)
  695. const order: string[] = []
  696. const session = ctx.sessions.prepare(SessionId('reentrant-detach'))
  697. const detach = ctx.sessions.enter(session)
  698. ctx.on('session/created', (created) => {
  699. order.push('created:first')
  700. detach()
  701. expect(ctx.sessions.get(created.id)).toBe(created)
  702. })
  703. ctx.on('session/created', (created) => {
  704. order.push('created:second')
  705. expect(ctx.sessions.get(created.id)).toBe(created)
  706. })
  707. ctx.on('session/disposed', (disposed) => {
  708. order.push('disposed')
  709. expect(ctx.sessions.get(disposed.id)).toBeUndefined()
  710. })
  711. ctx.sessions.announce(session)
  712. expect(order).toEqual(['created:first', 'created:second', 'disposed'])
  713. expect(ctx.sessions.get(session.id)).toBeUndefined()
  714. detach()
  715. })
  716. it('rolls back create when its owner unloads from session/created', async () => {
  717. const ctx = new Context()
  718. await ctx.plugin(SessionStore)
  719. let ownerCtx!: Context
  720. const owner = await ctx.plugin(Object.assign((inner: Context) => { ownerCtx = inner }, { inject: ['sessions'] }))
  721. const id = SessionId('create-unload-race')
  722. ctx.on('session/created', (session) => {
  723. if (session.id === id) void owner.dispose()
  724. })
  725. ownerCtx.sessions.create(id)
  726. await owner.dispose()
  727. expect(ctx.sessions.get(id)).toBeUndefined()
  728. })
  729. it('synthesizes a minimal current-version header for a bare-created session', async () => {
  730. const ctx = new Context()
  731. await ctx.plugin(SessionStore)
  732. const session = ctx.sessions.create(SessionId('plain'))
  733. expect(session.header).toMatchObject({ version: SESSION_FORMAT_VERSION, id: 'plain' })
  734. expect(typeof session.header.createdAt).toBe('number')
  735. expect(session.header.cwd).toBeUndefined()
  736. expect(session.header.parentSession).toBeUndefined()
  737. })
  738. it('attaches cwd and parentSession from meta to the header', async () => {
  739. const ctx = new Context()
  740. await ctx.plugin(SessionStore)
  741. const session = ctx.sessions.create(SessionId('child'), {
  742. meta: { cwd: '/work/project', parentSession: SessionId('parent') },
  743. })
  744. expect(session.header).toMatchObject({
  745. version: SESSION_FORMAT_VERSION,
  746. id: 'child',
  747. cwd: '/work/project',
  748. parentSession: 'parent',
  749. })
  750. })
  751. it('rejects non-JSON and invalid scalar session metadata', async () => {
  752. const ctx = new Context()
  753. await ctx.plugin(SessionStore)
  754. const cases: Array<{ meta: unknown; error: RegExp }> = [
  755. { meta: { parentSession: 1n }, error: /header is not losslessly JSON-serializable/ },
  756. { meta: { cwd: 1 }, error: /header cwd must be a string/ },
  757. { meta: { parentSession: 1 }, error: /header parentSession must be a string/ },
  758. { meta: { createdAt: '123' }, error: /header createdAt must be a finite number/ },
  759. { meta: { seedLength: '1' }, error: /seedLength must be a non-negative safe integer/ },
  760. { meta: { seedLength: 0.5 }, error: /seedLength must be a non-negative safe integer/ },
  761. { meta: { seedLength: -1 }, error: /seedLength must be a non-negative safe integer/ },
  762. ]
  763. for (const [index, { meta, error }] of cases.entries()) {
  764. expect(() => ctx.sessions.prepare(SessionId(`bad-meta-${index}`), {
  765. meta: meta as NonNullable<CreateSessionOptions['meta']>,
  766. })).toThrow(error)
  767. }
  768. })
  769. it('rejects a non-absolute meta.cwd', async () => {
  770. const ctx = new Context()
  771. await ctx.plugin(SessionStore)
  772. expect(() => ctx.sessions.create(SessionId('rel'), { meta: { cwd: 'relative/path' } }))
  773. .toThrow(/cwd must be an absolute path/)
  774. // the rejected session was not registered
  775. expect(ctx.sessions.get(SessionId('rel'))).toBeUndefined()
  776. })
  777. it('a bare Session() constructed without the store still exposes a current-version header', () => {
  778. const session = new Session(SessionId('bare'))
  779. expect(session.header).toMatchObject({ version: SESSION_FORMAT_VERSION, id: 'bare' })
  780. expect(typeof session.header.createdAt).toBe('number')
  781. })
  782. it('detaches sessions when the creating fiber is disposed (HMR safety)', async () => {
  783. const ctx = new Context()
  784. await ctx.plugin(SessionStore)
  785. let session!: Session
  786. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  787. session = inner.sessions.create(SessionId('scoped'))
  788. }, { inject: ['sessions'] }))
  789. expect(ctx.sessions.get(SessionId('scoped'))).toBe(session)
  790. let observed = 0
  791. ctx.on('session/event', () => void observed++)
  792. await fiber.dispose()
  793. expect(ctx.sessions.get(SessionId('scoped'))).toBeUndefined()
  794. session.append('user/message', { content: [{ type: 'text', text: 'late' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  795. expect(observed).toBe(0)
  796. })
  797. it('pairs a partial session/created announcement with disposal during rollback', async () => {
  798. const ctx = new Context()
  799. await ctx.plugin(SessionStore)
  800. let threw = false
  801. const disposed: Session[] = []
  802. ctx.on('session/disposed', (session) => { disposed.push(session) })
  803. ctx.on('session/created', () => {
  804. if (!threw) { threw = true; throw new Error('boom created listener') }
  805. })
  806. // The throwing emit must roll the store entry back, not leak it.
  807. expect(() => ctx.sessions.create(SessionId('fixed'))).toThrow('boom created listener')
  808. expect(ctx.sessions.get(SessionId('fixed'))).toBeUndefined() // rolled back, not leaked
  809. expect(disposed.map(session => session.id)).toEqual(['fixed'])
  810. // A subsequent create of the SAME id succeeds (the already-exists check is
  811. // not wedged) and its store-owned publication hooks are correctly wired.
  812. const events: SessionEvent[] = []
  813. ctx.on('session/event', (_session, event) => void events.push(event))
  814. const session = ctx.sessions.create(SessionId('fixed'))
  815. expect(ctx.sessions.get(SessionId('fixed'))).toBe(session)
  816. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  817. expect(events).toHaveLength(1)
  818. })
  819. it('contains session/event observer failures after the append commit point', async () => {
  820. const ctx = new Context()
  821. await ctx.plugin(SessionStore)
  822. const warnings: string[] = []
  823. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  824. const session = ctx.sessions.create(SessionId('contained-event'))
  825. const heard: SessionEvent[] = []
  826. let committedBeforeNotify = false
  827. ctx.on('session/event', (observedSession, event) => {
  828. committedBeforeNotify = observedSession.events.at(-1) === event
  829. throw new Error('sync event observer')
  830. })
  831. ctx.on('session/event', () => Promise.reject(new Error('async event observer')) as never)
  832. ctx.on('session/event', (_observedSession, event) => { heard.push(event) })
  833. let appended!: SessionEvent
  834. expect(() => {
  835. appended = session.append('turn/start', {
  836. turn: 1,
  837. trigger: { kind: 'message', source: { kind: 'user' } },
  838. })
  839. }).not.toThrow()
  840. expect(committedBeforeNotify).toBe(true)
  841. expect(session.events).toEqual([appended])
  842. expect(heard).toEqual([appended])
  843. await Promise.resolve()
  844. await Promise.resolve()
  845. expect(warnings).toEqual([
  846. 'session "contained-event": session/event listener threw: Error: sync event observer',
  847. 'session "contained-event": session/event listener rejected: Error: async event observer',
  848. ])
  849. })
  850. it('runs internal dispatch validation on one frozen candidate before commit and resets after a veto', async () => {
  851. const ctx = new Context()
  852. await ctx.plugin(SessionStore)
  853. const session = ctx.sessions.create(SessionId('dispatch-veto'))
  854. const validations: Array<{ event: SessionEvent; logLength: number; frozen: boolean }> = []
  855. const observed: SessionEvent[] = []
  856. let reject = true
  857. ctx.on('internal/dispatch', (_mode, name, args) => {
  858. if (name !== 'session/event') return
  859. const [observedSession, event] = args as [Session, SessionEvent]
  860. validations.push({
  861. event,
  862. logLength: observedSession.events.length,
  863. frozen: Object.isFrozen(event) && Object.isFrozen(event.data),
  864. })
  865. if (reject) {
  866. reject = false
  867. throw new Error('reject first candidate')
  868. }
  869. })
  870. ctx.on('session/event', (_observedSession, event) => { observed.push(event) })
  871. expect(() => session.append('turn/start', {
  872. turn: 1,
  873. trigger: { kind: 'message', source: { kind: 'user' } },
  874. })).toThrow('reject first candidate')
  875. expect(session.events).toEqual([])
  876. expect(observed).toEqual([])
  877. const appended = session.append('turn/start', {
  878. turn: 1,
  879. trigger: { kind: 'message', source: { kind: 'user' } },
  880. })
  881. expect(validations.map(({ logLength, frozen }) => ({ logLength, frozen }))).toEqual([
  882. { logLength: 0, frozen: true },
  883. { logLength: 0, frozen: true },
  884. ])
  885. expect(validations.map(({ event }) => event.seq)).toEqual([0, 0])
  886. expect(validations[1]!.event).toBe(appended)
  887. expect(session.events).toEqual([appended])
  888. expect(observed).toEqual([appended])
  889. })
  890. it('resolves session/event dispatch before commit so instrumentation failure cannot hide a logged event', async () => {
  891. const ctx = new Context()
  892. await ctx.plugin(SessionStore)
  893. const session = ctx.sessions.create(SessionId('dispatch-check'))
  894. const observed: SessionEvent[] = []
  895. ctx.on('internal/dispatch', (_mode, name) => {
  896. if (name === 'session/event') throw new Error('dispatch instrumentation rejected the carrier')
  897. })
  898. ctx.on('session/event', (_observedSession, event) => { observed.push(event) })
  899. expect(() => session.append('turn/start', {
  900. turn: 1,
  901. trigger: { kind: 'message', source: { kind: 'user' } },
  902. })).toThrow('dispatch instrumentation rejected the carrier')
  903. expect(session.events).toEqual([])
  904. expect(observed).toEqual([])
  905. })
  906. it('contains a reentrant observer append without reordering later observers', async () => {
  907. const ctx = new Context()
  908. await ctx.plugin(SessionStore)
  909. const warnings: string[] = []
  910. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  911. const session = ctx.sessions.create(SessionId('reentrant-observer'))
  912. const heard: SessionEvent[] = []
  913. ctx.on('session/event', (observedSession) => {
  914. observedSession.append('todo/write', { todos: [] })
  915. })
  916. ctx.on('session/event', (_observedSession, event) => { heard.push(event) })
  917. const appended = session.append('turn/start', {
  918. turn: 1,
  919. trigger: { kind: 'message', source: { kind: 'user' } },
  920. })
  921. expect(session.events).toEqual([appended])
  922. expect(heard).toEqual([appended])
  923. expect(warnings).toEqual([
  924. 'session "reentrant-observer": session/event listener threw: Error: session append cannot reenter while another append is being published',
  925. ])
  926. })
  927. it('defers detach through dispatch resolution, commit, and observer publication', async () => {
  928. const ctx = new Context()
  929. await ctx.plugin(SessionStore)
  930. const order: string[] = []
  931. const session = ctx.sessions.prepare(SessionId('detach-during-append'))
  932. const detach = ctx.sessions.enter(session)
  933. ctx.on('internal/dispatch', (_mode, name, args) => {
  934. if (name !== 'session/event') return
  935. const session = args[0] as Session
  936. order.push(`resolve:${ctx.sessions.get(session.id) === session ? 'live' : 'detached'}`)
  937. detach()
  938. })
  939. ctx.on('session/event', (session) => {
  940. order.push(`observe:${ctx.sessions.get(session.id) === session ? 'live' : 'detached'}`)
  941. })
  942. ctx.on('session/disposed', (session) => {
  943. order.push(`dispose:${ctx.sessions.get(session.id) === session ? 'live' : 'detached'}`)
  944. })
  945. ctx.sessions.announce(session)
  946. const appended = session.append('turn/start', {
  947. turn: 1,
  948. trigger: { kind: 'message', source: { kind: 'user' } },
  949. })
  950. expect(session.events).toEqual([appended])
  951. expect(order).toEqual(['resolve:live', 'observe:live', 'dispose:detached'])
  952. expect(ctx.sessions.get(session.id)).toBeUndefined()
  953. })
  954. it('observes async session/created rejection without rolling back or starving peers', async () => {
  955. const ctx = new Context()
  956. await ctx.plugin(SessionStore)
  957. const warnings: string[] = []
  958. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  959. const heard: string[] = []
  960. ctx.on('session/created', () => Promise.reject(new Error('late creation failure')) as never)
  961. ctx.on('session/created', (session) => { heard.push(session.id) })
  962. const session = ctx.sessions.create(SessionId('async-created'))
  963. await Promise.resolve()
  964. await Promise.resolve()
  965. expect(ctx.sessions.get(session.id)).toBe(session)
  966. expect(heard).toEqual(['async-created'])
  967. expect(warnings).toEqual([
  968. 'session "async-created": session/created listener rejected: Error: late creation failure',
  969. ])
  970. })
  971. it('contains synchronous and async session/disposed listener failures per observer', async () => {
  972. const ctx = new Context()
  973. await ctx.plugin(SessionStore)
  974. const warnings: string[] = []
  975. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  976. const heard: string[] = []
  977. ctx.on('session/disposed', () => { throw new Error('sync disposed') })
  978. ctx.on('session/disposed', () => Promise.reject(new Error('async disposed')) as never)
  979. ctx.on('session/disposed', (session) => { heard.push(session.id) })
  980. const unannounced = ctx.sessions.prepare(SessionId('never-announced'))
  981. const detachUnannounced = ctx.sessions.enter(unannounced)
  982. detachUnannounced()
  983. expect(heard).toEqual([])
  984. const announced = ctx.sessions.prepare(SessionId('contained-disposal'))
  985. const detach = ctx.sessions.enter(announced)
  986. ctx.sessions.announce(announced)
  987. expect(() => { detach() }).not.toThrow()
  988. await Promise.resolve()
  989. await Promise.resolve()
  990. expect(heard).toEqual(['contained-disposal'])
  991. expect(warnings).toEqual([
  992. 'session "contained-disposal": session/disposed listener threw: Error: sync disposed',
  993. 'session "contained-disposal": session/disposed listener rejected: Error: async disposed',
  994. ])
  995. })
  996. it('contains internal dispatch failure after session detachment', async () => {
  997. const ctx = new Context()
  998. await ctx.plugin(SessionStore)
  999. const warnings: string[] = []
  1000. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  1001. const heard: Session[] = []
  1002. ctx.on('internal/dispatch', (_mode, name) => {
  1003. if (name === 'session/disposed') throw new Error('disposed dispatch instrumentation')
  1004. })
  1005. ctx.on('session/disposed', (session) => { heard.push(session) })
  1006. const session = ctx.sessions.prepare(SessionId('disposed-dispatch'))
  1007. const detach = ctx.sessions.enter(session)
  1008. ctx.sessions.announce(session)
  1009. expect(() => { detach() }).not.toThrow()
  1010. expect(ctx.sessions.get(session.id)).toBeUndefined()
  1011. expect(heard).toEqual([])
  1012. expect(warnings).toEqual([
  1013. 'session "disposed-dispatch": session/disposed dispatch threw: Error: disposed dispatch instrumentation',
  1014. ])
  1015. })
  1016. it('does not let internal dispatch replace the disposed callback tuple', async () => {
  1017. const ctx = new Context()
  1018. await ctx.plugin(SessionStore)
  1019. const replacement = new Session(SessionId('replacement-disposed'))
  1020. const heard: Session[] = []
  1021. ctx.on('internal/dispatch', (_mode, name, args) => {
  1022. if (name === 'session/disposed') args[0] = replacement
  1023. })
  1024. ctx.on('session/disposed', (session) => { heard.push(session) })
  1025. const session = ctx.sessions.prepare(SessionId('fixed-disposed-tuple'))
  1026. const detach = ctx.sessions.enter(session)
  1027. ctx.sessions.announce(session)
  1028. detach()
  1029. expect(heard).toEqual([session])
  1030. })
  1031. })
  1032. describe('todo/write event', () => {
  1033. it('appends the whole-list snapshot and isolates the log from later mutation', () => {
  1034. const session = new Session(SessionId('t1'))
  1035. const todos: TodoItem[] = [
  1036. { content: 'plan the work', status: 'in_progress' },
  1037. { content: 'write the code', status: 'pending' },
  1038. ]
  1039. session.append('todo/write', { todos })
  1040. const event = session.events.findLast(e => e.type === 'todo/write')!
  1041. expect(event.type).toBe('todo/write')
  1042. expect(event.data.todos).toEqual(todos)
  1043. // The append snapshots its input: mutating the caller's array afterward must
  1044. // not change what the log holds (the durable-source-of-truth contract).
  1045. todos.push({ content: 'sneak in', status: 'pending' })
  1046. todos[0]!.status = 'completed'
  1047. expect(event.data.todos).toEqual([
  1048. { content: 'plan the work', status: 'in_progress' },
  1049. { content: 'write the code', status: 'pending' },
  1050. ])
  1051. })
  1052. it('is last-write-wins: the current list is the most recent todo/write', () => {
  1053. const session = new Session(SessionId('t2'))
  1054. session.append('todo/write', { todos: [{ content: 'first', status: 'pending' }] })
  1055. session.append('todo/write', { todos: [
  1056. { content: 'first', status: 'completed' },
  1057. { content: 'second', status: 'in_progress' },
  1058. ] })
  1059. const current = session.events.findLast(e => e.type === 'todo/write')!.data.todos
  1060. expect(current).toEqual([
  1061. { content: 'first', status: 'completed' },
  1062. { content: 'second', status: 'in_progress' },
  1063. ])
  1064. })
  1065. it('is NOT a surface event: it produces no derived message and joins no surface node', () => {
  1066. const session = new Session(SessionId('t3'))
  1067. session.append('user/message', { content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1068. const before = session.deriveMessages().length
  1069. session.append('todo/write', { todos: [{ content: 'a task', status: 'pending' }] })
  1070. // The todo event must not add a message to the derived history…
  1071. expect(session.deriveMessages()).toHaveLength(before)
  1072. // …and must not appear on the surface linked list.
  1073. expect(session.surface.nodes.some(node => node.seq === session.seq - 1)).toBe(false)
  1074. })
  1075. it('round-trips through a seeded replay identically (durable, no surfaceOp needed)', () => {
  1076. const original = new Session(SessionId('t4'))
  1077. original.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  1078. original.append('todo/write', { todos: [{ content: 'only', status: 'completed' }] })
  1079. original.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  1080. // Seeding a non-surface event with no surfaceOp must not throw.
  1081. const replayed = new Session(SessionId('t4-replay'), [...original.events])
  1082. expect(replayed.events.findLast(e => e.type === 'todo/write')!.data.todos)
  1083. .toEqual([{ content: 'only', status: 'completed' }])
  1084. expect(replayed.seq).toBe(original.seq)
  1085. })
  1086. })