surface.spec.ts 18 KB

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