transcript-hydration.test.ts 143 KB

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