conversation-node-definitions.client.spec.ts 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258
  1. import { describe, expect, it } from 'vitest'
  2. import type {
  3. ChatConversationViewNode, ChatSnapshot,
  4. } from '@deepseek-ai/dsh-client-ui-chat/client'
  5. import type {
  6. SessionEventLikeEntry, SessionLiveEventEntry,
  7. } from '@deepseek-ai/dsh-api-session-controller/client'
  8. import {
  9. ConversationNodeAssembler,
  10. type ConversationNodeDefinition,
  11. type ConversationViewDefinition,
  12. } from '@deepseek-ai/dsh-client-ui-conversation/client'
  13. import type { SessionEvent } from '@deepseek-ai/dsh-session/types'
  14. import { AssistantStreamAccumulator } from '@deepseek-ai/dsh-llm/assistant-stream'
  15. import type { StreamChunk } from '@deepseek-ai/dsh-llm'
  16. import { hasAssistantReplyContent } from '../src/client/contract/assistant-content.ts'
  17. import { assistantDefinition } from '../src/client/conversation-nodes/assistant.ts'
  18. import { chatViewDefinition } from '../src/client/conversation-nodes/chat-snapshot-builder.ts'
  19. import { commandDefinition } from '../src/client/conversation-nodes/command.ts'
  20. import { compactionDefinition } from '../src/client/conversation-nodes/compaction.ts'
  21. import { unknownFallbackDefinition } from '../src/client/conversation-nodes/fallback.ts'
  22. import { nextStepInboxDefinition } from '../src/client/conversation-nodes/inbox.ts'
  23. import { messageDefinition } from '../src/client/conversation-nodes/message.ts'
  24. import { inspectRequestPrompt } from '@deepseek-ai/dsh-client-ui-conversation/client'
  25. import { requestPromptDefinition, systemMessageDefinition } from '../src/client/conversation-nodes/request-prompt.ts'
  26. import { retryDefinition } from '../src/client/conversation-nodes/retry.ts'
  27. import { toolDefinition } from '../src/client/conversation-nodes/tool.ts'
  28. import { turnErrorDefinition } from '../src/client/conversation-nodes/turn-error.ts'
  29. import { turnMaxTokensDefinition } from '../src/client/conversation-nodes/turn-max-tokens.ts'
  30. import { turnTailDefinition } from '../src/client/conversation-nodes/turn-tail.ts'
  31. import { turnProcessDefinition } from '../src/client/conversation-nodes/turn-process.ts'
  32. import type {
  33. AssistantChatData, ManualCompactionChatData, RetryChatData, ToolChatData, TurnTailChatData,
  34. } from '../src/client/contract/chat-nodes.ts'
  35. const DEFINITIONS: readonly ConversationNodeDefinition[] = [
  36. nextStepInboxDefinition,
  37. messageDefinition,
  38. systemMessageDefinition,
  39. requestPromptDefinition(inspectRequestPrompt),
  40. assistantDefinition,
  41. turnProcessDefinition,
  42. toolDefinition,
  43. commandDefinition,
  44. compactionDefinition,
  45. retryDefinition,
  46. turnErrorDefinition,
  47. turnMaxTokensDefinition,
  48. turnTailDefinition,
  49. ]
  50. class TestEventDefinitions {
  51. entries(): readonly ConversationNodeDefinition[] {
  52. return DEFINITIONS
  53. }
  54. fallbackEntry(): ConversationNodeDefinition {
  55. return unknownFallbackDefinition
  56. }
  57. }
  58. class TestViewDefinitions {
  59. entries(): readonly ConversationViewDefinition[] {
  60. return [chatViewDefinition]
  61. }
  62. }
  63. function at(
  64. seq: number,
  65. type: string,
  66. data: unknown,
  67. extra: Record<string, unknown> = {},
  68. ): SessionLiveEventEntry {
  69. const payload = type === 'assistant/message' && typeof data === 'object' && data !== null
  70. ? { ...(data as Record<string, unknown>), stream: (data as { stream?: unknown }).stream ?? [] }
  71. : data
  72. return {
  73. type: 'event',
  74. event: {
  75. seq,
  76. time: 1_700_000_000_000 + seq,
  77. type,
  78. data: payload,
  79. ...extra,
  80. } as unknown as SessionEvent,
  81. }
  82. }
  83. function packedInputs(entries: readonly SessionLiveEventEntry[]): SessionEventLikeEntry[] {
  84. const output: SessionEventLikeEntry[] = []
  85. let active: {
  86. readonly turn: number
  87. readonly step: number
  88. readonly stream: AssistantStreamAccumulator
  89. last: SessionLiveEventEntry
  90. } | undefined
  91. const flush = (): void => {
  92. if (active === undefined) return
  93. output.push(at(active.last.event.seq, 'assistant/attempt', {
  94. turn: active.turn,
  95. step: active.step,
  96. stream: active.stream.snapshot(),
  97. }, { time: active.last.event.time }))
  98. active = undefined
  99. }
  100. for (const entry of entries) {
  101. const event = entry.event as unknown as {
  102. readonly type: string
  103. readonly time: number
  104. readonly data: { readonly turn?: number; readonly step?: number; readonly chunk?: StreamChunk }
  105. }
  106. if (event.type === 'assistant/live-chunk'
  107. && event.data.turn !== undefined
  108. && event.data.step !== undefined
  109. && event.data.chunk !== undefined) {
  110. if (active !== undefined && (active.turn !== event.data.turn || active.step !== event.data.step)) flush()
  111. const current = active ?? {
  112. turn: event.data.turn,
  113. step: event.data.step,
  114. stream: new AssistantStreamAccumulator(),
  115. last: entry,
  116. }
  117. active = current
  118. current.stream.push({ time: event.time, chunk: event.data.chunk })
  119. current.last = entry
  120. continue
  121. }
  122. const current = active
  123. if (event.type === 'assistant/message'
  124. && current !== undefined
  125. && current.turn === event.data.turn
  126. && current.step === event.data.step) {
  127. output.push({
  128. ...entry,
  129. event: {
  130. ...entry.event,
  131. data: { ...entry.event.data, stream: current.stream.snapshot() },
  132. } as SessionEvent,
  133. })
  134. active = undefined
  135. continue
  136. }
  137. flush()
  138. output.push(entry)
  139. }
  140. flush()
  141. return output
  142. }
  143. function assembler(entries: readonly SessionEventLikeEntry[] = [], hasMore = false): ConversationNodeAssembler {
  144. const value = new ConversationNodeAssembler(new TestEventDefinitions(), new TestViewDefinitions())
  145. value.replaceWindow(entries, hasMore)
  146. value.activateTarget('chat')
  147. return value
  148. }
  149. function snapshot(value: ConversationNodeAssembler): ChatSnapshot {
  150. const current = value.snapshot('chat') as ChatSnapshot | undefined
  151. if (current === undefined) throw new Error('chat view was not registered')
  152. return current
  153. }
  154. function node(value: ChatSnapshot, kind: string): ChatConversationViewNode | undefined {
  155. return value.nodes.values().find(candidate => candidate.kind === kind)
  156. }
  157. function textMessage(id: string, text: string) {
  158. return {
  159. id,
  160. role: 'user',
  161. content: [{ type: 'text', text }],
  162. source: { kind: 'user' },
  163. }
  164. }
  165. function systemMessage(text: string) {
  166. return {
  167. id: `system-${text}`,
  168. role: 'system',
  169. content: text === '' ? [] : [{ type: 'text', text }],
  170. source: { kind: 'plugin', plugin: '@deepseek-ai/dsh-system-prompt' },
  171. }
  172. }
  173. /** Append the first system prompt node or replace the node at `replaces`. */
  174. function systemAt(seq: number, text: string, replaces?: number): SessionLiveEventEntry {
  175. return at(seq, 'system/message', { turn: 1, step: 1, message: systemMessage(text) }, replaces === undefined
  176. ? { surfaceOp: 'append' }
  177. : { surfaceOp: { op: 'replace', start: replaces, end: replaces }, sourceEventSeqs: [replaces] })
  178. }
  179. function assistantMessage(id: string, text: string) {
  180. return {
  181. id,
  182. role: 'assistant',
  183. content: [{ type: 'text', text }],
  184. source: { kind: 'model', provider: 'fake', model: 'fake' },
  185. }
  186. }
  187. function toolResult(callId: string, text: string, isError = false) {
  188. return {
  189. id: `result-${callId}`,
  190. role: 'user',
  191. source: { kind: 'tool', callId },
  192. content: [{
  193. type: 'tool-result',
  194. toolCallId: callId,
  195. content: [{ type: 'text', text }],
  196. isError,
  197. }],
  198. }
  199. }
  200. describe('built-in conversation node Definitions', () => {
  201. it('rejects an unrelated event passed directly to the request-prompt start', () => {
  202. const input = at(1, 'turn/start', { turn: 1 })
  203. const invalidStart = {
  204. ...input,
  205. role: 'start' as const,
  206. location: { kind: 'session' as const },
  207. }
  208. expect(() => requestPromptDefinition(inspectRequestPrompt).start({} as never, invalidStart, {} as never))
  209. .toThrow('request-prompt start requires request/header')
  210. })
  211. it('pins the system-message Definition edges the engine cannot reach', () => {
  212. const input = at(1, 'turn/start', { turn: 1 })
  213. const invalidStart = {
  214. ...input,
  215. role: 'start' as const,
  216. location: { kind: 'session' as const },
  217. }
  218. const state = { seq: 1, time: 1, text: '# System' }
  219. expect(() => systemMessageDefinition.start({} as never, invalidStart, {} as never))
  220. .toThrow('system-message start requires system/message')
  221. expect(systemMessageDefinition.update({ state } as never, invalidStart)).toBe(state)
  222. })
  223. it('keeps ordinary command-only history inactive for the Conversation shell', () => {
  224. const value = assembler([
  225. at(1, 'command/run', {
  226. commandId: 'command-1',
  227. name: 'help',
  228. source: { kind: 'user' },
  229. }),
  230. at(2, 'command/done', {
  231. commandId: 'command-1',
  232. kind: 'success',
  233. }),
  234. ])
  235. const current = snapshot(value)
  236. expect(current.order).toHaveLength(1)
  237. expect(current.nodes.get(current.order[0] ?? '')?.kind).toBe('command')
  238. expect(chatViewDefinition.isActive?.(current)).toBe(false)
  239. })
  240. it('keeps the Turn rail projection current when a chunk updates one node in place', () => {
  241. const value = assembler([
  242. at(1, 'turn/start', { turn: 1 }),
  243. at(2, 'user/message', textMessage('user-1', 'navigate here'), { surfaceOp: 'append' }),
  244. at(3, 'step/start', { turn: 1, step: 1 }),
  245. at(4, 'assistant/live-chunk', {
  246. turn: 1,
  247. step: 1,
  248. chunk: { type: 'text-delta', index: 0, text: 'first' },
  249. }),
  250. ])
  251. const opening = snapshot(value).navigation.items()
  252. expect(opening).toHaveLength(1)
  253. expect(opening[0]?.turn).toBe(1)
  254. expect(opening[0]?.prompt).toBe('navigate here')
  255. expect(opening[0]?.response).toBe('first')
  256. // Content-only upsert: the node keeps its key, so the rail's preview has to
  257. // follow the in-place update rather than the last structural publication.
  258. value.append(at(5, 'assistant/live-chunk', {
  259. turn: 1,
  260. step: 1,
  261. chunk: { type: 'text-delta', index: 0, text: ' and more' },
  262. }))
  263. value.flush()
  264. const streamed = snapshot(value).navigation.items()
  265. expect(streamed[0]?.response).toBe('first and more')
  266. expect(streamed).not.toBe(opening)
  267. })
  268. it('bounds each rail preview at its card budget instead of copying the whole transcript', () => {
  269. const long = 'x'.repeat(400)
  270. const value = assembler([
  271. at(1, 'turn/start', { turn: 1 }),
  272. at(2, 'user/message', textMessage('user-1', long), { surfaceOp: 'append' }),
  273. ])
  274. const items = snapshot(value).navigation.items()
  275. // One clipped prompt line: 49 characters plus the trailing ellipsis.
  276. expect(items[0]?.prompt.length).toBe(50)
  277. expect(items[0]?.prompt.endsWith('…')).toBe(true)
  278. })
  279. it('classifies reply content separately from reasoning and Tool protocol blocks', () => {
  280. expect(hasAssistantReplyContent([{ kind: 'text', text: ' ' }])).toBe(false)
  281. expect(hasAssistantReplyContent([{ kind: 'reasoning', text: 'thinking' }])).toBe(false)
  282. expect(hasAssistantReplyContent([{ kind: 'tool-call', callId: 'c', name: 'read', argsRaw: '{}' }])).toBe(false)
  283. expect(hasAssistantReplyContent([{ kind: 'text', text: 'answer' }])).toBe(true)
  284. expect(hasAssistantReplyContent([{ kind: 'image', attachment: {} as never }])).toBe(true)
  285. expect(hasAssistantReplyContent([{ kind: 'other', block: { type: 'future' } }])).toBe(true)
  286. })
  287. it('projects one reversible process window before the finalized answer', () => {
  288. const value = assembler([
  289. at(1, 'turn/start', { turn: 1 }),
  290. at(2, 'step/start', { turn: 1, step: 1 }),
  291. at(3, 'user/message', {
  292. ...textMessage('context-1', 'workspace context'),
  293. turn: 1,
  294. step: 1,
  295. source: { kind: 'plugin', plugin: 'context' },
  296. }, { surfaceOp: 'append' }),
  297. at(4, 'assistant/live-chunk', {
  298. turn: 1, step: 1, chunk: { type: 'reasoning-delta', index: 0, text: 'thinking' },
  299. }),
  300. at(5, 'assistant/live-chunk', {
  301. turn: 1, step: 1, chunk: { type: 'text-delta', index: 1, text: 'checking' },
  302. }),
  303. at(6, 'assistant/live-chunk', {
  304. turn: 1,
  305. step: 1,
  306. chunk: { type: 'tool-call-delta', index: 2, id: 'call-1', name: 'read', argumentsDelta: '{}' },
  307. }),
  308. ])
  309. const process = () => snapshot(value).timeline.turns.get(1)?.data.get('turn-process')
  310. expect(process()).toMatchObject({ processStartSeq: 4, answerAnchorSeq: null, answerStep: null })
  311. expect(node(snapshot(value), 'turn-process')?.data).toMatchObject({ answerAnchorSeq: null })
  312. value.append(at(7, 'tool/call', {
  313. turn: 1, step: 1, callId: 'call-1', name: 'read', arguments: '{}',
  314. }))
  315. value.append(at(8, 'tool/result', {
  316. turn: 1, step: 1, message: toolResult('call-1', 'done'),
  317. }, { surfaceOp: 'append' }))
  318. value.append(at(9, 'step/end', { turn: 1, step: 1 }))
  319. value.append(at(10, 'step/start', { turn: 1, step: 2 }))
  320. value.append(at(11, 'assistant/live-chunk', {
  321. turn: 1, step: 2, chunk: { type: 'reasoning-delta', index: 0, text: 'final thinking' },
  322. }))
  323. value.append(at(12, 'assistant/live-chunk', {
  324. turn: 1, step: 2, chunk: { type: 'text-delta', index: 1, text: 'final reply' },
  325. }))
  326. value.flush()
  327. expect(process()).toMatchObject({
  328. processStartSeq: 4,
  329. answerAnchorSeq: null,
  330. answerStep: null,
  331. inlineReasoning: false,
  332. })
  333. value.append(at(13, 'llm/retry', {
  334. retryId: 'retry-tail', turn: 1, step: 2, provider: 'fake', mode: 'normal',
  335. policyKey: 'fake-normal', retry: 1, maxRetries: 2, delayMs: 10,
  336. failure: { code: 'TRANSPORT', message: 'temporary' },
  337. }))
  338. value.flush()
  339. expect(process()).toMatchObject({ answerAnchorSeq: null, answerStep: null })
  340. value.append(at(14, 'assistant/live-chunk', {
  341. turn: 1,
  342. step: 2,
  343. chunk: { type: 'text-delta', index: 0, text: 'replacement reply' },
  344. }))
  345. value.flush()
  346. expect(process()).toMatchObject({ answerAnchorSeq: null, answerStep: null })
  347. value.append(at(15, 'step/end', { turn: 1, step: 2 }))
  348. value.append(at(16, 'turn/end', {
  349. turn: 1,
  350. reason: { kind: 'aborted', reason: { kind: 'user' } },
  351. }))
  352. value.flush()
  353. expect(process()).toMatchObject({ answerAnchorSeq: 14.1, answerStep: 2 })
  354. const recovered = assembler([
  355. at(20, 'turn/start', { turn: 2 }),
  356. at(21, 'step/start', { turn: 2, step: 1 }),
  357. at(22, 'assistant/message', {
  358. turn: 2, step: 1, message: assistantMessage('recovered-1', 'settled reply'),
  359. }, { surfaceOp: 'append' }),
  360. at(23, 'step/end', { turn: 2, step: 1 }),
  361. at(24, 'step/start', { turn: 2, step: 2 }),
  362. at(25, 'assistant/live-chunk', {
  363. turn: 2, step: 2, chunk: { type: 'text-delta', index: 0, text: 'crash partial' },
  364. }),
  365. at(26, 'turn/end', { turn: 2, reason: { kind: 'interrupted' } }),
  366. ])
  367. const recoveredProcess = snapshot(recovered).timeline.turns.get(2)?.data.get('turn-process')
  368. expect(recoveredProcess)
  369. .toMatchObject({ answerStep: 2, answerAnchorSeq: 25.1 })
  370. const partialWindow = assembler([
  371. at(30, 'assistant/live-chunk', {
  372. turn: 3, step: 4, chunk: { type: 'text-delta', index: 0, text: 'loaded tail' },
  373. }),
  374. at(31, 'step/end', { turn: 3, step: 4 }),
  375. ], true)
  376. const partialProcess = snapshot(partialWindow).timeline.turns.get(3)?.data.get('turn-process')
  377. expect(partialProcess)
  378. .toMatchObject({ processStartSeq: 30.1, answerAnchorSeq: 30.1, answerStep: 4 })
  379. })
  380. it('counts Assistant messages, Tool calls, and subagent delegations per Turn', () => {
  381. const value = assembler([
  382. at(1, 'turn/start', { turn: 1 }),
  383. at(2, 'step/start', { turn: 1, step: 1 }),
  384. at(3, 'assistant/message', {
  385. turn: 1, step: 1, message: assistantMessage('message-1', 'checking'),
  386. }, { surfaceOp: 'append' }),
  387. at(4, 'tool/call', {
  388. turn: 1, step: 1, callId: 'call-read', name: 'read', arguments: '{}',
  389. }),
  390. at(5, 'tool/result', {
  391. turn: 1, step: 1, message: toolResult('call-read', 'read done'),
  392. }, { surfaceOp: 'append' }),
  393. at(6, 'tool/call', {
  394. turn: 1, step: 1, callId: 'call-subagent', name: 'subagent_fork', arguments: '{}',
  395. }),
  396. at(7, 'tool/result', {
  397. turn: 1, step: 1, message: toolResult('call-subagent', 'delegation done'),
  398. }, { surfaceOp: 'append' }),
  399. at(8, 'step/end', { turn: 1, step: 1 }),
  400. at(9, 'step/start', { turn: 1, step: 2 }),
  401. at(10, 'assistant/message', {
  402. turn: 1, step: 2, message: assistantMessage('message-2', 'final answer'),
  403. }, { surfaceOp: 'append' }),
  404. at(11, 'step/end', { turn: 1, step: 2 }),
  405. at(12, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
  406. ])
  407. const process = snapshot(value).timeline.turns.get(1)?.data.get('turn-process')
  408. expect(process).toMatchObject({
  409. messageCount: 1,
  410. toolCallCount: 1,
  411. subagentCount: 1,
  412. })
  413. })
  414. it('orders the opening User before its process control and later steering', () => {
  415. const steering = textMessage('steer-1', 'change direction')
  416. const value = assembler([
  417. at(1, 'turn/start', { turn: 1 }),
  418. at(2, 'user/message', {
  419. ...textMessage('context-1', 'runtime context'),
  420. source: { kind: 'plugin', plugin: 'context' },
  421. }, { surfaceOp: 'append' }),
  422. at(3, 'user/message', textMessage('user-1', 'question'), { surfaceOp: 'append' }),
  423. at(4, 'step/start', { turn: 1, step: 1 }),
  424. ])
  425. const opening = snapshot(value)
  426. expect(opening.order.map(key => opening.nodes.get(key)?.kind)).toEqual([
  427. 'user', 'context',
  428. ])
  429. value.append(at(5, 'assistant/live-chunk', {
  430. turn: 1, step: 1, chunk: { type: 'reasoning-delta', index: 0, text: 'thinking' },
  431. }))
  432. value.flush()
  433. const running = snapshot(value)
  434. expect(running.order.map(key => running.nodes.get(key)?.kind)).toEqual([
  435. 'user', 'turn-process', 'context', 'assistant-step',
  436. ])
  437. value.append(at(6, 'agent/inbox/spliced', {
  438. target: 'next-step', start: 0, inserted: [steering],
  439. }))
  440. value.append(at(7, 'agent/inbox/spliced', {
  441. target: 'next-step', start: 0, removedCount: 1, inserted: [],
  442. }))
  443. value.append(at(8, 'user/message', steering, { surfaceOp: 'append' }))
  444. value.append(at(9, 'step/end', { turn: 1, step: 1 }))
  445. value.append(at(10, 'step/start', { turn: 1, step: 2 }))
  446. value.append(at(11, 'assistant/message', {
  447. turn: 1, step: 2, message: assistantMessage('answer-1', 'answer'),
  448. }, { surfaceOp: 'append' }))
  449. value.append(at(12, 'step/end', { turn: 1, step: 2 }))
  450. value.append(at(13, 'turn/end', { turn: 1, reason: { kind: 'completed' } }))
  451. value.flush()
  452. const current = snapshot(value)
  453. expect(current.order.map(key => current.nodes.get(key)?.kind)).toEqual([
  454. 'user', 'turn-process', 'context', 'steering', 'assistant-step', 'assistant-step', 'turn-tail',
  455. ])
  456. })
  457. it('replays pending splice chains and scopes steering to the current claim', () => {
  458. const first = textMessage('claim-first', 'first')
  459. const second = textMessage('claim-second', 'second')
  460. const canceled = textMessage('claim-canceled', 'canceled')
  461. const requeued = textMessage('claim-requeued', 'requeued')
  462. const later = textMessage('claim-later', 'later')
  463. const current = snapshot(assembler([
  464. at(1, 'agent/inbox/spliced', {
  465. target: 'next-step', start: 0, inserted: [first],
  466. }),
  467. at(2, 'agent/inbox/spliced', {
  468. target: 'next-step', start: 1, inserted: [canceled],
  469. }),
  470. at(3, 'agent/inbox/spliced', {
  471. target: 'next-step', start: 1, inserted: [second],
  472. }),
  473. at(4, 'agent/inbox/spliced', {
  474. target: 'next-step', start: 2, removedCount: 1, inserted: [], outcome: 'canceled',
  475. }),
  476. at(5, 'agent/inbox/spliced', {
  477. target: 'next-step', start: 0, removedCount: 2, inserted: [],
  478. }),
  479. at(6, 'user/message', first, { surfaceOp: 'append' }),
  480. at(7, 'user/message', second, { surfaceOp: 'append' }),
  481. at(8, 'agent/inbox/spliced', {
  482. target: 'next-step', start: 0, inserted: [requeued],
  483. }),
  484. at(9, 'agent/inbox/spliced', {
  485. target: 'next-step', start: 0, removedCount: 1, inserted: [],
  486. }),
  487. at(10, 'agent/inbox/spliced', {
  488. target: 'next-step', start: 0, inserted: [requeued],
  489. }),
  490. at(11, 'user/message', requeued, { surfaceOp: 'append' }),
  491. at(12, 'user/message', canceled, { surfaceOp: 'append' }),
  492. at(13, 'agent/inbox/spliced', {
  493. target: 'next-step', start: 0, removedCount: 1, inserted: [], outcome: 'canceled',
  494. }),
  495. at(14, 'agent/inbox/spliced', {
  496. target: 'next-step', start: 0, inserted: [later],
  497. }),
  498. at(15, 'agent/inbox/spliced', {
  499. target: 'next-step', start: 0, removedCount: 1, inserted: [],
  500. }),
  501. at(16, 'user/message', later, { surfaceOp: 'append' }),
  502. ]))
  503. expect(current.order.map(key => current.nodes.get(key)).filter(node =>
  504. node?.kind === 'user' || node?.kind === 'steering')).toMatchObject([
  505. { kind: 'steering', data: { seq: 6 } },
  506. { kind: 'steering', data: { seq: 7 } },
  507. { kind: 'user', data: { seq: 11 } },
  508. { kind: 'user', data: { seq: 12 } },
  509. { kind: 'steering', data: { seq: 16 } },
  510. ])
  511. })
  512. it('orders a command-started Turn first steering before its process control', () => {
  513. const steering = textMessage('command-task', 'plan this change')
  514. const value = assembler([
  515. at(1, 'turn/start', { turn: 1 }),
  516. at(2, 'agent/inbox/spliced', {
  517. target: 'next-step', start: 0, inserted: [steering],
  518. }),
  519. at(3, 'agent/inbox/spliced', {
  520. target: 'next-step', start: 0, removedCount: 1, inserted: [],
  521. }),
  522. at(4, 'user/message', steering, { surfaceOp: 'append' }),
  523. at(5, 'step/start', { turn: 1, step: 1 }),
  524. at(6, 'assistant/live-chunk', {
  525. turn: 1, step: 1, chunk: { type: 'reasoning-delta', index: 0, text: 'thinking' },
  526. }),
  527. at(7, 'step/end', { turn: 1, step: 1 }),
  528. at(8, 'step/start', { turn: 1, step: 2 }),
  529. at(9, 'assistant/message', {
  530. turn: 1, step: 2, message: assistantMessage('answer-1', 'answer'),
  531. }, { surfaceOp: 'append' }),
  532. at(10, 'step/end', { turn: 1, step: 2 }),
  533. at(11, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
  534. ])
  535. const current = snapshot(value)
  536. expect(current.order.map(key => current.nodes.get(key)?.kind)).toEqual([
  537. 'steering', 'turn-process', 'assistant-step', 'assistant-step', 'turn-tail',
  538. ])
  539. })
  540. it('keeps a first human message after process evidence at its event position', () => {
  541. const steering = textMessage('late-steering', 'change direction')
  542. const value = assembler([
  543. at(1, 'turn/start', { turn: 1 }),
  544. at(2, 'step/start', { turn: 1, step: 1 }),
  545. at(3, 'tool/call', {
  546. turn: 1, step: 1, callId: 'call-1', name: 'read', arguments: '{}',
  547. }),
  548. at(4, 'tool/result', {
  549. turn: 1, step: 1, message: toolResult('call-1', 'done'),
  550. }, { surfaceOp: 'append' }),
  551. at(5, 'agent/inbox/spliced', {
  552. target: 'next-step', start: 0, inserted: [steering],
  553. }),
  554. at(6, 'agent/inbox/spliced', {
  555. target: 'next-step', start: 0, removedCount: 1, inserted: [],
  556. }),
  557. at(7, 'user/message', steering, { surfaceOp: 'append' }),
  558. at(8, 'step/end', { turn: 1, step: 1 }),
  559. at(9, 'step/start', { turn: 1, step: 2 }),
  560. at(10, 'assistant/message', {
  561. turn: 1, step: 2, message: assistantMessage('answer-1', 'answer'),
  562. }, { surfaceOp: 'append' }),
  563. at(11, 'step/end', { turn: 1, step: 2 }),
  564. at(12, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
  565. ])
  566. const current = snapshot(value)
  567. expect(current.order.map(key => current.nodes.get(key)?.kind)).toEqual([
  568. 'turn-process', 'tool-call', 'steering', 'assistant-step', 'turn-tail',
  569. ])
  570. })
  571. it('keeps Process before pre-User Context as answer eligibility changes', () => {
  572. const value = assembler([
  573. at(1, 'turn/start', { turn: 1 }),
  574. at(2, 'user/message', {
  575. ...textMessage('context-1', 'runtime context'),
  576. source: { kind: 'plugin', plugin: 'context' },
  577. }, { surfaceOp: 'append' }),
  578. at(3, 'step/start', { turn: 1, step: 1 }),
  579. at(4, 'assistant/live-chunk', {
  580. turn: 1, step: 1, chunk: { type: 'reasoning-delta', index: 0, text: 'thinking' },
  581. }),
  582. ])
  583. const running = snapshot(value)
  584. expect(running.order.map(key => running.nodes.get(key)?.kind)).toEqual([
  585. 'turn-process', 'context', 'assistant-step',
  586. ])
  587. value.append(at(5, 'step/end', { turn: 1, step: 1 }))
  588. value.append(at(6, 'step/start', { turn: 1, step: 2 }))
  589. value.append(at(7, 'assistant/message', {
  590. turn: 1, step: 2, message: assistantMessage('answer-1', 'answer'),
  591. }, { surfaceOp: 'append' }))
  592. value.flush()
  593. const answered = snapshot(value)
  594. expect(answered.order.map(key => answered.nodes.get(key)?.kind)).toEqual([
  595. 'turn-process', 'context', 'assistant-step', 'assistant-step',
  596. ])
  597. value.append(at(8, 'llm/retry', {
  598. retryId: 'retry-tail', turn: 1, step: 2, provider: 'fake', mode: 'normal',
  599. policyKey: 'fake-normal', retry: 1, maxRetries: 2, delayMs: 10,
  600. failure: { code: 'TRANSPORT', message: 'temporary' },
  601. }))
  602. value.flush()
  603. const retried = snapshot(value)
  604. expect(retried.order.map(key => retried.nodes.get(key)?.kind)).toEqual([
  605. 'turn-process', 'context', 'assistant-step', 'model-retry',
  606. ])
  607. })
  608. it('establishes the answer boundary only when a streamed answer finalizes', () => {
  609. const value = assembler([
  610. at(40, 'turn/start', { turn: 4 }),
  611. at(41, 'step/start', { turn: 4, step: 1 }),
  612. at(42, 'assistant/live-chunk', {
  613. turn: 4, step: 1, chunk: { type: 'reasoning-delta', index: 0, text: 'thinking' },
  614. }),
  615. at(43, 'assistant/live-chunk', {
  616. turn: 4, step: 1, chunk: { type: 'text-delta', index: 1, text: 'answer' },
  617. }),
  618. ])
  619. const read = () => {
  620. const process = snapshot(value).timeline.turns.get(4)?.data.get('turn-process')
  621. if (process === undefined) throw new Error('turn-process data is unavailable')
  622. return process
  623. }
  624. const streamingNode = node(snapshot(value), 'assistant-step')
  625. if (streamingNode === undefined) throw new Error('streaming Assistant node is unavailable')
  626. const processSource = snapshot(value).nodes.processSource(streamingNode.key)
  627. let processNotifications = 0
  628. processSource.subscribe(() => { processNotifications++ })
  629. const streaming = read()
  630. value.append(at(44, 'assistant/message', {
  631. turn: 4, step: 1, message: assistantMessage('settled-4', 'answer'),
  632. }, { surfaceOp: 'append' }))
  633. value.flush()
  634. const settled = read()
  635. expect(streaming).toMatchObject({ answerAnchorSeq: null, answerStep: null })
  636. expect(settled.answerAnchorSeq).toBe(44)
  637. expect(settled.answerStep).toBe(1)
  638. expect(processNotifications).toBe(1)
  639. expect(processSource.getSnapshot()?.spec.answerAnchorSeq).toBe(44)
  640. })
  641. it('reuses the open Turn-process projection across continuing Assistant chunks', () => {
  642. const value = assembler([
  643. at(1, 'turn/start', { turn: 1 }),
  644. at(2, 'step/start', { turn: 1, step: 1 }),
  645. at(3, 'assistant/live-chunk', {
  646. turn: 1, step: 1, chunk: { type: 'reasoning-delta', index: 0, text: 'first' },
  647. }),
  648. ])
  649. const before = snapshot(value)
  650. const processNode = node(before, 'turn-process')
  651. const processData = before.timeline.turns.get(1)?.data.get('turn-process')
  652. const assistantNode = node(before, 'assistant-step')
  653. if (assistantNode === undefined) throw new Error('Assistant node is unavailable')
  654. const processSource = before.nodes.processSource(assistantNode.key)
  655. const processPresentation = processSource.getSnapshot()
  656. let processNotifications = 0
  657. processSource.subscribe(() => { processNotifications++ })
  658. value.append(at(4, 'assistant/live-chunk', {
  659. turn: 1, step: 1, chunk: { type: 'reasoning-delta', index: 0, text: ' second' },
  660. }))
  661. value.flush()
  662. const after = snapshot(value)
  663. expect(after.timeline.turns.get(1)?.data.get('turn-process')).toBe(processData)
  664. expect(node(after, 'turn-process')).toBe(processNode)
  665. expect(node(after, 'assistant-step')).not.toBe(assistantNode)
  666. expect(processSource.getSnapshot()).toBe(processPresentation)
  667. expect(processNotifications).toBe(0)
  668. })
  669. it('notifies process sources only for Nodes in the changed Turn', () => {
  670. const value = assembler([
  671. at(1, 'turn/start', { turn: 1 }),
  672. at(2, 'step/start', { turn: 1, step: 1 }),
  673. at(3, 'assistant/message', {
  674. turn: 1, step: 1, message: assistantMessage('answer-1', 'first answer'),
  675. }, { surfaceOp: 'append' }),
  676. at(4, 'step/end', { turn: 1, step: 1 }),
  677. at(5, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
  678. at(6, 'turn/start', { turn: 2 }),
  679. at(7, 'step/start', { turn: 2, step: 1 }),
  680. at(8, 'assistant/live-chunk', {
  681. turn: 2, step: 1, chunk: { type: 'reasoning-delta', index: 0, text: 'thinking' },
  682. }),
  683. ])
  684. const assistants = snapshot(value).nodes.values()
  685. .filter((candidate): candidate is ChatConversationViewNode & { data: AssistantChatData } => (
  686. candidate.kind === 'assistant-step'
  687. ))
  688. const first = assistants.find(candidate => candidate.data.turn === 1)
  689. const second = assistants.find(candidate => candidate.data.turn === 2)
  690. if (first === undefined || second === undefined) throw new Error('Assistant fixtures are unavailable')
  691. let firstNotifications = 0
  692. let secondNotifications = 0
  693. snapshot(value).nodes.processSource(first.key).subscribe(() => { firstNotifications++ })
  694. snapshot(value).nodes.processSource(second.key).subscribe(() => { secondNotifications++ })
  695. value.append(at(9, 'assistant/message', {
  696. turn: 2, step: 1, message: assistantMessage('answer-2', 'second answer'),
  697. }, { surfaceOp: 'append' }))
  698. value.append(at(10, 'step/end', { turn: 2, step: 1 }))
  699. value.append(at(11, 'turn/end', { turn: 2, reason: { kind: 'completed' } }))
  700. value.flush()
  701. expect(firstNotifications).toBe(0)
  702. expect(secondNotifications).toBe(1)
  703. })
  704. it('anchors a streamed non-text answer from its block start', () => {
  705. const value = assembler([
  706. at(50, 'turn/start', { turn: 5 }),
  707. at(51, 'step/start', { turn: 5, step: 1 }),
  708. at(52, 'assistant/live-chunk', {
  709. turn: 5, step: 1, chunk: { type: 'block-start', index: 0, blockType: 'image' },
  710. }),
  711. ])
  712. const current = snapshot(value)
  713. const process = node(current, 'turn-process')
  714. const answer = node(current, 'assistant-step')
  715. const processData = current.timeline.turns.get(5)?.data.get('turn-process')
  716. expect(process?.anchorSeq).toBe(51.9)
  717. expect(answer?.anchorSeq).toBe(52)
  718. expect(processData)
  719. .toMatchObject({ answerAnchorSeq: null, answerStep: null })
  720. })
  721. it('keeps one keyed Assistant node while streaming settles and materializes interruption from Location', () => {
  722. const value = assembler([
  723. at(1, 'turn/start', { turn: 1 }),
  724. at(2, 'step/start', { turn: 1, step: 1 }),
  725. at(3, 'assistant/live-chunk', {
  726. turn: 1,
  727. step: 1,
  728. chunk: { type: 'text-delta', index: 0, text: 'streaming' },
  729. }),
  730. ])
  731. const runningSnapshot = snapshot(value)
  732. const running = node(runningSnapshot, 'assistant-step')
  733. expect(running?.data).toMatchObject({ status: 'running', blocks: [{ kind: 'text', text: 'streaming' }] })
  734. expect(running?.location.kind === 'step'
  735. ? running.location.step.data.get('assistant-step')
  736. : undefined).toBe(running?.data)
  737. const order = runningSnapshot.order
  738. value.append(at(4, 'assistant/message', {
  739. turn: 1,
  740. step: 1,
  741. message: assistantMessage('assistant-1', 'settled'),
  742. }, { surfaceOp: 'append' }))
  743. value.flush()
  744. const settledSnapshot = snapshot(value)
  745. const settled = node(settledSnapshot, 'assistant-step')
  746. expect(settled?.key).toBe(running?.key)
  747. expect(settledSnapshot.order).toBe(order)
  748. expect(settled?.data).toMatchObject({ status: 'settled', blocks: [{ kind: 'text', text: 'settled' }] })
  749. expect(settled?.location.kind === 'step'
  750. ? settled.location.step.data.get('assistant-step')
  751. : undefined).toBe(settled?.data)
  752. const interruptedValue = assembler([
  753. at(10, 'turn/start', { turn: 2 }),
  754. at(11, 'step/start', { turn: 2, step: 1 }),
  755. at(12, 'assistant/live-chunk', {
  756. turn: 2,
  757. step: 1,
  758. chunk: { type: 'text-delta', index: 0, text: 'partial' },
  759. }),
  760. at(13, 'step/end', { turn: 2, step: 1 }),
  761. ])
  762. const interrupted = node(snapshot(interruptedValue), 'assistant-step')
  763. expect(interrupted?.data).toMatchObject({ status: 'interrupted' })
  764. expect((interrupted?.data as AssistantChatData).finalNode?.interrupted).toBe(true)
  765. const markedValue = assembler([
  766. at(20, 'turn/start', { turn: 3 }),
  767. at(21, 'step/start', { turn: 3, step: 1 }),
  768. at(22, 'assistant/message', {
  769. turn: 3,
  770. step: 1,
  771. message: assistantMessage('assistant-3', 'cut short'),
  772. interrupted: true,
  773. }, { surfaceOp: 'append' }),
  774. ])
  775. const marked = node(snapshot(markedValue), 'assistant-step')
  776. expect(marked?.data).toMatchObject({ status: 'interrupted', blocks: [{ kind: 'text', text: 'cut short' }] })
  777. expect((marked?.data as AssistantChatData).finalNode?.interrupted).toBe(true)
  778. const hiddenValue = assembler([
  779. at(20, 'turn/start', { turn: 3 }),
  780. at(21, 'step/start', { turn: 3, step: 1 }),
  781. at(22, 'llm/retry', {
  782. retryId: 'retry-hidden',
  783. turn: 3,
  784. step: 1,
  785. provider: 'fake',
  786. mode: 'normal',
  787. policyKey: 'fake-normal',
  788. retry: 1,
  789. maxRetries: 2,
  790. delayMs: 10,
  791. failure: { code: 'TRANSPORT', message: 'temporary' },
  792. }),
  793. ])
  794. expect(node(snapshot(hiddenValue), 'assistant-step')).toBeUndefined()
  795. const toolOnlyValue = assembler([
  796. at(30, 'turn/start', { turn: 4 }),
  797. at(31, 'step/start', { turn: 4, step: 1 }),
  798. at(32, 'assistant/live-chunk', {
  799. turn: 4,
  800. step: 1,
  801. chunk: { type: 'tool-call-delta', index: 0, id: 'call-1', name: 'read', argumentsDelta: '' },
  802. }),
  803. at(33, 'assistant/message', {
  804. turn: 4,
  805. step: 1,
  806. message: {
  807. ...assistantMessage('assistant-tool-only', ''),
  808. content: [{ type: 'tool-call', id: 'call-1', name: 'read', arguments: '{}' }],
  809. },
  810. }, { surfaceOp: 'append' }),
  811. ])
  812. const toolOnlySnapshot = snapshot(toolOnlyValue)
  813. expect(toolOnlySnapshot.order).toEqual([])
  814. expect(node(toolOnlySnapshot, 'assistant-step')?.visibility).toBe('hidden')
  815. expect(toolOnlySnapshot.legacy.nodes).toMatchObject([{
  816. kind: 'assistant',
  817. seq: 33,
  818. timing: { firstTokenTime: 1_700_000_000_032 },
  819. }])
  820. const interruptedToolOnlyValue = assembler([
  821. at(35, 'turn/start', { turn: 5 }),
  822. at(36, 'step/start', { turn: 5, step: 1 }),
  823. at(37, 'assistant/live-chunk', {
  824. turn: 5,
  825. step: 1,
  826. chunk: { type: 'tool-call-delta', index: 0, id: 'call-2', name: 'read', argumentsDelta: '' },
  827. }),
  828. at(38, 'step/end', { turn: 5, step: 1 }),
  829. ])
  830. const interruptedToolOnly = node(snapshot(interruptedToolOnlyValue), 'assistant-step')
  831. expect(interruptedToolOnly?.visibility).toBe('visible')
  832. expect(interruptedToolOnly?.data).toMatchObject({ status: 'interrupted' })
  833. const retryTimingValue = assembler([
  834. at(50, 'turn/start', { turn: 6 }),
  835. at(51, 'step/start', { turn: 6, step: 1 }),
  836. at(52, 'assistant/live-chunk', {
  837. turn: 6,
  838. step: 1,
  839. chunk: { type: 'text-delta', index: 0, text: 'first attempt' },
  840. }),
  841. at(53, 'llm/retry', {
  842. retryId: 'retry-timing', turn: 6, step: 1, provider: 'fake', mode: 'normal',
  843. policyKey: 'fake-normal', retry: 1, maxRetries: 2, delayMs: 10,
  844. failure: { code: 'TRANSPORT', message: 'temporary' },
  845. }),
  846. at(54, 'assistant/live-chunk', {
  847. turn: 6,
  848. step: 1,
  849. chunk: { type: 'text-delta', index: 0, text: 'second attempt' },
  850. }),
  851. at(55, 'assistant/message', {
  852. turn: 6,
  853. step: 1,
  854. message: assistantMessage('assistant-retried', 'done'),
  855. }, { surfaceOp: 'append' }),
  856. ])
  857. const retryTiming = (node(snapshot(retryTimingValue), 'assistant-step')?.data as AssistantChatData).finalNode
  858. expect(retryTiming?.timing?.firstTokenTime).toBe(1_700_000_000_052)
  859. const partialWindow = assembler([
  860. at(40, 'assistant/live-chunk', {
  861. turn: 5,
  862. step: 2,
  863. chunk: { type: 'text-delta', index: 0, text: 'loaded partial' },
  864. }),
  865. at(41, 'step/end', { turn: 5, step: 2 }),
  866. ], true)
  867. const recovered = node(snapshot(partialWindow), 'assistant-step')
  868. expect(recovered?.data).toMatchObject({
  869. status: 'interrupted',
  870. blocks: [{ kind: 'text', text: 'loaded partial' }],
  871. })
  872. })
  873. it('uses live Assistant deltas without replaying settled embedded streams', () => {
  874. const runningHistory = [
  875. at(1, 'turn/start', { turn: 1 }),
  876. at(2, 'step/start', { turn: 1, step: 1 }),
  877. at(3, 'assistant/live-chunk', {
  878. turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: '' },
  879. }, { time: 1_000 }),
  880. at(4, 'assistant/live-chunk', {
  881. turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: ' ' },
  882. }, { time: 1_000 }),
  883. at(5, 'assistant/live-chunk', {
  884. turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: '\t' },
  885. }, { time: 995 }),
  886. at(6, 'assistant/live-chunk', {
  887. turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'answer' },
  888. }, { time: 1_004 }),
  889. at(7, 'assistant/live-chunk', {
  890. turn: 1, step: 1, chunk: { type: 'reasoning-delta', index: 1, text: '' },
  891. }),
  892. at(8, 'assistant/live-chunk', {
  893. turn: 1, step: 1, chunk: { type: 'reasoning-delta', index: 1, text: 'think' },
  894. }),
  895. at(9, 'assistant/live-chunk', {
  896. turn: 1, step: 1, chunk: { type: 'reasoning-delta', index: 1, text: 'ing' },
  897. }),
  898. at(10, 'assistant/live-chunk', {
  899. turn: 1, step: 1,
  900. chunk: { type: 'tool-call-delta', index: 2, id: 'call-1', argumentsDelta: '' },
  901. }),
  902. at(11, 'assistant/live-chunk', {
  903. turn: 1, step: 1,
  904. chunk: { type: 'tool-call-delta', index: 2, id: 'call-1', argumentsDelta: '{"x":' },
  905. }),
  906. at(12, 'assistant/live-chunk', {
  907. turn: 1, step: 1,
  908. chunk: { type: 'tool-call-delta', index: 2, id: 'call-1', argumentsDelta: '1}' },
  909. }),
  910. ]
  911. const scalar = assembler(runningHistory)
  912. const packedHistory = packedInputs(runningHistory)
  913. expect(packedHistory).toHaveLength(3)
  914. const runningAttempt = packedHistory.at(-1)?.event
  915. expect(runningAttempt?.type).toBe('assistant/attempt')
  916. if (runningAttempt?.type !== 'assistant/attempt') throw new Error('expected packed running attempt')
  917. expect(runningAttempt.data.stream.length).toBeGreaterThan(0)
  918. const packed = assembler(packedHistory)
  919. const running = node(snapshot(scalar), 'assistant-step')
  920. expect(running?.data).toMatchObject({
  921. time: 1_004,
  922. blocks: [
  923. { kind: 'text', text: ' \tanswer' },
  924. { kind: 'reasoning', text: 'thinking' },
  925. { kind: 'tool-call', callId: 'call-1', name: '', argsRaw: '{"x":1}' },
  926. ],
  927. })
  928. expect(snapshot(packed).legacy.partial).toBeNull()
  929. expect(node(snapshot(packed), 'assistant-step')).toBeUndefined()
  930. for (const value of [scalar, packed]) {
  931. value.append(at(13, 'step/end', { turn: 1, step: 1 }))
  932. value.append(at(14, 'turn/end', { turn: 1, reason: { kind: 'completed' } }))
  933. value.flush()
  934. }
  935. expect(node(snapshot(scalar), 'assistant-step')?.data).toMatchObject({ status: 'interrupted' })
  936. expect(node(snapshot(packed), 'assistant-step')).toBeUndefined()
  937. const partialHistory = [
  938. ...runningHistory.slice(2),
  939. at(13, 'step/end', { turn: 1, step: 1 }),
  940. at(14, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
  941. ]
  942. const partialPacked = snapshot(assembler(packedInputs(partialHistory), true))
  943. expect(partialPacked.legacy.partial).toBeNull()
  944. expect(node(partialPacked, 'assistant-step')).toBeUndefined()
  945. const finalizedHistory = [
  946. at(20, 'turn/start', { turn: 2 }),
  947. at(21, 'step/start', { turn: 2, step: 1 }),
  948. at(22, 'assistant/live-chunk', {
  949. turn: 2, step: 1, chunk: { type: 'text-delta', index: 0, text: '' },
  950. }, { time: 2_000 }),
  951. at(23, 'assistant/live-chunk', {
  952. turn: 2, step: 1, chunk: { type: 'text-delta', index: 0, text: ' ' },
  953. }, { time: 1_999 }),
  954. at(24, 'assistant/live-chunk', {
  955. turn: 2, step: 1, chunk: { type: 'text-delta', index: 0, text: 'first' },
  956. }, { time: 2_000 }),
  957. at(25, 'llm/retry', {
  958. retryId: 'packed-retry', turn: 2, step: 1, provider: 'fake', mode: 'normal',
  959. policyKey: 'fake-normal', retry: 1, maxRetries: 2, delayMs: 10,
  960. failure: { code: 'TRANSPORT', message: 'temporary' },
  961. }),
  962. at(26, 'assistant/live-chunk', {
  963. turn: 2, step: 1, chunk: { type: 'text-delta', index: 0, text: '' },
  964. }),
  965. at(27, 'assistant/live-chunk', {
  966. turn: 2, step: 1, chunk: { type: 'text-delta', index: 0, text: 'second' },
  967. }),
  968. at(28, 'assistant/live-chunk', {
  969. turn: 2, step: 1, chunk: { type: 'text-delta', index: 0, text: ' attempt' },
  970. }),
  971. at(29, 'assistant/message', {
  972. turn: 2, step: 1, message: assistantMessage('packed-final', 'done'),
  973. }, { surfaceOp: 'append' }),
  974. ]
  975. const finalizedInputs = packedInputs(finalizedHistory)
  976. expect(finalizedInputs.filter(input => input.event.type === 'assistant/attempt')).toHaveLength(1)
  977. const finalizedMessage = finalizedInputs.find(input => input.event.type === 'assistant/message')?.event
  978. if (finalizedMessage?.type !== 'assistant/message') throw new Error('expected packed final message')
  979. expect(finalizedMessage.data.stream.length).toBeGreaterThan(0)
  980. const finalizedPacked = snapshot(assembler(finalizedInputs))
  981. const finalNode = (node(finalizedPacked, 'assistant-step')?.data as AssistantChatData).finalNode
  982. expect(finalNode).toMatchObject({
  983. blocks: [{ kind: 'text', text: 'done' }],
  984. timing: { firstTokenTime: null },
  985. })
  986. const namedToolHistory = [
  987. at(40, 'turn/start', { turn: 3 }),
  988. at(41, 'step/start', { turn: 3, step: 1 }),
  989. ...[42, 43, 44].map(seq => at(seq, 'assistant/live-chunk', {
  990. turn: 3, step: 1,
  991. chunk: { type: 'tool-call-delta', index: 0, id: 'call-2', name: 'read', argumentsDelta: '' },
  992. }, { time: 4_000 + seq - 42 })),
  993. at(45, 'assistant/message', {
  994. turn: 3,
  995. step: 1,
  996. message: {
  997. ...assistantMessage('named-tool-final', ''),
  998. content: [{ type: 'tool-call', id: 'call-2', name: 'read', arguments: '' }],
  999. },
  1000. }, { surfaceOp: 'append' }),
  1001. ]
  1002. const namedToolInputs = packedInputs(namedToolHistory)
  1003. const namedToolMessage = namedToolInputs.find(input => input.event.type === 'assistant/message')?.event
  1004. if (namedToolMessage?.type !== 'assistant/message') throw new Error('expected packed named-tool message')
  1005. expect(namedToolMessage.data.stream.length).toBeGreaterThan(0)
  1006. const namedToolPacked = snapshot(assembler(namedToolInputs))
  1007. const namedTool = (node(namedToolPacked, 'assistant-step')?.data as AssistantChatData).finalNode
  1008. expect(namedTool).toMatchObject({
  1009. blocks: [{ kind: 'tool-call', callId: 'call-2', name: 'read', argsRaw: '' }],
  1010. timing: { firstTokenTime: null },
  1011. })
  1012. })
  1013. it('keeps one keyed Tool node from running through settlement and replays nested dispatch after prepend', () => {
  1014. const value = assembler([
  1015. at(1, 'turn/start', { turn: 1 }),
  1016. at(2, 'step/start', { turn: 1, step: 1 }),
  1017. at(3, 'tool/call', { turn: 1, step: 1, callId: 'root', name: 'code', arguments: '{}' }),
  1018. ])
  1019. const runningSnapshot = snapshot(value)
  1020. const running = node(runningSnapshot, 'tool-call')
  1021. expect((running?.data as ToolChatData).root).toMatchObject({ callId: 'root', name: 'code' })
  1022. const order = runningSnapshot.order
  1023. value.append(at(4, 'tool/result', {
  1024. turn: 1,
  1025. step: 1,
  1026. message: toolResult('root', 'done', true),
  1027. error: { name: 'ToolError', code: 'failed' },
  1028. meta: { presentation: 'raw' },
  1029. }, { surfaceOp: 'append' }))
  1030. value.flush()
  1031. const settledSnapshot = snapshot(value)
  1032. const settled = node(settledSnapshot, 'tool-call')
  1033. expect(settled?.key).toBe(running?.key)
  1034. expect(settledSnapshot.order).toBe(order)
  1035. expect((settled?.data as ToolChatData).root).toMatchObject({
  1036. kind: 'tool-result',
  1037. callId: 'root',
  1038. call: { name: 'code', argsRaw: '{}' },
  1039. content: [{ type: 'text', text: 'done' }],
  1040. isError: true,
  1041. error: { name: 'ToolError', code: 'failed' },
  1042. meta: { presentation: 'raw' },
  1043. })
  1044. const history = assembler([
  1045. at(14, 'tool/code-dispatch-start', {
  1046. rootCallId: 'history-root',
  1047. parentCallId: 'history-root',
  1048. subCallId: 'child',
  1049. name: 'read',
  1050. arguments: { path: 'README.md' },
  1051. }),
  1052. at(15, 'tool/code-dispatch', {
  1053. rootCallId: 'history-root',
  1054. parentCallId: 'history-root',
  1055. subCallId: 'child',
  1056. name: 'read',
  1057. arguments: { path: 'README.md' },
  1058. isError: false,
  1059. content: [{ type: 'text', text: 'contents' }],
  1060. }),
  1061. at(16, 'tool/result', {
  1062. turn: 2,
  1063. step: 1,
  1064. message: toolResult('history-root', 'root done'),
  1065. }, { surfaceOp: 'append' }),
  1066. ], true)
  1067. const before = node(snapshot(history), 'tool-call')
  1068. expect((before?.data as ToolChatData).root.subCalls).toMatchObject([
  1069. { kind: 'tool-result', callId: 'child', parentCallId: 'history-root', call: { name: 'read' } },
  1070. ])
  1071. history.prepend([
  1072. at(10, 'turn/start', { turn: 2 }),
  1073. at(11, 'step/start', { turn: 2, step: 1 }),
  1074. at(13, 'tool/call', {
  1075. turn: 2,
  1076. step: 1,
  1077. callId: 'history-root',
  1078. name: 'code',
  1079. arguments: '{}',
  1080. }),
  1081. ], false)
  1082. history.flush()
  1083. const after = node(snapshot(history), 'tool-call')
  1084. expect(after?.key).toBe(before?.key)
  1085. expect((after?.data as ToolChatData).root.subCalls).toMatchObject([
  1086. { kind: 'tool-result', callId: 'child', parentCallId: 'history-root', call: { name: 'read' } },
  1087. ])
  1088. const firstChild = (after?.data as ToolChatData).root.subCalls[0]
  1089. history.append(at(17, 'tool/code-dispatch-start', {
  1090. rootCallId: 'history-root',
  1091. parentCallId: 'history-root',
  1092. subCallId: 'second-child',
  1093. name: 'write',
  1094. arguments: { path: 'out.txt' },
  1095. }))
  1096. history.flush()
  1097. const withSecondChild = node(snapshot(history), 'tool-call')
  1098. expect((withSecondChild?.data as ToolChatData).root.subCalls[0]).toBe(firstChild)
  1099. })
  1100. it('prepends an older turn without replacing already materialized nodes', () => {
  1101. const value = assembler([
  1102. at(20, 'turn/start', { turn: 2 }),
  1103. at(21, 'user/message', textMessage('newer-user', 'newer'), { surfaceOp: 'append' }),
  1104. at(22, 'step/start', { turn: 2, step: 1 }),
  1105. at(23, 'assistant/message', {
  1106. turn: 2,
  1107. step: 1,
  1108. message: assistantMessage('newer-assistant', 'newer answer'),
  1109. }, { surfaceOp: 'append' }),
  1110. at(24, 'step/end', { turn: 2, step: 1 }),
  1111. at(25, 'turn/end', { turn: 2, reason: { kind: 'completed' } }),
  1112. ], true)
  1113. const before = snapshot(value)
  1114. const existing = before.nodes.get(before.order.find(key => before.nodes.get(key)?.kind === 'assistant-step') ?? '')
  1115. const store = before.nodes
  1116. value.prepend([
  1117. at(10, 'turn/start', { turn: 1 }),
  1118. at(11, 'user/message', textMessage('older-user', 'older'), { surfaceOp: 'append' }),
  1119. at(12, 'step/start', { turn: 1, step: 1 }),
  1120. at(13, 'assistant/message', {
  1121. turn: 1,
  1122. step: 1,
  1123. message: assistantMessage('older-assistant', 'older answer'),
  1124. }, { surfaceOp: 'append' }),
  1125. at(14, 'step/end', { turn: 1, step: 1 }),
  1126. at(15, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
  1127. ], false)
  1128. value.flush()
  1129. const after = snapshot(value)
  1130. expect(after.nodes).toBe(store)
  1131. expect(after.nodes.get(existing?.key ?? '')).toBe(existing)
  1132. expect(after.order).toHaveLength(before.order.length + 4)
  1133. expect(after.order.map(key => after.nodes.get(key)?.kind)).toEqual([
  1134. 'user', 'turn-process', 'assistant-step', 'turn-tail',
  1135. 'user', 'turn-process', 'assistant-step', 'turn-tail',
  1136. ])
  1137. })
  1138. it('appends a later turn without replacing nodes from the completed turn', () => {
  1139. const value = assembler([
  1140. at(1, 'turn/start', { turn: 1 }),
  1141. at(2, 'user/message', textMessage('first-user', 'first'), { surfaceOp: 'append' }),
  1142. at(3, 'step/start', { turn: 1, step: 1 }),
  1143. at(4, 'assistant/message', {
  1144. turn: 1,
  1145. step: 1,
  1146. message: assistantMessage('first-assistant', 'first answer'),
  1147. }, { surfaceOp: 'append' }),
  1148. at(5, 'step/end', { turn: 1, step: 1 }),
  1149. at(6, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
  1150. ])
  1151. const before = snapshot(value)
  1152. const oldOrder = before.order
  1153. const oldNodes = oldOrder.map(key => before.nodes.get(key))
  1154. value.append(at(7, 'turn/start', { turn: 2 }))
  1155. value.append(at(8, 'user/message', textMessage('second-user', 'second'), { surfaceOp: 'append' }))
  1156. value.flush()
  1157. const after = snapshot(value)
  1158. expect(after.nodes).toBe(before.nodes)
  1159. expect(after.order.slice(0, oldOrder.length)).toEqual(oldOrder)
  1160. expect(oldOrder.map(key => after.nodes.get(key))).toEqual(oldNodes)
  1161. expect(after.order.map(key => after.nodes.get(key)?.kind)).toEqual([
  1162. 'user', 'turn-process', 'assistant-step', 'turn-tail', 'user',
  1163. ])
  1164. })
  1165. it('keeps branching unavailable when a tool result follows the closing Assistant', () => {
  1166. const value = assembler([
  1167. at(1, 'turn/start', { turn: 1 }),
  1168. at(2, 'step/start', { turn: 1, step: 1 }),
  1169. at(3, 'assistant/message', {
  1170. turn: 1,
  1171. step: 1,
  1172. message: assistantMessage('assistant-before-tool', 'running a tool'),
  1173. }, { surfaceOp: 'append' }),
  1174. at(4, 'tool/call', { turn: 1, step: 1, callId: 'late-tool', name: 'read', arguments: '{}' }),
  1175. at(5, 'tool/result', {
  1176. turn: 1,
  1177. step: 1,
  1178. message: toolResult('late-tool', 'done'),
  1179. }, { surfaceOp: 'append' }),
  1180. at(6, 'step/end', { turn: 1, step: 1 }),
  1181. at(7, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
  1182. ])
  1183. const tail = node(snapshot(value), 'turn-tail')?.data as TurnTailChatData
  1184. expect(tail.closing?.finalNode.seq).toBe(3)
  1185. expect(tail.branchUnavailable).toBe(true)
  1186. })
  1187. it('publishes exact Turn usage only after pagination supplies the full lifecycle window', () => {
  1188. const value = assembler([
  1189. at(3, 'assistant/message', {
  1190. turn: 1,
  1191. step: 1,
  1192. message: assistantMessage('usage-assistant', 'done'),
  1193. usage: {
  1194. inputTokens: 10,
  1195. outputTokens: 4,
  1196. totalTokens: 17,
  1197. cacheReadTokens: 2,
  1198. cacheWriteTokens: 1,
  1199. reasoningTokens: 1,
  1200. },
  1201. }, { surfaceOp: 'append' }),
  1202. at(4, 'step/end', { turn: 1, step: 1 }),
  1203. at(5, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
  1204. ], true)
  1205. expect((node(snapshot(value), 'turn-tail')?.data as TurnTailChatData).tokenUsage).toBeUndefined()
  1206. value.prepend([
  1207. at(1, 'turn/start', { turn: 1 }),
  1208. at(2, 'step/start', { turn: 1, step: 1 }),
  1209. ], false)
  1210. value.flush()
  1211. expect((node(snapshot(value), 'turn-tail')?.data as TurnTailChatData).tokenUsage).toEqual({
  1212. uncachedInputTokens: 10,
  1213. outputTokens: 4,
  1214. totalTokens: 17,
  1215. cacheReadTokens: 2,
  1216. cacheWriteTokens: 1,
  1217. reasoningTokens: 1,
  1218. routes: [{ provider: 'fake', model: 'fake' }],
  1219. })
  1220. })
  1221. it('replays inbox predecessors after prepend and reclassifies the dependent message as steering', () => {
  1222. const value = assembler([
  1223. at(3, 'user/message', textMessage('steer-1', 'change direction'), { surfaceOp: 'append' }),
  1224. ], true)
  1225. const before = node(snapshot(value), 'user')
  1226. expect(before).toBeDefined()
  1227. value.prepend([
  1228. at(1, 'agent/inbox/spliced', {
  1229. target: 'next-step',
  1230. start: 0,
  1231. inserted: [textMessage('steer-1', 'change direction')],
  1232. }),
  1233. at(2, 'agent/inbox/spliced', {
  1234. target: 'next-step',
  1235. start: 0,
  1236. removedCount: 1,
  1237. inserted: [],
  1238. }),
  1239. ], false)
  1240. value.flush()
  1241. const after = node(snapshot(value), 'steering')
  1242. expect(after?.key).toBe(before?.key)
  1243. expect(after?.data).toMatchObject({ kind: 'steering', messageId: 'steer-1' })
  1244. expect(node(snapshot(value), 'user')).toBeUndefined()
  1245. })
  1246. it('orders claimed steering after the finalized Turn tail', () => {
  1247. const steering = textMessage('steer-after-answer', 'change direction')
  1248. const value = assembler([
  1249. at(1, 'turn/start', { turn: 1 }),
  1250. at(2, 'step/start', { turn: 1, step: 1 }),
  1251. at(3, 'assistant/message', {
  1252. turn: 1,
  1253. step: 1,
  1254. message: assistantMessage('assistant-before-steering', 'initial answer'),
  1255. }, { surfaceOp: 'append' }),
  1256. at(4, 'agent/inbox/spliced', {
  1257. target: 'next-step',
  1258. start: 0,
  1259. inserted: [steering],
  1260. }),
  1261. at(5, 'agent/inbox/spliced', {
  1262. target: 'next-step',
  1263. start: 0,
  1264. removedCount: 1,
  1265. inserted: [],
  1266. }),
  1267. at(6, 'user/message', steering, { surfaceOp: 'append' }),
  1268. at(7, 'step/end', { turn: 1, step: 1 }),
  1269. at(8, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
  1270. ])
  1271. const current = snapshot(value)
  1272. const steeringNode = node(current, 'steering')
  1273. expect(steeringNode).toBeDefined()
  1274. expect(current.locations.getTurn(1).at(-1)).toBe(steeringNode?.key)
  1275. })
  1276. it('classifies appended producer context from durable source metadata', () => {
  1277. const value = assembler([
  1278. at(1, 'user/message', {
  1279. ...textMessage('skill-context', 'follow these instructions'),
  1280. source: { kind: 'skill-invocation', name: 'demo-skill', form: 'instructions' },
  1281. }, { surfaceOp: 'append' }),
  1282. ])
  1283. expect(node(snapshot(value), 'context')?.data).toMatchObject({
  1284. kind: 'context',
  1285. provenance: { role: 'inject', label: 'demo-skill' },
  1286. form: 'instructions',
  1287. })
  1288. })
  1289. it('materializes series starts and system node replacements but not same-series config or tool changes', () => {
  1290. const tools = [{ name: 'read', description: 'Read', parameters: { type: 'object' } }]
  1291. const expandedTools = [...tools, { name: 'write', description: 'Write', parameters: { type: 'object' } }]
  1292. const value = assembler([
  1293. systemAt(1, '# Initial'),
  1294. at(2, 'request/header', {
  1295. reason: 'initial',
  1296. header: { config: { provider: 'fake', model: 'fake' }, tools },
  1297. }),
  1298. at(3, 'request/header', {
  1299. reason: 'change',
  1300. header: { config: { provider: 'fake', model: 'fake' }, tools: expandedTools },
  1301. }),
  1302. at(4, 'request/header', {
  1303. reason: 'change',
  1304. header: { config: { provider: 'fake', model: 'fake', maxTokens: 1_024 }, tools: expandedTools },
  1305. }),
  1306. at(5, 'request/header', {
  1307. reason: 'change',
  1308. startsSeries: true,
  1309. header: { config: { provider: 'fake', model: 'fake', maxTokens: 2_048 }, tools: expandedTools },
  1310. }),
  1311. at(6, 'request/header', {
  1312. reason: 'resume',
  1313. header: { config: { provider: 'fake', model: 'fake', maxTokens: 2_048 }, tools: expandedTools },
  1314. }),
  1315. systemAt(7, '# Updated', 1),
  1316. at(8, 'request/header', {
  1317. reason: 'change',
  1318. header: { config: { provider: 'fake', model: 'fake', maxTokens: 4_096 }, tools: expandedTools },
  1319. }),
  1320. ])
  1321. const current = snapshot(value)
  1322. const prompts = current.nodes.values()
  1323. .filter(candidate => candidate.kind === 'system-prompt')
  1324. expect(prompts.map(prompt => ({ anchorSeq: prompt.anchorSeq, data: prompt.data }))).toEqual([
  1325. { anchorSeq: 2, data: { text: '# Initial' } },
  1326. { anchorSeq: 5, data: { text: '# Initial' } },
  1327. { anchorSeq: 6, data: { text: '# Initial' } },
  1328. { anchorSeq: 8, data: { text: '# Updated' } },
  1329. ])
  1330. expect(current.nodes.values().filter(candidate => candidate.kind === 'unknown')).toEqual([])
  1331. })
  1332. it('renders a windowed prompt from its in-window system node and fills a missing node after prepend', () => {
  1333. const windowed = assembler([
  1334. systemAt(10, '# Resumed prompt', 5),
  1335. at(11, 'request/header', {
  1336. reason: 'resume',
  1337. header: { config: { provider: 'fake', model: 'fake' } },
  1338. }),
  1339. ], true)
  1340. const nodeless = assembler([
  1341. at(11, 'request/header', {
  1342. reason: 'resume',
  1343. header: { config: { provider: 'fake', model: 'fake' } },
  1344. }),
  1345. ], true)
  1346. const systemless = assembler([
  1347. at(20, 'request/header', {
  1348. reason: 'initial',
  1349. header: { config: { provider: 'fake', model: 'fake' } },
  1350. }),
  1351. ])
  1352. expect(node(snapshot(windowed), 'system-prompt')?.data).toEqual({ text: '# Resumed prompt' })
  1353. expect(node(snapshot(nodeless), 'system-prompt')).toBeUndefined()
  1354. expect(node(snapshot(systemless), 'system-prompt')).toBeUndefined()
  1355. const older = [
  1356. systemAt(5, '# Original prompt'),
  1357. at(6, 'request/header', {
  1358. reason: 'initial',
  1359. header: { config: { provider: 'fake', model: 'fake' } },
  1360. }),
  1361. ]
  1362. const promptTexts = (value: ConversationNodeAssembler) => {
  1363. const restored = snapshot(value)
  1364. return restored.order.flatMap((key) => {
  1365. const candidate = restored.nodes.get(key)
  1366. return candidate?.kind === 'system-prompt' ? [candidate.data] : []
  1367. })
  1368. }
  1369. windowed.prepend(older, false)
  1370. windowed.flush()
  1371. nodeless.prepend(older, false)
  1372. nodeless.flush()
  1373. expect(promptTexts(windowed)).toEqual([{ text: '# Original prompt' }, { text: '# Resumed prompt' }])
  1374. expect(promptTexts(nodeless)).toEqual([{ text: '# Original prompt' }, { text: '# Original prompt' }])
  1375. })
  1376. it('shows the system node text as the request prompt card before the request messages', () => {
  1377. const value = assembler([
  1378. at(1, 'turn/start', { turn: 1 }),
  1379. at(2, 'step/start', { turn: 1, step: 1 }),
  1380. systemAt(3, '# System\n\nFollow instructions.'),
  1381. at(4, 'user/message', textMessage('direct-user', 'prompt'), { surfaceOp: 'append' }),
  1382. at(5, 'user/message', {
  1383. ...textMessage('runtime-context', 'runtime facts'),
  1384. source: { kind: 'plugin', plugin: '@deepseek-ai/dsh-system-prompt', form: 'snapshot' },
  1385. }, { surfaceOp: 'append' }),
  1386. at(6, 'request/header', {
  1387. reason: 'initial',
  1388. header: { config: { provider: 'fake', model: 'fake' } },
  1389. }),
  1390. ])
  1391. const current = snapshot(value)
  1392. expect(current.order.map(key => current.nodes.get(key)?.kind)).toEqual([
  1393. 'system-prompt',
  1394. 'user',
  1395. 'context',
  1396. ])
  1397. expect(node(current, 'system-prompt')?.anchorSeq).toBe(1)
  1398. expect(node(current, 'system-prompt')?.data).toEqual({ text: '# System\n\nFollow instructions.' })
  1399. })
  1400. it('never renders a system/message as a transcript bubble', () => {
  1401. const value = assembler([
  1402. at(1, 'turn/start', { turn: 1 }),
  1403. at(2, 'step/start', { turn: 1, step: 1 }),
  1404. systemAt(3, '# System'),
  1405. at(4, 'user/message', textMessage('direct-user', 'prompt'), { surfaceOp: 'append' }),
  1406. ])
  1407. const current = snapshot(value)
  1408. expect(current.order.map(key => current.nodes.get(key)?.kind)).toEqual(['user'])
  1409. value.append(systemAt(5, '# Replaced', 3))
  1410. value.flush()
  1411. const replaced = snapshot(value)
  1412. expect(replaced.order.map(key => replaced.nodes.get(key)?.kind)).toEqual(['user'])
  1413. })
  1414. it('keeps the initial system prompt before the opening User as Turn process state changes', () => {
  1415. const value = assembler([
  1416. at(1, 'turn/start', { turn: 1 }),
  1417. at(2, 'step/start', { turn: 1, step: 1 }),
  1418. systemAt(3, '# System'),
  1419. at(4, 'user/message', textMessage('direct-user', 'prompt'), { surfaceOp: 'append' }),
  1420. at(5, 'user/message', {
  1421. ...textMessage('runtime-context', 'runtime facts'),
  1422. source: { kind: 'plugin', plugin: 'context' },
  1423. }, { surfaceOp: 'append' }),
  1424. at(6, 'request/header', {
  1425. reason: 'initial',
  1426. header: { config: { provider: 'fake', model: 'fake' } },
  1427. }),
  1428. ])
  1429. const kinds = () => {
  1430. const current = snapshot(value)
  1431. return current.order.map(key => current.nodes.get(key)?.kind)
  1432. }
  1433. const promptKey = node(snapshot(value), 'system-prompt')?.key
  1434. expect(kinds()).toEqual(['system-prompt', 'user', 'context'])
  1435. value.append(at(7, 'assistant/live-chunk', {
  1436. turn: 1, step: 1, chunk: { type: 'reasoning-delta', index: 0, text: 'thinking' },
  1437. }))
  1438. value.flush()
  1439. expect(kinds()).toEqual([
  1440. 'system-prompt', 'user', 'turn-process', 'context', 'assistant-step',
  1441. ])
  1442. value.append(at(8, 'step/end', { turn: 1, step: 1 }))
  1443. value.append(at(9, 'step/start', { turn: 1, step: 2 }))
  1444. value.append(at(10, 'assistant/message', {
  1445. turn: 1, step: 2, message: assistantMessage('answer-1', 'answer'),
  1446. }, { surfaceOp: 'append' }))
  1447. value.append(at(11, 'step/end', { turn: 1, step: 2 }))
  1448. value.append(at(12, 'turn/end', { turn: 1, reason: { kind: 'completed' } }))
  1449. value.flush()
  1450. expect(kinds()).toEqual([
  1451. 'system-prompt', 'user', 'turn-process', 'context', 'assistant-step', 'assistant-step', 'turn-tail',
  1452. ])
  1453. expect(node(snapshot(value), 'system-prompt')?.key).toBe(promptKey)
  1454. })
  1455. it('keeps an append-only later user turn in the existing system-prompt series', () => {
  1456. const value = assembler([
  1457. at(1, 'turn/start', { turn: 1 }),
  1458. at(2, 'step/start', { turn: 1, step: 1 }),
  1459. systemAt(3, '# System'),
  1460. at(4, 'user/message', textMessage('first-user', 'first'), { surfaceOp: 'append' }),
  1461. at(5, 'request/header', {
  1462. reason: 'initial',
  1463. header: { config: { provider: 'fake', model: 'fake' } },
  1464. }),
  1465. at(6, 'step/end', { turn: 1, step: 1 }),
  1466. at(7, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
  1467. at(8, 'turn/start', { turn: 2 }),
  1468. at(9, 'step/start', { turn: 2, step: 1 }),
  1469. at(10, 'user/message', textMessage('second-user', 'second'), { surfaceOp: 'append' }),
  1470. ])
  1471. const current = snapshot(value)
  1472. const ordered = current.order.flatMap((key) => {
  1473. const candidate = current.nodes.get(key)
  1474. return candidate?.kind === 'system-prompt' || candidate?.kind === 'user' ? [candidate] : []
  1475. })
  1476. expect(ordered.map(candidate => candidate.kind)).toEqual(['system-prompt', 'user', 'user'])
  1477. })
  1478. it('keeps a windowed System prompt in place when prepend supplies the preceding header', () => {
  1479. const reasons = ['change', 'resume', 'series'] as const
  1480. for (const reason of reasons) {
  1481. const windowedSystem = reason === 'series' ? '# Original' : '# Windowed'
  1482. const windowed = assembler([
  1483. at(6, 'turn/start', { turn: 2 }),
  1484. at(7, 'step/start', { turn: 2, step: 1 }),
  1485. systemAt(8, windowedSystem, 3),
  1486. at(9, 'user/message', textMessage(`second-user-${reason}`, 'second'), { surfaceOp: 'append' }),
  1487. at(10, 'request/header', {
  1488. reason,
  1489. header: { config: { provider: 'fake', model: 'fake' } },
  1490. }),
  1491. ], true)
  1492. const before = snapshot(windowed)
  1493. const prompt = node(before, 'system-prompt')
  1494. const user = node(before, 'user')
  1495. if (prompt === undefined || user === undefined) throw new Error('windowed prompt fixture is incomplete')
  1496. const stableOrder = [user.key, prompt.key]
  1497. expect(prompt.anchorSeq).toBe(10)
  1498. expect(prompt.data).toEqual({ text: windowedSystem })
  1499. expect(before.order.filter(key => stableOrder.includes(key))).toEqual(stableOrder)
  1500. windowed.prepend([
  1501. at(1, 'turn/start', { turn: 1 }),
  1502. at(2, 'step/start', { turn: 1, step: 1 }),
  1503. systemAt(3, '# Original'),
  1504. at(4, 'user/message', textMessage(`first-user-${reason}`, 'first'), { surfaceOp: 'append' }),
  1505. at(5, 'request/header', {
  1506. reason: 'initial',
  1507. header: { config: { provider: 'fake', model: 'fake' } },
  1508. }),
  1509. ], false)
  1510. windowed.flush()
  1511. const restored = snapshot(windowed)
  1512. const prompts = restored.order.flatMap((key) => {
  1513. const candidate = restored.nodes.get(key)
  1514. return candidate?.kind === 'system-prompt' ? [candidate] : []
  1515. })
  1516. expect(prompts.map(candidate => candidate.anchorSeq)).toEqual([1, 10])
  1517. expect(restored.nodes.get(prompt.key)?.anchorSeq).toBe(10)
  1518. expect(restored.order.filter(key => stableOrder.includes(key))).toEqual(stableOrder)
  1519. }
  1520. })
  1521. it('repeats an unchanged system prompt after a surface rewrite and before an explicit later series', () => {
  1522. const value = assembler([
  1523. at(1, 'turn/start', { turn: 1 }),
  1524. at(2, 'step/start', { turn: 1, step: 1 }),
  1525. systemAt(3, '# Same'),
  1526. at(4, 'user/message', textMessage('first-user', 'first'), { surfaceOp: 'append' }),
  1527. at(5, 'request/header', {
  1528. reason: 'initial',
  1529. header: { config: { provider: 'fake', model: 'fake' } },
  1530. }),
  1531. at(6, 'user/message', {
  1532. ...textMessage('compacted', 'summary'),
  1533. source: { kind: 'plugin', plugin: 'compact' },
  1534. }, { surfaceOp: { op: 'replace', start: 4, end: 4 } }),
  1535. at(7, 'request/header', {
  1536. reason: 'series',
  1537. header: { config: { provider: 'fake', model: 'fake' } },
  1538. }),
  1539. at(8, 'step/end', { turn: 1, step: 1 }),
  1540. at(9, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
  1541. at(10, 'turn/start', { turn: 2 }),
  1542. at(11, 'step/start', { turn: 2, step: 1 }),
  1543. at(12, 'user/message', textMessage('second-user', 'second'), { surfaceOp: 'append' }),
  1544. at(13, 'request/header', {
  1545. reason: 'series',
  1546. header: { config: { provider: 'fake', model: 'fake' } },
  1547. }),
  1548. ])
  1549. const current = snapshot(value)
  1550. const ordered = current.order.flatMap((key) => {
  1551. const candidate = current.nodes.get(key)
  1552. return candidate?.kind === 'system-prompt' || candidate?.kind === 'user' ? [candidate] : []
  1553. })
  1554. expect(ordered.map(candidate => candidate?.kind)).toEqual([
  1555. 'system-prompt', 'user', 'system-prompt', 'system-prompt', 'user',
  1556. ])
  1557. expect(ordered.filter(candidate => candidate?.kind === 'system-prompt')
  1558. .map(candidate => candidate?.anchorSeq)).toEqual([1, 7, 10])
  1559. })
  1560. it('associates each direct message with its immediately following session recall', () => {
  1561. const value = assembler([
  1562. at(1, 'user/message', textMessage('citing-research', '@Research notes what changed?'), { surfaceOp: 'append' }),
  1563. at(2, 'user/message', {
  1564. ...textMessage('research-context', 'snapshot'),
  1565. source: {
  1566. kind: 'session-reference',
  1567. form: 'recall',
  1568. version: 1,
  1569. references: [{ sessionId: 'source-a', label: 'Research notes' }],
  1570. },
  1571. }, { surfaceOp: 'append' }),
  1572. at(3, 'user/message', textMessage('citing-review', '@Review next'), { surfaceOp: 'append' }),
  1573. at(4, 'user/message', {
  1574. ...textMessage('review-context', 'snapshot'),
  1575. source: {
  1576. kind: 'session-reference',
  1577. form: 'recall',
  1578. version: 1,
  1579. references: [{ sessionId: 'source-b', label: 'Review' }],
  1580. },
  1581. }, { surfaceOp: 'append' }),
  1582. at(6, 'user/message', textMessage('later-user', 'unrelated'), { surfaceOp: 'append' }),
  1583. ])
  1584. const current = snapshot(value)
  1585. const messages = [...current.nodes.values()]
  1586. .filter(candidate => candidate.kind === 'user' || candidate.kind === 'context')
  1587. const users = [...current.nodes.values()].filter(candidate => candidate.kind === 'user')
  1588. expect(messages.map(candidate => candidate.kind)).toEqual(['user', 'context', 'user', 'context', 'user'])
  1589. expect(users[0]?.data).toMatchObject({ referenceLabels: ['Research notes'] })
  1590. expect(users[1]?.data).toMatchObject({ referenceLabels: ['Review'] })
  1591. expect(users[2]?.data).not.toHaveProperty('referenceLabels')
  1592. })
  1593. it('updates an already published direct node when its following recall arrives', () => {
  1594. const value = assembler([
  1595. at(1, 'user/message', textMessage('citing-user', '@Research notes what changed?'), { surfaceOp: 'append' }),
  1596. ])
  1597. const before = node(snapshot(value), 'user')
  1598. expect(before?.data).not.toHaveProperty('referenceLabels')
  1599. value.append(at(2, 'user/message', {
  1600. ...textMessage('reference-context', 'snapshot'),
  1601. source: {
  1602. kind: 'session-reference',
  1603. form: 'recall',
  1604. version: 1,
  1605. references: [{ sessionId: 'source-a', label: 'Research notes' }],
  1606. },
  1607. }, { surfaceOp: 'append' }))
  1608. value.flush()
  1609. const current = snapshot(value)
  1610. const nodes = [...current.nodes.values()]
  1611. .filter(candidate => candidate.kind === 'user' || candidate.kind === 'context')
  1612. expect(nodes.map(candidate => candidate.kind)).toEqual(['user', 'context'])
  1613. expect(nodes[0]?.key).toBe(before?.key)
  1614. expect(nodes[0]?.data).toMatchObject({ referenceLabels: ['Research notes'] })
  1615. expect(current.legacy.nodes[0]).toMatchObject({ referenceLabels: ['Research notes'] })
  1616. })
  1617. it('associates a claimed steering message with its following recall', () => {
  1618. const steering = textMessage('steering-reference', '@Research notes continue')
  1619. const value = assembler([
  1620. at(1, 'agent/inbox/spliced', {
  1621. target: 'next-step',
  1622. start: 0,
  1623. inserted: [steering],
  1624. }),
  1625. at(2, 'agent/inbox/spliced', {
  1626. target: 'next-step',
  1627. start: 0,
  1628. removedCount: 1,
  1629. inserted: [],
  1630. }),
  1631. at(3, 'user/message', steering, { surfaceOp: 'append' }),
  1632. at(4, 'user/message', {
  1633. ...textMessage('steering-reference-context', 'snapshot'),
  1634. source: {
  1635. kind: 'session-reference',
  1636. form: 'recall',
  1637. version: 1,
  1638. references: [{ sessionId: 'source-a', label: 'Research notes' }],
  1639. },
  1640. }, { surfaceOp: 'append' }),
  1641. ])
  1642. expect(node(snapshot(value), 'steering')?.data).toMatchObject({
  1643. messageId: 'steering-reference',
  1644. referenceLabels: ['Research notes'],
  1645. })
  1646. })
  1647. it('associates a direct message with the skill invocations injected for its step', () => {
  1648. const skillInvocation = (id: string) => ({
  1649. ...textMessage(id, 'instructions'),
  1650. source: { kind: 'skill-invocation', name: 'demo-skill', form: 'instructions' },
  1651. })
  1652. const instructions = (id: string) => ({
  1653. ...textMessage(id, 'workspace rules'),
  1654. source: { kind: 'agent-instructions', changes: [{ path: 'AGENTS.md' }] },
  1655. })
  1656. const value = assembler([
  1657. at(1, 'turn/start', { turn: 1 }),
  1658. at(2, 'user/message', textMessage('gesture', '/demo-skill go'), { surfaceOp: 'append' }),
  1659. at(3, 'step/start', { turn: 1, step: 1 }),
  1660. at(4, 'user/message', instructions('rules-1'), { surfaceOp: 'append' }),
  1661. at(5, 'user/message', skillInvocation('skill-body'), { surfaceOp: 'append' }),
  1662. at(6, 'assistant/message', {
  1663. turn: 1,
  1664. step: 1,
  1665. message: assistantMessage('answer-1', 'done'),
  1666. }, { surfaceOp: 'append' }),
  1667. at(7, 'step/end', { turn: 1, step: 1 }),
  1668. at(8, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
  1669. at(9, 'turn/start', { turn: 2 }),
  1670. at(10, 'user/message', textMessage('later', '/demo-skill again?'), { surfaceOp: 'append' }),
  1671. at(11, 'step/start', { turn: 2, step: 1 }),
  1672. at(12, 'user/message', instructions('rules-2'), { surfaceOp: 'append' }),
  1673. ])
  1674. const users = [...snapshot(value).nodes.values()].filter(candidate => candidate.kind === 'user')
  1675. expect(users).toHaveLength(2)
  1676. expect(users[0]?.data).toMatchObject({ skillNames: ['demo-skill'] })
  1677. expect(users[1]?.data).not.toHaveProperty('skillNames')
  1678. })
  1679. it('updates an already published direct node when its skill injection arrives', () => {
  1680. const value = assembler([
  1681. at(1, 'user/message', textMessage('gesture', '/demo-skill go'), { surfaceOp: 'append' }),
  1682. ])
  1683. const before = node(snapshot(value), 'user')
  1684. expect(before?.data).not.toHaveProperty('skillNames')
  1685. value.append(at(2, 'user/message', {
  1686. ...textMessage('skill-body', 'instructions'),
  1687. source: { kind: 'skill-invocation', name: 'demo-skill', form: 'instructions' },
  1688. }, { surfaceOp: 'append' }))
  1689. value.flush()
  1690. const after = node(snapshot(value), 'user')
  1691. expect(after?.key).toBe(before?.key)
  1692. expect(after?.data).toMatchObject({ skillNames: ['demo-skill'] })
  1693. })
  1694. it('keeps replacement copies out of Chat business nodes', () => {
  1695. const value = assembler([
  1696. at(1, 'turn/start', { turn: 1 }),
  1697. at(2, 'step/start', { turn: 1, step: 1 }),
  1698. at(3, 'user/message', {
  1699. ...textMessage('replacement-user', 'model-only context'),
  1700. source: { kind: 'plugin', plugin: 'foreign' },
  1701. }, { surfaceOp: { op: 'replace', start: 1, end: 1 } }),
  1702. at(4, 'assistant/message', {
  1703. turn: 1,
  1704. step: 1,
  1705. message: assistantMessage('replacement-assistant', 'rewritten answer'),
  1706. }, { surfaceOp: { op: 'replace', start: 2, end: 2 } }),
  1707. at(5, 'tool/call', { turn: 1, step: 1, callId: 'root', name: 'read', arguments: '{}' }),
  1708. at(6, 'tool/result', {
  1709. turn: 1,
  1710. step: 1,
  1711. message: toolResult('root', 'pruned result'),
  1712. }, { surfaceOp: { op: 'replace', start: 3, end: 3 } }),
  1713. ])
  1714. const current = snapshot(value)
  1715. expect(node(current, 'user')).toBeUndefined()
  1716. expect(node(current, 'context')).toBeUndefined()
  1717. expect(node(current, 'assistant-step')).toBeUndefined()
  1718. expect((node(current, 'tool-call')?.data as ToolChatData).root).not.toHaveProperty('kind')
  1719. })
  1720. it('assembles retry chains and keeps manual and automatic compaction ownership separate', () => {
  1721. const retry = assembler([
  1722. at(1, 'turn/start', { turn: 1 }),
  1723. at(2, 'step/start', { turn: 1, step: 1 }),
  1724. at(3, 'llm/retry', {
  1725. retryId: 'retry-1',
  1726. turn: 1,
  1727. step: 1,
  1728. provider: 'fake',
  1729. mode: 'normal',
  1730. policyKey: 'fake-normal',
  1731. retry: 1,
  1732. maxRetries: 2,
  1733. delayMs: 10,
  1734. failure: { code: 'TRANSPORT', message: 'first' },
  1735. }),
  1736. at(4, 'llm/retry-started', { retryId: 'retry-1', turn: 1, step: 1, retry: 1 }),
  1737. at(5, 'llm/retry', {
  1738. retryId: 'retry-1',
  1739. turn: 1,
  1740. step: 1,
  1741. provider: 'fake',
  1742. mode: 'normal',
  1743. policyKey: 'fake-normal',
  1744. retry: 2,
  1745. maxRetries: 2,
  1746. delayMs: 20,
  1747. failure: { code: 'TRANSPORT', message: 'second' },
  1748. }),
  1749. at(6, 'step/end', { turn: 1, step: 1 }),
  1750. at(7, 'turn/end', {
  1751. turn: 1,
  1752. reason: { kind: 'error', error: { code: 'TRANSPORT', message: 'failed' } },
  1753. }),
  1754. ])
  1755. const retryNode = node(snapshot(retry), 'model-retry')
  1756. const retryData = retryNode?.data as RetryChatData
  1757. expect(retryData.attempts.map(attempt => attempt.retryState)).toEqual(['started', 'cancelled'])
  1758. expect(node(snapshot(retry), 'turn-error')?.data).toMatchObject({
  1759. kind: 'turn-error',
  1760. turn: 1,
  1761. message: 'failed',
  1762. code: 'TRANSPORT',
  1763. })
  1764. const compactions = assembler([
  1765. at(10, 'command/run', {
  1766. commandId: 'command-1',
  1767. name: 'compact',
  1768. source: { kind: 'user' },
  1769. }),
  1770. at(11, 'compaction/start', {
  1771. compactionId: 'manual-1',
  1772. sourceCommandId: 'command-1',
  1773. turn: null,
  1774. }),
  1775. at(12, 'compaction/summary', {
  1776. compactionId: 'manual-1',
  1777. sourceCommandId: 'command-1',
  1778. summary: [{ type: 'text', text: 'manual summary' }],
  1779. shadowedSeqs: [1, 2],
  1780. shadowedTokenCount: 100,
  1781. }),
  1782. at(13, 'user/message', {
  1783. ...textMessage('manual-checkpoint', 'checkpoint'),
  1784. source: {
  1785. kind: 'plugin',
  1786. plugin: 'compact',
  1787. compactionId: 'manual-1',
  1788. sourceCommandId: 'command-1',
  1789. },
  1790. }, { surfaceOp: { op: 'replace', start: 1, end: 2 } }),
  1791. at(14, 'compaction/end', {
  1792. compactionId: 'manual-1',
  1793. sourceCommandId: 'command-1',
  1794. turn: null,
  1795. }),
  1796. at(15, 'command/done', {
  1797. commandId: 'command-1',
  1798. kind: 'success',
  1799. sourceEventSeq: 12,
  1800. }),
  1801. at(20, 'compaction/start', { compactionId: 'automatic-1', turn: null }),
  1802. at(21, 'compaction/summary', {
  1803. compactionId: 'automatic-1',
  1804. summary: [{ type: 'text', text: 'automatic summary' }],
  1805. shadowedSeqs: [3, 4],
  1806. shadowedTokenCount: 200,
  1807. }),
  1808. at(22, 'user/message', {
  1809. ...textMessage('automatic-checkpoint', 'checkpoint'),
  1810. source: { kind: 'plugin', plugin: 'compact', compactionId: 'automatic-1' },
  1811. }, { surfaceOp: { op: 'replace', start: 3, end: 4 } }),
  1812. at(23, 'compaction/end', { compactionId: 'automatic-1', turn: null }),
  1813. ])
  1814. const manual = node(snapshot(compactions), 'manual-compaction')
  1815. expect((manual?.data as ManualCompactionChatData).compaction).toMatchObject({
  1816. summary: 'manual summary',
  1817. summaryEventSeq: 12,
  1818. })
  1819. const automatic = node(snapshot(compactions), 'compaction')
  1820. expect(automatic?.data).toMatchObject({ summary: 'automatic summary', summaryEventSeq: 21 })
  1821. expect(snapshot(compactions).nodes.values().filter(candidate => candidate.kind === 'compaction')).toHaveLength(1)
  1822. })
  1823. it('fills a landed compaction marker when an older page supplies its summary', () => {
  1824. const value = assembler([
  1825. at(13, 'user/message', {
  1826. ...textMessage('checkpoint', 'checkpoint'),
  1827. source: { kind: 'plugin', plugin: 'compact', compactionId: 'compact-1' },
  1828. }, { surfaceOp: { op: 'replace', start: 1, end: 8 } }),
  1829. ], true)
  1830. const before = node(snapshot(value), 'compaction')
  1831. expect(before?.data).toMatchObject({ summary: null, summaryEventSeq: null })
  1832. value.prepend([
  1833. at(9, 'compaction/start', { compactionId: 'compact-1', turn: null }),
  1834. at(10, 'compaction/summary', {
  1835. compactionId: 'compact-1',
  1836. summary: [
  1837. { type: 'text', text: 'older ' },
  1838. { type: 'image', data: 'ignored' },
  1839. { type: 'text', text: 'summary' },
  1840. ],
  1841. shadowedSeqs: [1, 2, 3],
  1842. shadowedTokenCount: 42,
  1843. }),
  1844. ], false)
  1845. value.flush()
  1846. const after = node(snapshot(value), 'compaction')
  1847. expect(after?.key).toBe(before?.key)
  1848. expect(after?.data).toMatchObject({
  1849. summary: 'older summary',
  1850. summaryEventSeq: 10,
  1851. shadowedItemCount: 3,
  1852. shadowedTokenCount: 42,
  1853. })
  1854. })
  1855. it('renders a historical compaction when its start remains outside the loaded window', () => {
  1856. const value = assembler([
  1857. at(10, 'compaction/summary', {
  1858. compactionId: 'compact-windowed',
  1859. summary: [{ type: 'text', text: 'loaded summary' }],
  1860. shadowedSeqs: [1, 2, 3],
  1861. shadowedTokenCount: 42,
  1862. }),
  1863. at(11, 'user/message', {
  1864. ...textMessage('checkpoint-windowed', 'checkpoint'),
  1865. source: { kind: 'plugin', plugin: 'compact', compactionId: 'compact-windowed' },
  1866. }, { surfaceOp: { op: 'replace', start: 1, end: 3 } }),
  1867. ], true)
  1868. expect(node(snapshot(value), 'compaction')?.data).toMatchObject({
  1869. summary: 'loaded summary',
  1870. summaryEventSeq: 10,
  1871. shadowedItemCount: 3,
  1872. shadowedTokenCount: 42,
  1873. })
  1874. })
  1875. it('ignores legacy compaction transactions without correlation ids', () => {
  1876. const value = assembler([
  1877. at(10, 'compaction/start', { turn: null }),
  1878. at(11, 'compaction/end', { turn: null, error: 'This operation was aborted' }),
  1879. at(20, 'compaction/start', { turn: null }),
  1880. at(21, 'compaction/summary', {
  1881. summary: [{ type: 'text', text: 'legacy summary' }],
  1882. shadowedSeqs: [1, 2, 3],
  1883. shadowedTokenCount: 42,
  1884. }),
  1885. at(22, 'user/message', {
  1886. ...textMessage('legacy-checkpoint', 'checkpoint'),
  1887. source: { kind: 'plugin', plugin: 'compact' },
  1888. }, { surfaceOp: { op: 'replace', start: 1, end: 3 } }),
  1889. at(23, 'compaction/end', { turn: null }),
  1890. ], true)
  1891. expect(node(snapshot(value), 'compaction')).toBeUndefined()
  1892. })
  1893. it('ignores legacy retry and code-dispatch events without correlation ids', () => {
  1894. const value = assembler([
  1895. at(10, 'llm/retry', {
  1896. turn: 1,
  1897. step: 1,
  1898. provider: 'fake',
  1899. mode: 'normal',
  1900. policyKey: 'fake-normal',
  1901. retry: 1,
  1902. maxRetries: 2,
  1903. delayMs: 10,
  1904. failure: { code: 'TRANSPORT', message: 'first legacy retry' },
  1905. }),
  1906. at(11, 'llm/retry-started', { turn: 1, step: 1, retry: 1 }),
  1907. at(20, 'llm/retry', {
  1908. turn: 2,
  1909. step: 1,
  1910. provider: 'fake',
  1911. mode: 'normal',
  1912. policyKey: 'fake-normal',
  1913. retry: 1,
  1914. maxRetries: 2,
  1915. delayMs: 10,
  1916. failure: { code: 'TRANSPORT', message: 'second legacy retry' },
  1917. }),
  1918. at(30, 'tool/code-dispatch-start', {
  1919. parentCallId: 'root',
  1920. subCallId: 'child',
  1921. name: 'legacy-subcall',
  1922. arguments: {},
  1923. }),
  1924. at(31, 'tool/code-dispatch', {
  1925. parentCallId: 'root',
  1926. subCallId: 'child',
  1927. name: 'legacy-subcall',
  1928. arguments: {},
  1929. content: [],
  1930. }),
  1931. ], true)
  1932. expect(node(snapshot(value), 'model-retry')).toBeUndefined()
  1933. expect(node(snapshot(value), 'tool-call')).toBeUndefined()
  1934. })
  1935. it('renders the exhausted-retry turn error in a partial tail window and after prepending the chain', () => {
  1936. const value = assembler([
  1937. at(5, 'llm/retry', {
  1938. retryId: 'retry-paged',
  1939. turn: 1,
  1940. step: 1,
  1941. provider: 'fake',
  1942. mode: 'normal',
  1943. policyKey: 'fake-normal',
  1944. retry: 2,
  1945. maxRetries: 2,
  1946. delayMs: 20,
  1947. failure: { code: 'TRANSPORT', message: 'second' },
  1948. }),
  1949. at(6, 'step/end', { turn: 1, step: 1 }),
  1950. at(7, 'turn/end', {
  1951. turn: 1,
  1952. reason: { kind: 'error', error: { code: 'TRANSPORT', message: 'failed' } },
  1953. }),
  1954. ], true)
  1955. expect(node(snapshot(value), 'model-retry')).toBeUndefined()
  1956. expect(node(snapshot(value), 'turn-error')?.data).toMatchObject({
  1957. kind: 'turn-error',
  1958. seq: 7,
  1959. turn: 1,
  1960. message: 'failed',
  1961. code: 'TRANSPORT',
  1962. })
  1963. value.prepend([
  1964. at(1, 'turn/start', { turn: 1 }),
  1965. at(2, 'step/start', { turn: 1, step: 1 }),
  1966. at(3, 'llm/retry', {
  1967. retryId: 'retry-paged',
  1968. turn: 1,
  1969. step: 1,
  1970. provider: 'fake',
  1971. mode: 'normal',
  1972. policyKey: 'fake-normal',
  1973. retry: 1,
  1974. maxRetries: 2,
  1975. delayMs: 10,
  1976. failure: { code: 'TRANSPORT', message: 'first' },
  1977. }),
  1978. at(4, 'llm/retry-started', {
  1979. retryId: 'retry-paged', turn: 1, step: 1, retry: 1,
  1980. }),
  1981. ], false)
  1982. value.flush()
  1983. const retry = node(snapshot(value), 'model-retry')
  1984. expect((retry?.data as RetryChatData).attempts).toHaveLength(2)
  1985. expect(node(snapshot(value), 'turn-error')?.data).toMatchObject({
  1986. kind: 'turn-error',
  1987. seq: 7,
  1988. turn: 1,
  1989. message: 'failed',
  1990. code: 'TRANSPORT',
  1991. })
  1992. })
  1993. it('materializes a max-tokens notice and keeps completed and error turns clean', () => {
  1994. const value = assembler([
  1995. at(1, 'turn/start', { turn: 1 }),
  1996. at(2, 'step/start', { turn: 1, step: 1 }),
  1997. at(3, 'assistant/message', {
  1998. turn: 1, step: 1, message: assistantMessage('a1', 'truncated answer'),
  1999. }, { surfaceOp: 'append' }),
  2000. at(4, 'step/end', { turn: 1, step: 1 }),
  2001. at(5, 'turn/end', { turn: 1, reason: { kind: 'max-tokens' } }),
  2002. ])
  2003. const notice = node(snapshot(value), 'turn-max-tokens')
  2004. expect(notice?.data).toMatchObject({ kind: 'turn-max-tokens', seq: 5, turn: 1, step: 1 })
  2005. expect(node(snapshot(value), 'turn-error')).toBeUndefined()
  2006. // The tail stays the turn's last node so its branch action survives; the
  2007. // notice slots between the truncated closing Assistant and the tail.
  2008. const tail = node(snapshot(value), 'turn-tail')
  2009. expect(notice?.anchorSeq).toBeLessThan(tail?.anchorSeq ?? Number.NEGATIVE_INFINITY)
  2010. expect(notice?.anchorSeq).toBeGreaterThan(3)
  2011. const completed = assembler([
  2012. at(1, 'turn/start', { turn: 1 }),
  2013. at(2, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
  2014. ])
  2015. expect(node(snapshot(completed), 'turn-max-tokens')).toBeUndefined()
  2016. const failed = assembler([
  2017. at(1, 'turn/start', { turn: 1 }),
  2018. at(2, 'turn/end', {
  2019. turn: 1,
  2020. reason: { kind: 'error', error: { code: 'TRANSPORT', message: 'failed' } },
  2021. }),
  2022. ])
  2023. expect(node(snapshot(failed), 'turn-max-tokens')).toBeUndefined()
  2024. expect(node(snapshot(failed), 'turn-error')).toBeDefined()
  2025. })
  2026. it('keeps the max-tokens notice when the window starts after the owning turn/start', () => {
  2027. const value = assembler([
  2028. at(9, 'turn/end', { turn: 3, reason: { kind: 'max-tokens' } }),
  2029. ], true)
  2030. const notice = node(snapshot(value), 'turn-max-tokens')
  2031. expect(notice?.data).toMatchObject({ kind: 'turn-max-tokens', seq: 9, turn: 3 })
  2032. })
  2033. it('pins the max-tokens Definition edges the engine cannot reach', () => {
  2034. // The engine only hands start the single matched turn/end and never emits
  2035. // update Matches for this kind; these direct calls pin the declared
  2036. // behavior of both required Definition members anyway.
  2037. const match = (seq: number, type: string, data: unknown) => ({
  2038. event: { seq, time: seq * 1_000, type, data },
  2039. role: 'start',
  2040. location: undefined,
  2041. }) as unknown as Parameters<typeof turnMaxTokensDefinition.start>[1]
  2042. const context = (state: unknown, matches: unknown[] = []) => ({
  2043. key: 'k', kind: 'turn-max-tokens', id: '1', matches, start: undefined, state, current: new Map(),
  2044. }) as unknown as Parameters<NonNullable<typeof turnMaxTokensDefinition.buildViewNode>>[0]
  2045. const reader = { previous: () => undefined }
  2046. expect(() => turnMaxTokensDefinition.start(context(undefined), match(1, 'turn/start', { turn: 1 }), reader))
  2047. .toThrow('turn-max-tokens start requires a max-tokens turn/end')
  2048. const state = { turn: 1, seq: 5, time: 5_000 }
  2049. expect(turnMaxTokensDefinition.update(
  2050. context(state) as Parameters<typeof turnMaxTokensDefinition.update>[0],
  2051. match(6, 'turn/end', { turn: 1, reason: { kind: 'completed' } }),
  2052. )).toBe(state)
  2053. expect(turnMaxTokensDefinition.buildViewNode?.(context(undefined))).toBeNull()
  2054. })
  2055. it('preserves nested Tools and manual compaction evidence when their start events are outside the window', () => {
  2056. const value = assembler([
  2057. at(12, 'tool/code-dispatch-start', {
  2058. rootCallId: 'root', parentCallId: 'root', subCallId: 'child', name: 'read_file', arguments: { path: 'a' },
  2059. }),
  2060. at(13, 'tool/code-dispatch', {
  2061. rootCallId: 'root', parentCallId: 'root', subCallId: 'child', name: 'read_file', arguments: { path: 'a' },
  2062. isError: false, content: [{ type: 'text', text: 'child result' }],
  2063. }),
  2064. at(14, 'tool/result', {
  2065. turn: 1,
  2066. step: 1,
  2067. message: toolResult('root', 'root result'),
  2068. }, { surfaceOp: 'append' }),
  2069. at(20, 'compaction/summary', {
  2070. compactionId: 'manual-1',
  2071. sourceCommandId: 'command-1',
  2072. summary: [{ type: 'text', text: 'manual summary' }],
  2073. shadowedSeqs: [1, 2],
  2074. shadowedTokenCount: 100,
  2075. }),
  2076. at(21, 'user/message', {
  2077. ...textMessage('manual-checkpoint', 'checkpoint'),
  2078. source: {
  2079. kind: 'plugin',
  2080. plugin: 'compact',
  2081. compactionId: 'manual-1',
  2082. sourceCommandId: 'command-1',
  2083. },
  2084. }, { surfaceOp: { op: 'replace', start: 1, end: 2 } }),
  2085. at(22, 'command/done', {
  2086. commandId: 'command-1',
  2087. kind: 'success',
  2088. sourceEventSeq: 20,
  2089. }),
  2090. ], true)
  2091. const tool = node(snapshot(value), 'tool-call')
  2092. const root = (tool?.data as ToolChatData).root
  2093. expect(root.subCalls).toHaveLength(1)
  2094. expect(root.subCalls[0]).toMatchObject({ callId: 'child', kind: 'tool-result' })
  2095. const manual = node(snapshot(value), 'manual-compaction')
  2096. expect((manual?.data as ManualCompactionChatData)).toMatchObject({
  2097. command: { commandId: 'command-1', name: 'compact', outcome: { kind: 'success' } },
  2098. compaction: { summary: 'manual summary', summaryEventSeq: 20 },
  2099. })
  2100. })
  2101. })