surface.spec.ts 20 KB

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