surface.spec.ts 19 KB

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