surface.spec.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. expect(() => s.append(
  133. 'assistant/message',
  134. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'invalid' }] },
  135. { surfaceOp: { op: 'replace', start: 0, end: 0 } },
  136. )).toThrow(/missing 0/)
  137. expect(s.events).toHaveLength(1)
  138. s.append('user/message', { content: [{ type: 'text', text: 'b' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  139. expect(s.surface.nodes).toEqual([0, 1])
  140. })
  141. it('foldSurface rejects a surface-eligible event without its mandatory marker', () => {
  142. const malformed: SessionEvent = {
  143. type: 'user/message',
  144. seq: 0,
  145. time: 1,
  146. data: { content: [{ type: 'text', text: 'hidden' }], source: { kind: 'user' } },
  147. }
  148. expect(() => foldSurface([malformed]))
  149. .toThrow(/surface-eligible and requires a surfaceOp marker/)
  150. })
  151. it('foldSurface rejects surfaceOp on a non-surface event', () => {
  152. const malformed = {
  153. type: 'turn/start',
  154. seq: 0,
  155. time: 1,
  156. data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
  157. surfaceOp: 'append',
  158. } as unknown as SessionEvent
  159. expect(() => foldSurface([malformed]))
  160. .toThrow(/not surface-eligible and cannot carry surfaceOp/)
  161. })
  162. it('folds an ordered sequence list from surfaceOp: append markers', () => {
  163. const s = surfaceSession()
  164. const nodes = s.surface.nodes
  165. // Only the user/message and assistant/message carry surfaceOp: 'append'.
  166. // The turn boundaries do not have surface markers.
  167. expect(nodes).toEqual([1, 2])
  168. })
  169. it('empty surface yields empty nodes', () => {
  170. const s = new Session(SessionId('empty'))
  171. // Only turn boundaries, no surface nodes.
  172. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  173. s.append('step/start', { turn: 1, step: 1 })
  174. s.append('step/end', { turn: 1, step: 1 })
  175. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  176. expect(s.surface.nodes.length).toBe(0)
  177. // deriveMessages returns empty array
  178. expect(s.deriveMessages()).toEqual([])
  179. })
  180. it('picks up new events incrementally (delta processing)', () => {
  181. const s = surfaceSession()
  182. expect(s.surface.nodes.length).toBe(2)
  183. // Append another surface node
  184. s.append('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'ok' }], isError: false }, { surfaceOp: 'append' })
  185. expect(s.surface.nodes.length).toBe(3)
  186. expect(s.surface.nodes[2]!).toBe(4) // seq 4: after turn/end at seq 3
  187. })
  188. it('replays identically from a seeded log with surface markers', () => {
  189. const original = surfaceSession()
  190. original.append('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'ok' }], isError: false }, { surfaceOp: 'append' })
  191. const replayed = new Session(SessionId('replay'), [...original.events])
  192. // Surface rebuilds from the seeded log's markers.
  193. expect(replayed.surface.nodes).toEqual([1, 2, 4])
  194. expect(replayed.deriveMessages()).toEqual(original.deriveMessages())
  195. })
  196. it('rebuild with replace operation splices out shadowed nodes', () => {
  197. const s = surfaceSession()
  198. s.append('assistant/message',
  199. { provenance: { provider: 'mock', model: 'mock' }, turn: 2, step: 1, content: [{ type: 'text', text: 'summary' }] },
  200. { surfaceOp: { op: 'replace', start: 1, end: 2 }, sourceEventSeqs: [1, 2] },
  201. )
  202. expect(s.surface.nodes).toEqual([4])
  203. })
  204. it('replace with both ends at real nodes splices only the range', () => {
  205. const s = new Session(SessionId('range'))
  206. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 0
  207. s.append('user/message', { content: [{ type: 'text', text: 'b' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 1
  208. s.append('user/message', { content: [{ type: 'text', text: 'c' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 2
  209. // Replace seq 0 through 1 inclusive: shadow a and b, keep c.
  210. s.append('assistant/message',
  211. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'summary' }] },
  212. { surfaceOp: { op: 'replace', start: 0, end: 1 }, sourceEventSeqs: [0, 1] },
  213. ) // seq 3
  214. expect(s.surface.nodes).toEqual([3, 2])
  215. })
  216. it('single-node replacement (start === end)', () => {
  217. const s = new Session(SessionId('single'))
  218. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 0
  219. s.append('user/message', { content: [{ type: 'text', text: 'b' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 1
  220. // Replace only seq 1 (single node).
  221. s.append('assistant/message',
  222. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'x' }] },
  223. { surfaceOp: { op: 'replace', start: 1, end: 1 }, sourceEventSeqs: [1] },
  224. ) // seq 2
  225. expect(s.surface.nodes).toEqual([0, 2])
  226. })
  227. it('throws when replace start is not found', () => {
  228. const s = new Session(SessionId('bad-start'))
  229. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 0
  230. expect(() => s.append('assistant/message',
  231. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'y' }] },
  232. { surfaceOp: { op: 'replace', start: 5, end: 0 }, sourceEventSeqs: [0] },
  233. )).toThrow(/surface replace: start seq 5 not found/)
  234. })
  235. it('throws when replace end is not found', () => {
  236. const s = new Session(SessionId('bad-end'))
  237. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 0
  238. expect(() => s.append('assistant/message',
  239. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'y' }] },
  240. { surfaceOp: { op: 'replace', start: 0, end: 99 }, sourceEventSeqs: [0] },
  241. )).toThrow(/surface replace: end seq 99 not found/)
  242. })
  243. it('throws when start is after end', () => {
  244. const s = new Session(SessionId('reversed'))
  245. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 0
  246. s.append('user/message', { content: [{ type: 'text', text: 'b' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 1
  247. // start=1, end=0 would be reversed order.
  248. expect(() => s.append('assistant/message',
  249. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'y' }] },
  250. { surfaceOp: { op: 'replace', start: 1, end: 0 }, sourceEventSeqs: [1, 0] },
  251. )).toThrow(/start seq 1.*after end seq 0/)
  252. })
  253. it('sourceEventSeqs is snapshot so caller mutation does not affect logged event', () => {
  254. const s = new Session(SessionId('immutable'))
  255. s.append('user/message', { content: [{ type: 'text', text: 'source' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  256. const sources = [0]
  257. s.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'h' }] }, { surfaceOp: 'append', sourceEventSeqs: sources })
  258. // Mutate caller's array after append.
  259. sources.push(1)
  260. sources[0] = 99
  261. const logged = s.events[1]! as SurfaceEvent
  262. expect(logged.sourceEventSeqs).toEqual([0])
  263. })
  264. it('replace starting at non-head position preserves surrounding order', () => {
  265. const s = new Session(SessionId('mid-replace'))
  266. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 0
  267. s.append('user/message', { content: [{ type: 'text', text: 'b' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 1
  268. s.append('user/message', { content: [{ type: 'text', text: 'c' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) // seq 2
  269. // Replace the middle node (seq 1) only, keeping seq 0 and seq 2.
  270. s.append('assistant/message',
  271. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'x' }] },
  272. { surfaceOp: { op: 'replace', start: 1, end: 1 }, sourceEventSeqs: [1] },
  273. ) // seq 3
  274. expect(s.surface.nodes).toEqual([0, 3, 2])
  275. })
  276. it('surfaceOp replace object is snapshot so caller mutation is isolated', () => {
  277. const s = new Session(SessionId('immutable-op'))
  278. s.append('user/message', { content: [{ type: 'text', text: 'a' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  279. const op = { op: 'replace' as const, start: 0, end: 0 }
  280. s.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 's' }] }, { surfaceOp: op, sourceEventSeqs: [0] })
  281. // Mutate caller's object after append.
  282. op.start = 99
  283. const logged = s.events[1]! as SurfaceEvent
  284. expect(logged.surfaceOp).toEqual({ op: 'replace', start: 0, end: 0 })
  285. })
  286. })
  287. describe('deriveMessages with surface', () => {
  288. it('uses the surface path when surface markers are present', () => {
  289. const s = surfaceSession()
  290. const messages = s.deriveMessages()
  291. expect(messages).toHaveLength(2)
  292. expect(messages[0]!.role).toBe('user')
  293. expect(messages[0]!.content[0]).toMatchObject({ type: 'text', text: 'hello' })
  294. expect(messages[1]!.role).toBe('assistant')
  295. expect(messages[1]!.content[0]).toMatchObject({ type: 'text', text: 'hi' })
  296. })
  297. it('surface path skips non-surface events (chunks, boundaries)', () => {
  298. const s = new Session(SessionId('filter'))
  299. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  300. s.append('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'h' } })
  301. s.append('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'text-delta', index: 1, text: 'i' } })
  302. s.append('user/message', { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  303. s.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'hi' }] }, { surfaceOp: 'append' })
  304. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  305. // Chunks and boundaries are NOT in the surface, so only 2 messages.
  306. expect(s.deriveMessages()).toHaveLength(2)
  307. })
  308. it('deriveMessages via surface respects replace (shadowed nodes are excluded)', () => {
  309. const s = new Session(SessionId('compacted'))
  310. s.append('user/message', { content: [{ type: 'text', text: 'original' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  311. 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] })
  312. // Only the compaction node is visible.
  313. const messages = s.deriveMessages()
  314. expect(messages).toHaveLength(1)
  315. expect(messages[0]!.content[0]).toMatchObject({ type: 'text', text: 'compacted' })
  316. })
  317. it('context/message and steering/message appear on surface', () => {
  318. const s = new Session(SessionId('ctx'))
  319. s.append('context/message', { content: [{ type: 'text', text: 'file changed' }], source: { kind: 'plugin', plugin: 'watcher' } }, { surfaceOp: 'append' })
  320. s.append('steering/message', { turn: 1, content: [{ type: 'text', text: 'focus' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  321. const messages = s.deriveMessages()
  322. expect(messages).toHaveLength(2)
  323. expect(messages[0]!.content[0]).toMatchObject({ type: 'text', text: '<context source="plugin">' })
  324. expect(messages[1]!.content[0]).toMatchObject({ type: 'text', text: '<steering source="user">' })
  325. })
  326. })
  327. describe('Session.append surface opts', () => {
  328. it('records sourceEventSeqs and surfaceOp on the event', () => {
  329. const s = new Session(SessionId('opts'))
  330. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  331. s.append('step/start', { turn: 1, step: 1 })
  332. const event = s.append('assistant/message',
  333. { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'h' }] },
  334. { surfaceOp: 'append', sourceEventSeqs: [0, 1] },
  335. )
  336. expect(event.sourceEventSeqs).toEqual([0, 1])
  337. expect(event.surfaceOp).toBe('append')
  338. // The logged event matches the returned event.
  339. expect((s.events[2]! as SurfaceEvent).sourceEventSeqs).toEqual([0, 1])
  340. expect((s.events[2]! as SurfaceEvent).surfaceOp).toBe('append')
  341. })
  342. it('deriveMessages skips a surface node that derives to null (empty assistant/message)', () => {
  343. // An empty-content assistant/message is surface-eligible (it can host usage)
  344. // but _deriveOneMessage returns null for it, so the surface derivation path's
  345. // null-check is exercised — the node is on the surface yet produces no message.
  346. const seed: SessionEvent[] = [
  347. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  348. { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } },
  349. { type: 'assistant/message', seq: 2, time: 3, data: { turn: 1, step: 1, content: [], provenance: { provider: 'mock', model: 'mock' } }, surfaceOp: 'append' },
  350. { type: 'step/end', seq: 3, time: 4, data: { turn: 1, step: 1 } },
  351. { type: 'turn/end', seq: 4, time: 5, data: { turn: 1, reason: { kind: 'completed' } } },
  352. ]
  353. const s = new Session(SessionId('nomessage'), seed)
  354. // The empty assistant/message is on the surface but _deriveOneMessage returns null for it.
  355. expect(s.deriveMessages()).toHaveLength(0)
  356. })
  357. it('a non-surface event carries no surface fields', () => {
  358. const s = new Session(SessionId('noopts'))
  359. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  360. expect((s.events[0] as SessionEvent<SurfaceEventType>).sourceEventSeqs).toBeUndefined()
  361. expect((s.events[0] as SessionEvent<SurfaceEventType>).surfaceOp).toBeUndefined()
  362. })
  363. it('surfaceOp primitives are not cloned (they are immutable)', () => {
  364. const s = new Session(SessionId('prim'))
  365. const event = s.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [] }, { surfaceOp: 'append' })
  366. // The string 'append' is a primitive — identity-preserving is fine.
  367. expect(event.surfaceOp).toBe('append')
  368. })
  369. it('isSurfaceEvent rejects a surface-eligible type missing its surfaceOp marker', () => {
  370. // A raw event (not built via append, which mandates the marker) of a
  371. // surface-eligible type but with no surfaceOp must NOT narrow to a
  372. // SurfaceEvent — it would otherwise be silently dropped from the surface.
  373. const noMarker: SessionEvent = {
  374. type: 'user/message', seq: 0, time: 1,
  375. data: { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } },
  376. }
  377. expect(isSurfaceEvent(noMarker)).toBe(false)
  378. // A non-surface type is rejected too (the type gate).
  379. const boundary: SessionEvent = { type: 'turn/start', seq: 1, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }
  380. expect(isSurfaceEvent(boundary)).toBe(false)
  381. // A properly-marked surface event narrows.
  382. const marked = { ...noMarker, surfaceOp: 'append' } as SurfaceEvent
  383. expect(isSurfaceEvent(marked)).toBe(true)
  384. })
  385. })
  386. describe('surface type guards', () => {
  387. it('isSurfaceEligibleType is true only for message-producing types', () => {
  388. expect(isSurfaceEligibleType('user/message')).toBe(true)
  389. expect(isSurfaceEligibleType('assistant/message')).toBe(true)
  390. expect(isSurfaceEligibleType('tool/result')).toBe(true)
  391. expect(isSurfaceEligibleType('context/message')).toBe(true)
  392. expect(isSurfaceEligibleType('steering/message')).toBe(true)
  393. expect(isSurfaceEligibleType('turn/start')).toBe(false)
  394. expect(isSurfaceEligibleType('assistant/chunk')).toBe(false)
  395. })
  396. it('isSurfaceEvent narrows a fully-formed surface event', () => {
  397. const s = surfaceSession()
  398. const userMessage = s.events.find(e => e.type === 'user/message')!
  399. expect(isSurfaceEvent(userMessage)).toBe(true)
  400. })
  401. it('isSurfaceEvent rejects a non-surface-eligible type', () => {
  402. const s = surfaceSession()
  403. const turnStart = s.events.find(e => e.type === 'turn/start')!
  404. expect(isSurfaceEvent(turnStart)).toBe(false)
  405. })
  406. it('isSurfaceEvent rejects a surface-eligible type missing its surfaceOp marker', () => {
  407. // A surface-eligible type whose mandatory surfaceOp is absent — the state a
  408. // seed/load log can carry before the marker is validated. surfaceOp is
  409. // optional on SessionEvent, so this is a representable runtime value.
  410. const markerless: SessionEvent = {
  411. type: 'user/message',
  412. seq: 0,
  413. time: 0,
  414. data: { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } },
  415. }
  416. expect(isSurfaceEligibleType(markerless.type)).toBe(true)
  417. expect(isSurfaceEvent(markerless)).toBe(false)
  418. })
  419. })
  420. describe('SurfaceManager.replaceGeneration', () => {
  421. it('folds the pending log delta on access and counts replaces', () => {
  422. const s = new Session(SessionId('gen'))
  423. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  424. s.append('user/message', { content: [{ type: 'text', text: 'one' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  425. s.append('user/message', { content: [{ type: 'text', text: 'two' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  426. // Read the generation FIRST — before nodes — so the getter itself folds
  427. // the pending delta rather than piggybacking on a nodes read.
  428. expect(s.surface.replaceGeneration).toBe(0)
  429. const nodes = s.surface.nodes
  430. s.append('context/message', {
  431. content: [{ type: 'text', text: 'summary' }], source: { kind: 'plugin', plugin: 'compact' },
  432. }, { surfaceOp: { op: 'replace', start: nodes[0]!, end: nodes[1]! }, sourceEventSeqs: [nodes[0]!, nodes[1]!] })
  433. expect(s.surface.replaceGeneration).toBe(1)
  434. })
  435. })