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

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