surface.spec.ts 26 KB

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