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

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