transcript-hydration.test.ts 122 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496
  1. // M4 transcript→event 合成 golden(13 §9 reduce(transcript) ≡ reduce(events) 的子集)。
  2. import { describe, expect, it } from "vitest";
  3. import {
  4. CompactTimelineStatus,
  5. CompactTrigger,
  6. ModelErrorCode,
  7. SessionEventType,
  8. STREAM_RECOVERY_DISCARDED_ERROR_NAME,
  9. STREAM_RECOVERY_DISCARDED_FINISH,
  10. type MessagePart,
  11. type MessageWithParts,
  12. type SessionEvent,
  13. } from "@zcode/contracts";
  14. import {
  15. toolCallGetWorkflowRunDisplaySchema,
  16. type CommandEnvelope,
  17. } from "@zcode/shared/zcode-protocol-v4";
  18. import { ProductProjection } from "../src/zcode-protocol-v4/index.js";
  19. import { inputIntentMetadata } from "../src/zcode-protocol-v4/commands/input-intent.js";
  20. import {
  21. eventsCoverTranscript,
  22. synthesizeEventsFromMessages,
  23. } from "../src/zcode-protocol-v4/transcript-hydration.js";
  24. function userMessage(id: string, text: string, created: number): MessageWithParts {
  25. return {
  26. info: {
  27. id: id as never,
  28. sessionID: "s1" as never,
  29. role: "user",
  30. time: { created },
  31. agent: "default",
  32. modelSelection: { providerId: "p" as never, modelId: "m" as never },
  33. },
  34. parts: [
  35. {
  36. id: `${id}-t` as never,
  37. sessionID: "s1" as never,
  38. messageID: id as never,
  39. type: "text",
  40. text,
  41. },
  42. ],
  43. };
  44. }
  45. function syntheticUserMessage(
  46. id: string,
  47. text: string,
  48. created: number,
  49. options: {
  50. metadata?: Record<string, unknown>;
  51. semantics?: MessageWithParts["info"]["semantics"];
  52. source?: string;
  53. visibility?: string;
  54. } = {},
  55. ): MessageWithParts {
  56. return {
  57. info: {
  58. id: id as never,
  59. sessionID: "s1" as never,
  60. role: "user",
  61. time: { created },
  62. agent: "default",
  63. modelSelection: { providerId: "p" as never, modelId: "m" as never },
  64. metadata: options.metadata,
  65. semantics: options.semantics,
  66. source: options.source as never,
  67. synthetic: true,
  68. visibility: options.visibility as never,
  69. },
  70. parts: [
  71. {
  72. id: `${id}-t` as never,
  73. sessionID: "s1" as never,
  74. messageID: id as never,
  75. type: "text",
  76. text,
  77. metadata: options.metadata,
  78. synthetic: true,
  79. },
  80. ],
  81. };
  82. }
  83. function assistantMessage(
  84. id: string,
  85. parentId: string,
  86. text: string,
  87. created: number,
  88. completed = created + 1,
  89. ): MessageWithParts {
  90. return {
  91. info: {
  92. id: id as never,
  93. sessionID: "s1" as never,
  94. role: "assistant",
  95. time: { created, completed },
  96. parentID: parentId as never,
  97. modelId: "m" as never,
  98. providerId: "p" as never,
  99. mode: "default",
  100. agent: "default",
  101. path: { cwd: "/", root: "/" },
  102. cost: 0,
  103. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  104. },
  105. parts: [
  106. {
  107. id: `${id}-t` as never,
  108. sessionID: "s1" as never,
  109. messageID: id as never,
  110. type: "text",
  111. text,
  112. },
  113. ],
  114. };
  115. }
  116. function assistantMessageWithParts(
  117. id: string,
  118. parentId: string,
  119. parts: MessagePart[],
  120. created: number,
  121. ): MessageWithParts {
  122. return {
  123. ...assistantMessage(id, parentId, "", created),
  124. parts,
  125. };
  126. }
  127. function reduce(messages: MessageWithParts[]) {
  128. const events = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  129. const projection = new ProductProjection("s1", "epoch");
  130. for (const event of events) projection.applyEvent(event);
  131. return { events, projection };
  132. }
  133. describe("transcript→event 合成", () => {
  134. it("冷恢复把缺少完成时间的 orphan assistant 收口为 completedInterrupted", () => {
  135. const user = userMessage("u-orphan", "执行任务", 1000);
  136. const orphan = assistantMessage("a-orphan", "u-orphan", "未完成的部分结果", 1001);
  137. delete orphan.info.time.completed;
  138. const { events, projection } = reduce([user, orphan]);
  139. expect(events).toContainEqual(
  140. expect.objectContaining({
  141. type: SessionEventType.TurnComplete,
  142. payload: expect.objectContaining({ resultType: "cancelled" }),
  143. }),
  144. );
  145. expect(projection.getSnapshot().control.phase).toBe("completedInterrupted");
  146. expect(projection.getSnapshot().rows.window).toContainEqual(
  147. expect.objectContaining({ kind: "turnHeader", state: "completedInterrupted" }),
  148. );
  149. });
  150. it("冷恢复从最终 assistant anchor 恢复 query 历史轮次数", () => {
  151. const user = userMessage("u-round", "问题", 1000);
  152. user.info.anchor = { sourceCommandId: "query-round" };
  153. const assistant = assistantMessage("a-round", "u-round", "回答", 1001);
  154. assistant.info.anchor = { historyRoundCount: 3 };
  155. const { projection } = reduce([user, assistant]);
  156. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  157. expect(header).toMatchObject({
  158. kind: "turnHeader",
  159. sourceCommandId: "query-round",
  160. historyRoundCount: 3,
  161. state: "completedSuccess",
  162. });
  163. });
  164. it("OTC08 cold:持久化 finish=length 的连续正文恢复为一条 assistantText", () => {
  165. const user = userMessage("u-output-continue", "写一段长回复", 1000);
  166. const first = assistantMessage("a-output-p1", user.info.id, "即使底层已经", 1001);
  167. first.info.finish = "length";
  168. const second = assistantMessage("a-output-p2", user.info.id, "发起新的请求并停在", 1002);
  169. second.info.finish = "length";
  170. const final = assistantMessage("a-output-p3", user.info.id, "一个尚未完成的位置。", 1003);
  171. final.info.finish = "end_turn";
  172. const { projection } = reduce([user, first, second, final]);
  173. const snapshot = projection.getSnapshot();
  174. const assistantRows = snapshot.rows.window.filter((row) => row.kind === "assistantText");
  175. expect(assistantRows).toHaveLength(1);
  176. expect(assistantRows[0]).toMatchObject({
  177. text: "即使底层已经发起新的请求并停在一个尚未完成的位置。",
  178. assistantResponseId: "a-output-p3",
  179. entityId: "a-output-p3",
  180. state: "complete",
  181. });
  182. expect(projection.getMessageIdForRow(assistantRows[0]!.rowId)).toBe("a-output-p3");
  183. const header = snapshot.rows.window.find((row) => row.kind === "turnHeader");
  184. expect(projection.getMessageIdsForTurnRow(header!.rowId)).toEqual(
  185. expect.arrayContaining(["u-output-continue", "a-output-p1", "a-output-p2", "a-output-p3"]),
  186. );
  187. });
  188. it("冷恢复使用调用方注入的当前模型上下文窗口", () => {
  189. const events = synthesizeEventsFromMessages(
  190. [
  191. userMessage("u-context-window", "问题", 1000),
  192. assistantMessage("a-context-window", "u-context-window", "回答", 1001),
  193. ],
  194. { sessionId: "s1", contextWindow: 1_000_000 },
  195. );
  196. expect(events.find((event) => event.type === SessionEventType.SessionCreated)?.payload).toEqual(
  197. {
  198. mode: "default",
  199. contextWindow: 1_000_000,
  200. },
  201. );
  202. expect(
  203. events.find((event) => event.type === SessionEventType.ModelComplete)?.payload,
  204. ).toMatchObject({ contextWindow: 1_000_000 });
  205. });
  206. it("assistant feedback 从 transcript metadata 恢复为权威 row 字段", () => {
  207. const assistant = assistantMessage("a-feedback", "u-feedback", "回复", 1001);
  208. assistant.info.metadata = { assistantFeedback: "like" };
  209. const { events, projection } = reduce([userMessage("u-feedback", "问题", 1000), assistant]);
  210. expect(events).toContainEqual(
  211. expect.objectContaining({
  212. type: SessionEventType.AssistantFeedbackUpdated,
  213. payload: { entityId: "a-feedback", feedback: "like" },
  214. }),
  215. );
  216. expect(
  217. projection
  218. .getSnapshot()
  219. .rows.window.find((row) => row.kind === "assistantText" && row.entityId === "a-feedback"),
  220. ).toMatchObject({ feedback: "like" });
  221. projection.applyEvent({
  222. id: "feedback-clear" as never,
  223. sessionId: "s1" as never,
  224. turnId: events.find((event) => event.type === SessionEventType.TurnStarted)?.turnId,
  225. type: SessionEventType.AssistantFeedbackUpdated,
  226. timestamp: new Date(2000),
  227. traceId: "trace-feedback" as never,
  228. sequenceNumber: (events.at(-1)?.sequenceNumber ?? 0) + 1,
  229. payload: { entityId: "a-feedback", feedback: null },
  230. });
  231. expect(
  232. projection
  233. .getSnapshot()
  234. .rows.window.find((row) => row.kind === "assistantText" && row.entityId === "a-feedback"),
  235. ).not.toHaveProperty("feedback");
  236. });
  237. it("首订阅晚于完成时仍从真实持久化语义恢复 assistant 正文", () => {
  238. const persistedAssistant = assistantMessage("a1", "u1", "快速首轮回复", 1001);
  239. const messages = [
  240. userMessage("u1", "开始", 1000),
  241. {
  242. ...persistedAssistant,
  243. info: {
  244. ...persistedAssistant.info,
  245. semantics: {
  246. origin: "agent_runtime",
  247. kind: "assistant_response",
  248. uiVisibility: "visible",
  249. providerVisibility: "visible",
  250. transcriptVisibility: "visible",
  251. },
  252. } as MessageWithParts["info"],
  253. },
  254. ];
  255. const { events, projection } = reduce(messages);
  256. const visibleTexts = projection
  257. .getSnapshot()
  258. .rows.window.filter((row) => row.kind === "userInput" || row.kind === "assistantText")
  259. .map((row) => row.text);
  260. expect(visibleTexts).toEqual(["开始", "快速首轮回复"]);
  261. expect(eventsCoverTranscript(events, messages)).toBe(true);
  262. });
  263. it("user+assistant 文本轮 → userInput + assistantText rows", () => {
  264. const messages = [
  265. userMessage("u1", "问题一", 1000),
  266. assistantMessage("a1", "u1", "回答一", 1001),
  267. userMessage("u2", "问题二", 2000),
  268. assistantMessage("a2", "u2", "回答二", 2001),
  269. ];
  270. const { events, projection } = reduce(messages);
  271. const rows = projection.getSnapshot().rows.window;
  272. const texts = rows
  273. .filter((r) => r.kind === "userInput" || r.kind === "assistantText")
  274. .map((r) => (r.kind === "userInput" || r.kind === "assistantText" ? r.text : ""));
  275. expect(texts).toEqual(["问题一", "回答一", "问题二", "回答二"]);
  276. // 两轮都 completedSuccess。
  277. const turnHeaders = rows.filter((r) => r.kind === "turnHeader");
  278. expect(turnHeaders).toHaveLength(2);
  279. expect(
  280. turnHeaders.every((r) => r.kind === "turnHeader" && r.state === "completedSuccess"),
  281. ).toBe(true);
  282. const starts = events.filter((event) => event.type === SessionEventType.TurnStarted);
  283. expect(starts.map((event) => (event.payload as { messageId?: string }).messageId)).toEqual([
  284. "u1",
  285. "u2",
  286. ]);
  287. const userRows = rows.filter((row) => row.kind === "userInput");
  288. const assistantRows = rows.filter((row) => row.kind === "assistantText");
  289. // Bugfix 回归:cold 合成必须保留各 assistant message 的真实创建时间,不能全部
  290. // 退化成首条 transcript 时间附近的合成序号。
  291. expect(assistantRows.map((row) => row.createdAt)).toEqual([1001, 2001]);
  292. expect(userRows[0]?.actions?.canEdit).not.toBe(true);
  293. expect(userRows[1]?.actions?.canEdit).toBe(true);
  294. expect(projection.getMessageIdForRow(userRows[1]!.rowId)).toBe("u2");
  295. expect(projection.getTurnRewindAnchor(userRows[1]!.rowId)).toBe("u2");
  296. });
  297. it("canonical assistant 与 interrupted ExitPlanMode 冷恢复后仍保留可见行", () => {
  298. const assistant = assistantMessageWithParts(
  299. "a-plan",
  300. "u-plan",
  301. [
  302. {
  303. id: "a-plan-text" as never,
  304. sessionID: "s1" as never,
  305. messageID: "a-plan" as never,
  306. type: "text",
  307. text: "计划如下",
  308. },
  309. {
  310. id: "a-plan-tool" as never,
  311. sessionID: "s1" as never,
  312. messageID: "a-plan" as never,
  313. type: "tool",
  314. callID: "call-plan",
  315. tool: "ExitPlanMode",
  316. state: {
  317. status: "running",
  318. input: { plan: "# 实施计划\n\n第一步\n第二步" },
  319. title: "ExitPlanMode",
  320. time: { start: 1001 },
  321. },
  322. },
  323. ],
  324. 1001,
  325. );
  326. assistant.info.semantics = {
  327. kind: "assistant_response",
  328. origin: "agent_runtime",
  329. providerVisibility: "visible",
  330. transcriptVisibility: "visible",
  331. uiVisibility: "visible",
  332. };
  333. const { projection } = reduce([userMessage("u-plan", "写计划", 1000), assistant]);
  334. const rows = projection.getSnapshot().rows.window;
  335. expect(rows.find((row) => row.kind === "assistantText")).toMatchObject({
  336. text: "计划如下",
  337. state: "complete",
  338. });
  339. expect(rows.find((row) => row.kind === "toolCall")).toMatchObject({
  340. input: { plan: "# 实施计划\n\n第一步\n第二步" },
  341. status: "cancelled",
  342. toolCallId: "call-plan",
  343. toolName: "ExitPlanMode",
  344. });
  345. });
  346. it("冷恢复为同一 assistant response 的 reasoning、text 与 CUA tool 投影关联 ID", () => {
  347. const assistant = assistantMessageWithParts(
  348. "a-cua",
  349. "u-cua",
  350. [
  351. {
  352. id: "a-cua-reasoning" as never,
  353. sessionID: "s1" as never,
  354. messageID: "a-cua" as never,
  355. type: "reasoning",
  356. text: "先确认电脑操作权限。",
  357. time: { start: 1001, end: 1002 },
  358. },
  359. {
  360. id: "a-cua-text" as never,
  361. sessionID: "s1" as never,
  362. messageID: "a-cua" as never,
  363. type: "text",
  364. text: "我先检查电脑操作权限与应用列表。",
  365. },
  366. {
  367. id: "a-cua-tool" as never,
  368. sessionID: "s1" as never,
  369. messageID: "a-cua" as never,
  370. type: "tool",
  371. callID: "call-cua",
  372. tool: "mcp__computer-use__request_access",
  373. state: {
  374. status: "running",
  375. input: {},
  376. title: "request_access",
  377. time: { start: 1001 },
  378. },
  379. },
  380. ],
  381. 1001,
  382. );
  383. const rows = reduce([
  384. userMessage("u-cua", "检查权限", 1000),
  385. assistant,
  386. ]).projection.getSnapshot().rows.window;
  387. expect(rows.find((row) => row.kind === "reasoning")?.assistantResponseId).toBe("a-cua");
  388. expect(rows.find((row) => row.kind === "assistantText")?.assistantResponseId).toBe("a-cua");
  389. expect(rows.find((row) => row.kind === "toolCall")?.assistantResponseId).toBe("a-cua");
  390. });
  391. it("legacy /compact 缺 visibility 时由 CLI hydration 归一化,不下发 visible user row", () => {
  392. const compactHost = assistantMessageWithParts(
  393. "a-compact-legacy",
  394. "u-compact-legacy",
  395. [
  396. {
  397. id: "a-compact-legacy-part" as never,
  398. sessionID: "s1" as never,
  399. messageID: "a-compact-legacy" as never,
  400. type: "timeline",
  401. timelineType: "context_compaction",
  402. display: "separator",
  403. status: CompactTimelineStatus.Completed,
  404. operationId: "cmp-legacy",
  405. trigger: CompactTrigger.Manual,
  406. },
  407. ],
  408. 1001,
  409. );
  410. const { projection } = reduce([
  411. userMessage("u-compact-legacy", "/compact keep recent files", 1000),
  412. compactHost,
  413. ]);
  414. const rows = projection.getSnapshot().rows.window;
  415. expect(rows.some((row) => row.kind === "userInput")).toBe(false);
  416. expect(rows.some((row) => row.kind === "timelineMarker" && row.marker.type === "compact")).toBe(
  417. true,
  418. );
  419. });
  420. it.each([
  421. {
  422. name: "tool-only",
  423. assistant: assistantMessageWithParts(
  424. "a-tool",
  425. "u-latest",
  426. [
  427. {
  428. id: "a-tool-part" as never,
  429. sessionID: "s1" as never,
  430. messageID: "a-tool" as never,
  431. type: "tool" as const,
  432. callID: "call-read",
  433. tool: "Read",
  434. state: {
  435. status: "completed" as const,
  436. input: { file_path: "README.md" },
  437. output: "ok",
  438. title: "Read README.md",
  439. metadata: {},
  440. time: { start: 1001, end: 1002 },
  441. },
  442. },
  443. ],
  444. 1001,
  445. ),
  446. },
  447. {
  448. name: "empty assistant",
  449. assistant: assistantMessage("a-empty", "u-latest", "", 1001),
  450. },
  451. {
  452. name: "failed before first token",
  453. assistant: {
  454. ...assistantMessage("a-failed", "u-latest", "", 1001),
  455. info: {
  456. ...assistantMessage("a-failed", "u-latest", "", 1001).info,
  457. error: { name: "ProviderError" },
  458. },
  459. } satisfies MessageWithParts,
  460. },
  461. ])("cold $name:latest real user 保持可编辑且 target 可解析", ({ assistant }) => {
  462. const { projection } = reduce([userMessage("u-latest", "继续", 1000), assistant]);
  463. const rows = projection.getSnapshot().rows.window;
  464. const userRow = rows.find((row) => row.kind === "userInput");
  465. expect(userRow).toBeDefined();
  466. expect(userRow?.actions?.canEdit).toBe(true);
  467. expect(projection.isLatestEditableUserRow(userRow!.rowId)).toBe(true);
  468. expect(projection.getMessageIdForRow(userRow!.rowId)).toBe("u-latest");
  469. expect(projection.getTurnRewindAnchor(userRow!.rowId)).toBe("u-latest");
  470. expect(rows.some((row) => row.actions?.canRetry === true)).toBe(false);
  471. });
  472. it.each([true, false])(
  473. "cold first-token failure restores retryable=%s from the structured runtime error",
  474. (retryable) => {
  475. const failed = assistantMessage("a-failed-structured", "u-failed", "", 1001);
  476. const { projection } = reduce([
  477. userMessage("u-failed", "trigger failure", 1000),
  478. {
  479. ...failed,
  480. info: {
  481. ...failed.info,
  482. error: {
  483. name: "ProviderError",
  484. data: { message: "rate limited before first token", retryable },
  485. },
  486. },
  487. } satisfies MessageWithParts,
  488. ]);
  489. expect(projection.getSnapshot().control.lastError).toMatchObject({
  490. code: "ProviderError",
  491. message: "rate limited before first token",
  492. recoverable: retryable,
  493. source: "runtime",
  494. });
  495. },
  496. );
  497. it("cold first-token failure restores the same structured attribution as live TurnError", () => {
  498. const failed = assistantMessage("a-failed-attribution", "u-failed-attribution", "", 1001);
  499. const { events, projection } = reduce([
  500. userMessage("u-failed-attribution", "trigger network failure", 1000),
  501. {
  502. ...failed,
  503. info: {
  504. ...failed.info,
  505. error: {
  506. name: "AiSdkModelAdapterError",
  507. data: {
  508. message: "Provider stream failed",
  509. attribution: {
  510. source: "network",
  511. reason: "network_error",
  512. errorPhase: "stream",
  513. exceptionKind: "transport",
  514. providerId: "default-deepseek",
  515. modelId: "deepseek-v4-flash",
  516. providerKind: "anthropic",
  517. transport: "sse",
  518. statusCode: 503,
  519. retryable: true,
  520. },
  521. },
  522. },
  523. },
  524. } satisfies MessageWithParts,
  525. ]);
  526. expect(events).toContainEqual(
  527. expect.objectContaining({
  528. type: SessionEventType.TurnError,
  529. payload: expect.objectContaining({
  530. error: expect.objectContaining({
  531. attribution: expect.objectContaining({
  532. source: "network",
  533. reason: "network_error",
  534. errorPhase: "stream",
  535. exceptionKind: "transport",
  536. transport: "sse",
  537. }),
  538. }),
  539. }),
  540. }),
  541. );
  542. expect(projection.getSnapshot().control.lastError).toMatchObject({
  543. source: "network",
  544. attribution: {
  545. source: "network",
  546. reason: "network_error",
  547. errorPhase: "stream",
  548. exceptionKind: "transport",
  549. providerId: "default-deepseek",
  550. modelId: "deepseek-v4-flash",
  551. providerKind: "anthropic",
  552. transport: "sse",
  553. statusCode: 503,
  554. retryable: true,
  555. },
  556. });
  557. });
  558. it("cold empty output-limit exhaustion restores only its error state", () => {
  559. const failed = assistantMessage("a-output-limit", "u-output-limit", "", 1001);
  560. const { events, projection } = reduce([
  561. userMessage("u-output-limit", "exhaust output continuation", 1000),
  562. {
  563. ...failed,
  564. info: {
  565. ...failed.info,
  566. error: {
  567. name: "model_output_limit_exceeded",
  568. data: {
  569. code: "model_output_limit_exceeded",
  570. message: "The model's response exceeded the output token maximum.",
  571. retryable: true,
  572. attribution: {
  573. source: "provider",
  574. reason: "model_output_limit_exceeded",
  575. providerErrorCode: "model_output_limit_exceeded",
  576. },
  577. },
  578. },
  579. },
  580. } satisfies MessageWithParts,
  581. ]);
  582. expect(events).toContainEqual(
  583. expect.objectContaining({
  584. type: SessionEventType.TurnError,
  585. payload: expect.objectContaining({
  586. error: expect.objectContaining({
  587. type: "model_output_limit_exceeded",
  588. message: "The model's response exceeded the output token maximum.",
  589. retryable: true,
  590. attribution: expect.objectContaining({ source: "provider" }),
  591. }),
  592. }),
  593. }),
  594. );
  595. const snapshot = projection.getSnapshot();
  596. expect(snapshot.rows.window.some((row) => row.kind === "assistantText")).toBe(false);
  597. expect(snapshot.control.lastError).toMatchObject({
  598. code: "model_output_limit_exceeded",
  599. message: "The model's response exceeded the output token maximum.",
  600. recoverable: true,
  601. source: "provider",
  602. });
  603. });
  604. it.each([
  605. {
  606. name: "typed cancellation",
  607. error: {
  608. name: "AiSdkModelAdapterError",
  609. data: {
  610. code: ModelErrorCode.ModelRequestCancelled,
  611. message: "Model request was cancelled.",
  612. turnResult: "cancelled",
  613. },
  614. },
  615. },
  616. {
  617. name: "legacy canonical cancellation",
  618. error: {
  619. name: "AiSdkModelAdapterError",
  620. data: { message: "Model request was cancelled." },
  621. },
  622. },
  623. {
  624. name: "legacy protocol session stop",
  625. error: {
  626. name: "Error",
  627. data: { message: "ZCode Protocol session stopped" },
  628. },
  629. },
  630. ])("cold $name restores interrupted completion instead of TurnError", ({ error }) => {
  631. const cancelled = assistantMessage("a-cancelled", "u-cancelled", "partial", 1001);
  632. const { events, projection } = reduce([
  633. userMessage("u-cancelled", "stop this turn", 1000),
  634. {
  635. ...cancelled,
  636. info: { ...cancelled.info, error },
  637. } satisfies MessageWithParts,
  638. ]);
  639. expect(events.some((event) => event.type === SessionEventType.TurnError)).toBe(false);
  640. expect(events).toContainEqual(
  641. expect.objectContaining({
  642. type: SessionEventType.TurnComplete,
  643. payload: expect.objectContaining({ resultType: "cancelled", historyRoundCount: 1 }),
  644. }),
  645. );
  646. expect(projection.getSnapshot().control).toMatchObject({
  647. phase: "completedInterrupted",
  648. lastError: null,
  649. });
  650. expect(projection.getSnapshot().rows.window).toContainEqual(
  651. expect.objectContaining({ kind: "turnHeader", state: "completedInterrupted" }),
  652. );
  653. });
  654. function streamRecoveryDiscardedMessage(id: string, parentId: string, created: number) {
  655. const discarded = assistantMessage(id, parentId, "partial output", created);
  656. return {
  657. ...discarded,
  658. info: {
  659. ...discarded.info,
  660. finish: STREAM_RECOVERY_DISCARDED_FINISH,
  661. error: {
  662. name: STREAM_RECOVERY_DISCARDED_ERROR_NAME,
  663. data: {
  664. message: "Partial assistant output was discarded before a streaming retry.",
  665. retryNumber: 1,
  666. },
  667. },
  668. },
  669. } satisfies MessageWithParts;
  670. }
  671. it("cold stream recovery discard followed by a recovered answer restores success, not TurnError", () => {
  672. const { events, projection } = reduce([
  673. userMessage("u-recover", "keep going", 1000),
  674. streamRecoveryDiscardedMessage("a-discarded", "u-recover", 1001),
  675. assistantMessage("a-recovered", "u-recover", "final answer", 1003),
  676. ]);
  677. expect(events.some((event) => event.type === SessionEventType.TurnError)).toBe(false);
  678. expect(events).toContainEqual(
  679. expect.objectContaining({
  680. type: SessionEventType.TurnComplete,
  681. payload: expect.objectContaining({ resultType: "success", historyRoundCount: 2 }),
  682. }),
  683. );
  684. const control = projection.getSnapshot().control;
  685. expect(control.lastError).toBeNull();
  686. expect(control.phase).not.toBe("error");
  687. expect(projection.getSnapshot().rows.window).toContainEqual(
  688. expect.objectContaining({ kind: "assistantText", text: "final answer" }),
  689. );
  690. });
  691. it("cold stream recovery discard without a recovered answer restores interrupted completion", () => {
  692. const { events, projection } = reduce([
  693. userMessage("u-recover-lost", "keep going", 1000),
  694. streamRecoveryDiscardedMessage("a-discarded-last", "u-recover-lost", 1001),
  695. ]);
  696. expect(events.some((event) => event.type === SessionEventType.TurnError)).toBe(false);
  697. expect(events).toContainEqual(
  698. expect.objectContaining({
  699. type: SessionEventType.TurnComplete,
  700. payload: expect.objectContaining({ resultType: "cancelled" }),
  701. }),
  702. );
  703. expect(projection.getSnapshot().control).toMatchObject({
  704. phase: "completedInterrupted",
  705. lastError: null,
  706. });
  707. });
  708. it("does not suppress a typed provider failure that reuses the cancellation message", () => {
  709. const failed = assistantMessage("a-failed-cancel-text", "u-failed-cancel-text", "", 1001);
  710. const { events, projection } = reduce([
  711. userMessage("u-failed-cancel-text", "trigger provider failure", 1000),
  712. {
  713. ...failed,
  714. info: {
  715. ...failed.info,
  716. error: {
  717. name: "AiSdkModelAdapterError",
  718. data: {
  719. code: ModelErrorCode.ModelRequestFailed,
  720. message: "Model request was cancelled.",
  721. },
  722. },
  723. },
  724. } satisfies MessageWithParts,
  725. ]);
  726. expect(events.some((event) => event.type === SessionEventType.TurnError)).toBe(true);
  727. expect(projection.getSnapshot().control).toMatchObject({
  728. phase: "error",
  729. lastError: {
  730. code: "AiSdkModelAdapterError",
  731. message: "Model request was cancelled.",
  732. },
  733. });
  734. });
  735. it("live/cold goal use persisted canonical intent text instead of visible command text", () => {
  736. const goalInput = userMessage("u-goal", "/GoAl replace X", 1000);
  737. goalInput.info.anchor = { sourceCommandId: "command-goal" };
  738. goalInput.info.metadata = {
  739. conversationInputIntent: {
  740. sourceCommandId: "command-goal",
  741. queueItemId: "queue_command-goal",
  742. clientId: "desktop-goal",
  743. kind: "sendGoalCommand",
  744. text: "X",
  745. attachments: [],
  746. delivery: { requested: "startNow", admitted: "startNow" },
  747. order: { admissionSeq: 3 },
  748. steer: { state: "notRequested" },
  749. dispatch: { state: "drained" },
  750. admittedAt: 999,
  751. },
  752. };
  753. const { projection: cold } = reduce([
  754. goalInput,
  755. assistantMessage("a-goal", "u-goal", "working on it", 1001),
  756. ]);
  757. const row = cold.getSnapshot().rows.window.find((candidate) => candidate.kind === "userInput");
  758. const envelope = {
  759. type: "sendGoalCommand",
  760. payload: { text: "X", displayText: "/GoAl replace X" },
  761. sessionId: "s1",
  762. commandId: "command-goal",
  763. clientId: "desktop-goal",
  764. baseRevision: 0,
  765. __v4Admission: {
  766. admissionSeq: 3,
  767. admittedAt: 999,
  768. queueItemId: "queue_command-goal",
  769. },
  770. } as unknown as CommandEnvelope;
  771. const liveIntent = inputIntentMetadata(envelope, {
  772. requestedDelivery: "startNow",
  773. text: "X",
  774. });
  775. const live = new ProductProjection("s1", "epoch-live");
  776. live.applyEvent({
  777. id: "live-goal" as never,
  778. sessionId: "s1" as never,
  779. turnId: "runtime-goal" as never,
  780. type: SessionEventType.TurnStarted,
  781. timestamp: new Date(1000),
  782. traceId: "live-goal-trace" as never,
  783. sequenceNumber: 1,
  784. payload: {
  785. turnNumber: 1,
  786. input: "/GoAl replace X",
  787. messageId: "u-goal",
  788. inputId: "command-goal",
  789. intent: liveIntent,
  790. },
  791. });
  792. expect(row).toMatchObject({
  793. entityId: "u-goal",
  794. productTurnId: "u-goal",
  795. sourceCommandId: "command-goal",
  796. actions: { canEdit: true },
  797. });
  798. const coldTarget = cold.resolveEditTargetByEntityId("u-goal");
  799. const liveTarget = live.resolveEditTargetByEntityId("u-goal");
  800. expect(liveTarget).toEqual(coldTarget);
  801. expect(liveTarget).toMatchObject({
  802. coveredByStableCompact: false,
  803. entityId: "u-goal",
  804. productTurnId: "u-goal",
  805. transcriptMessageId: "u-goal",
  806. intent: {
  807. clientId: "desktop-goal",
  808. kind: "sendGoalCommand",
  809. sourceCommandId: "command-goal",
  810. text: "X",
  811. },
  812. });
  813. });
  814. it("cold hydration projects persisted highspeed metadata onto the user input row", () => {
  815. const input = userMessage("u-highspeed", "accelerated prompt", 1000);
  816. input.info.metadata = {
  817. conversationInputIntent: {
  818. sourceCommandId: "command-highspeed",
  819. queueItemId: "queue-highspeed",
  820. clientId: "desktop-highspeed",
  821. kind: "sendText",
  822. text: "accelerated prompt",
  823. attachments: [],
  824. delivery: { requested: "startNow", admitted: "startNow" },
  825. order: { admissionSeq: 5 },
  826. steer: { state: "notRequested" },
  827. dispatch: { state: "drained" },
  828. admittedAt: 1000,
  829. highspeed: {
  830. schemaVersion: 1,
  831. cardId: "hsc-persisted",
  832. taskId: "s1",
  833. provider: "zai",
  834. model: "glm-5",
  835. issuedAt: 900,
  836. expiresAt: 1900,
  837. regularTps: 73,
  838. outputTokens: 120_000,
  839. durationMs: 881_000,
  840. savedDurationMs: 762_836,
  841. // CR-02:fallbackAt 是权威 metadata 字段,cold hydration 必须原样恢复。
  842. fallbackAt: 1500,
  843. },
  844. },
  845. };
  846. const { projection } = reduce([
  847. input,
  848. assistantMessage("a-highspeed", "u-highspeed", "accelerated answer", 1001),
  849. ]);
  850. expect(
  851. projection.getSnapshot().rows.window.find((row) => row.kind === "userInput"),
  852. ).toMatchObject({
  853. sourceCommandId: "command-highspeed",
  854. highspeed: {
  855. schemaVersion: 1,
  856. cardId: "hsc-persisted",
  857. taskId: "s1",
  858. provider: "zai",
  859. model: "glm-5",
  860. issuedAt: 900,
  861. expiresAt: 1900,
  862. regularTps: 73,
  863. outputTokens: 120_000,
  864. durationMs: 881_000,
  865. savedDurationMs: 762_836,
  866. fallbackAt: 1500,
  867. },
  868. });
  869. const turnId = projection
  870. .getSnapshot()
  871. .rows.window.find((row) => row.kind === "turnHeader")?.turnId;
  872. projection.applyEvent({
  873. id: "highspeed-metrics-update" as never,
  874. sessionId: "s1" as never,
  875. turnId,
  876. type: SessionEventType.HighspeedMetricsUpdated,
  877. timestamp: new Date(2000),
  878. traceId: "trace-highspeed" as never,
  879. sequenceNumber: 99,
  880. payload: {
  881. entityId: "u-highspeed",
  882. highspeed: {
  883. schemaVersion: 1,
  884. cardId: "hsc-persisted",
  885. taskId: "s1",
  886. provider: "zai",
  887. model: "glm-5",
  888. issuedAt: 900,
  889. expiresAt: 1900,
  890. regularTps: 73,
  891. outputTokens: 130_000,
  892. durationMs: 900_000,
  893. savedDurationMs: 880_822,
  894. },
  895. },
  896. });
  897. expect(
  898. projection.getSnapshot().rows.window.find((row) => row.kind === "userInput"),
  899. ).toMatchObject({
  900. // CR-02:终态指标更新是字段级合并,不含 fallbackAt 的 payload 不得清掉已持久化的 fallbackAt。
  901. highspeed: { outputTokens: 130_000, savedDurationMs: 880_822, fallbackAt: 1500 },
  902. });
  903. });
  904. it("cold retry intent preserves original cause provenance", () => {
  905. const retried = userMessage("u-retry", "original text", 1000);
  906. retried.info.metadata = {
  907. conversationInputIntent: {
  908. sourceCommandId: "command-retry",
  909. queueItemId: "queue-retry",
  910. clientId: "desktop-new",
  911. kind: "sendText",
  912. text: "original text",
  913. attachments: [],
  914. delivery: { requested: "guide", admitted: "queue" },
  915. order: { admissionSeq: 4 },
  916. steer: {
  917. state: "fellBack",
  918. reasonCode: "guide.attachmentsUnsupported",
  919. },
  920. dispatch: { state: "drained" },
  921. admittedAt: 1000,
  922. provenance: {
  923. sourceCommandId: "command-original",
  924. queueItemId: "queue-original",
  925. clientId: "desktop-original",
  926. },
  927. },
  928. };
  929. const { projection } = reduce([
  930. retried,
  931. assistantMessage("a-retry", "u-retry", "answer", 1001),
  932. ]);
  933. expect(
  934. projection.getSnapshot().rows.window.find((row) => row.kind === "userInput"),
  935. ).toMatchObject({
  936. sourceCommandId: "command-retry",
  937. rootSourceCommandId: "command-original",
  938. });
  939. expect(projection.resolveEditTargetByEntityId("u-retry")).toMatchObject({
  940. intent: {
  941. sourceCommandId: "command-retry",
  942. provenance: {
  943. sourceCommandId: "command-original",
  944. queueItemId: "queue-original",
  945. clientId: "desktop-original",
  946. },
  947. },
  948. });
  949. });
  950. it("cold compact boundary marks only its stable message coverage in the edit target", () => {
  951. const compactHost = assistantMessageWithParts(
  952. "a-compact",
  953. "u-compact",
  954. [
  955. {
  956. id: "compact-boundary-part" as never,
  957. sessionID: "s1" as never,
  958. messageID: "a-compact" as never,
  959. type: "compaction",
  960. auto: false,
  961. operationId: "compact-operation",
  962. timelineStatus: CompactTimelineStatus.Completed,
  963. tail_start_id: "u-compact" as never,
  964. },
  965. ],
  966. 1001,
  967. );
  968. const { projection } = reduce([userMessage("u-compact", "covered input", 1000), compactHost]);
  969. const row = projection
  970. .getSnapshot()
  971. .rows.window.find((candidate) => candidate.kind === "userInput");
  972. expect(projection.resolveEditTarget(row!.rowId)).toMatchObject({
  973. transcriptMessageId: "u-compact",
  974. coveredByStableCompact: true,
  975. });
  976. });
  977. it("cold compact prefers the durable coverage boundary over an earlier timeline part", () => {
  978. const compactHost = assistantMessageWithParts(
  979. "a-compact-durable",
  980. "u-compact-durable",
  981. [
  982. {
  983. id: "compact-timeline-first" as never,
  984. sessionID: "s1" as never,
  985. messageID: "a-compact-durable" as never,
  986. type: "timeline",
  987. timelineType: "context_compaction",
  988. display: "separator",
  989. status: CompactTimelineStatus.Completed,
  990. operationId: "compact-operation-durable",
  991. trigger: CompactTrigger.Manual,
  992. },
  993. {
  994. id: "compact-durable-second" as never,
  995. sessionID: "s1" as never,
  996. messageID: "a-compact-durable" as never,
  997. type: "compaction",
  998. auto: false,
  999. operationId: "compact-operation-durable",
  1000. tail_start_id: "u-compact-durable" as never,
  1001. },
  1002. ],
  1003. 1001,
  1004. );
  1005. const { events } = reduce([
  1006. userMessage("u-compact-durable", "covered input", 1000),
  1007. compactHost,
  1008. ]);
  1009. const completed = events.find((event) => event.type === SessionEventType.CompactCompleted);
  1010. expect(completed?.payload).toMatchObject({
  1011. operationId: "compact-operation-durable",
  1012. tailStartMessageId: "u-compact-durable",
  1013. });
  1014. });
  1015. it("live/cold 的 edit/retry action 与 command target 逐行等价", () => {
  1016. const messages = [
  1017. userMessage("u-live-cold", "问题", 1000),
  1018. assistantMessage("a-live-cold", "u-live-cold", "回答", 1001),
  1019. ];
  1020. const cold = reduce(messages).projection;
  1021. const live = new ProductProjection("s1", "epoch");
  1022. const liveEvents = [
  1023. {
  1024. type: SessionEventType.SessionCreated,
  1025. payload: { mode: "default", contextWindow: 200_000 },
  1026. },
  1027. {
  1028. type: SessionEventType.TurnStarted,
  1029. payload: { turnNumber: 1, input: "问题", messageId: "u-live-cold" },
  1030. turnId: "hydrate-turn-1",
  1031. },
  1032. {
  1033. type: SessionEventType.ModelStreaming,
  1034. payload: {
  1035. kind: "text_start",
  1036. delta: "",
  1037. done: false,
  1038. assistantMessageId: "a-live-cold",
  1039. },
  1040. turnId: "hydrate-turn-1",
  1041. },
  1042. {
  1043. type: SessionEventType.ModelStreaming,
  1044. payload: { kind: "text_delta", delta: "回答", done: false },
  1045. turnId: "hydrate-turn-1",
  1046. },
  1047. {
  1048. type: SessionEventType.ModelStreaming,
  1049. payload: { kind: "text_end", delta: "", done: false },
  1050. turnId: "hydrate-turn-1",
  1051. },
  1052. {
  1053. type: SessionEventType.TurnComplete,
  1054. payload: {
  1055. response: "回答",
  1056. tokenCount: 0,
  1057. toolCallCount: 0,
  1058. duration: 1,
  1059. resultType: "success",
  1060. },
  1061. turnId: "hydrate-turn-1",
  1062. },
  1063. ].map(
  1064. (event, index) =>
  1065. ({
  1066. id: `live-${index + 1}`,
  1067. sessionId: "s1",
  1068. timestamp: new Date(1000 + index),
  1069. traceId: "live-trace",
  1070. sequenceNumber: index + 1,
  1071. ...event,
  1072. }) as unknown as SessionEvent,
  1073. );
  1074. for (const event of liveEvents) live.applyEvent(event);
  1075. const coldEntityResolver = (
  1076. cold as unknown as {
  1077. resolveEditTargetByEntityId?: (entityId: string) => unknown;
  1078. }
  1079. ).resolveEditTargetByEntityId;
  1080. const liveEntityResolver = (
  1081. live as unknown as {
  1082. resolveEditTargetByEntityId?: (entityId: string) => unknown;
  1083. }
  1084. ).resolveEditTargetByEntityId;
  1085. expect(coldEntityResolver).toBeTypeOf("function");
  1086. expect(liveEntityResolver).toBeTypeOf("function");
  1087. if (!coldEntityResolver || !liveEntityResolver) return;
  1088. const commandFacts = (
  1089. projection: ProductProjection,
  1090. resolveByEntityId: (entityId: string) => unknown,
  1091. ) =>
  1092. projection
  1093. .getSnapshot()
  1094. .rows.window.filter((row) => row.kind === "userInput" || row.kind === "assistantText")
  1095. .map((row) => {
  1096. const entityId = projection.getEntityIdForRow(row.rowId);
  1097. return {
  1098. actions: row.actions,
  1099. entityId,
  1100. kind: row.kind,
  1101. messageId: projection.getMessageIdForRow(row.rowId),
  1102. rewindAnchor: projection.getTurnRewindAnchor(row.rowId),
  1103. target: entityId ? resolveByEntityId.call(projection, entityId) : null,
  1104. text: row.text,
  1105. };
  1106. });
  1107. expect(commandFacts(cold, coldEntityResolver)).toEqual(commandFacts(live, liveEntityResolver));
  1108. expect(commandFacts(cold, coldEntityResolver)).toEqual(
  1109. expect.arrayContaining([
  1110. expect.objectContaining({
  1111. entityId: "u-live-cold",
  1112. target: {
  1113. coveredByStableCompact: false,
  1114. entityId: "u-live-cold",
  1115. intent: { kind: "sendText", text: "问题" },
  1116. productTurnId: "u-live-cold",
  1117. transcriptMessageId: "u-live-cold",
  1118. },
  1119. }),
  1120. ]),
  1121. );
  1122. for (const row of cold.getSnapshot().rows.window) {
  1123. if (row.actions?.canEdit) {
  1124. expect(cold.getMessageIdForRow(row.rowId)).not.toBeNull();
  1125. expect(cold.getTurnRewindAnchor(row.rowId)).not.toBeNull();
  1126. }
  1127. if (row.actions?.canRetry) expect(cold.getMessageIdForRow(row.rowId)).not.toBeNull();
  1128. }
  1129. });
  1130. it("冷恢复用同一轮历史消息跨度合成 turnHeader activeMs", () => {
  1131. const messages = [
  1132. userMessage("u1", "排查一个慢任务", 1000),
  1133. assistantMessage("a1", "u1", "先读文件", 1200, 3400),
  1134. assistantMessage("a2", "u1", "再跑命令", 5000, 61_000),
  1135. ];
  1136. const { events, projection } = reduce(messages);
  1137. const turnComplete = events.find((event) => event.type === SessionEventType.TurnComplete);
  1138. expect(turnComplete?.payload).toMatchObject({ duration: 60_000 });
  1139. const turnHeader = projection
  1140. .getSnapshot()
  1141. .rows.window.find((row) => row.kind === "turnHeader");
  1142. expect(turnHeader).toMatchObject({
  1143. activeMs: 60_000,
  1144. state: "completedSuccess",
  1145. });
  1146. });
  1147. it("assistant 行携带 assistantMessageId → fork-of-fork 可解析", () => {
  1148. const messages = [userMessage("u1", "hi", 1000), assistantMessage("a1", "u1", "yo", 1001)];
  1149. const { projection } = reduce(messages);
  1150. const assistantRow = projection
  1151. .getSnapshot()
  1152. .rows.window.find((r) => r.kind === "assistantText");
  1153. expect(assistantRow).toBeDefined();
  1154. // messageId 侧表用合成时的 assistant message id。
  1155. expect(projection.getMessageIdForRow(assistantRow!.rowId)).toBe("a1");
  1156. });
  1157. it("eventsCoverTranscript:事件日志缺 user 轮 → false(应改走合成)", () => {
  1158. const messages = [userMessage("u1", "a", 1000), assistantMessage("a1", "u1", "b", 1001)];
  1159. // 空事件日志 vs 有 1 个 user 消息 → 不覆盖。
  1160. expect(eventsCoverTranscript([], messages)).toBe(false);
  1161. // 合成出的事件 → 覆盖。
  1162. const { events } = reduce(messages);
  1163. expect(eventsCoverTranscript(events, messages)).toBe(true);
  1164. });
  1165. it("model-only 唤醒(goal continuation)开独立 model-only 轮,无可见气泡(S11/BG-wake-cold)", () => {
  1166. // 16-plan P2 语义变更(2026-07-08):wake/continuation 触发的 synthetic user
  1167. // 与 live 一致开 model-only 轮(旧冷路径把其后 assistant 并进上一轮——前审 F2 分叉)。
  1168. const messages = [
  1169. userMessage("u1", "a", 1000),
  1170. assistantMessage("a1", "u1", "b", 1002),
  1171. syntheticUserMessage("u_goal", "continue goal", 2000, {
  1172. metadata: { source: "goal-continuation", visibility: "model-only" },
  1173. source: "goal-continuation",
  1174. visibility: "model-only",
  1175. }),
  1176. assistantMessage("a2", "u_goal", "续跑产出", 2001),
  1177. ];
  1178. const { events, projection } = reduce(messages);
  1179. const turnStarts = events.filter((event) => event.type === SessionEventType.TurnStarted);
  1180. expect(turnStarts).toHaveLength(2);
  1181. expect(turnStarts[1]?.payload).toMatchObject({
  1182. inputVisibility: "model-only",
  1183. inputSource: "goal-continuation",
  1184. messageId: "u_goal",
  1185. });
  1186. expect(eventsCoverTranscript(events, messages)).toBe(true);
  1187. const rows = projection.getSnapshot().rows.window;
  1188. // 唤醒轮无可见 user 气泡;两轮 assistant 内容都在、各归自己的轮。
  1189. const userRows = rows.filter((row) => row.kind === "userInput");
  1190. expect(userRows).toHaveLength(1);
  1191. expect(userRows[0]?.kind === "userInput" ? userRows[0].text : "").toBe("a");
  1192. const assistantRows = rows.filter((row) => row.kind === "assistantText");
  1193. expect(assistantRows.map((row) => row.turnId)).toEqual(["u1", "u_goal"]);
  1194. expect(rows.filter((row) => row.kind === "turnHeader")).toHaveLength(2);
  1195. });
  1196. it("H17 cold:切模型后的 controlOnly goal query 与 continuation 保持独立执行语义", () => {
  1197. const previousUser = userMessageWithModel("u-before-goal", "上一轮", 1000, {
  1198. providerId: "p1",
  1199. modelId: "m1",
  1200. });
  1201. const previousAssistant = assistantMessage("a-before-goal", "u-before-goal", "完成", 1001);
  1202. previousAssistant.info.providerId = "p1" as never;
  1203. previousAssistant.info.modelId = "m1" as never;
  1204. const goalInput = userMessageWithModel("u-goal", "/Goal 开发招投标系统", 2000, {
  1205. providerId: "p2",
  1206. modelId: "m2",
  1207. });
  1208. goalInput.info.metadata = { executionKind: "controlOnly" };
  1209. const continuation = syntheticUserMessage("u-goal-continuation", "继续目标", 2001, {
  1210. metadata: { source: "goal-continuation", visibility: "model-only" },
  1211. source: "goal-continuation",
  1212. visibility: "model-only",
  1213. });
  1214. continuation.info.modelSelection = { providerId: "p2" as never, modelId: "m2" as never };
  1215. const continuationAssistant = assistantMessage(
  1216. "a-goal-continuation",
  1217. "u-goal-continuation",
  1218. "执行中",
  1219. 2002,
  1220. );
  1221. continuationAssistant.info.providerId = "p2" as never;
  1222. continuationAssistant.info.modelId = "m2" as never;
  1223. const messages = [
  1224. previousUser,
  1225. previousAssistant,
  1226. goalInput,
  1227. continuation,
  1228. continuationAssistant,
  1229. ];
  1230. const events = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  1231. const goalStart = events.find(
  1232. (event) =>
  1233. event.type === SessionEventType.TurnStarted &&
  1234. (event.payload as { messageId?: string }).messageId === "u-goal",
  1235. );
  1236. expect(goalStart?.payload).toMatchObject({ executionKind: "controlOnly" });
  1237. const projection = new ProductProjection("s1", "epoch");
  1238. let activeMessageId: string | undefined;
  1239. for (const event of events) {
  1240. if (event.type === SessionEventType.TurnStarted) {
  1241. activeMessageId = (event.payload as { messageId?: string }).messageId;
  1242. }
  1243. projection.applyEvent(event);
  1244. if (event.type === SessionEventType.TurnComplete && activeMessageId === "u-goal") {
  1245. expect(projection.getSnapshot().control).toMatchObject({
  1246. phase: "completedSuccess",
  1247. activeWorks: [],
  1248. });
  1249. }
  1250. }
  1251. const rows = projection.getSnapshot().rows.window;
  1252. const headers = rows.filter((row) => row.kind === "turnHeader");
  1253. expect(headers.find((row) => row.turnId === "u-goal")).toMatchObject({
  1254. executionKind: "controlOnly",
  1255. state: "completedSuccess",
  1256. });
  1257. expect(headers.find((row) => row.turnId === "u-goal")).not.toHaveProperty("activeMs");
  1258. expect(headers.find((row) => row.turnId === "u-goal-continuation")).toMatchObject({
  1259. executionKind: "agent",
  1260. state: "completedSuccess",
  1261. });
  1262. expect(
  1263. rows.filter((row) => row.kind === "timelineMarker" && row.marker.type === "modelChange"),
  1264. ).toHaveLength(1);
  1265. expect(eventsCoverTranscript(events, messages)).toBe(true);
  1266. });
  1267. it("cold hydration strips the withdrawn refined names from a persisted CreateWorkflow display", () => {
  1268. // docs/dynamic-workflow/presentation.md:旧 part 的 display 里还带着
  1269. // `refinedName` / `refinedLabel`,而渲染端按严格 schema 校验每一帧。三个携带 display 的
  1270. // 事件都必须拿到剥离后的同一份,否则旧会话在订阅时整帧被拒。
  1271. const plainGraph = {
  1272. steps: [{ id: "ask#1", kind: "ask", label: "planner", lane: "actor#1", phase: "phase#1" }],
  1273. lanes: [{ id: "actor#1", name: "planner" }],
  1274. participants: [
  1275. { id: "phase#1:actor#1", phase: "phase#1", lane: "actor#1", steps: ["ask#1"] },
  1276. ],
  1277. handoffs: [],
  1278. phases: [{ id: "phase#1", name: "plan" }],
  1279. };
  1280. const refinedGraph = {
  1281. ...plainGraph,
  1282. steps: [{ ...plainGraph.steps[0], refinedLabel: "拟定计划" }],
  1283. lanes: [{ ...plainGraph.lanes[0], refinedName: "规划者" }],
  1284. phases: [{ ...plainGraph.phases[0], refinedName: "规划" }],
  1285. };
  1286. const displayOf = (causalityGraph: unknown) => ({
  1287. kind: "create_workflow",
  1288. ok: true,
  1289. errorCount: 0,
  1290. diagnostics: [],
  1291. causalityGraph,
  1292. });
  1293. const messages = [
  1294. userMessage("u1", "run the workflow", 1000),
  1295. assistantMessageWithParts(
  1296. "a1",
  1297. "u1",
  1298. [
  1299. {
  1300. id: "a1-tool-create-workflow" as never,
  1301. sessionID: "s1" as never,
  1302. messageID: "a1" as never,
  1303. type: "tool",
  1304. callID: "call-create-workflow",
  1305. tool: "CreateWorkflow",
  1306. state: {
  1307. status: "completed",
  1308. input: { script: "phase('plan'); return await agent('planner').ask('plan');" },
  1309. output: "started",
  1310. title: "CreateWorkflow",
  1311. metadata: { schemaVersion: 1, display: displayOf(refinedGraph) },
  1312. time: { start: 1001, end: 1002 },
  1313. },
  1314. },
  1315. ],
  1316. 1001,
  1317. ),
  1318. ];
  1319. const { events } = reduce(messages);
  1320. const displays = events
  1321. .filter(
  1322. (event) =>
  1323. event.type === SessionEventType.ToolCallScheduled ||
  1324. event.type === SessionEventType.ToolCallStarted ||
  1325. event.type === SessionEventType.ToolCallResult,
  1326. )
  1327. .map((event) => {
  1328. const payload = event.payload as { display?: unknown; result?: { display?: unknown } };
  1329. return payload.display ?? payload.result?.display;
  1330. });
  1331. expect(displays).toHaveLength(3);
  1332. for (const display of displays) expect(display).toEqual(displayOf(plainGraph));
  1333. });
  1334. it("cold hydration strips providerStop from a persisted GetWorkflowRun display", () => {
  1335. // docs/dynamic-workflow/launch.md「Their cards」:旧 part 的 display 里还带着工具输出
  1336. // 那份 `error.providerStop`,而渲染端按镜像 schema 校验每一帧。三个携带 display
  1337. // 的事件都必须拿到剥离后的同一份,否则这个会话一订阅就整帧被拒。
  1338. const plainDisplay = {
  1339. kind: "get_workflow_run",
  1340. runId: "dwfrun_stopped",
  1341. label: "nightly-sync",
  1342. status: "stopped",
  1343. stopReason: "provider",
  1344. usage: {
  1345. spentTokens: 12_345,
  1346. nodesObserved: 7,
  1347. nodesRunning: 0,
  1348. nodesCompleted: 4,
  1349. nodesFailed: 1,
  1350. },
  1351. actors: [{ siteId: "agent#1", ordinal: 1, name: "scout" }],
  1352. logTail: [{ sequence: 1, message: "started" }],
  1353. error: { code: "ProviderStop", message: "The provider stopped the run: rate limited." },
  1354. };
  1355. const persistedDisplay = {
  1356. ...plainDisplay,
  1357. error: {
  1358. ...plainDisplay.error,
  1359. providerStop: { kind: "quota", reason: "rate_limited", providerCode: "1308" },
  1360. },
  1361. };
  1362. const messages = [
  1363. userMessage("u1", "how is the run doing", 1000),
  1364. assistantMessageWithParts(
  1365. "a1",
  1366. "u1",
  1367. [
  1368. {
  1369. id: "a1-tool-get-workflow-run" as never,
  1370. sessionID: "s1" as never,
  1371. messageID: "a1" as never,
  1372. type: "tool",
  1373. callID: "call-get-workflow-run",
  1374. tool: "GetWorkflowRun",
  1375. state: {
  1376. status: "completed",
  1377. input: { run_id: "dwfrun_stopped" },
  1378. output: "stopped",
  1379. title: "GetWorkflowRun",
  1380. metadata: { schemaVersion: 1, display: persistedDisplay },
  1381. time: { start: 1001, end: 1002 },
  1382. },
  1383. },
  1384. ],
  1385. 1001,
  1386. ),
  1387. ];
  1388. const { events } = reduce(messages);
  1389. const displays = events
  1390. .filter(
  1391. (event) =>
  1392. event.type === SessionEventType.ToolCallScheduled ||
  1393. event.type === SessionEventType.ToolCallStarted ||
  1394. event.type === SessionEventType.ToolCallResult,
  1395. )
  1396. .map((event) => {
  1397. const payload = event.payload as { display?: unknown; result?: { display?: unknown } };
  1398. return payload.display ?? payload.result?.display;
  1399. });
  1400. expect(displays).toHaveLength(3);
  1401. for (const display of displays) {
  1402. expect(display).toEqual(plainDisplay);
  1403. // 水合出来的每一帧都要过渲染端那把尺。
  1404. const mirrored = toolCallGetWorkflowRunDisplaySchema.strict().safeParse(display);
  1405. expect(mirrored.success ? [] : mirrored.error.issues).toEqual([]);
  1406. }
  1407. });
  1408. it("BG26:cold hydration 保留 background notification 原文并恢复 Agent 失败终态", () => {
  1409. const toolCallId = "call-agent-rate-limit";
  1410. const error = "Requests are too frequent. Request id: bg26-cold";
  1411. const result = `Agent general-purpose task \"分析世界杯\" failed. ${error}`;
  1412. const launchOutput = [
  1413. "Async agent launched successfully.",
  1414. "agentId: agent-bg26 (internal ID - do not mention to user.)",
  1415. "The agent is working in the background.",
  1416. ].join("\n");
  1417. const messages = [
  1418. userMessage("u1", "launch agent", 1000),
  1419. assistantMessageWithParts(
  1420. "a1",
  1421. "u1",
  1422. [
  1423. {
  1424. id: "a1-tool-agent-bg26" as never,
  1425. sessionID: "s1" as never,
  1426. messageID: "a1" as never,
  1427. type: "tool",
  1428. callID: toolCallId,
  1429. tool: "Agent",
  1430. state: {
  1431. status: "completed",
  1432. input: {
  1433. description: "分析世界杯",
  1434. run_in_background: true,
  1435. subagent_type: "general-purpose",
  1436. },
  1437. output: launchOutput,
  1438. title: "Agent 分析世界杯",
  1439. metadata: {},
  1440. time: { start: 1001, end: 1002 },
  1441. },
  1442. },
  1443. ],
  1444. 1001,
  1445. ),
  1446. syntheticUserMessage(
  1447. "u-agent-notification",
  1448. [
  1449. "<task-notification>",
  1450. `<tool-use-id>${toolCallId}</tool-use-id>`,
  1451. "<status>failed</status>",
  1452. `<result>${result}</result>`,
  1453. `<error>${error}</error>`,
  1454. "</task-notification>",
  1455. ].join("\n"),
  1456. 2000,
  1457. {
  1458. metadata: { source: "background_task", visibility: "model-only" },
  1459. source: "background_task",
  1460. visibility: "model-only",
  1461. },
  1462. ),
  1463. assistantMessage("a2", "u-agent-notification", "父会话已处理失败", 2001),
  1464. ];
  1465. const { events, projection } = reduce(messages);
  1466. const notificationStart = events
  1467. .filter((event) => event.type === SessionEventType.TurnStarted)
  1468. .find(
  1469. (event) => (event.payload as { messageId?: string }).messageId === "u-agent-notification",
  1470. );
  1471. expect(notificationStart?.payload).toMatchObject({
  1472. inputVisibility: "model-only",
  1473. inputSource: "background_task",
  1474. input: expect.stringContaining(`<tool-use-id>${toolCallId}</tool-use-id>`),
  1475. });
  1476. expect(
  1477. projection.getSnapshot().rows.window.filter((row) => row.kind === "userInput"),
  1478. ).toHaveLength(1);
  1479. expect(
  1480. projection
  1481. .getSnapshot()
  1482. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1483. ).toMatchObject({
  1484. error: {
  1485. code: "fault.runtime.backgroundTaskFailed",
  1486. message: error,
  1487. },
  1488. output: { text: result },
  1489. status: "error",
  1490. });
  1491. expect(
  1492. projection
  1493. .getSnapshot()
  1494. .rows.window.find((row) => row.kind === "subagent" && row.parentToolCallId === toolCallId),
  1495. ).toMatchObject({
  1496. childSessionId: "sess_subagent_agent-bg26",
  1497. });
  1498. });
  1499. it("selection side chat 的继承历史只进 provider context,冷恢复时间线从新问题开始", () => {
  1500. const inheritedUser = userMessage("u_selection_parent", "父任务问题", 1000);
  1501. const inheritedAssistant = assistantMessage(
  1502. "a_selection_parent",
  1503. inheritedUser.info.id,
  1504. "父任务回答",
  1505. 1001,
  1506. );
  1507. const hideInheritedMessage = (message: MessageWithParts): MessageWithParts => ({
  1508. ...message,
  1509. info: {
  1510. ...message.info,
  1511. visibility: "model-only",
  1512. semantics: {
  1513. kind: "system_reminder",
  1514. origin: "migration",
  1515. providerVisibility: "visible",
  1516. transcriptVisibility: "hidden",
  1517. uiVisibility: "hidden",
  1518. },
  1519. },
  1520. });
  1521. const boundary = syntheticUserMessage("u_selection_boundary", "side chat boundary", 1002, {
  1522. source: "selection_side_chat",
  1523. visibility: "model-only",
  1524. semantics: {
  1525. kind: "system_reminder",
  1526. origin: "system",
  1527. providerVisibility: "visible",
  1528. source: "selection_side_chat",
  1529. transcriptVisibility: "hidden",
  1530. uiVisibility: "hidden",
  1531. },
  1532. });
  1533. const sideUser = userMessage("u_selection_visible", "解释这个片段", 2000);
  1534. const sideAssistant = assistantMessage(
  1535. "a_selection_visible",
  1536. sideUser.info.id,
  1537. "这是副屏回答",
  1538. 2001,
  1539. );
  1540. const messages = [
  1541. hideInheritedMessage(inheritedUser),
  1542. hideInheritedMessage(inheritedAssistant),
  1543. boundary,
  1544. sideUser,
  1545. sideAssistant,
  1546. ];
  1547. const { events, projection } = reduce(messages);
  1548. const snapshot = projection.getSnapshot();
  1549. const visibleTexts = snapshot.rows.window
  1550. .filter((row) => row.kind === "userInput" || row.kind === "assistantText")
  1551. .map((row) => row.text);
  1552. expect(eventsCoverTranscript(events, messages)).toBe(true);
  1553. expect(visibleTexts).toEqual(["解释这个片段", "这是副屏回答"]);
  1554. expect(JSON.stringify(snapshot.rows.window)).not.toContain("父任务");
  1555. expect(snapshot.rows.totalCount).toBe(snapshot.rows.window.length);
  1556. });
  1557. it("subagent_message idle carrier 的 live/cold identity 与 fork target 完全一致", () => {
  1558. const carrierId = "u-subagent-message-idle";
  1559. const assistantId = "a-subagent-message-idle";
  1560. const carrier = syntheticUserMessage(carrierId, "internal coordinator response", 1000, {
  1561. metadata: { source: "subagent_message", visibility: "model-only" },
  1562. source: "subagent_message",
  1563. visibility: "model-only",
  1564. });
  1565. const cold = reduce([
  1566. carrier,
  1567. assistantMessage(assistantId, carrierId, "subagent follow-up", 1001),
  1568. ]).projection;
  1569. const live = new ProductProjection("s1", "epoch-live-subagent-message");
  1570. const liveEvents = [
  1571. {
  1572. type: SessionEventType.SessionCreated,
  1573. payload: { mode: "default", contextWindow: 200_000 },
  1574. },
  1575. {
  1576. type: SessionEventType.TurnStarted,
  1577. payload: {
  1578. turnNumber: 1,
  1579. input: "",
  1580. inputVisibility: "model-only",
  1581. inputSource: "subagent_message",
  1582. messageId: carrierId,
  1583. },
  1584. turnId: "runtime-subagent-message-turn",
  1585. },
  1586. {
  1587. type: SessionEventType.ModelStreaming,
  1588. payload: {
  1589. kind: "text_start",
  1590. delta: "",
  1591. done: false,
  1592. assistantMessageId: assistantId,
  1593. },
  1594. turnId: "runtime-subagent-message-turn",
  1595. },
  1596. {
  1597. type: SessionEventType.ModelStreaming,
  1598. payload: { kind: "text_delta", delta: "subagent follow-up", done: false },
  1599. turnId: "runtime-subagent-message-turn",
  1600. },
  1601. {
  1602. type: SessionEventType.ModelStreaming,
  1603. payload: { kind: "text_end", delta: "", done: false },
  1604. turnId: "runtime-subagent-message-turn",
  1605. },
  1606. {
  1607. type: SessionEventType.TurnComplete,
  1608. payload: {
  1609. response: "subagent follow-up",
  1610. tokenCount: 0,
  1611. toolCallCount: 0,
  1612. duration: 1,
  1613. resultType: "success",
  1614. },
  1615. turnId: "runtime-subagent-message-turn",
  1616. },
  1617. ].map(
  1618. (event, index) =>
  1619. ({
  1620. id: `live-subagent-message-${index + 1}`,
  1621. sessionId: "s1",
  1622. timestamp: new Date(1000 + index),
  1623. traceId: "live-subagent-message-trace",
  1624. sequenceNumber: index + 1,
  1625. ...event,
  1626. }) as unknown as SessionEvent,
  1627. );
  1628. for (const event of liveEvents) live.applyEvent(event);
  1629. const identity = (projection: ProductProjection) => {
  1630. const row = projection
  1631. .getSnapshot()
  1632. .rows.window.find((candidate) => candidate.kind === "assistantText");
  1633. expect(row).toBeDefined();
  1634. if (!row) return null;
  1635. const entityId = projection.getEntityIdForRow(row.rowId);
  1636. expect(entityId).toBeTruthy();
  1637. const target = projection.resolveRowActionTarget(
  1638. { rowId: row.rowId, entityId: entityId! },
  1639. "forkAssistant",
  1640. );
  1641. return {
  1642. actionTarget:
  1643. target.ok && target.action === "forkAssistant"
  1644. ? {
  1645. entityId: target.row.entityId,
  1646. messageId: target.messageId,
  1647. productTurnId: target.row.productTurnId,
  1648. }
  1649. : target,
  1650. actions: row.actions,
  1651. entityId,
  1652. messageId: projection.getMessageIdForRow(row.rowId),
  1653. productTurnId: row.productTurnId,
  1654. turnId: row.turnId,
  1655. };
  1656. };
  1657. expect(identity(cold)).toEqual(identity(live));
  1658. expect(identity(cold)).toMatchObject({
  1659. actionTarget: {
  1660. entityId: assistantId,
  1661. messageId: assistantId,
  1662. productTurnId: carrierId,
  1663. },
  1664. entityId: assistantId,
  1665. messageId: assistantId,
  1666. productTurnId: carrierId,
  1667. turnId: carrierId,
  1668. });
  1669. });
  1670. it("BG36:multi-notification batch 冷恢复只生成一个 background result turn", () => {
  1671. const originMeta = {
  1672. backgroundSource: "subagent" as const,
  1673. title: "Inspect renderer state · Inspect service state",
  1674. workId: "batch-agent-1",
  1675. };
  1676. const batchText = [
  1677. "<task-notification><task-id>batch-agent-1</task-id><status>completed</status></task-notification>",
  1678. "<task-notification><task-id>batch-agent-2</task-id><status>completed</status></task-notification>",
  1679. ].join("\n\n");
  1680. const { events, projection } = reduce([
  1681. syntheticUserMessage("wake-batch", batchText, 2000, {
  1682. metadata: { originMeta, source: "background_task", visibility: "model-only" },
  1683. source: "background_task",
  1684. visibility: "model-only",
  1685. }),
  1686. assistantMessage("a-wake-batch", "wake-batch", "processed batch", 2001),
  1687. ]);
  1688. const turnStarts = events.filter((event) => event.type === SessionEventType.TurnStarted);
  1689. const rows = projection.getSnapshot().rows.window;
  1690. expect(turnStarts).toHaveLength(1);
  1691. expect(turnStarts[0]?.payload).toMatchObject({
  1692. input: expect.stringContaining("<task-id>batch-agent-1</task-id>"),
  1693. inputSource: "background_task",
  1694. inputVisibility: "model-only",
  1695. messageId: "wake-batch",
  1696. originMeta,
  1697. });
  1698. expect((turnStarts[0]?.payload as { input?: string }).input).toContain(
  1699. "<task-id>batch-agent-2</task-id>",
  1700. );
  1701. expect(rows.filter((row) => row.kind === "userInput")).toHaveLength(0);
  1702. const turnHeaders = rows.filter((row) => row.kind === "turnHeader");
  1703. expect(turnHeaders).toHaveLength(1);
  1704. expect(turnHeaders[0]).toMatchObject({
  1705. origin: "backgroundResult",
  1706. originMeta,
  1707. });
  1708. const assistantRows = rows.filter((row) => row.kind === "assistantText");
  1709. expect(assistantRows).toHaveLength(1);
  1710. expect(assistantRows[0]).toMatchObject({
  1711. productTurnId: "wake-batch",
  1712. turnId: "wake-batch",
  1713. });
  1714. });
  1715. it("multiple background wakes each keep an independent stable productTurnId", () => {
  1716. const background = (id: string, created: number) =>
  1717. syntheticUserMessage(id, "background result", created, {
  1718. metadata: { source: "background_task", visibility: "model-only" },
  1719. source: "background_task",
  1720. visibility: "model-only",
  1721. });
  1722. const { projection } = reduce([
  1723. userMessage("u1", "start", 1000),
  1724. assistantMessage("a1", "u1", "initial", 1001),
  1725. background("wake-1", 2000),
  1726. assistantMessage("a-wake-1", "wake-1", "wake answer 1", 2001),
  1727. background("wake-2", 3000),
  1728. assistantMessage("a-wake-2", "wake-2", "wake answer 2", 3001),
  1729. ]);
  1730. const rows = projection.getSnapshot().rows.window;
  1731. const answers = rows.filter((row) => row.kind === "assistantText");
  1732. expect(answers.map((row) => row.turnId)).toEqual(["u1", "wake-1", "wake-2"]);
  1733. expect(new Set(answers.map((row) => row.productTurnId)).size).toBe(3);
  1734. expect(rows.filter((row) => row.kind === "userInput")).toHaveLength(1);
  1735. expect(answers.map((row) => row.actions?.canRetry === true)).toEqual([false, false, false]);
  1736. expect(answers[2]!.actions?.canFork).toBe(true);
  1737. const withNextRealUserTurn = reduce([
  1738. userMessage("u1", "start", 1000),
  1739. assistantMessage("a1", "u1", "initial", 1001),
  1740. background("wake-1", 2000),
  1741. assistantMessage("a-wake-1", "wake-1", "wake answer 1", 2001),
  1742. background("wake-2", 3000),
  1743. assistantMessage("a-wake-2", "wake-2", "wake answer 2", 3001),
  1744. userMessage("u2", "continue", 4000),
  1745. assistantMessage("a2", "u2", "latest real-user answer", 4001),
  1746. ]).projection;
  1747. const hydratedAnswers = withNextRealUserTurn
  1748. .getSnapshot()
  1749. .rows.window.filter((row) => row.kind === "assistantText");
  1750. expect(hydratedAnswers.map((row) => row.actions?.canRetry === true)).toEqual([
  1751. false,
  1752. false,
  1753. false,
  1754. true,
  1755. ]);
  1756. });
  1757. it("BG27/BG28:cold hydration 只从结构化 metadata 恢复后台结果标题", () => {
  1758. const background = syntheticUserMessage("wake-title", "background result", 2000, {
  1759. metadata: {
  1760. originMeta: {
  1761. backgroundSource: "bash",
  1762. title: "pnpm typecheck",
  1763. workId: "bash-typecheck",
  1764. },
  1765. source: "background_task",
  1766. visibility: "model-only",
  1767. },
  1768. source: "background_task",
  1769. visibility: "model-only",
  1770. });
  1771. const { projection } = reduce([
  1772. background,
  1773. assistantMessage("a-wake-title", "wake-title", "typecheck complete", 2001),
  1774. ]);
  1775. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  1776. expect(header).toMatchObject({
  1777. origin: "backgroundResult",
  1778. originMeta: {
  1779. backgroundSource: "bash",
  1780. title: "pnpm typecheck",
  1781. workId: "bash-typecheck",
  1782. },
  1783. });
  1784. });
  1785. // dwf run 的完成通知走同一条后台管线,backgroundSource 是第三个取值 "workflow"。
  1786. // 冷恢复的 originMeta 过滤器此前只放行 bash|subagent,漏掉它会让 workflow 的后台结果轮
  1787. // 静默退化成一条无标题的 model-only 消息(工具卡→详情页的关联键 workId 一起丢掉)。
  1788. it("cold hydration 恢复 workflow 后台结果的 originMeta", () => {
  1789. const background = syntheticUserMessage("wake-workflow", "workflow result", 2000, {
  1790. metadata: {
  1791. originMeta: {
  1792. backgroundSource: "workflow",
  1793. title: "review the diff",
  1794. workId: "dwfrun-abc",
  1795. },
  1796. source: "background_task",
  1797. visibility: "model-only",
  1798. },
  1799. source: "background_task",
  1800. visibility: "model-only",
  1801. });
  1802. const { projection } = reduce([
  1803. background,
  1804. assistantMessage("a-wake-workflow", "wake-workflow", "workflow done", 2001),
  1805. ]);
  1806. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  1807. expect(header).toMatchObject({
  1808. origin: "backgroundResult",
  1809. originMeta: {
  1810. backgroundSource: "workflow",
  1811. title: "review the diff",
  1812. workId: "dwfrun-abc",
  1813. },
  1814. });
  1815. });
  1816. // manifest 载荷(workflowNotification)也要过冷恢复:读取器此前只回读三基字段,
  1817. // 载荷会在冷恢复后静默丢失,manifest 条目退回裸标题行(本特性最隐蔽的坑)。
  1818. it("cold hydration 恢复 workflow originMeta 的 manifest 载荷(terminal)", () => {
  1819. const workflowNotification = {
  1820. kind: "terminal",
  1821. status: "completed",
  1822. summary: "review the diff",
  1823. result: "final artifact",
  1824. resultForm: "prose",
  1825. reports: { count: 3, shown: 1, preview: ["第一步"] },
  1826. durationMs: 4200,
  1827. };
  1828. const background = syntheticUserMessage("wake-workflow-meta", "workflow result", 2000, {
  1829. metadata: {
  1830. originMeta: {
  1831. backgroundSource: "workflow",
  1832. title: "review the diff",
  1833. workId: "dwfrun-meta",
  1834. workflowNotification,
  1835. },
  1836. source: "background_task",
  1837. visibility: "model-only",
  1838. },
  1839. source: "background_task",
  1840. visibility: "model-only",
  1841. });
  1842. const { projection } = reduce([
  1843. background,
  1844. assistantMessage("a-wake-meta", "wake-workflow-meta", "workflow done", 2001),
  1845. ]);
  1846. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  1847. expect(header).toMatchObject({
  1848. origin: "backgroundResult",
  1849. originMeta: { backgroundSource: "workflow", workId: "dwfrun-meta", workflowNotification },
  1850. });
  1851. });
  1852. // 防御性读取:畸形载荷(status 不在枚举内)只丢载荷、保三基字段,绝不打挂整条冷恢复。
  1853. it("cold hydration 丢弃畸形 manifest 载荷但保留三基字段", () => {
  1854. const background = syntheticUserMessage("wake-workflow-bad", "workflow result", 2000, {
  1855. metadata: {
  1856. originMeta: {
  1857. backgroundSource: "workflow",
  1858. title: "review the diff",
  1859. workId: "dwfrun-bad",
  1860. // status 非法(不在 completed/failed/cancelled 内)→ zod 拒收 → 只丢载荷。
  1861. workflowNotification: { kind: "terminal", status: "running", summary: "x" },
  1862. },
  1863. source: "background_task",
  1864. visibility: "model-only",
  1865. },
  1866. source: "background_task",
  1867. visibility: "model-only",
  1868. });
  1869. const { projection } = reduce([
  1870. background,
  1871. assistantMessage("a-wake-bad", "wake-workflow-bad", "workflow done", 2001),
  1872. ]);
  1873. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  1874. expect(header).toMatchObject({
  1875. origin: "backgroundResult",
  1876. originMeta: { backgroundSource: "workflow", title: "review the diff", workId: "dwfrun-bad" },
  1877. });
  1878. // 载荷被丢弃,不带进投影。
  1879. expect(
  1880. (header as { originMeta?: { workflowNotification?: unknown } }).originMeta
  1881. ?.workflowNotification,
  1882. ).toBeUndefined();
  1883. });
  1884. // 用户面产物的 chips 载荷(docs/dynamic-workflow/authoring.md「How the user sees them」)走同一条读取器。
  1885. // 读取器本身是 `workflowNotificationMetaSchema.safeParse` 的直传,而那份 zod **剥离**未声明
  1886. // 的键——所以「schema 里没加 artifacts」的症状不是报错,是 chips 在冷恢复后无声消失。
  1887. // 这条正向断言就是那个坑的钉子。
  1888. it("cold hydration 恢复 manifest 载荷里的 artifacts 与 artifactsTruncated", () => {
  1889. const workflowNotification = {
  1890. kind: "terminal",
  1891. status: "completed",
  1892. summary: "nightly audit",
  1893. artifacts: [
  1894. { id: "audit", kind: "file", title: "审计报告", version: 2, contentType: "application/pdf" },
  1895. { id: "perf", kind: "chart", version: 1 },
  1896. ],
  1897. artifactsTruncated: true,
  1898. };
  1899. const background = syntheticUserMessage("wake-workflow-art", "workflow result", 2000, {
  1900. metadata: {
  1901. originMeta: {
  1902. backgroundSource: "workflow",
  1903. title: "nightly audit",
  1904. workId: "dwfrun-art",
  1905. workflowNotification,
  1906. },
  1907. source: "background_task",
  1908. visibility: "model-only",
  1909. },
  1910. source: "background_task",
  1911. visibility: "model-only",
  1912. });
  1913. const { projection } = reduce([
  1914. background,
  1915. assistantMessage("a-wake-art", "wake-workflow-art", "workflow done", 2001),
  1916. ]);
  1917. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  1918. const restored = (header as { originMeta?: { workflowNotification?: Record<string, unknown> } })
  1919. .originMeta?.workflowNotification;
  1920. expect(restored?.artifacts).toEqual(workflowNotification.artifacts);
  1921. expect(restored?.artifactsTruncated).toBe(true);
  1922. });
  1923. // 畸形产物条目(未知 kind)让整份载荷被 zod 拒掉 → 只丢载荷、保三基字段。发射侧因此必须
  1924. // 在构造前过滤未知 kind,而不是指望读取端救场。
  1925. it("cold hydration 丢弃带未知 artifact kind 的载荷但保留三基字段", () => {
  1926. const background = syntheticUserMessage("wake-workflow-art-bad", "workflow result", 2000, {
  1927. metadata: {
  1928. originMeta: {
  1929. backgroundSource: "workflow",
  1930. title: "nightly audit",
  1931. workId: "dwfrun-art-bad",
  1932. workflowNotification: {
  1933. kind: "terminal",
  1934. status: "completed",
  1935. summary: "nightly audit",
  1936. artifacts: [{ id: "future", kind: "hologram", version: 1 }],
  1937. },
  1938. },
  1939. source: "background_task",
  1940. visibility: "model-only",
  1941. },
  1942. source: "background_task",
  1943. visibility: "model-only",
  1944. });
  1945. const { projection } = reduce([
  1946. background,
  1947. assistantMessage("a-wake-art-bad", "wake-workflow-art-bad", "workflow done", 2001),
  1948. ]);
  1949. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  1950. expect(header).toMatchObject({
  1951. originMeta: { backgroundSource: "workflow", title: "nightly audit", workId: "dwfrun-art-bad" },
  1952. });
  1953. expect(
  1954. (header as { originMeta?: { workflowNotification?: unknown } }).originMeta?.workflowNotification,
  1955. ).toBeUndefined();
  1956. });
  1957. it("legacy fork synthetic user 合成为 fork timeline,不合成为 userInput", () => {
  1958. const forkMetadata = {
  1959. forkContext: {
  1960. kind: "session_fork",
  1961. parentSessionId: "sess_parent",
  1962. restoredFileCount: 0,
  1963. targetMessageId: "msg_parent_assistant",
  1964. },
  1965. source: "fork",
  1966. visibility: "user-visible",
  1967. };
  1968. const messages = [
  1969. syntheticUserMessage(
  1970. "u_fork",
  1971. "This session was forked from a previous session message.",
  1972. 1000,
  1973. {
  1974. metadata: forkMetadata,
  1975. source: "fork",
  1976. visibility: "user-visible",
  1977. },
  1978. ),
  1979. ];
  1980. const { events, projection } = reduce(messages);
  1981. expect(events.some((event) => event.type === SessionEventType.TurnStarted)).toBe(false);
  1982. expect(events.some((event) => event.type === SessionEventType.SessionForked)).toBe(true);
  1983. expect(eventsCoverTranscript([], messages)).toBe(false);
  1984. const rows = projection.getSnapshot().rows.window;
  1985. expect(rows.some((row) => row.kind === "userInput")).toBe(false);
  1986. expect(rows).toContainEqual(
  1987. expect.objectContaining({
  1988. kind: "timelineMarker",
  1989. marker: expect.objectContaining({
  1990. parentSessionId: "sess_parent",
  1991. type: "forkNotice",
  1992. }),
  1993. }),
  1994. );
  1995. });
  1996. it("model-only fork raw notice 不重复合成 fork timeline", () => {
  1997. const forkMetadata = {
  1998. forkContext: {
  1999. kind: "session_fork",
  2000. parentSessionId: "sess_parent",
  2001. restoredFileCount: 0,
  2002. targetMessageId: "msg_parent_assistant",
  2003. },
  2004. source: "fork",
  2005. visibility: "model-only",
  2006. };
  2007. const messages = [
  2008. assistantMessageWithParts(
  2009. "a_fork_timeline",
  2010. "u1",
  2011. [
  2012. {
  2013. id: "a_fork_timeline_part" as never,
  2014. sessionID: "s1" as never,
  2015. messageID: "a_fork_timeline" as never,
  2016. type: "timeline",
  2017. timelineType: "session_fork",
  2018. display: "separator",
  2019. status: "completed",
  2020. parentSessionId: "sess_parent" as never,
  2021. targetMessageId: "msg_parent_assistant" as never,
  2022. restoredFileCount: 0,
  2023. },
  2024. ],
  2025. 1000,
  2026. ),
  2027. syntheticUserMessage(
  2028. "u_fork_raw",
  2029. "This session was forked from a previous session message.",
  2030. 1001,
  2031. {
  2032. metadata: forkMetadata,
  2033. semantics: {
  2034. kind: "fork_notice",
  2035. origin: "agent_runtime",
  2036. providerVisibility: "visible",
  2037. source: "fork",
  2038. transcriptVisibility: "hidden",
  2039. uiVisibility: "hidden",
  2040. },
  2041. source: "fork",
  2042. visibility: "model-only",
  2043. },
  2044. ),
  2045. ];
  2046. const { events, projection } = reduce(messages);
  2047. expect(events.filter((event) => event.type === SessionEventType.TurnStarted)).toHaveLength(0);
  2048. expect(events.filter((event) => event.type === SessionEventType.SessionForked)).toHaveLength(1);
  2049. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2050. expect(
  2051. projection
  2052. .getSnapshot()
  2053. .rows.window.filter(
  2054. (row) =>
  2055. row.kind === "timelineMarker" &&
  2056. (row.marker.type === "forkNotice" || row.marker.type === "forkCreated"),
  2057. ),
  2058. ).toHaveLength(1);
  2059. });
  2060. it("assistant reasoning/tool/compact/Agent part → 对应 v4 rows,Agent tool 同时保留 subagent row", () => {
  2061. const agentOutput = JSON.stringify({
  2062. agentId: "agent-1",
  2063. agentType: "Explore",
  2064. childSessionId: "sess_child_1",
  2065. description: "探索项目",
  2066. content: [{ type: "text", text: "子代理总结" }],
  2067. status: "completed",
  2068. });
  2069. const messages = [
  2070. userMessage("u1", "分析一下", 1000),
  2071. assistantMessageWithParts(
  2072. "a1",
  2073. "u1",
  2074. [
  2075. {
  2076. id: "a1-r" as never,
  2077. sessionID: "s1" as never,
  2078. messageID: "a1" as never,
  2079. type: "reasoning",
  2080. text: "先想一想",
  2081. time: { start: 1001, end: 1002 },
  2082. },
  2083. {
  2084. id: "a1-tool-read" as never,
  2085. sessionID: "s1" as never,
  2086. messageID: "a1" as never,
  2087. type: "tool",
  2088. callID: "call-read",
  2089. tool: "Read",
  2090. state: {
  2091. status: "completed",
  2092. input: { file_path: "README.md" },
  2093. output: "README 内容",
  2094. title: "Read README.md",
  2095. metadata: {},
  2096. time: { start: 1002, end: 1003 },
  2097. },
  2098. },
  2099. {
  2100. id: "a1-compact" as never,
  2101. sessionID: "s1" as never,
  2102. messageID: "a1" as never,
  2103. type: "timeline",
  2104. timelineType: "context_compaction",
  2105. display: "separator",
  2106. status: CompactTimelineStatus.Completed,
  2107. operationId: "cmp-1",
  2108. trigger: CompactTrigger.Manual,
  2109. sourceCommandId: "command-compact-cold",
  2110. preCompactTokenCount: 900,
  2111. postCompactTokenCount: 300,
  2112. },
  2113. {
  2114. id: "a1-browser-shot" as never,
  2115. sessionID: "s1" as never,
  2116. messageID: "a1" as never,
  2117. type: "tool",
  2118. callID: "call-browser-shot",
  2119. tool: "mcp__node_repl__js",
  2120. state: {
  2121. status: "completed",
  2122. input: { source: "browser_turn_end" },
  2123. output: "",
  2124. title: "mcp__node_repl__js",
  2125. metadata: {
  2126. schemaVersion: 1,
  2127. display: {
  2128. kind: "node_repl_images",
  2129. source: "browser_turn_end",
  2130. images: [{ base64: "AAAA", mimeType: "image/png" }],
  2131. },
  2132. },
  2133. time: { start: 1003, end: 1003 },
  2134. },
  2135. },
  2136. {
  2137. id: "a1-mcp-tool" as never,
  2138. sessionID: "s1" as never,
  2139. messageID: "a1" as never,
  2140. type: "tool",
  2141. callID: "call-mcp-tool",
  2142. tool: "custom-provider-visible-name",
  2143. state: {
  2144. status: "completed",
  2145. input: { query: "is:open" },
  2146. output: "12 issues",
  2147. title: "custom-provider-visible-name",
  2148. metadata: {
  2149. schemaVersion: 1,
  2150. display: {
  2151. kind: "mcp_tool",
  2152. serverName: "s".repeat(256),
  2153. toolName: "t".repeat(256),
  2154. description: "d".repeat(4 * 1024),
  2155. },
  2156. },
  2157. time: { start: 1003, end: 1004 },
  2158. },
  2159. },
  2160. {
  2161. id: "a1-tool-agent" as never,
  2162. sessionID: "s1" as never,
  2163. messageID: "a1" as never,
  2164. type: "tool",
  2165. callID: "call-agent",
  2166. tool: "Agent",
  2167. state: {
  2168. status: "completed",
  2169. input: { description: "探索项目", prompt: "请探索项目" },
  2170. output: agentOutput,
  2171. title: "Agent 探索项目",
  2172. metadata: {},
  2173. time: { start: 1004, end: 1010 },
  2174. },
  2175. },
  2176. {
  2177. id: "a1-cua-shot" as never,
  2178. sessionID: "s1" as never,
  2179. messageID: "a1" as never,
  2180. type: "tool",
  2181. callID: "call-cua-shot",
  2182. tool: "mcp__computer-use__computer-use",
  2183. state: {
  2184. status: "completed",
  2185. input: { action: "screenshot" },
  2186. output: "[Attached image/jpeg: MCP image]",
  2187. title: "computer-use screenshot",
  2188. metadata: {
  2189. schemaVersion: 1,
  2190. display: {
  2191. kind: "cua",
  2192. schemaVersion: 1,
  2193. toolName: "computer-use",
  2194. status: "success",
  2195. input: '{"action":"screenshot"}',
  2196. media: [{ mimeType: "image/jpeg", data: "AAAA" }],
  2197. },
  2198. },
  2199. time: { start: 1003, end: 1004 },
  2200. },
  2201. },
  2202. {
  2203. id: "a1-t" as never,
  2204. sessionID: "s1" as never,
  2205. messageID: "a1" as never,
  2206. type: "text",
  2207. text: "完成",
  2208. },
  2209. ],
  2210. 1001,
  2211. ),
  2212. ];
  2213. const { events, projection } = reduce(messages);
  2214. const rows = projection.getSnapshot().rows.window;
  2215. expect(eventsCoverTranscript([], messages)).toBe(false);
  2216. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2217. expect(rows.find((row) => row.kind === "reasoning")).toMatchObject({
  2218. text: "先想一想",
  2219. state: "complete",
  2220. });
  2221. expect(
  2222. rows.find((row) => row.kind === "toolCall" && row.toolCallId === "call-read"),
  2223. ).toMatchObject({
  2224. status: "success",
  2225. output: { text: "README 内容" },
  2226. });
  2227. expect(
  2228. rows.find((row) => row.kind === "toolCall" && row.toolCallId === "call-agent"),
  2229. ).toMatchObject({
  2230. status: "success",
  2231. });
  2232. expect(
  2233. rows.find((row) => row.kind === "toolCall" && row.toolCallId === "call-browser-shot"),
  2234. ).toMatchObject({
  2235. status: "success",
  2236. display: { kind: "node_repl_images", source: "browser_turn_end" },
  2237. });
  2238. expect(
  2239. rows.find((row) => row.kind === "toolCall" && row.toolCallId === "call-mcp-tool"),
  2240. ).toMatchObject({
  2241. status: "success",
  2242. display: {
  2243. kind: "mcp_tool",
  2244. serverName: "s".repeat(256),
  2245. toolName: "t".repeat(256),
  2246. description: "d".repeat(4 * 1024),
  2247. },
  2248. });
  2249. expect(
  2250. rows.find((row) => row.kind === "toolCall" && row.toolCallId === "call-cua-shot"),
  2251. ).toMatchObject({
  2252. status: "success",
  2253. output: {
  2254. text: "[Attached image/jpeg: MCP image]",
  2255. display: {
  2256. kind: "cua",
  2257. media: [{ mimeType: "image/jpeg", data: "AAAA" }],
  2258. },
  2259. },
  2260. });
  2261. expect(rows.find((row) => row.kind === "subagent")).toMatchObject({
  2262. childSessionId: "sess_child_1",
  2263. parentToolCallId: "call-agent",
  2264. status: "success",
  2265. subagentType: "Explore",
  2266. summaryText: "子代理总结",
  2267. });
  2268. expect(rows.find((row) => row.kind === "timelineMarker")).toMatchObject({
  2269. lane: "assistantWork",
  2270. sourceCommandId: "command-compact-cold",
  2271. marker: {
  2272. status: "success",
  2273. tokensAfter: 300,
  2274. tokensBefore: 900,
  2275. type: "compact",
  2276. },
  2277. });
  2278. });
  2279. it("历史 pending/running tool 不复活 active work,冷恢复收口为 cancelled", () => {
  2280. const messages = [
  2281. userMessage("u1", "跑个长任务", 1000),
  2282. assistantMessageWithParts(
  2283. "a1",
  2284. "u1",
  2285. [
  2286. {
  2287. id: "a1-tool" as never,
  2288. sessionID: "s1" as never,
  2289. messageID: "a1" as never,
  2290. type: "tool",
  2291. callID: "call-bash",
  2292. tool: "Bash",
  2293. state: {
  2294. status: "running",
  2295. input: { command: "sleep 100" },
  2296. title: "sleep 100",
  2297. metadata: {
  2298. schemaVersion: 1,
  2299. display: {
  2300. kind: "mcp_tool",
  2301. serverName: "firebase",
  2302. toolName: "read_resources",
  2303. },
  2304. },
  2305. time: { start: 1001 },
  2306. },
  2307. },
  2308. ],
  2309. 1001,
  2310. ),
  2311. ];
  2312. const { projection } = reduce(messages);
  2313. const snapshot = projection.getSnapshot();
  2314. expect(snapshot.control.phase).toBe("completedInterrupted");
  2315. expect(snapshot.control.activeWorks).toEqual([]);
  2316. expect(snapshot.control.canStop).toBe(false);
  2317. expect(snapshot.rows.window.find((row) => row.kind === "toolCall")).toMatchObject({
  2318. status: "cancelled",
  2319. display: { kind: "mcp_tool", serverName: "firebase", toolName: "read_resources" },
  2320. });
  2321. });
  2322. it("eventsCoverTranscript:事件有 turn 但缺 tool footprint → false", () => {
  2323. const messages = [
  2324. userMessage("u1", "读文件", 1000),
  2325. assistantMessageWithParts(
  2326. "a1",
  2327. "u1",
  2328. [
  2329. {
  2330. id: "a1-tool" as never,
  2331. sessionID: "s1" as never,
  2332. messageID: "a1" as never,
  2333. type: "tool",
  2334. callID: "call-read",
  2335. tool: "Read",
  2336. state: {
  2337. status: "completed",
  2338. input: { file_path: "README.md" },
  2339. output: "README",
  2340. title: "Read README.md",
  2341. metadata: {},
  2342. time: { start: 1001, end: 1002 },
  2343. },
  2344. },
  2345. ],
  2346. 1001,
  2347. ),
  2348. ];
  2349. const textOnlyEvents = synthesizeEventsFromMessages(
  2350. [userMessage("u1", "读文件", 1000), assistantMessage("a1", "u1", "", 1001)],
  2351. { sessionId: "s1" },
  2352. );
  2353. expect(eventsCoverTranscript(textOnlyEvents, messages)).toBe(false);
  2354. });
  2355. it.each(["", " \t "])(
  2356. "空名恢复 tool part(%j)不生成冷恢复工具行,也不进入可见 footprint",
  2357. (toolName) => {
  2358. const messages = [
  2359. userMessage("u-empty-tool", "继续", 1000),
  2360. assistantMessageWithParts(
  2361. "a-empty-tool",
  2362. "u-empty-tool",
  2363. [
  2364. {
  2365. id: "a-empty-tool-part" as never,
  2366. sessionID: "s1" as never,
  2367. messageID: "a-empty-tool" as never,
  2368. type: "tool",
  2369. callID: "call-empty-tool",
  2370. tool: toolName,
  2371. state: {
  2372. status: "error",
  2373. input: {},
  2374. error: "Model returned an invalid tool call: tool name is empty.",
  2375. time: { start: 1001, end: 1002 },
  2376. },
  2377. },
  2378. ],
  2379. 1001,
  2380. ),
  2381. ];
  2382. const { events, projection } = reduce(messages);
  2383. expect(projection.getSnapshot().rows.window.filter((row) => row.kind === "toolCall")).toEqual(
  2384. [],
  2385. );
  2386. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2387. },
  2388. );
  2389. it("带原始空名 metadata 的存储占位不生成冷恢复工具行", () => {
  2390. const messages = [
  2391. userMessage("u-empty-tool", "继续", 1000),
  2392. assistantMessageWithParts(
  2393. "a-empty-tool",
  2394. "u-empty-tool",
  2395. [
  2396. {
  2397. id: "a-empty-tool-part" as never,
  2398. sessionID: "s1" as never,
  2399. messageID: "a-empty-tool" as never,
  2400. type: "tool",
  2401. callID: "call-empty-tool",
  2402. tool: "empty_tool_name",
  2403. metadata: { providerToolName: "" },
  2404. state: {
  2405. status: "error",
  2406. input: {},
  2407. error: "Model returned an invalid tool call: tool name is empty.",
  2408. time: { start: 1001, end: 1002 },
  2409. },
  2410. },
  2411. ],
  2412. 1001,
  2413. ),
  2414. ];
  2415. const { events, projection } = reduce(messages);
  2416. expect(projection.getSnapshot().rows.window.filter((row) => row.kind === "toolCall")).toEqual(
  2417. [],
  2418. );
  2419. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2420. });
  2421. it("裸 empty_tool_name 按合法工具生成冷恢复工具行和可见 footprint", () => {
  2422. const messages = [
  2423. userMessage("u-legitimate-tool", "运行工具", 1000),
  2424. assistantMessageWithParts(
  2425. "a-legitimate-tool",
  2426. "u-legitimate-tool",
  2427. [
  2428. {
  2429. id: "a-legitimate-tool-part" as never,
  2430. sessionID: "s1" as never,
  2431. messageID: "a-legitimate-tool" as never,
  2432. type: "tool",
  2433. callID: "call-legitimate-tool",
  2434. tool: "empty_tool_name",
  2435. state: {
  2436. status: "completed",
  2437. input: { value: 1 },
  2438. output: "ok",
  2439. title: "empty_tool_name",
  2440. metadata: {},
  2441. time: { start: 1001, end: 1002 },
  2442. },
  2443. },
  2444. ],
  2445. 1001,
  2446. ),
  2447. ];
  2448. const { events, projection } = reduce(messages);
  2449. expect(
  2450. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2451. ).toMatchObject({
  2452. status: "success",
  2453. toolCallId: "call-legitimate-tool",
  2454. toolName: "empty_tool_name",
  2455. });
  2456. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2457. });
  2458. it("无 user 消息的 transcript → 视为已覆盖(不触发合成)", () => {
  2459. expect(eventsCoverTranscript([], [])).toBe(true);
  2460. });
  2461. it("确定性:同一 transcript 合成两次逐字节相等", () => {
  2462. const messages = [userMessage("u1", "x", 1000), assistantMessage("a1", "u1", "y", 1001)];
  2463. const a = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  2464. const b = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  2465. expect(JSON.stringify(a)).toBe(JSON.stringify(b));
  2466. });
  2467. });
  2468. // ── M5④ 附件渲染:FilePart → 合成 TurnStarted.attachments → row.attachments ──
  2469. describe("transcript 附件合成(M5④)", () => {
  2470. function userMessageWithFile(id: string, text: string, created: number): MessageWithParts {
  2471. const base = userMessage(id, text, created);
  2472. return {
  2473. ...base,
  2474. info: {
  2475. ...base.info,
  2476. anchor: { sourceCommandId: "command-cold" },
  2477. metadata: {
  2478. conversationInputIntent: {
  2479. sourceCommandId: "command-cold",
  2480. queueItemId: "queue_command-cold",
  2481. clientId: "mobile-cold",
  2482. kind: "sendText",
  2483. text,
  2484. attachments: [],
  2485. delivery: { requested: "startNow", admitted: "startNow" },
  2486. order: { admissionSeq: 8 },
  2487. steer: { state: "notRequested" },
  2488. dispatch: { state: "drained" },
  2489. admittedAt: 999,
  2490. },
  2491. },
  2492. },
  2493. parts: [
  2494. ...base.parts,
  2495. {
  2496. id: `${id}-f1` as never,
  2497. sessionID: "s1" as never,
  2498. messageID: id as never,
  2499. type: "file",
  2500. mime: "image/png",
  2501. filename: "diagram.png",
  2502. url: "/workspace/diagram.png",
  2503. metadata: { sizeBytes: 2048 },
  2504. },
  2505. // data URL:无稳定引用 → ref 缺省;filename 缺省 → 序号占位。
  2506. {
  2507. id: `${id}-f2` as never,
  2508. sessionID: "s1" as never,
  2509. messageID: id as never,
  2510. type: "file",
  2511. mime: "text/plain",
  2512. url: "data:text/plain;base64,aGk=",
  2513. },
  2514. ],
  2515. };
  2516. }
  2517. it("file parts 进入 userInput row.attachments(冷路径与 live 同一投影入口)", () => {
  2518. const { projection } = reduce([
  2519. userMessageWithFile("u1", "看图", 1000),
  2520. assistantMessage("a1", "u1", "好的", 2000),
  2521. ]);
  2522. const userInput = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  2523. const attachments = userInput?.kind === "userInput" ? userInput.attachments : undefined;
  2524. expect(userInput).toMatchObject({
  2525. sourceCommandId: "command-cold",
  2526. clientId: "mobile-cold",
  2527. });
  2528. expect(attachments).toHaveLength(2);
  2529. expect(attachments?.[0]).toEqual({
  2530. ref: "/workspace/diagram.png",
  2531. fileName: "diagram.png",
  2532. mime: "image/png",
  2533. bytes: 2048,
  2534. });
  2535. expect(attachments?.[1]).toMatchObject({
  2536. fileName: "attachment-2",
  2537. mime: "text/plain",
  2538. bytes: 0,
  2539. });
  2540. });
  2541. it("无 file part 的消息不带 attachments(合成保持最小序列)", () => {
  2542. const { projection } = reduce([
  2543. userMessage("u1", "纯文本", 1000),
  2544. assistantMessage("a1", "u1", "好的", 2000),
  2545. ]);
  2546. const userInput = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  2547. expect(userInput?.kind === "userInput" ? "attachments" in userInput : null).toBe(false);
  2548. });
  2549. // ── 16-timeline-authority-plan P1 golden ──
  2550. it("GV-cold:goal_verification timeline part 冷恢复后 marker 仍在(含身份/结论/无 goal 状态不丢)", () => {
  2551. const messages = [
  2552. userMessage("u1", "修 lint", 1000),
  2553. assistantMessage("a1", "u1", "修好了", 1001),
  2554. goalVerificationHostMessage("gv1", "a1", 2000, {
  2555. status: "completed",
  2556. goalIteration: 1,
  2557. verification: { passed: true, reason: "全部通过" },
  2558. }),
  2559. ];
  2560. // 空事件日志对含 goal verify 的 transcript 不再被误判为已覆盖(守恒判据曾对此全盲)。
  2561. const turnOnlyEvents = synthesizeEventsFromMessages(
  2562. [userMessage("u1", "修 lint", 1000), assistantMessage("a1", "u1", "修好了", 1001)],
  2563. { sessionId: "s1" },
  2564. );
  2565. expect(eventsCoverTranscript(turnOnlyEvents, messages)).toBe(false);
  2566. const { events, projection } = reduce(messages);
  2567. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2568. const marker = projection
  2569. .getSnapshot()
  2570. .rows.window.find((row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify");
  2571. expect(marker).toBeDefined();
  2572. expect(marker?.kind === "timelineMarker" ? marker.marker : null).toMatchObject({
  2573. type: "goalVerify",
  2574. iteration: 1,
  2575. outcome: "pass",
  2576. });
  2577. // 合成事件流没有 TargetChanged → goal 状态保持 null,但 boundary 不再被整条丢弃。
  2578. expect(projection.getSnapshot().goal).toBeNull();
  2579. });
  2580. it("GV-cold:started 态残留的 verifier 冷恢复收口为 failed(cancelled),不复活 running", () => {
  2581. const { projection } = reduce([
  2582. userMessage("u1", "修 lint", 1000),
  2583. assistantMessage("a1", "u1", "修好了", 1001),
  2584. goalVerificationHostMessage("gv1", "a1", 2000, { status: "started", goalIteration: 2 }),
  2585. ]);
  2586. const marker = projection
  2587. .getSnapshot()
  2588. .rows.window.find((row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify");
  2589. expect(marker?.kind === "timelineMarker" ? marker.marker : null).toMatchObject({
  2590. iteration: 2,
  2591. outcome: "failed",
  2592. detail: "cancelled",
  2593. });
  2594. // 冷恢复不得复活 active work / stop 入口。
  2595. expect(projection.getSnapshot().control.activeWorks).toEqual([]);
  2596. });
  2597. it("MC-cold:相邻轮持久化选型不同 → modelChange marker 重建;首轮不产 marker", () => {
  2598. const messages = [
  2599. userMessageWithModel("u1", "先用 A", 1000, { providerId: "p1", modelId: "m1" }),
  2600. assistantMessage("a1", "u1", "好的", 1001),
  2601. userMessageWithModel("u2", "换 B 再来", 2000, { providerId: "p2", modelId: "m2" }),
  2602. assistantMessage("a2", "u2", "已切换", 2001),
  2603. ];
  2604. const { events, projection } = reduce(messages);
  2605. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2606. const markers = projection
  2607. .getSnapshot()
  2608. .rows.window.filter(
  2609. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  2610. );
  2611. expect(markers).toHaveLength(1);
  2612. expect(markers[0]?.kind === "timelineMarker" ? markers[0].marker : null).toMatchObject({
  2613. type: "modelChange",
  2614. fromProvider: "p1",
  2615. fromModel: "m1",
  2616. toProvider: "p2",
  2617. toModel: "m2",
  2618. });
  2619. // marker 位于第二轮 turnHeader 之前(同 turnId、先 append)。
  2620. const rows = projection.getSnapshot().rows.window;
  2621. const markerIndex = rows.findIndex(
  2622. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  2623. );
  2624. const secondHeaderIndex = rows.findIndex(
  2625. (row, index) =>
  2626. row.kind === "turnHeader" && index > 0 && rows[index]!.turnId === rows[markerIndex]!.turnId,
  2627. );
  2628. expect(markerIndex).toBeGreaterThan(-1);
  2629. expect(secondHeaderIndex).toBe(markerIndex + 1);
  2630. });
  2631. it("MC-cold:Highspeed 单轮执行模型不参与普通模型切换基线", () => {
  2632. const messages = [
  2633. userMessageWithModel("u1", "普通模型执行", 1000, { providerId: "p1", modelId: "m1" }),
  2634. assistantMessage("a1", "u1", "完成", 1001),
  2635. // 加速轮持久化的 Selection 指向隐藏的加速卡内建 Provider,冷恢复必须按 Family 谓词
  2636. // 识别并跳过,不能参与 modelChange 基线。
  2637. userMessageWithModel("u2", "加速执行", 2000, {
  2638. providerId: "account:bigmodel-highspeed-card",
  2639. modelId: "GLM-5.3",
  2640. }),
  2641. assistantMessage("a2", "u2", "加速完成", 2001),
  2642. userMessageWithModel("u3", "继续使用普通模型", 3000, {
  2643. providerId: "p1",
  2644. modelId: "m1",
  2645. }),
  2646. assistantMessage("a3", "u3", "完成", 3001),
  2647. ];
  2648. const { events, projection } = reduce(messages);
  2649. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2650. expect(
  2651. projection
  2652. .getSnapshot()
  2653. .rows.window.filter(
  2654. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  2655. ),
  2656. ).toHaveLength(0);
  2657. });
  2658. it("MC-cold:Highspeed 后真实切换普通模型仍重建原普通模型到新模型的 marker", () => {
  2659. const messages = [
  2660. userMessageWithModel("u1", "普通模型 A", 1000, { providerId: "p1", modelId: "m1" }),
  2661. assistantMessage("a1", "u1", "完成", 1001),
  2662. userMessageWithModel("u2", "加速执行", 2000, {
  2663. providerId: "account:bigmodel-highspeed-card",
  2664. modelId: "GLM-5.3",
  2665. }),
  2666. assistantMessage("a2", "u2", "加速完成", 2001),
  2667. userMessageWithModel("u3", "切换普通模型 B", 3000, {
  2668. providerId: "p2",
  2669. modelId: "m2",
  2670. }),
  2671. assistantMessage("a3", "u3", "完成", 3001),
  2672. ];
  2673. const { events, projection } = reduce(messages);
  2674. const markers = projection
  2675. .getSnapshot()
  2676. .rows.window.filter(
  2677. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  2678. );
  2679. expect(eventsCoverTranscript(events, messages)).toBe(true);
  2680. expect(markers).toHaveLength(1);
  2681. expect(markers[0]).toMatchObject({
  2682. marker: {
  2683. type: "modelChange",
  2684. fromProvider: "p1",
  2685. fromModel: "m1",
  2686. toProvider: "p2",
  2687. toModel: "m2",
  2688. },
  2689. });
  2690. });
  2691. it("MC-cold:source-less model_change 恢复 Subagent 初始模型 marker 且只出现一次", () => {
  2692. const messages = [
  2693. initialModelHostMessage("mc-initial", 900),
  2694. userMessageWithModel("u1", "child prompt", 1000, {
  2695. providerId: "child-provider",
  2696. modelId: "child-model",
  2697. }),
  2698. assistantMessage("a1", "u1", "done", 1001),
  2699. ];
  2700. const { events, projection } = reduce(messages);
  2701. const markers = projection
  2702. .getSnapshot()
  2703. .rows.window.filter(
  2704. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  2705. );
  2706. expect(markers).toHaveLength(1);
  2707. expect(markers[0]).toMatchObject({
  2708. marker: {
  2709. type: "modelChange",
  2710. toProvider: "child-provider",
  2711. toModel: "child-model",
  2712. },
  2713. });
  2714. expect(markers[0]?.kind === "timelineMarker" ? markers[0].marker : {}).not.toHaveProperty(
  2715. "fromModel",
  2716. );
  2717. expect(events.filter((event) => event.type === SessionEventType.ModelSelected)).toEqual([
  2718. expect.objectContaining({
  2719. payload: expect.objectContaining({ previousModelSelection: null }),
  2720. }),
  2721. ]);
  2722. });
  2723. it("assistant-head-skip:首条真实用户消息之前的 assistant 回复不再整段消失", () => {
  2724. // 会话头部是 compact summary(providerContextOnly,非真实用户)→ 其后的 assistant
  2725. // 回复旧实现整段跳过:刷新后「上一轮回复没了」的冷路径向量。
  2726. const messages = [
  2727. syntheticUserMessage("u_sum", "compact 摘要", 900, {
  2728. semantics: { kind: "compact_summary" } as never,
  2729. }),
  2730. assistantMessage("a0", "u_sum", "基于摘要继续的回复", 901),
  2731. userMessage("u1", "下一个问题", 2000),
  2732. assistantMessage("a1", "u1", "答", 2001),
  2733. ];
  2734. const { projection } = reduce(messages);
  2735. const rows = projection.getSnapshot().rows.window;
  2736. const assistantTexts = rows
  2737. .filter((row) => row.kind === "assistantText")
  2738. .map((row) => (row.kind === "assistantText" ? row.text : ""));
  2739. expect(assistantTexts).toEqual(["基于摘要继续的回复", "答"]);
  2740. // preface 轮是 model-only:不产可见 user 气泡,可见 user 轮数不受影响。
  2741. const userRows = rows.filter((row) => row.kind === "userInput");
  2742. expect(userRows).toHaveLength(1);
  2743. expect(rows.filter((row) => row.kind === "turnHeader")).toHaveLength(2);
  2744. });
  2745. it("GV-cold-session_entry:goal verify 只存在 legacy session_entry 时冷恢复可重建(含生命周期合并/锚定落位)", () => {
  2746. const messages = [
  2747. userMessage("u1", "修 lint", 1000),
  2748. assistantMessage("a1", "u1", "修好了", 1001),
  2749. userMessage("u2", "再看看测试", 2000),
  2750. assistantMessage("a2", "u2", "测试也过了", 2001),
  2751. ];
  2752. // legacy 形态:同一 verification 的 started/terminal 各一条 entry,无 timeline part。
  2753. const goalVerificationEntries = [
  2754. {
  2755. payload: {
  2756. targetId: "target-1",
  2757. status: "started",
  2758. verificationId: "v1",
  2759. goalIteration: 1,
  2760. anchorAssistantMessageId: "a1",
  2761. },
  2762. sequenceNumber: 5,
  2763. timeCreated: 1500,
  2764. },
  2765. {
  2766. payload: {
  2767. targetId: "target-1",
  2768. status: "completed",
  2769. verificationId: "v1",
  2770. goalIteration: 1,
  2771. anchorAssistantMessageId: "a1",
  2772. verification: { passed: true, reason: "ok" },
  2773. },
  2774. sequenceNumber: 9,
  2775. timeCreated: 1600,
  2776. },
  2777. ];
  2778. // 覆盖判据必须看见 entry 源:空事件日志不再被误判为已覆盖。
  2779. const turnOnlyEvents = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  2780. expect(eventsCoverTranscript(turnOnlyEvents, messages, { goalVerificationEntries })).toBe(
  2781. false,
  2782. );
  2783. const events = synthesizeEventsFromMessages(messages, {
  2784. sessionId: "s1",
  2785. goalVerificationEntries,
  2786. });
  2787. expect(eventsCoverTranscript(events, messages, { goalVerificationEntries })).toBe(true);
  2788. const projection = new ProductProjection("s1", "epoch");
  2789. for (const event of events) projection.applyEvent(event);
  2790. const rows = projection.getSnapshot().rows.window;
  2791. const markers = rows.filter(
  2792. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  2793. );
  2794. // 生命周期两条 entry 合并为单一 marker,终态覆盖 started。
  2795. expect(markers).toHaveLength(1);
  2796. expect(markers[0]?.kind === "timelineMarker" ? markers[0].marker : null).toMatchObject({
  2797. iteration: 1,
  2798. outcome: "pass",
  2799. });
  2800. // 锚定落位:marker 归属 a1 所在的第一轮(turn tail),不漂到第二轮之后。
  2801. const markerIndex = rows.findIndex(
  2802. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  2803. );
  2804. const secondTurnFirstIndex = rows.findIndex(
  2805. (row) => row.kind === "userInput" && row.text === "再看看测试",
  2806. );
  2807. expect(markerIndex).toBeGreaterThan(-1);
  2808. expect(markerIndex).toBeLessThan(secondTurnFirstIndex);
  2809. });
  2810. it("GV 跨源去重:timeline part 与 session_entry 表达同一事实 → 单一 marker;无 anchor 的 entry 落尾不丢", () => {
  2811. const messages = [
  2812. userMessage("u1", "修 lint", 1000),
  2813. assistantMessage("a1", "u1", "修好了", 1001),
  2814. goalVerificationHostMessage("gv1", "a1", 1500, {
  2815. status: "completed",
  2816. goalIteration: 1,
  2817. verification: { passed: true, reason: "ok" },
  2818. }),
  2819. ];
  2820. const goalVerificationEntries = [
  2821. // 与 part 同 key(target-1_1):去重,不产生第二个 marker。
  2822. {
  2823. payload: {
  2824. targetId: "target-1",
  2825. status: "completed",
  2826. verificationId: "verify-gv1",
  2827. goalIteration: 1,
  2828. anchorAssistantMessageId: "a1",
  2829. verification: { passed: true, reason: "ok" },
  2830. },
  2831. timeCreated: 1500,
  2832. },
  2833. // 无 anchor 的孤儿 entry(iteration 2):落到已知时间线末尾,不静默丢。
  2834. {
  2835. payload: {
  2836. targetId: "target-1",
  2837. status: "completed",
  2838. verificationId: "v-orphan",
  2839. goalIteration: 2,
  2840. verification: { passed: false, reason: "还差一点" },
  2841. },
  2842. timeCreated: 1700,
  2843. },
  2844. ];
  2845. const events = synthesizeEventsFromMessages(messages, {
  2846. sessionId: "s1",
  2847. goalVerificationEntries,
  2848. });
  2849. const projection = new ProductProjection("s1", "epoch");
  2850. for (const event of events) projection.applyEvent(event);
  2851. const markers = projection
  2852. .getSnapshot()
  2853. .rows.window.filter(
  2854. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  2855. );
  2856. expect(markers).toHaveLength(2);
  2857. expect(markers.map((row) => (row.kind === "timelineMarker" ? row.marker : null))).toEqual([
  2858. expect.objectContaining({ iteration: 1, outcome: "pass" }),
  2859. expect.objectContaining({ iteration: 2, outcome: "notSatisfied" }),
  2860. ]);
  2861. });
  2862. it("S1 cold:guide steer 持久标记内联当前轮;queue 标记独立轮(与 live 切分一致)", () => {
  2863. const withDelivery = (
  2864. message: MessageWithParts,
  2865. delivery: "guide" | "queue",
  2866. ): MessageWithParts => ({
  2867. ...message,
  2868. info: {
  2869. ...message.info,
  2870. metadata: { turnSteerDelivery: delivery },
  2871. } as MessageWithParts["info"],
  2872. });
  2873. const messages = [
  2874. userMessage("u1", "问题一", 1000),
  2875. assistantMessage("a1", "u1", "回答一", 1001),
  2876. withDelivery(userMessage("u_steer", "补充说明", 1500), "guide"),
  2877. assistantMessage("a2", "u1", "回答二", 1600),
  2878. withDelivery(userMessage("u_q2", "排队问题", 2000), "queue"),
  2879. assistantMessage("a3", "u_q2", "排队回答", 2001),
  2880. ];
  2881. const { projection } = reduce(messages);
  2882. const rows = projection.getSnapshot().rows.window;
  2883. // guide steer 内联:u_steer 与 a1/a2 同轮;queue 项独立轮。
  2884. const visible = rows
  2885. .filter((row) => row.kind === "userInput" || row.kind === "assistantText")
  2886. .map((row) => [
  2887. row.turnId,
  2888. row.kind === "userInput" || row.kind === "assistantText" ? row.text : "",
  2889. ]);
  2890. expect(visible).toEqual([
  2891. ["u1", "问题一"],
  2892. ["u1", "回答一"],
  2893. ["u1", "补充说明"],
  2894. ["u1", "回答二"],
  2895. ["u_q2", "排队问题"],
  2896. ["u_q2", "排队回答"],
  2897. ]);
  2898. expect(rows.filter((row) => row.kind === "turnHeader")).toHaveLength(2);
  2899. // 内联 steer 行登记了持久 messageId(entityId 派生)。
  2900. const steerRow = rows.find((row) => row.kind === "userInput" && row.text === "补充说明");
  2901. expect(projection.getMessageIdForRow(steerRow!.rowId)).toBe("u_steer");
  2902. const guideHeader = rows.find((row) => row.kind === "turnHeader" && row.turnId === "u1");
  2903. expect(guideHeader).toMatchObject({
  2904. workSegments: [
  2905. { segmentId: "u1:initial", startedAt: 1000, endedAt: 1500, activeMs: 500 },
  2906. {
  2907. segmentId: "u_steer",
  2908. triggerEntityId: "u_steer",
  2909. startedAt: 1500,
  2910. endedAt: 1601,
  2911. activeMs: 101,
  2912. },
  2913. ],
  2914. });
  2915. });
  2916. it("S1 cold:guide steer 从持久 metadata 恢复完整 intent,row 与 live 字段保真", () => {
  2917. const guide = userMessage("u_guide", "带附件补充", 1500);
  2918. const attachment = {
  2919. ref: "attachment://guide-1",
  2920. fileName: "guide.png",
  2921. mime: "image/png",
  2922. bytes: 2048,
  2923. previewRef: "preview://guide-1",
  2924. };
  2925. const messages: MessageWithParts[] = [
  2926. userMessage("u1", "问题一", 1000),
  2927. assistantMessage("a1", "u1", "回答一", 1001),
  2928. {
  2929. ...guide,
  2930. info: {
  2931. ...guide.info,
  2932. anchor: { sourceCommandId: "command-guide-1" },
  2933. metadata: {
  2934. turnSteerDelivery: "guide",
  2935. conversationInputIntent: {
  2936. sourceCommandId: "command-guide-1",
  2937. queueItemId: "queue_command-guide-1",
  2938. clientId: "mobile-guide",
  2939. kind: "sendGoalCommand",
  2940. text: "带附件补充",
  2941. attachments: [attachment],
  2942. delivery: {
  2943. requested: "guide",
  2944. admitted: "guide",
  2945. fallbackReasonCode: "guide_fallback_test",
  2946. },
  2947. order: { admissionSeq: 19, queuePosition: 2 },
  2948. steer: { state: "guided" },
  2949. dispatch: { state: "drained" },
  2950. admittedAt: 1499,
  2951. },
  2952. },
  2953. } as MessageWithParts["info"],
  2954. },
  2955. assistantMessage("a2", "u1", "回答二", 1600),
  2956. ];
  2957. const events = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  2958. const drained = events.find((event) => event.type === SessionEventType.TurnSteerDrained);
  2959. expect(drained?.payload).toMatchObject({
  2960. pendingInputIds: ["queue_command-guide-1"],
  2961. drainedInputs: [
  2962. {
  2963. pendingInputId: "queue_command-guide-1",
  2964. messageId: "u_guide",
  2965. text: "带附件补充",
  2966. delivery: "guide",
  2967. intent: {
  2968. sourceCommandId: "command-guide-1",
  2969. queueItemId: "queue_command-guide-1",
  2970. clientId: "mobile-guide",
  2971. kind: "sendGoalCommand",
  2972. admissionSeq: 19,
  2973. queuePosition: 2,
  2974. admittedAt: 1499,
  2975. requestedDelivery: "guide",
  2976. admittedDelivery: "guide",
  2977. fallbackReasonCode: "guide_fallback_test",
  2978. attachmentRefs: [attachment],
  2979. },
  2980. },
  2981. ],
  2982. });
  2983. const projection = new ProductProjection("s1", "epoch");
  2984. for (const event of events) projection.applyEvent(event);
  2985. const row = projection
  2986. .getSnapshot()
  2987. .rows.window.find((candidate) => candidate.kind === "userInput" && candidate.guided);
  2988. expect(row).toMatchObject({
  2989. turnId: "u1",
  2990. text: "带附件补充",
  2991. guided: true,
  2992. sourceCommandId: "command-guide-1",
  2993. clientId: "mobile-guide",
  2994. attachments: [attachment],
  2995. });
  2996. });
  2997. it("timeline 宿主消息(model_change)不开 preface 空轮", () => {
  2998. const messages = [
  2999. userMessageWithModel("u1", "先用 A", 1000, { providerId: "p1", modelId: "m1" }),
  3000. assistantMessage("a1", "u1", "好的", 1001),
  3001. modelChangeHostMessage("mc1", "a1", 1500),
  3002. userMessageWithModel("u2", "换 B", 2000, { providerId: "p2", modelId: "m2" }),
  3003. assistantMessage("a2", "u2", "已切换", 2001),
  3004. ];
  3005. const { projection } = reduce(messages);
  3006. const rows = projection.getSnapshot().rows.window;
  3007. // 宿主消息本身无可渲染内容:不产生第三个 turnHeader,也不产生空「已工作」壳。
  3008. expect(rows.filter((row) => row.kind === "turnHeader")).toHaveLength(2);
  3009. // marker 仍由选型事实重建(宿主的 defaultModelSelection 占位不参与选型来源)。
  3010. expect(
  3011. rows.filter((row) => row.kind === "timelineMarker" && row.marker.type === "modelChange"),
  3012. ).toHaveLength(1);
  3013. });
  3014. it("MC-cold:model_change timeline part 在后续 user model 快照滞后时仍是边界权威", () => {
  3015. const messages = [
  3016. userMessageWithModel("u1", "先用 A", 1000, { providerId: "p1", modelId: "m1" }),
  3017. assistantMessage("a1", "u1", "好的", 1001),
  3018. modelChangeHostMessage("mc1", "a1", 1500),
  3019. syntheticUserMessage("legacy-context", "internal context", 1600, {
  3020. source: "rewind",
  3021. visibility: "model-only",
  3022. }),
  3023. // 模拟旧数据:user message 仍带上一轮快照,但 timeline part 已持久 p2/m2。
  3024. userMessageWithModel("u2", "换 B", 2000, { providerId: "p1", modelId: "m1" }),
  3025. assistantMessage("a2", "u2", "已切换", 2001),
  3026. ];
  3027. const { events, projection } = reduce(messages);
  3028. const marker = projection
  3029. .getSnapshot()
  3030. .rows.window.find(
  3031. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  3032. );
  3033. expect(marker).toEqual(
  3034. expect.objectContaining({
  3035. marker: expect.objectContaining({
  3036. fromProvider: "p1",
  3037. fromModel: "m1",
  3038. toProvider: "p2",
  3039. toModel: "m2",
  3040. }),
  3041. }),
  3042. );
  3043. expect(
  3044. eventsCoverTranscript(
  3045. events.filter((event) => event.type !== SessionEventType.ModelSelected),
  3046. messages,
  3047. ),
  3048. ).toBe(false);
  3049. });
  3050. });
  3051. function userMessageWithModel(
  3052. id: string,
  3053. text: string,
  3054. created: number,
  3055. model: { providerId: string; modelId: string; reasoningLevel?: string },
  3056. ): MessageWithParts {
  3057. const base = userMessage(id, text, created);
  3058. return {
  3059. ...base,
  3060. info: {
  3061. ...base.info,
  3062. modelSelection: {
  3063. providerId: model.providerId as never,
  3064. modelId: model.modelId as never,
  3065. ...(model.reasoningLevel ? { options: { reasoningLevel: model.reasoningLevel } } : {}),
  3066. },
  3067. } as MessageWithParts["info"],
  3068. };
  3069. }
  3070. const TIMELINE_HOST_SEMANTICS = {
  3071. origin: "system",
  3072. kind: "timeline_event",
  3073. uiVisibility: "visible",
  3074. providerVisibility: "hidden",
  3075. transcriptVisibility: "visible",
  3076. } as never;
  3077. function goalVerificationHostMessage(
  3078. id: string,
  3079. parentId: string,
  3080. created: number,
  3081. overrides: {
  3082. status: string;
  3083. goalIteration?: number;
  3084. verification?: { passed: boolean; reason: string };
  3085. },
  3086. ): MessageWithParts {
  3087. const base = assistantMessage(id, parentId, "", created);
  3088. return {
  3089. ...base,
  3090. info: { ...base.info, semantics: TIMELINE_HOST_SEMANTICS } as MessageWithParts["info"],
  3091. parts: [
  3092. {
  3093. id: `${id}-timeline` as never,
  3094. sessionID: "s1" as never,
  3095. messageID: id as never,
  3096. type: "timeline",
  3097. timelineType: "goal_verification",
  3098. display: "separator",
  3099. status: overrides.status,
  3100. targetId: "target-1",
  3101. verificationId: `verify-${id}`,
  3102. ...(overrides.goalIteration !== undefined
  3103. ? { goalIteration: overrides.goalIteration }
  3104. : {}),
  3105. anchorMessageId: parentId as never,
  3106. ...(overrides.verification ? { verification: overrides.verification } : {}),
  3107. } as MessagePart,
  3108. ],
  3109. };
  3110. }
  3111. function modelChangeHostMessage(id: string, parentId: string, created: number): MessageWithParts {
  3112. const base = assistantMessage(id, parentId, "", created);
  3113. return {
  3114. ...base,
  3115. info: { ...base.info, semantics: TIMELINE_HOST_SEMANTICS } as MessageWithParts["info"],
  3116. parts: [
  3117. {
  3118. id: `${id}-timeline` as never,
  3119. sessionID: "s1" as never,
  3120. messageID: id as never,
  3121. type: "timeline",
  3122. timelineType: "model_change",
  3123. display: "separator",
  3124. status: "completed",
  3125. anchorMessageId: parentId as never,
  3126. fromModel: { providerId: "p1" as never, modelId: "m1" as never, label: "A" },
  3127. toModel: { providerId: "p2" as never, modelId: "m2" as never, label: "B" },
  3128. } as MessagePart,
  3129. ],
  3130. };
  3131. }
  3132. function initialModelHostMessage(id: string, created: number): MessageWithParts {
  3133. // 首条 timeline 事实没有上一条 conversation message,运行时会把 parentID
  3134. // 固定为自身。测试必须保持这一真实持久化形态,防止冷恢复只在理想夹具下通过。
  3135. const base = assistantMessage(id, id, "", created);
  3136. return {
  3137. ...base,
  3138. info: { ...base.info, semantics: TIMELINE_HOST_SEMANTICS } as MessageWithParts["info"],
  3139. parts: [
  3140. {
  3141. id: `${id}-timeline` as never,
  3142. sessionID: "s1" as never,
  3143. messageID: id as never,
  3144. type: "timeline",
  3145. timelineType: "model_change",
  3146. display: "separator",
  3147. status: "completed",
  3148. toModel: {
  3149. providerId: "child-provider" as never,
  3150. modelId: "child-model" as never,
  3151. label: "Child Model",
  3152. },
  3153. } as MessagePart,
  3154. ],
  3155. };
  3156. }
  3157. // 中枢直接启动已保存工作流的启动轮(docs/dynamic-workflow/launch.md):冷恢复由 source
  3158. // "workflow_launch" + metadata.workflowLaunch 重建可见 controlOnly 启动轮。这条消息是 synthetic
  3159. // 却语义上属用户真实动作,共享 policy 会把它归成 hiddenSynthetic;若无专用分支就会被跳过。
  3160. // 断言:冷路径产出的 turnHeader/userInput 行在相关字段上与活投影逐字相等(origin/executionKind/
  3161. // text/workflowLaunch),且无助手行。
  3162. describe("workflow-direct-launch 启动轮冷恢复", () => {
  3163. const workflowLaunch = {
  3164. runId: "dwfrun-9",
  3165. toolCallId: "launch-abc",
  3166. name: "deep-research",
  3167. scope: "global" as const,
  3168. path: "/home/u/.zcode/workflows/deep-research.ts",
  3169. args: { topic: "adaptive concurrency" },
  3170. description: "Deep-dive a topic",
  3171. };
  3172. const launchText = 'Started the saved workflow "deep-research" (global) as run dwfrun-9.';
  3173. // GUI「配置」的设置轮(docs/dynamic-workflow/launch.md「The settings turn」):同一条冷路径,元数据
  3174. // 没有 scope / path,多一块 amend。
  3175. const settingsLaunch = {
  3176. runId: "dwfrun-10",
  3177. toolCallId: "settings-abc",
  3178. name: "deep-research",
  3179. amend: {
  3180. predecessorRunId: "dwfrun-9",
  3181. maxConcurrency: { from: 13, to: 4 },
  3182. ceiling: 13,
  3183. },
  3184. };
  3185. function launchMessage(meta: object = workflowLaunch): MessageWithParts {
  3186. return syntheticUserMessage("message-launch-1", launchText, 1_700_000_000_000, {
  3187. source: "workflow_launch",
  3188. visibility: "user-visible",
  3189. metadata: { workflowLaunch: meta },
  3190. semantics: {
  3191. origin: "real_user",
  3192. kind: "user_prompt",
  3193. source: "workflow_launch",
  3194. uiVisibility: "visible",
  3195. providerVisibility: "visible",
  3196. transcriptVisibility: "visible",
  3197. } as MessageWithParts["info"]["semantics"],
  3198. });
  3199. }
  3200. // 相关字段投影:跨 live/cold 稳定(不含 rowId / turnId / createdAt 这些身份差异字段)。
  3201. function relevantRow(row: Record<string, unknown>): Record<string, unknown> {
  3202. return {
  3203. kind: row.kind,
  3204. origin: row.origin,
  3205. ...(row.executionKind !== undefined ? { executionKind: row.executionKind } : {}),
  3206. ...(row.state !== undefined ? { state: row.state } : {}),
  3207. ...(row.text !== undefined ? { text: row.text } : {}),
  3208. ...(row.workflowLaunch !== undefined ? { workflowLaunch: row.workflowLaunch } : {}),
  3209. };
  3210. }
  3211. function liveRows(meta: object = workflowLaunch): Record<string, unknown>[] {
  3212. const projection = new ProductProjection("s1", "epoch");
  3213. const base = (seq: number) => ({
  3214. id: `event-${seq}` as never,
  3215. sessionId: "s1" as never,
  3216. traceId: "trace-live" as never,
  3217. sequenceNumber: seq,
  3218. timestamp: new Date(1_700_000_000_000 + seq),
  3219. });
  3220. const events: SessionEvent[] = [
  3221. {
  3222. ...base(1),
  3223. type: SessionEventType.SessionCreated,
  3224. payload: { mode: "default", contextWindow: 200_000 },
  3225. } as unknown as SessionEvent,
  3226. {
  3227. ...base(2),
  3228. turnId: "turn-launch" as never,
  3229. type: SessionEventType.TurnStarted,
  3230. payload: {
  3231. turnNumber: 1,
  3232. input: launchText,
  3233. messageId: "message-launch-1",
  3234. executionKind: "controlOnly",
  3235. inputSource: "workflow_launch",
  3236. workflowLaunch: meta,
  3237. },
  3238. } as unknown as SessionEvent,
  3239. {
  3240. ...base(3),
  3241. turnId: "turn-launch" as never,
  3242. type: SessionEventType.TurnComplete,
  3243. payload: {
  3244. response: "",
  3245. tokenCount: 0,
  3246. toolCallCount: 0,
  3247. duration: 0,
  3248. resultType: "success",
  3249. },
  3250. } as unknown as SessionEvent,
  3251. ];
  3252. for (const event of events) projection.applyEvent(event);
  3253. return projection
  3254. .getSnapshot()
  3255. .rows.window.map((row) => relevantRow(row as Record<string, unknown>));
  3256. }
  3257. it("冷恢复重建双行(origin=workflowLaunch + 元数据),且与活投影相关字段逐字相等,无助手行", () => {
  3258. const { projection } = reduce([launchMessage()]);
  3259. const coldRows = projection
  3260. .getSnapshot()
  3261. .rows.window.map((row) => relevantRow(row as Record<string, unknown>));
  3262. expect(coldRows).toEqual([
  3263. {
  3264. kind: "turnHeader",
  3265. origin: "workflowLaunch",
  3266. executionKind: "controlOnly",
  3267. state: "completedSuccess",
  3268. workflowLaunch,
  3269. },
  3270. {
  3271. kind: "userInput",
  3272. origin: "workflowLaunch",
  3273. text: launchText,
  3274. workflowLaunch,
  3275. },
  3276. ]);
  3277. // 冷热同形:相关字段逐字相等(rowId/turnId 等身份字段除外)。
  3278. expect(coldRows).toEqual(liveRows());
  3279. });
  3280. it("设置轮(无 scope / path、带 amend 块)走同一条冷路径,冷热同形", () => {
  3281. const { projection } = reduce([launchMessage(settingsLaunch)]);
  3282. const coldRows = projection
  3283. .getSnapshot()
  3284. .rows.window.map((row) => relevantRow(row as Record<string, unknown>));
  3285. expect(coldRows).toEqual([
  3286. {
  3287. kind: "turnHeader",
  3288. origin: "workflowLaunch",
  3289. executionKind: "controlOnly",
  3290. state: "completedSuccess",
  3291. workflowLaunch: settingsLaunch,
  3292. },
  3293. {
  3294. kind: "userInput",
  3295. origin: "workflowLaunch",
  3296. text: launchText,
  3297. workflowLaunch: settingsLaunch,
  3298. },
  3299. ]);
  3300. expect(coldRows).toEqual(liveRows(settingsLaunch));
  3301. });
  3302. });
  3303. // docs/dynamic-workflow/transcript-and-notifications.md:冷路径从用户消息 metadata 读回边界,
  3304. // 与热路径落在同一个 TurnStarted 字段上;非非负整数按缺席处理。
  3305. describe("epilogueStart 冷恢复", () => {
  3306. function turnStartedOf(events: SessionEvent[], messageId: string) {
  3307. return events.find(
  3308. (event) =>
  3309. event.type === SessionEventType.TurnStarted &&
  3310. (event.payload as { messageId?: string }).messageId === messageId,
  3311. );
  3312. }
  3313. it("metadata.epilogueStart → TurnStarted.epilogueStart → userInput 行", () => {
  3314. const ask = userMessage("u-ask", "Summarize\n\n---\nStandard", 1000);
  3315. ask.info.metadata = { epilogueStart: 9 };
  3316. const nudge = userMessage("u-nudge", "You ended your turn without submitting a result.", 2000);
  3317. nudge.info.metadata = { epilogueStart: 0 };
  3318. const plain = userMessage("u-plain", "plain", 3000);
  3319. const bogus = userMessage("u-bogus", "bogus", 4000);
  3320. bogus.info.metadata = { epilogueStart: -3 };
  3321. const events = synthesizeEventsFromMessages([ask, nudge, plain, bogus], { sessionId: "s1" });
  3322. expect(turnStartedOf(events, "u-ask")?.payload).toMatchObject({ epilogueStart: 9 });
  3323. expect(turnStartedOf(events, "u-nudge")?.payload).toMatchObject({ epilogueStart: 0 });
  3324. expect(turnStartedOf(events, "u-plain")?.payload).not.toHaveProperty("epilogueStart");
  3325. expect(turnStartedOf(events, "u-bogus")?.payload).not.toHaveProperty("epilogueStart");
  3326. const projection = new ProductProjection("s1", "epoch");
  3327. for (const event of events) projection.applyEvent(event);
  3328. const rows = projection.getSnapshot().rows.window.filter((row) => row.kind === "userInput");
  3329. expect(rows.map((row) => (row.kind === "userInput" ? row.epilogueStart : null))).toEqual([
  3330. 9,
  3331. 0,
  3332. undefined,
  3333. undefined,
  3334. ]);
  3335. });
  3336. });