transcript-hydration.test.ts 125 KB

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