transcript-hydration.test.ts 134 KB

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