surface.spec.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. import { describe, expect, it } from 'vitest'
  2. import type { SessionEvent, SurfaceEvent, SurfaceEventType } from '@deepseek-ai/dsh-session'
  3. import {
  4. Session,
  5. SessionId,
  6. foldSurface,
  7. isSurfaceEligibleType,
  8. isSurfaceEvent,
  9. } from '@deepseek-ai/dsh-session'
  10. import { CallId } from '@deepseek-ai/dsh-llm'
  11. /** Build a minimal session with turn boundaries and a single user message. */
  12. function surfaceSession(): Session {
  13. const s = new Session(SessionId('ss'))
  14. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  15. s.append('user/message', { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  16. s.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'hi' }] }, { surfaceOp: 'append' })
  17. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  18. return s
  19. }
  20. function provenanceEvent(seq: number, sourceEventSeqs: unknown): SessionEvent {
  21. return {
  22. type: 'user/message',
  23. seq,
  24. time: seq,
  25. data: { content: [], source: { kind: 'user' } },
  26. surfaceOp: 'append',
  27. ...sourceEventSeqs === undefined ? {} : { sourceEventSeqs },
  28. } as unknown as SessionEvent
  29. }
  30. describe('foldSurface provenance', () => {
  31. it('accepts absent or valid provenance and complete replacement coverage', () => {
  32. const events = [
  33. provenanceEvent(0, undefined),
  34. provenanceEvent(1, undefined),
  35. {
  36. ...provenanceEvent(2, [0, 1]),
  37. surfaceOp: { op: 'replace', start: 0, end: 1 },
  38. },
  39. ] as SessionEvent[]
  40. expect(() => foldSurface(events)).not.toThrow()
  41. })
  42. it('rejects provenance on a non-surface event', () => {
  43. const event = {
  44. type: 'turn/start',
  45. seq: 0,
  46. time: 1,
  47. data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
  48. sourceEventSeqs: [0],
  49. } as unknown as SessionEvent
  50. expect(() => foldSurface([event])).toThrow(/cannot carry sourceEventSeqs/)
  51. })
  52. it('accepts explicit empty provenance on an assistant message', () => {
  53. const event = {
  54. type: 'assistant/message',
  55. seq: 0,
  56. time: 0,
  57. data: {
  58. provenance: { provider: 'mock', model: 'mock' },
  59. turn: 1,
  60. step: 1,
  61. content: [],
  62. },
  63. surfaceOp: 'append',
  64. sourceEventSeqs: [],
  65. } as SessionEvent
  66. expect(() => foldSurface([event])).not.toThrow()
  67. })
  68. it.each([
  69. ['a non-array', [{ ...provenanceEvent(0, undefined), sourceEventSeqs: 'invalid' }], /must be an array/],
  70. ['an empty array', [provenanceEvent(0, [])], /must not be empty/],
  71. ['duplicates', [provenanceEvent(0, undefined), provenanceEvent(1, [0, 0])], /must not contain duplicates/],
  72. ['a sparse array', [provenanceEvent(0, Array<number>(1))], /densely contain/],
  73. ['a non-number', [{ ...provenanceEvent(0, undefined), sourceEventSeqs: ['0'] }], /non-negative safe integers/],
  74. ['a fractional number', [provenanceEvent(0, [0.5])], /non-negative safe integers/],
  75. ['a negative number', [provenanceEvent(0, [-1])], /non-negative safe integers/],
  76. ['a self reference', [provenanceEvent(0, [0])], /must reference earlier events/],
  77. ['a non-contiguous event seq', [provenanceEvent(0, undefined), provenanceEvent(2, [1])], /seq 2 is not contiguous; expected 1/],
  78. ['incomplete replacement coverage', [
  79. provenanceEvent(0, undefined),
  80. provenanceEvent(1, undefined),
  81. { ...provenanceEvent(2, [0]), surfaceOp: { op: 'replace', start: 0, end: 1 } },
  82. ], /missing 1/],
  83. ] as const)(
  84. 'rejects %s',
  85. (_name, events, expected) => {
  86. expect(() => foldSurface(events as unknown as SessionEvent[])).toThrow(expected)
  87. },
  88. )
  89. })
  90. describe('SurfaceManager', () => {
  91. it('shares ordered entries and nested replacement ranges with foldSurface', () => {
  92. const s = new Session(SessionId('shared-fold'))
  93. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  94. s.append('user/message', { content: [{ type: 'text', text: 'b' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  95. s.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'summary' }] }, { surfaceOp: { op: 'replace', start: 0, end: 0 }, sourceEventSeqs: [0] })
  96. s.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 2, content: [{ type: 'text', text: 'summary 2' }] }, { surfaceOp: { op: 'replace', start: 2, end: 1 }, sourceEventSeqs: [2, 1] })
  97. const folded = foldSurface(s.events)
  98. expect(folded.nodes).toEqual(s.surface.nodes)
  99. expect(folded.replacements).toEqual([
  100. { seq: 2, start: 0, end: 0, shadowedSeqs: [0] },
  101. { seq: 3, start: 2, end: 1, shadowedSeqs: [2, 1] },
  102. ])
  103. folded.nodes[0] = 99
  104. folded.replacements[0]!.shadowedSeqs.push(99)
  105. expect(s.surface.nodes).toEqual([3])
  106. expect(foldSurface(s.events).nodes).toEqual([3])
  107. expect(foldSurface(s.events).replacements[0]!.shadowedSeqs).toEqual([0])
  108. })
  109. it('does not retain fold-only replacement history in incremental state', () => {
  110. const s = new Session(SessionId('incremental-state'))
  111. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  112. s.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'b' }] }, { surfaceOp: { op: 'replace', start: 0, end: 0 }, sourceEventSeqs: [0] })
  113. expect(s.surface.nodes).toEqual([1])
  114. const manager = s.surface as unknown as { _state: object }
  115. expect(Object.hasOwn(manager._state, 'replacements')).toBe(false)
  116. expect(foldSurface(s.events).replacements).toEqual([
  117. { seq: 1, start: 0, end: 0, shadowedSeqs: [0] },
  118. ])
  119. })
  120. it('foldSurface reports the same invalid replacement failures as the incremental manager', () => {
  121. const events = [
  122. provenanceEvent(0, undefined),
  123. { ...provenanceEvent(1, [0]), surfaceOp: { op: 'replace', start: 42, end: 0 } },
  124. ] as SessionEvent[]
  125. expect(() => foldSurface(events)).toThrow(/start seq 42 not found/)
  126. expect(() => new Session(SessionId('shared-fold-invalid'), events))
  127. .toThrow(/start seq 42 not found/)
  128. })
  129. it('leaves incremental state unchanged when candidate validation fails', () => {
  130. const s = new Session(SessionId('atomic-validation'))
  131. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  132. const surface = s.surface
  133. const nodes = surface.nodes
  134. expect(nodes).toEqual(foldSurface(s.events).nodes)
  135. expect(surface.replaceGeneration).toBe(0)
  136. expect(() => s.append(
  137. 'assistant/message',
  138. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'invalid' }] },
  139. { surfaceOp: { op: 'replace', start: 0, end: 0 } },
  140. )).toThrow(/missing 0/)
  141. expect(s.events).toHaveLength(1)
  142. expect(s.surface).toBe(surface)
  143. expect(surface.nodes).toEqual([0])
  144. expect(surface.replaceGeneration).toBe(0)
  145. expect(surface.nodes).toEqual(foldSurface(s.events).nodes)
  146. s.append('user/message', { content: [{ type: 'text', text: 'b' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  147. expect(surface.nodes).toBe(nodes)
  148. expect(surface.nodes).toEqual([0, 1])
  149. expect(surface.replaceGeneration).toBe(0)
  150. expect(surface.nodes).toEqual(foldSurface(s.events).nodes)
  151. })
  152. it('foldSurface rejects a surface-eligible event without its mandatory marker', () => {
  153. const malformed: SessionEvent = {
  154. type: 'user/message',
  155. seq: 0,
  156. time: 1,
  157. data: { content: [{ type: 'text', text: 'hidden' }], source: { kind: 'user' } },
  158. }
  159. expect(() => foldSurface([malformed]))
  160. .toThrow(/surface-eligible and requires a surfaceOp marker/)
  161. })
  162. it('foldSurface rejects surfaceOp on a non-surface event', () => {
  163. const malformed = {
  164. type: 'turn/start',
  165. seq: 0,
  166. time: 1,
  167. data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
  168. surfaceOp: 'append',
  169. } as unknown as SessionEvent
  170. expect(() => foldSurface([malformed]))
  171. .toThrow(/not surface-eligible and cannot carry surfaceOp/)
  172. })
  173. it('folds an ordered sequence list from surfaceOp: append markers', () => {
  174. const s = surfaceSession()
  175. const nodes = s.surface.nodes
  176. // Only the user/message and assistant/message carry surfaceOp: 'append'.
  177. // The turn boundaries do not have surface markers.
  178. expect(nodes).toEqual([1, 2])
  179. })
  180. it('empty surface yields empty nodes', () => {
  181. const s = new Session(SessionId('empty'))
  182. // Only turn boundaries, no surface nodes.
  183. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  184. s.append('step/start', { turn: 1, step: 1 })
  185. s.append('step/end', { turn: 1, step: 1 })
  186. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  187. expect(s.surface.nodes.length).toBe(0)
  188. // deriveMessages returns empty array
  189. expect(s.deriveMessages()).toEqual([])
  190. })
  191. it('picks up new events incrementally (delta processing)', () => {
  192. const s = surfaceSession()
  193. expect(s.surface.nodes.length).toBe(2)
  194. // Append another surface node
  195. s.append('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'ok' }], isError: false }, { surfaceOp: 'append' })
  196. expect(s.surface.nodes.length).toBe(3)
  197. expect(s.surface.nodes[2]!).toBe(4) // seq 4: after turn/end at seq 3
  198. })
  199. it('replays identically from a seeded log with surface markers', () => {
  200. const original = surfaceSession()
  201. original.append('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'ok' }], isError: false }, { surfaceOp: 'append' })
  202. const replayed = new Session(SessionId('replay'), [...original.events])
  203. // Surface rebuilds from the seeded log's markers.
  204. expect(replayed.surface.nodes).toEqual([1, 2, 4])
  205. expect(replayed.deriveMessages()).toEqual(original.deriveMessages())
  206. })
  207. it('rebuild with replace operation splices out shadowed nodes', () => {
  208. const s = surfaceSession()
  209. s.append('assistant/message',
  210. { provenance: { provider: 'mock', model: 'mock' }, turn: 2, step: 1, content: [{ type: 'text', text: 'summary' }] },
  211. { surfaceOp: { op: 'replace', start: 1, end: 2 }, sourceEventSeqs: [1, 2] },
  212. )
  213. expect(s.surface.nodes).toEqual([4])
  214. })
  215. it('replace with both ends at real nodes splices only the range', () => {
  216. const s = new Session(SessionId('range'))
  217. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 0
  218. s.append('user/message', { content: [{ type: 'text', text: 'b' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 1
  219. s.append('user/message', { content: [{ type: 'text', text: 'c' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 2
  220. // Replace seq 0 through 1 inclusive: shadow a and b, keep c.
  221. s.append('assistant/message',
  222. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'summary' }] },
  223. { surfaceOp: { op: 'replace', start: 0, end: 1 }, sourceEventSeqs: [0, 1] },
  224. ) // seq 3
  225. expect(s.surface.nodes).toEqual([3, 2])
  226. })
  227. it('single-node replacement (start === end)', () => {
  228. const s = new Session(SessionId('single'))
  229. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 0
  230. s.append('user/message', { content: [{ type: 'text', text: 'b' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 1
  231. // Replace only seq 1 (single node).
  232. s.append('assistant/message',
  233. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'x' }] },
  234. { surfaceOp: { op: 'replace', start: 1, end: 1 }, sourceEventSeqs: [1] },
  235. ) // seq 2
  236. expect(s.surface.nodes).toEqual([0, 2])
  237. })
  238. it('throws when replace start is not found', () => {
  239. const s = new Session(SessionId('bad-start'))
  240. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 0
  241. expect(() => s.append('assistant/message',
  242. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'y' }] },
  243. { surfaceOp: { op: 'replace', start: 5, end: 0 }, sourceEventSeqs: [0] },
  244. )).toThrow(/surface replace: start seq 5 not found/)
  245. })
  246. it('throws when replace end is not found', () => {
  247. const s = new Session(SessionId('bad-end'))
  248. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 0
  249. expect(() => s.append('assistant/message',
  250. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'y' }] },
  251. { surfaceOp: { op: 'replace', start: 0, end: 99 }, sourceEventSeqs: [0] },
  252. )).toThrow(/surface replace: end seq 99 not found/)
  253. })
  254. it('throws when start is after end', () => {
  255. const s = new Session(SessionId('reversed'))
  256. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 0
  257. s.append('user/message', { content: [{ type: 'text', text: 'b' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 1
  258. // start=1, end=0 would be reversed order.
  259. expect(() => s.append('assistant/message',
  260. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'y' }] },
  261. { surfaceOp: { op: 'replace', start: 1, end: 0 }, sourceEventSeqs: [1, 0] },
  262. )).toThrow(/start seq 1.*after end seq 0/)
  263. })
  264. it('sourceEventSeqs is snapshot so caller mutation does not affect logged event', () => {
  265. const s = new Session(SessionId('immutable'))
  266. s.append('user/message', { content: [{ type: 'text', text: 'source' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  267. const sources = [0]
  268. s.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'h' }] }, { surfaceOp: 'append', sourceEventSeqs: sources })
  269. // Mutate caller's array after append.
  270. sources.push(1)
  271. sources[0] = 99
  272. const logged = s.events[1]! as SurfaceEvent
  273. expect(logged.sourceEventSeqs).toEqual([0])
  274. })
  275. it('replace starting at non-head position preserves surrounding order', () => {
  276. const s = new Session(SessionId('mid-replace'))
  277. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 0
  278. s.append('user/message', { content: [{ type: 'text', text: 'b' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 1
  279. s.append('user/message', { content: [{ type: 'text', text: 'c' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 2
  280. // Replace the middle node (seq 1) only, keeping seq 0 and seq 2.
  281. s.append('assistant/message',
  282. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'x' }] },
  283. { surfaceOp: { op: 'replace', start: 1, end: 1 }, sourceEventSeqs: [1] },
  284. ) // seq 3
  285. expect(s.surface.nodes).toEqual([0, 3, 2])
  286. })
  287. it('surfaceOp replace object is snapshot so caller mutation is isolated', () => {
  288. const s = new Session(SessionId('immutable-op'))
  289. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  290. const op = { op: 'replace' as const, start: 0, end: 0 }
  291. s.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 's' }] }, { surfaceOp: op, sourceEventSeqs: [0] })
  292. // Mutate caller's object after append.
  293. op.start = 99
  294. const logged = s.events[1]! as SurfaceEvent
  295. expect(logged.surfaceOp).toEqual({ op: 'replace', start: 0, end: 0 })
  296. })
  297. })
  298. describe('deriveMessages with surface', () => {
  299. it('uses the surface path when surface markers are present', () => {
  300. const s = surfaceSession()
  301. const messages = s.deriveMessages()
  302. expect(messages).toHaveLength(2)
  303. expect(messages[0]!.role).toBe('user')
  304. expect(messages[0]!.content[0]).toMatchObject({ type: 'text', text: 'hello' })
  305. expect(messages[1]!.role).toBe('assistant')
  306. expect(messages[1]!.content[0]).toMatchObject({ type: 'text', text: 'hi' })
  307. })
  308. it('surface path skips non-surface events (chunks, boundaries)', () => {
  309. const s = new Session(SessionId('filter'))
  310. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  311. s.append('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'h' } })
  312. s.append('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'text-delta', index: 1, text: 'i' } })
  313. s.append('user/message', { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  314. s.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'hi' }] }, { surfaceOp: 'append' })
  315. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  316. // Chunks and boundaries are NOT in the surface, so only 2 messages.
  317. expect(s.deriveMessages()).toHaveLength(2)
  318. })
  319. it('deriveMessages via surface respects replace (shadowed nodes are excluded)', () => {
  320. const s = new Session(SessionId('compacted'))
  321. s.append('user/message', { content: [{ type: 'text', text: 'original' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  322. s.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'compacted' }] }, { surfaceOp: { op: 'replace', start: 0, end: 0 }, sourceEventSeqs: [0] })
  323. // Only the compaction node is visible.
  324. const messages = s.deriveMessages()
  325. expect(messages).toHaveLength(1)
  326. expect(messages[0]!.content[0]).toMatchObject({ type: 'text', text: 'compacted' })
  327. })
  328. it('context/message and steering/message appear on surface', () => {
  329. const s = new Session(SessionId('ctx'))
  330. s.append('context/message', { content: [{ type: 'text', text: 'file changed' }], source: { kind: 'plugin', plugin: 'watcher' } }, { surfaceOp: 'append' })
  331. s.append('steering/message', { turn: 1, content: [{ type: 'text', text: 'focus' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  332. const messages = s.deriveMessages()
  333. expect(messages).toHaveLength(2)
  334. expect(messages[0]!.content).toEqual([{ type: 'text', text: 'file changed' }])
  335. expect(messages[1]!.content).toEqual([{ type: 'text', text: 'focus' }])
  336. })
  337. })
  338. describe('Session.append surface opts', () => {
  339. it('records sourceEventSeqs and surfaceOp on the event', () => {
  340. const s = new Session(SessionId('opts'))
  341. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  342. s.append('step/start', { turn: 1, step: 1 })
  343. const event = s.append('assistant/message',
  344. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'h' }] },
  345. { surfaceOp: 'append', sourceEventSeqs: [0, 1] },
  346. )
  347. expect(event.sourceEventSeqs).toEqual([0, 1])
  348. expect(event.surfaceOp).toBe('append')
  349. // The logged event matches the returned event.
  350. expect((s.events[2]! as SurfaceEvent).sourceEventSeqs).toEqual([0, 1])
  351. expect((s.events[2]! as SurfaceEvent).surfaceOp).toBe('append')
  352. })
  353. it('deriveMessages skips a surface node that derives to null (empty assistant/message)', () => {
  354. // An empty-content assistant/message is surface-eligible (it can host usage)
  355. // but _deriveOneMessage returns null for it, so the surface derivation path's
  356. // null-check is exercised — the node is on the surface yet produces no message.
  357. const seed: SessionEvent[] = [
  358. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  359. { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } },
  360. { type: 'assistant/message', seq: 2, time: 3, data: { turn: 1, step: 1, content: [], provenance: { provider: 'mock', model: 'mock' } }, surfaceOp: 'append' },
  361. { type: 'step/end', seq: 3, time: 4, data: { turn: 1, step: 1 } },
  362. { type: 'turn/end', seq: 4, time: 5, data: { turn: 1, reason: { kind: 'completed' } } },
  363. ]
  364. const s = new Session(SessionId('nomessage'), seed)
  365. // The empty assistant/message is on the surface but _deriveOneMessage returns null for it.
  366. expect(s.deriveMessages()).toHaveLength(0)
  367. })
  368. it('a non-surface event carries no surface fields', () => {
  369. const s = new Session(SessionId('noopts'))
  370. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  371. expect((s.events[0] as SessionEvent<SurfaceEventType>).sourceEventSeqs).toBeUndefined()
  372. expect((s.events[0] as SessionEvent<SurfaceEventType>).surfaceOp).toBeUndefined()
  373. })
  374. it('surfaceOp primitives are not cloned (they are immutable)', () => {
  375. const s = new Session(SessionId('prim'))
  376. const event = s.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [] }, { surfaceOp: 'append' })
  377. // The string 'append' is a primitive — identity-preserving is fine.
  378. expect(event.surfaceOp).toBe('append')
  379. })
  380. it('isSurfaceEvent rejects a surface-eligible type missing its surfaceOp marker', () => {
  381. // A raw event (not built via append, which mandates the marker) of a
  382. // surface-eligible type but with no surfaceOp must NOT narrow to a
  383. // SurfaceEvent — it would otherwise be silently dropped from the surface.
  384. const noMarker: SessionEvent = {
  385. type: 'user/message', seq: 0, time: 1,
  386. data: { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } },
  387. }
  388. expect(isSurfaceEvent(noMarker)).toBe(false)
  389. // A non-surface type is rejected too (the type gate).
  390. const boundary: SessionEvent = { type: 'turn/start', seq: 1, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }
  391. expect(isSurfaceEvent(boundary)).toBe(false)
  392. // A properly-marked surface event narrows.
  393. const marked = { ...noMarker, surfaceOp: 'append' } as SurfaceEvent
  394. expect(isSurfaceEvent(marked)).toBe(true)
  395. })
  396. })
  397. describe('surface type guards', () => {
  398. it('isSurfaceEligibleType is true only for message-producing types', () => {
  399. expect(isSurfaceEligibleType('user/message')).toBe(true)
  400. expect(isSurfaceEligibleType('assistant/message')).toBe(true)
  401. expect(isSurfaceEligibleType('tool/result')).toBe(true)
  402. expect(isSurfaceEligibleType('context/message')).toBe(true)
  403. expect(isSurfaceEligibleType('steering/message')).toBe(true)
  404. expect(isSurfaceEligibleType('turn/start')).toBe(false)
  405. expect(isSurfaceEligibleType('assistant/chunk')).toBe(false)
  406. })
  407. it('isSurfaceEvent narrows a fully-formed surface event', () => {
  408. const s = surfaceSession()
  409. const userMessage = s.events.find(e => e.type === 'user/message')!
  410. expect(isSurfaceEvent(userMessage)).toBe(true)
  411. })
  412. it('isSurfaceEvent rejects a non-surface-eligible type', () => {
  413. const s = surfaceSession()
  414. const turnStart = s.events.find(e => e.type === 'turn/start')!
  415. expect(isSurfaceEvent(turnStart)).toBe(false)
  416. })
  417. it('isSurfaceEvent rejects a surface-eligible type missing its surfaceOp marker', () => {
  418. // A surface-eligible type whose mandatory surfaceOp is absent — the state a
  419. // seed/load log can carry before the marker is validated. surfaceOp is
  420. // optional on SessionEvent, so this is a representable runtime value.
  421. const markerless: SessionEvent = {
  422. type: 'user/message',
  423. seq: 0,
  424. time: 0,
  425. data: { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } },
  426. }
  427. expect(isSurfaceEligibleType(markerless.type)).toBe(true)
  428. expect(isSurfaceEvent(markerless)).toBe(false)
  429. })
  430. })
  431. describe('SurfaceManager.replaceGeneration', () => {
  432. it('folds the pending log delta on access and counts replaces', () => {
  433. const s = new Session(SessionId('gen'))
  434. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  435. s.append('user/message', { content: [{ type: 'text', text: 'one' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  436. s.append('user/message', { content: [{ type: 'text', text: 'two' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  437. // Read the generation FIRST — before nodes — so the getter itself folds
  438. // the pending delta rather than piggybacking on a nodes read.
  439. expect(s.surface.replaceGeneration).toBe(0)
  440. const nodes = s.surface.nodes
  441. s.append('context/message', {
  442. content: [{ type: 'text', text: 'summary' }], source: { kind: 'plugin', plugin: 'compact' },
  443. }, { surfaceOp: { op: 'replace', start: nodes[0]!, end: nodes[1]! }, sourceEventSeqs: [nodes[0]!, nodes[1]!] })
  444. expect(s.surface.replaceGeneration).toBe(1)
  445. })
  446. })