zcodeSessionProjection.test.ts 158 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. encodeCustomModelValue,
  4. formatModelPickerValue as formatSharedModelSelection,
  5. ZCODE_PROTOCOL_NAME,
  6. ZCODE_PROTOCOL_VERSION,
  7. type ZCodeSessionEvent,
  8. type ZCodeMessagePart,
  9. type ZCodeMessageWithParts,
  10. type ZCodeSessionSettingsState,
  11. type ZCodeSessionStateSnapshot,
  12. } from "@zcode/shared";
  13. import {
  14. formatModelPickerValue as formatProjectedModelSelection,
  15. parseModelPickerValue,
  16. type ZCodeSessionEventProjectionState,
  17. zcodeSessionEventToZCodeStreamEvents,
  18. zcodeSessionSettingsToConfigOptions,
  19. zcodeSessionSnapshotToZCodeTaskSnapshot,
  20. zcodeStateUpdatedToZCodeStreamEvents,
  21. zcodeUserInputRequestToZCodeStreamEvent,
  22. zcodeUserInputResponseToZCodeStreamEvent,
  23. } from "@/lib/zcodeSessionProjection.js";
  24. const workspace = {
  25. workspacePath: "/workspace/app",
  26. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  27. workspaceKey: "remote:ssh:dev:/workspace/app",
  28. };
  29. const subagentOrigin = {
  30. kind: "subagent",
  31. agentId: "agent_snapshot",
  32. agentType: "general",
  33. childSessionId: "sess_child_snapshot",
  34. childTurnId: "turn_child_snapshot",
  35. parentSessionId: "sess_1",
  36. parentToolCallId: "tool_parent_agent",
  37. parentTurnId: "turn_parent_snapshot",
  38. } as const;
  39. const model = { providerId: "glm", modelId: "glm-4.6" };
  40. const backgroundAgentProviderError =
  41. "Requests are too frequent. Please reduce your request frequency, wait a short moment, and retry your request. Request id: e2e-background-subagent-rate-limit";
  42. const settings = {
  43. model: {
  44. current: model,
  45. available: [{ ref: model, label: "GLM 4.6", contextWindow: 128000 }],
  46. lastUsed: model,
  47. },
  48. thoughtLevel: {
  49. enabled: true,
  50. current: "medium",
  51. available: [{ value: "medium", label: "Medium" }],
  52. },
  53. mode: {
  54. current: "build",
  55. },
  56. } satisfies ZCodeSessionSettingsState;
  57. const settingsWithDefaultThoughtLevel = {
  58. ...settings,
  59. thoughtLevel: {
  60. enabled: true,
  61. current: undefined,
  62. defaultLevel: "max",
  63. available: [
  64. { value: "high", label: "High" },
  65. { value: "max", label: "Max" },
  66. ],
  67. },
  68. } satisfies ZCodeSessionSettingsState;
  69. function createSnapshot(): ZCodeSessionStateSnapshot {
  70. return {
  71. protocol: {
  72. name: ZCODE_PROTOCOL_NAME,
  73. version: ZCODE_PROTOCOL_VERSION,
  74. },
  75. session: {
  76. sessionId: "sess_1",
  77. workspace,
  78. sessionKind: "interactive",
  79. title: "",
  80. mode: "build",
  81. status: "running",
  82. model,
  83. createdAt: 1,
  84. updatedAt: 2,
  85. },
  86. settings,
  87. projection: {
  88. sessionId: "sess_1",
  89. status: "running",
  90. mode: "build",
  91. turnCount: 1,
  92. totalTokenCount: 12,
  93. contextUsed: 12,
  94. contextWindow: 128000,
  95. pendingPermissions: [
  96. {
  97. requestId: "perm_1",
  98. toolCallId: "tool_1",
  99. toolName: "Bash",
  100. riskLevel: "medium",
  101. reason: "Run command",
  102. origin: subagentOrigin,
  103. requestedAt: 3,
  104. },
  105. ],
  106. activeToolCalls: [],
  107. backgroundJobs: [],
  108. },
  109. runtime: {
  110. eventSeq: 7,
  111. stateRevision: 3,
  112. deliveryKind: "desktop-continuous",
  113. pendingRequestIds: ["perm_1"],
  114. },
  115. messages: [
  116. {
  117. info: {
  118. messageId: "msg_user",
  119. sessionId: "sess_1",
  120. role: "user",
  121. time: { created: 1 },
  122. agent: "zcode-agent",
  123. model,
  124. },
  125. parts: [
  126. {
  127. partId: "part_user",
  128. sessionId: "sess_1",
  129. messageId: "msg_user",
  130. type: "text",
  131. text: "hello",
  132. },
  133. ],
  134. },
  135. {
  136. info: {
  137. messageId: "msg_assistant",
  138. sessionId: "sess_1",
  139. role: "assistant",
  140. parentMessageId: "msg_user",
  141. time: { created: 2, completed: 12 },
  142. agent: "zcode-agent",
  143. model,
  144. path: { cwd: "/workspace/app", root: "/workspace/app" },
  145. cost: 0,
  146. tokens: {
  147. input: 1,
  148. output: 2,
  149. reasoning: 3,
  150. total: 6,
  151. cache: { read: 0, write: 0 },
  152. },
  153. },
  154. parts: [
  155. {
  156. partId: "part_reasoning",
  157. sessionId: "sess_1",
  158. messageId: "msg_assistant",
  159. type: "reasoning",
  160. text: "thinking",
  161. },
  162. {
  163. partId: "part_tool",
  164. sessionId: "sess_1",
  165. messageId: "msg_assistant",
  166. type: "tool",
  167. callId: "tool_1",
  168. tool: "Bash",
  169. state: {
  170. status: "completed",
  171. input: { command: "pwd" },
  172. output: "/workspace/app",
  173. title: "Bash",
  174. metadata: {},
  175. startedAt: 4,
  176. completedAt: 5,
  177. },
  178. },
  179. {
  180. partId: "part_text",
  181. sessionId: "sess_1",
  182. messageId: "msg_assistant",
  183. type: "text",
  184. text: "done",
  185. },
  186. ],
  187. },
  188. ],
  189. };
  190. }
  191. describe("zcodeSessionProjection", () => {
  192. it.each(["desktop-continuous", "web-remote-replayable"] as const)(
  193. "%s 历史缺少模型来源时保留消息,不伪造模型",
  194. (deliveryKind) => {
  195. const snapshot = createSnapshot();
  196. snapshot.runtime.deliveryKind = deliveryKind;
  197. for (const message of snapshot.messages) delete message.info.model;
  198. const projected = zcodeSessionSnapshotToZCodeTaskSnapshot(snapshot);
  199. expect(projected.messages).toHaveLength(snapshot.messages.length);
  200. expect(projected.messages.every((message) => message.model === undefined)).toBe(true);
  201. expect(projected.messages[0]?.content).toBe("hello");
  202. },
  203. );
  204. it("preserves structured attribution when projecting a failed turn to task_error", () => {
  205. const events = zcodeSessionEventToZCodeStreamEvents({
  206. event: {
  207. eventId: "evt_turn_failed_attribution",
  208. seq: 8,
  209. sessionId: "sess_1",
  210. timestamp: 10,
  211. type: "turn.failed",
  212. payload: {
  213. turnPhase: "model",
  214. error: {
  215. type: "MODEL_ERROR",
  216. code: "model_request_failed",
  217. message: "[1301][Sensitive content rejected]",
  218. attribution: {
  219. source: "provider",
  220. reason: "unknown",
  221. providerId: "account:bigmodel-individual-coding-plan",
  222. providerErrorCode: "1301",
  223. },
  224. },
  225. },
  226. },
  227. taskId: "task_1",
  228. });
  229. expect(events).toContainEqual(
  230. expect.objectContaining({
  231. type: "task_error",
  232. attribution: {
  233. source: "provider",
  234. reason: "unknown",
  235. providerId: "account:bigmodel-individual-coding-plan",
  236. providerErrorCode: "1301",
  237. },
  238. }),
  239. );
  240. });
  241. it("preserves completed tool display metadata in snapshot raw output", () => {
  242. const base = createSnapshot();
  243. const assistant = base.messages[1]!;
  244. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  245. ...base,
  246. messages: [
  247. base.messages[0]!,
  248. {
  249. ...assistant,
  250. parts: [
  251. {
  252. partId: "part_node_repl_image",
  253. sessionId: "sess_1",
  254. messageId: assistant.info.messageId,
  255. type: "tool",
  256. callId: "tool_node_repl_image",
  257. tool: "mcp__node_repl__js",
  258. state: {
  259. status: "completed",
  260. input: { code: "nodeRepl.emitImage(await tab.screenshot());" },
  261. output: "(no output)\n[Attached image/png: MCP image]",
  262. title: "截图查看",
  263. metadata: {
  264. schemaVersion: 1,
  265. display: {
  266. kind: "node_repl_images",
  267. images: [{ base64: "AAAA", mimeType: "image/png" }],
  268. },
  269. },
  270. startedAt: 4,
  271. completedAt: 5,
  272. },
  273. },
  274. ],
  275. },
  276. ],
  277. });
  278. expect(snapshot.messages[1]?.tools[0]?.raw).toMatchObject({
  279. toolCallId: "tool_node_repl_image",
  280. display: {
  281. kind: "node_repl_images",
  282. images: [{ base64: "AAAA", mimeType: "image/png" }],
  283. },
  284. });
  285. });
  286. it("falls back to a valid thought level when session settings carry a stale current value", () => {
  287. const options = zcodeSessionSettingsToConfigOptions({
  288. ...settings,
  289. thoughtLevel: {
  290. enabled: true,
  291. current: "high",
  292. available: [
  293. { value: "enabled", label: "Enabled" },
  294. { value: "disabled", label: "Disabled" },
  295. ],
  296. },
  297. });
  298. expect(options.find((option) => option.category === "thought_level")?.currentValue).toBe(
  299. "enabled",
  300. );
  301. });
  302. it("uses thought defaultLevel before the first available level when current is empty", () => {
  303. const options = zcodeSessionSettingsToConfigOptions(settingsWithDefaultThoughtLevel);
  304. expect(options.find((option) => option.category === "thought_level")?.currentValue).toBe("max");
  305. });
  306. it("uses thought defaultLevel in model state updates when current is empty", () => {
  307. const events = zcodeStateUpdatedToZCodeStreamEvents({
  308. notification: {
  309. type: "state.updated",
  310. scope: "session",
  311. sessionId: "sess_1",
  312. revision: 2,
  313. reason: "model_changed",
  314. patch: settingsWithDefaultThoughtLevel,
  315. },
  316. settings: settingsWithDefaultThoughtLevel,
  317. taskId: "sess_1",
  318. });
  319. expect(events.find((event) => event.type === "glm_agent_model_state_update")).toMatchObject({
  320. type: "glm_agent_model_state_update",
  321. thoughtLevel: {
  322. enabled: true,
  323. currentValue: "max",
  324. options: [
  325. { value: "high", name: "High" },
  326. { value: "max", name: "Max" },
  327. ],
  328. },
  329. });
  330. });
  331. it("maps server-owned session snapshots into the current chat projection", () => {
  332. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot(createSnapshot());
  333. expect(snapshot.meta).toMatchObject({
  334. taskId: "sess_1",
  335. provider: "glm",
  336. title: "hello",
  337. status: "running",
  338. workspaceIdentity: workspace.workspaceIdentity,
  339. });
  340. expect(snapshot.messages).toHaveLength(2);
  341. expect(snapshot.messages[1]).toMatchObject({
  342. role: "assistant",
  343. content: "done",
  344. thought: "thinking",
  345. durationMs: 10,
  346. });
  347. expect(snapshot.messages[1]?.tools?.[0]).toMatchObject({
  348. toolName: "Bash",
  349. status: "completed",
  350. output: "/workspace/app",
  351. raw: {
  352. toolCallId: "tool_1",
  353. },
  354. });
  355. expect(snapshot.messages[1]?.tools?.[0]?.raw).toMatchObject({
  356. toolCallId: "tool_1",
  357. });
  358. expect(snapshot.runtime?.pendingPermissions?.[0]).toMatchObject({
  359. requestId: "perm_1",
  360. kind: "Bash",
  361. origin: subagentOrigin,
  362. });
  363. expect(snapshot.runtime?.contextUsage).toEqual({
  364. used: 12,
  365. size: 128000,
  366. cost: null,
  367. });
  368. });
  369. it("projects legacy fork synthetic user as a separator without raw text", () => {
  370. const base = createSnapshot();
  371. const forkMetadata = {
  372. forkContext: {
  373. kind: "session_fork",
  374. parentSessionId: "sess_parent",
  375. restoredFileCount: 0,
  376. targetMessageId: "msg_parent_assistant",
  377. },
  378. source: "fork",
  379. visibility: "user-visible",
  380. };
  381. const forkNotice: ZCodeMessageWithParts = {
  382. info: {
  383. messageId: "msg_fork_notice",
  384. sessionId: "sess_1",
  385. role: "user",
  386. time: { created: 3 },
  387. agent: "zcode-agent",
  388. model,
  389. metadata: forkMetadata,
  390. source: "fork",
  391. synthetic: true,
  392. visibility: "user-visible",
  393. },
  394. parts: [
  395. {
  396. partId: "part_fork_notice",
  397. sessionId: "sess_1",
  398. messageId: "msg_fork_notice",
  399. type: "text",
  400. text: "This session was forked from a previous session message.",
  401. metadata: forkMetadata,
  402. synthetic: true,
  403. },
  404. ],
  405. };
  406. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  407. ...base,
  408. messages: [...base.messages, forkNotice],
  409. });
  410. const forkTimeline = snapshot.messages.find(
  411. (message) => message.syntheticTimeline?.type === "session_fork",
  412. );
  413. expect(forkTimeline).toMatchObject({
  414. content: "",
  415. syntheticTimeline: {
  416. parentSessionId: "sess_parent",
  417. targetMessageId: "msg_parent_assistant",
  418. type: "session_fork",
  419. },
  420. });
  421. expect(
  422. snapshot.messages.some((message) => message.content.includes("This session was forked")),
  423. ).toBe(false);
  424. });
  425. it("projects persisted session_fork timeline parts after cold snapshot restore", () => {
  426. const base = createSnapshot();
  427. const timelineMessage: ZCodeMessageWithParts = {
  428. info: {
  429. messageId: "msg_fork_timeline",
  430. sessionId: "sess_1",
  431. role: "assistant",
  432. parentMessageId: "msg_assistant",
  433. time: { created: 4, completed: 4 },
  434. agent: "zcode-agent",
  435. model,
  436. path: { cwd: "/workspace/app", root: "/workspace/app" },
  437. cost: 0,
  438. tokens: {
  439. input: 0,
  440. output: 0,
  441. reasoning: 0,
  442. total: 0,
  443. cache: { read: 0, write: 0 },
  444. },
  445. },
  446. parts: [
  447. {
  448. partId: "part_fork_timeline",
  449. sessionId: "sess_1",
  450. messageId: "msg_fork_timeline",
  451. type: "timeline",
  452. timelineType: "session_fork",
  453. display: "separator",
  454. status: "completed",
  455. parentSessionId: "sess_parent",
  456. targetMessageId: "msg_parent_assistant",
  457. restoredFileCount: 1,
  458. },
  459. ],
  460. };
  461. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  462. ...base,
  463. messages: [...base.messages, timelineMessage],
  464. });
  465. expect(snapshot.messages.find((message) => message.id === "msg_fork_timeline")).toMatchObject({
  466. content: "",
  467. syntheticTimeline: {
  468. parentSessionId: "sess_parent",
  469. restoredFileCount: 1,
  470. targetMessageId: "msg_parent_assistant",
  471. type: "session_fork",
  472. },
  473. });
  474. });
  475. it("hides model-only fork raw notices when a structured fork timeline exists", () => {
  476. const base = createSnapshot();
  477. const forkMetadata = {
  478. forkContext: {
  479. kind: "session_fork",
  480. parentSessionId: "sess_parent",
  481. restoredFileCount: 0,
  482. targetMessageId: "msg_parent_assistant",
  483. },
  484. source: "fork",
  485. visibility: "model-only",
  486. };
  487. const timelineMessage: ZCodeMessageWithParts = {
  488. info: {
  489. messageId: "msg_fork_timeline",
  490. sessionId: "sess_1",
  491. role: "assistant",
  492. parentMessageId: "msg_assistant",
  493. time: { created: 4, completed: 4 },
  494. agent: "zcode-agent",
  495. model,
  496. path: { cwd: "/workspace/app", root: "/workspace/app" },
  497. cost: 0,
  498. tokens: {
  499. input: 0,
  500. output: 0,
  501. reasoning: 0,
  502. total: 0,
  503. cache: { read: 0, write: 0 },
  504. },
  505. },
  506. parts: [
  507. {
  508. partId: "part_fork_timeline",
  509. sessionId: "sess_1",
  510. messageId: "msg_fork_timeline",
  511. type: "timeline",
  512. timelineType: "session_fork",
  513. display: "separator",
  514. status: "completed",
  515. parentSessionId: "sess_parent",
  516. targetMessageId: "msg_parent_assistant",
  517. restoredFileCount: 0,
  518. },
  519. ],
  520. };
  521. const rawNotice: ZCodeMessageWithParts = {
  522. info: {
  523. messageId: "msg_fork_raw_notice",
  524. sessionId: "sess_1",
  525. role: "user",
  526. time: { created: 5 },
  527. agent: "zcode-agent",
  528. model,
  529. metadata: forkMetadata,
  530. semantics: {
  531. kind: "fork_notice",
  532. origin: "agent_runtime",
  533. providerVisibility: "visible",
  534. source: "fork",
  535. transcriptVisibility: "hidden",
  536. uiVisibility: "hidden",
  537. },
  538. source: "fork",
  539. synthetic: true,
  540. visibility: "model-only",
  541. },
  542. parts: [
  543. {
  544. partId: "part_fork_raw_notice",
  545. sessionId: "sess_1",
  546. messageId: "msg_fork_raw_notice",
  547. type: "text",
  548. text: "This session was forked from a previous session message.",
  549. metadata: forkMetadata,
  550. synthetic: true,
  551. },
  552. ],
  553. };
  554. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  555. ...base,
  556. messages: [...base.messages, timelineMessage, rawNotice],
  557. });
  558. const forkTimelines = snapshot.messages.filter(
  559. (message) => message.syntheticTimeline?.type === "session_fork",
  560. );
  561. expect(forkTimelines).toHaveLength(1);
  562. expect(forkTimelines[0]).toMatchObject({
  563. id: "msg_fork_timeline",
  564. content: "",
  565. syntheticTimeline: {
  566. parentSessionId: "sess_parent",
  567. targetMessageId: "msg_parent_assistant",
  568. type: "session_fork",
  569. },
  570. });
  571. expect(JSON.stringify(snapshot.messages)).not.toContain("This session was forked");
  572. });
  573. it("attaches hidden task notification metadata to the matching background Agent tool", () => {
  574. const base = createSnapshot();
  575. const assistantMessage = {
  576. info: {
  577. messageId: "msg_assistant_agent",
  578. sessionId: "sess_1",
  579. role: "assistant",
  580. parentMessageId: "msg_user",
  581. time: { created: 2, completed: 12 },
  582. agent: "zcode-agent",
  583. model,
  584. },
  585. parts: [
  586. {
  587. partId: "part_agent_tool",
  588. sessionId: "sess_1",
  589. messageId: "msg_assistant_agent",
  590. type: "tool",
  591. callId: "toolu_background_agent",
  592. tool: "Agent",
  593. state: {
  594. status: "completed",
  595. input: {
  596. prompt: "run background research",
  597. run_in_background: true,
  598. },
  599. output: "Async agent launched successfully.\noutput_file: /tmp/background-agent.output",
  600. title: "Agent",
  601. metadata: {
  602. _meta: {
  603. zcode: {
  604. backgroundAgent: {
  605. runInBackground: true,
  606. outputFile: "/tmp/background-agent.output",
  607. },
  608. },
  609. },
  610. },
  611. startedAt: 4,
  612. completedAt: 5,
  613. },
  614. },
  615. ],
  616. } satisfies ZCodeSessionStateSnapshot["messages"][number];
  617. const notificationMessage = {
  618. info: {
  619. messageId: "msg_task_notification",
  620. sessionId: "sess_1",
  621. role: "user",
  622. time: { created: 13 },
  623. agent: "zcode-agent",
  624. model,
  625. visibility: "model-only",
  626. },
  627. parts: [
  628. {
  629. partId: "part_task_notification",
  630. sessionId: "sess_1",
  631. messageId: "msg_task_notification",
  632. type: "text",
  633. synthetic: true,
  634. metadata: { source: "background_task" },
  635. text: [
  636. "<task-notification>",
  637. "<task-id>agent_1</task-id>",
  638. "<tool-use-id>toolu_background_agent</tool-use-id>",
  639. "<output-file>/tmp/background-agent.output</output-file>",
  640. "<status>completed</status>",
  641. "<result>Background agent result &amp; summary</result>",
  642. "</task-notification>",
  643. ].join("\n"),
  644. },
  645. ],
  646. } satisfies ZCodeSessionStateSnapshot["messages"][number];
  647. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  648. ...base,
  649. messages: [base.messages[0]!, assistantMessage, notificationMessage],
  650. });
  651. expect(snapshot.messages).toHaveLength(2);
  652. expect(snapshot.messages[1]?.tools?.[0]?.raw).toMatchObject({
  653. _meta: {
  654. zcode: {
  655. taskNotification: {
  656. outputFile: "/tmp/background-agent.output",
  657. result: "Background agent result & summary",
  658. status: "completed",
  659. taskId: "agent_1",
  660. },
  661. },
  662. },
  663. });
  664. });
  665. it.each([
  666. {
  667. expectedError: backgroundAgentProviderError,
  668. expectedStatus: "failed" as const,
  669. notificationStatus: "failed",
  670. },
  671. {
  672. expectedError: undefined,
  673. expectedStatus: "completed" as const,
  674. notificationStatus: "stopped",
  675. },
  676. ])(
  677. "restores a $notificationStatus background Agent notification without changing unrelated launch semantics",
  678. ({ expectedError, expectedStatus, notificationStatus }) => {
  679. const base = createSnapshot();
  680. const assistantMessage = {
  681. info: {
  682. messageId: "msg_assistant_failed_background_agent",
  683. sessionId: "sess_1",
  684. role: "assistant",
  685. parentMessageId: "msg_user",
  686. time: { created: 2, completed: 12 },
  687. agent: "zcode-agent",
  688. model,
  689. },
  690. parts: [
  691. {
  692. partId: "part_failed_background_agent_tool",
  693. sessionId: "sess_1",
  694. messageId: "msg_assistant_failed_background_agent",
  695. type: "tool",
  696. callId: "toolu_failed_background_agent",
  697. tool: "Agent",
  698. state: {
  699. status: "completed",
  700. input: {
  701. prompt: "run background research",
  702. run_in_background: true,
  703. },
  704. output:
  705. "Async agent launched successfully.\noutput_file: /tmp/background-agent.output",
  706. title: "Agent",
  707. metadata: {
  708. _meta: {
  709. zcode: {
  710. backgroundAgent: {
  711. runInBackground: true,
  712. outputFile: "/tmp/background-agent.output",
  713. },
  714. },
  715. },
  716. },
  717. startedAt: 4,
  718. completedAt: 5,
  719. },
  720. },
  721. ],
  722. } satisfies ZCodeSessionStateSnapshot["messages"][number];
  723. const notificationMessage = {
  724. info: {
  725. messageId: "msg_failed_task_notification",
  726. sessionId: "sess_1",
  727. role: "user",
  728. time: { created: 13 },
  729. agent: "zcode-agent",
  730. model,
  731. visibility: "model-only",
  732. },
  733. parts: [
  734. {
  735. partId: "part_failed_task_notification",
  736. sessionId: "sess_1",
  737. messageId: "msg_failed_task_notification",
  738. type: "text",
  739. synthetic: true,
  740. metadata: { source: "background_task" },
  741. text: [
  742. "<task-notification>",
  743. "<task-id>agent_failed</task-id>",
  744. "<tool-use-id>toolu_failed_background_agent</tool-use-id>",
  745. "<output-file>/tmp/background-agent.output</output-file>",
  746. `<status>${notificationStatus}</status>`,
  747. `<summary>Agent general-purpose task "Review" ${notificationStatus}.</summary>`,
  748. ...(expectedError ? [`<error>${expectedError}</error>`] : []),
  749. "</task-notification>",
  750. ].join("\n"),
  751. },
  752. ],
  753. } satisfies ZCodeSessionStateSnapshot["messages"][number];
  754. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  755. ...base,
  756. messages: [base.messages[0]!, assistantMessage, notificationMessage],
  757. });
  758. expect(snapshot.messages).toHaveLength(2);
  759. expect(snapshot.messages[1]?.tools?.[0]).toMatchObject({
  760. status: expectedStatus,
  761. output: "Async agent launched successfully.\noutput_file: /tmp/background-agent.output",
  762. raw: {
  763. _meta: {
  764. zcode: {
  765. taskNotification: {
  766. status: notificationStatus,
  767. summary: `Agent general-purpose task "Review" ${notificationStatus}.`,
  768. taskId: "agent_failed",
  769. },
  770. },
  771. },
  772. },
  773. });
  774. expect(snapshot.messages[1]?.tools?.[0]?.error).toBe(expectedError);
  775. },
  776. );
  777. it("maps pending ExitPlanMode approvals into pending elicitations", () => {
  778. const base = createSnapshot();
  779. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  780. ...base,
  781. projection: {
  782. ...base.projection,
  783. pendingPermissions: [
  784. {
  785. requestId: "exit_plan_1",
  786. toolCallId: "tool_exit_plan",
  787. toolName: "ExitPlanMode",
  788. riskLevel: "high",
  789. reason: "Exit plan mode",
  790. origin: subagentOrigin,
  791. requestedAt: 4,
  792. input: { plan: "1. Change runtime\n2. Add tests" },
  793. },
  794. ],
  795. },
  796. runtime: {
  797. ...base.runtime,
  798. pendingRequestIds: ["exit_plan_1"],
  799. },
  800. });
  801. expect(snapshot.runtime?.pendingPermissions).toEqual([]);
  802. expect(snapshot.runtime?.pendingElicitations?.[0]).toMatchObject({
  803. type: "elicitation_request",
  804. requestId: "exit_plan_1",
  805. message: "Review this implementation plan.",
  806. header: "Plan",
  807. options: [{ value: "approve", label: "Approve" }],
  808. origin: subagentOrigin,
  809. schema: { interaction: "plan_approval", toolName: "ExitPlanMode" },
  810. });
  811. });
  812. it("keeps tools when a tool-calls assistant is followed by final text", () => {
  813. const base = createSnapshot();
  814. const toolOnlyAssistant = {
  815. ...base.messages[1]!,
  816. info: {
  817. ...base.messages[1]!.info,
  818. finish: "tool-calls",
  819. messageId: "msg_tool_only",
  820. time: { created: 2, completed: 312 },
  821. },
  822. parts: [
  823. {
  824. partId: "part_tool_only_start",
  825. sessionId: "sess_1",
  826. messageId: "msg_tool_only",
  827. type: "tool",
  828. callId: "tool_read_guard",
  829. tool: "Read",
  830. state: {
  831. status: "completed",
  832. input: { file_path: "/tmp/zcode-e2e-tool-action-guard.txt" },
  833. output: "E2E_TOOL_FILE_CONTENT",
  834. title: "Read",
  835. metadata: {},
  836. startedAt: 300,
  837. completedAt: 310,
  838. },
  839. },
  840. ],
  841. } satisfies ZCodeSessionStateSnapshot["messages"][number];
  842. const finalAssistant = {
  843. ...base.messages[1]!,
  844. info: {
  845. ...base.messages[1]!.info,
  846. finish: "stop",
  847. messageId: "msg_final_text",
  848. time: { created: 314, completed: 360 },
  849. },
  850. parts: [
  851. {
  852. partId: "part_final_text",
  853. sessionId: "sess_1",
  854. messageId: "msg_final_text",
  855. type: "text",
  856. text: "deepseek-e2e-ok",
  857. },
  858. ],
  859. } satisfies ZCodeSessionStateSnapshot["messages"][number];
  860. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  861. ...base,
  862. session: {
  863. ...base.session,
  864. status: "idle",
  865. },
  866. projection: {
  867. ...base.projection,
  868. status: "idle",
  869. pendingPermissions: [],
  870. },
  871. runtime: {
  872. ...base.runtime,
  873. pendingRequestIds: [],
  874. },
  875. messages: [base.messages[0]!, toolOnlyAssistant, finalAssistant],
  876. });
  877. expect(snapshot.messages).toHaveLength(2);
  878. expect(snapshot.messages[1]).toMatchObject({
  879. id: "msg_tool_only",
  880. role: "assistant",
  881. content: "deepseek-e2e-ok",
  882. tools: [
  883. {
  884. toolName: "Read",
  885. status: "completed",
  886. },
  887. ],
  888. });
  889. expect(snapshot.messages[1]?.parts).toEqual([
  890. { type: "tool-call", toolIndex: 0 },
  891. { type: "content", content: "deepseek-e2e-ok" },
  892. ]);
  893. });
  894. it("restores user image, video, and PDF attachments from protocol file parts", () => {
  895. const base = createSnapshot();
  896. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  897. ...base,
  898. messages: [
  899. {
  900. ...base.messages[0]!,
  901. parts: [
  902. ...base.messages[0]!.parts,
  903. {
  904. partId: "part_image",
  905. sessionId: "sess_1",
  906. messageId: "msg_user",
  907. filename: "screen.png",
  908. metadata: {
  909. sizeBytes: 30,
  910. storageKind: "artifact",
  911. },
  912. mime: "image/png",
  913. type: "file",
  914. url: "data:image/png;base64,aW1hZ2U=",
  915. } satisfies ZCodeMessagePart,
  916. {
  917. partId: "part_video",
  918. sessionId: "sess_1",
  919. messageId: "msg_user",
  920. filename: "demo.mp4",
  921. metadata: {
  922. originalUrl: "/workspace/app/demo.mp4",
  923. sizeBytes: 5,
  924. storageKind: "inline",
  925. },
  926. mime: "video/mp4",
  927. type: "file",
  928. url: "data:video/mp4;base64,dmlkZW8=",
  929. } satisfies ZCodeMessagePart,
  930. {
  931. partId: "part_pdf",
  932. sessionId: "sess_1",
  933. messageId: "msg_user",
  934. filename: "report.pdf",
  935. metadata: {
  936. sizeBytes: 9,
  937. storageKind: "artifact",
  938. },
  939. mime: "application/pdf; charset=binary",
  940. type: "file",
  941. url: "zcode-artifact://sess_1/pdf-1",
  942. } satisfies ZCodeMessagePart,
  943. ],
  944. },
  945. ],
  946. });
  947. expect(snapshot.messages[0]?.attachments).toEqual([
  948. {
  949. kind: "image",
  950. filename: "screen.png",
  951. mimeType: "image/png",
  952. sizeBytes: 30,
  953. dataBase64: "aW1hZ2U=",
  954. },
  955. {
  956. kind: "video",
  957. filename: "demo.mp4",
  958. mimeType: "video/mp4",
  959. sizeBytes: 5,
  960. dataBase64: "dmlkZW8=",
  961. localPath: "/workspace/app/demo.mp4",
  962. },
  963. {
  964. kind: "pdf",
  965. filename: "report.pdf",
  966. mimeType: "application/pdf",
  967. sizeBytes: 9,
  968. },
  969. ]);
  970. });
  971. it("projects one attachment-only raw user message without exposing the wire fallback", () => {
  972. const base = createSnapshot();
  973. const rawMessage = {
  974. ...base.messages[0]!,
  975. parts: [
  976. {
  977. partId: "part_attachment_only_text",
  978. sessionId: "sess_1",
  979. messageId: "msg_user",
  980. type: "text",
  981. text: "",
  982. },
  983. {
  984. partId: "part_attachment_only_file",
  985. sessionId: "sess_1",
  986. messageId: "msg_user",
  987. filename: "notes.md",
  988. metadata: {
  989. preview: {
  990. text: "# Notes\nAttachment-only content.",
  991. truncated: false,
  992. originalBytes: 32,
  993. },
  994. recoverability: "provider_ready",
  995. sizeBytes: 32,
  996. storageKind: "inline",
  997. },
  998. mime: "text/plain",
  999. type: "file",
  1000. url: "inline:data-url",
  1001. },
  1002. ],
  1003. } satisfies ZCodeSessionStateSnapshot["messages"][number];
  1004. const originalParts = structuredClone(rawMessage.parts);
  1005. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1006. ...base,
  1007. messages: [rawMessage],
  1008. });
  1009. expect(snapshot.messages).toHaveLength(1);
  1010. expect(snapshot.messages[0]).toMatchObject({
  1011. id: "msg_user",
  1012. role: "user",
  1013. content: "",
  1014. attachments: [
  1015. {
  1016. kind: "file",
  1017. filename: "notes.md",
  1018. mimeType: "text/plain",
  1019. sizeBytes: 32,
  1020. textContent: "# Notes\nAttachment-only content.",
  1021. },
  1022. ],
  1023. });
  1024. expect(rawMessage.parts).toEqual(originalParts);
  1025. expect(JSON.stringify(snapshot.messages)).not.toContain("(no content)");
  1026. });
  1027. it("maps idle session snapshots with a completed assistant turn to completed task status", () => {
  1028. const base = createSnapshot();
  1029. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1030. ...base,
  1031. session: {
  1032. ...base.session,
  1033. status: "idle",
  1034. },
  1035. projection: {
  1036. ...base.projection,
  1037. status: "idle",
  1038. pendingPermissions: [],
  1039. activeToolCalls: [],
  1040. },
  1041. runtime: {
  1042. ...base.runtime,
  1043. pendingRequestIds: [],
  1044. },
  1045. });
  1046. expect(snapshot.meta.status).toBe("completed");
  1047. });
  1048. it("keeps an idle tool-calls assistant turn without a task terminal status", () => {
  1049. const base = createSnapshot();
  1050. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1051. ...base,
  1052. session: {
  1053. ...base.session,
  1054. status: "idle",
  1055. },
  1056. projection: {
  1057. ...base.projection,
  1058. status: "idle",
  1059. pendingPermissions: [],
  1060. activeToolCalls: [],
  1061. },
  1062. runtime: {
  1063. ...base.runtime,
  1064. pendingRequestIds: [],
  1065. },
  1066. messages: base.messages.map((message) =>
  1067. message.info.role === "assistant"
  1068. ? {
  1069. ...message,
  1070. info: {
  1071. ...message.info,
  1072. finish: "tool-calls",
  1073. },
  1074. }
  1075. : message,
  1076. ),
  1077. });
  1078. expect(snapshot.meta.status).toBeUndefined();
  1079. });
  1080. it("keeps an empty idle session without a task terminal status", () => {
  1081. const base = createSnapshot();
  1082. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1083. ...base,
  1084. session: {
  1085. ...base.session,
  1086. status: "idle",
  1087. },
  1088. projection: {
  1089. ...base.projection,
  1090. status: "idle",
  1091. pendingPermissions: [],
  1092. activeToolCalls: [],
  1093. },
  1094. runtime: {
  1095. ...base.runtime,
  1096. pendingRequestIds: [],
  1097. },
  1098. messages: [],
  1099. });
  1100. expect(snapshot.meta.status).toBeUndefined();
  1101. });
  1102. it("preserves protocol projection error type as task error code", () => {
  1103. const base = createSnapshot();
  1104. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1105. ...base,
  1106. projection: {
  1107. ...base.projection,
  1108. lastError: {
  1109. message: "历史任务使用的模型已不可用,请从当前模型列表中选择一个可用模型后继续。",
  1110. type: "ZCODE_RUNTIME_MODEL_UNAVAILABLE",
  1111. },
  1112. },
  1113. });
  1114. expect(snapshot.meta.lastError).toEqual({
  1115. code: "ZCODE_RUNTIME_MODEL_UNAVAILABLE",
  1116. message: "历史任务使用的模型已不可用,请从当前模型列表中选择一个可用模型后继续。",
  1117. });
  1118. });
  1119. it("prefers structured projection error code over wrapper error type in task meta", () => {
  1120. const base = createSnapshot();
  1121. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1122. ...base,
  1123. projection: {
  1124. ...base.projection,
  1125. lastError: {
  1126. message: "Model provider is not configured: stale-provider",
  1127. type: "MODEL_ERROR",
  1128. code: "provider_not_found",
  1129. detail: "stale-provider/gpt-5.5",
  1130. attribution: {
  1131. source: "runtime",
  1132. reason: "provider_not_configured",
  1133. providerId: "account:zai-individual-coding-plan",
  1134. },
  1135. },
  1136. },
  1137. });
  1138. expect(snapshot.meta.lastError).toEqual({
  1139. code: "provider_not_found",
  1140. detail: "stale-provider/gpt-5.5",
  1141. message: "Model provider is not configured: stale-provider",
  1142. attribution: {
  1143. source: "runtime",
  1144. reason: "provider_not_configured",
  1145. providerId: "account:zai-individual-coding-plan",
  1146. },
  1147. });
  1148. });
  1149. it("prioritizes projection lastError over a completed previous assistant turn", () => {
  1150. const base = createSnapshot();
  1151. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1152. ...base,
  1153. session: {
  1154. ...base.session,
  1155. status: "idle",
  1156. },
  1157. projection: {
  1158. ...base.projection,
  1159. status: "error",
  1160. pendingPermissions: [],
  1161. activeToolCalls: [],
  1162. lastError: {
  1163. message: "messages.content.type 参数非法,取值范围 ['text']",
  1164. type: "PROVIDER_BUSINESS_ERROR",
  1165. },
  1166. },
  1167. runtime: {
  1168. ...base.runtime,
  1169. activeTurnId: undefined,
  1170. pendingRequestIds: [],
  1171. },
  1172. });
  1173. expect(snapshot.meta.status).toBe("error");
  1174. expect(snapshot.meta.lastError).toEqual({
  1175. code: "PROVIDER_BUSINESS_ERROR",
  1176. message: "messages.content.type 参数非法,取值范围 ['text']",
  1177. });
  1178. });
  1179. it("uses the latest message model for task meta when restored settings were polluted", () => {
  1180. const pollutedModel = {
  1181. providerId: "36965ea6-734a-46a8-8851-3dfec026589e",
  1182. modelId: "glm-5.1-highspeed",
  1183. };
  1184. const historyModel = {
  1185. providerId: "default-deepseek",
  1186. modelId: "deepseek-v4-flash",
  1187. };
  1188. const base = createSnapshot();
  1189. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1190. ...base,
  1191. settings: {
  1192. ...base.settings,
  1193. model: {
  1194. ...base.settings.model,
  1195. current: pollutedModel,
  1196. available: [{ ref: pollutedModel, label: "glm-5.1-highspeed" }],
  1197. },
  1198. },
  1199. messages: base.messages.map((message) => ({
  1200. ...message,
  1201. info: {
  1202. ...message.info,
  1203. model: historyModel,
  1204. },
  1205. })),
  1206. });
  1207. expect(snapshot.meta.model).toBe("default-deepseek/deepseek-v4-flash");
  1208. });
  1209. it("maps persisted session todos into task runtime plan", () => {
  1210. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1211. ...createSnapshot(),
  1212. todos: [
  1213. { content: "实现 Lexer", priority: "high", status: "completed" },
  1214. { content: "实现 Parser", priority: "high", status: "in_progress" },
  1215. ],
  1216. });
  1217. expect(snapshot.runtime?.plan).toEqual([
  1218. { id: "todo-0", title: "实现 Lexer", status: "completed" },
  1219. { id: "todo-1", title: "实现 Parser", status: "in_progress" },
  1220. ]);
  1221. });
  1222. it("maps derived goal stats and grouped todos into task runtime", () => {
  1223. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1224. ...createSnapshot(),
  1225. runtime: {
  1226. ...createSnapshot().runtime,
  1227. goalVerifications: [
  1228. {
  1229. nextAction: "补齐移动端回归。",
  1230. passed: false,
  1231. reason: "第一轮证据不足。",
  1232. },
  1233. ],
  1234. },
  1235. goalStats: {
  1236. contextUsed: 38_200,
  1237. contextWindow: 120_000,
  1238. iterationCount: 4,
  1239. timeUsedSeconds: 8_667,
  1240. tokenBudget: 120_000,
  1241. tokensUsed: 38_200,
  1242. toolCallCount: 27,
  1243. },
  1244. todoGroups: [
  1245. {
  1246. id: "goal-iteration-1",
  1247. source: "goal_iteration",
  1248. goalIteration: 1,
  1249. targetId: "goal_1",
  1250. startedAt: 1_000,
  1251. updatedAt: 2_000,
  1252. todos: [
  1253. { content: "恢复目标统计", priority: "high", status: "completed" },
  1254. {
  1255. content: "按目标迭代分组 todo",
  1256. priority: "high",
  1257. status: "in_progress",
  1258. },
  1259. ],
  1260. },
  1261. ],
  1262. });
  1263. expect(snapshot.runtime?.goalStats).toEqual({
  1264. contextUsed: 38_200,
  1265. contextWindow: 120_000,
  1266. iterationCount: 4,
  1267. timeUsedSeconds: 8_667,
  1268. tokenBudget: 120_000,
  1269. tokensUsed: 38_200,
  1270. toolCallCount: 27,
  1271. });
  1272. expect(snapshot.runtime?.goalVerifications).toEqual([
  1273. {
  1274. nextAction: "补齐移动端回归。",
  1275. passed: false,
  1276. reason: "第一轮证据不足。",
  1277. },
  1278. ]);
  1279. expect(snapshot.runtime?.todoGroups).toEqual([
  1280. {
  1281. id: "goal-iteration-1",
  1282. source: "goal_iteration",
  1283. goalIteration: 1,
  1284. targetId: "goal_1",
  1285. startedAt: 1_000,
  1286. updatedAt: 2_000,
  1287. todos: [
  1288. {
  1289. id: "goal-iteration-1-todo-0",
  1290. title: "恢复目标统计",
  1291. status: "completed",
  1292. },
  1293. {
  1294. id: "goal-iteration-1-todo-1",
  1295. title: "按目标迭代分组 todo",
  1296. status: "in_progress",
  1297. },
  1298. ],
  1299. },
  1300. ]);
  1301. });
  1302. it("adds persisted goal verification lifecycle as a synthetic divider on snapshot restore", () => {
  1303. const baseSnapshot = createSnapshot();
  1304. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1305. ...baseSnapshot,
  1306. runtime: {
  1307. ...baseSnapshot.runtime,
  1308. goalVerificationTimeline: [
  1309. {
  1310. version: 1,
  1311. kind: "synthetic",
  1312. type: "goal_verification",
  1313. display: "separator",
  1314. targetId: "target_1",
  1315. verificationId: "verify_1",
  1316. status: "completed",
  1317. goalIteration: 2,
  1318. anchorAssistantMessageId: "msg_assistant",
  1319. anchorTurnId: "turn_1",
  1320. verification: {
  1321. nextAction: null,
  1322. passed: true,
  1323. reason: "所有目标要求都已完成。",
  1324. },
  1325. startedAt: 20,
  1326. updatedAt: 30,
  1327. },
  1328. ],
  1329. },
  1330. });
  1331. expect(snapshot.runtime?.goalVerificationTimeline).toHaveLength(1);
  1332. expect(snapshot.messages).toHaveLength(3);
  1333. expect(snapshot.messages[2]).toMatchObject({
  1334. id: "zcode-goal-verification-target_1-2",
  1335. role: "assistant",
  1336. content: "",
  1337. timestamp: 20,
  1338. syntheticTimeline: {
  1339. type: "goal_verification",
  1340. status: "completed",
  1341. verificationId: "verify_1",
  1342. goalIteration: 2,
  1343. anchorAssistantMessageId: "msg_assistant",
  1344. anchorTurnId: "turn_1",
  1345. },
  1346. });
  1347. });
  1348. it("anchors goal verification dividers to assistant messages that were coalesced", () => {
  1349. const objective = "写一篇短篇科幻小说";
  1350. const baseSnapshot = createSnapshot();
  1351. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1352. ...baseSnapshot,
  1353. projection: {
  1354. ...baseSnapshot.projection,
  1355. target: {
  1356. sessionId: "sess_1",
  1357. targetId: "goal_1",
  1358. objective,
  1359. summaryTitle: null,
  1360. status: "active",
  1361. tokenBudget: null,
  1362. tokensUsed: 0,
  1363. timeUsedSeconds: 0,
  1364. createdAt: 100,
  1365. updatedAt: 100,
  1366. },
  1367. },
  1368. runtime: {
  1369. ...baseSnapshot.runtime,
  1370. goalVerificationTimeline: [
  1371. {
  1372. version: 1,
  1373. kind: "synthetic",
  1374. type: "goal_verification",
  1375. display: "separator",
  1376. targetId: "goal_1",
  1377. verificationId: "verify_goal_1",
  1378. status: "completed",
  1379. goalIteration: 1,
  1380. anchorAssistantMessageId: "msg_assistant_second",
  1381. verification: {
  1382. nextAction: "continue",
  1383. passed: false,
  1384. reason: "第二轮仍未完成。",
  1385. },
  1386. startedAt: 400,
  1387. updatedAt: 410,
  1388. },
  1389. ],
  1390. },
  1391. messages: [
  1392. {
  1393. info: {
  1394. messageId: "msg_goal_user",
  1395. sessionId: "sess_1",
  1396. role: "user",
  1397. time: { created: 100 },
  1398. agent: "zcode-agent",
  1399. model,
  1400. },
  1401. parts: [
  1402. {
  1403. partId: "part_goal_user",
  1404. sessionId: "sess_1",
  1405. messageId: "msg_goal_user",
  1406. type: "text",
  1407. text: `/goal ${objective}`,
  1408. },
  1409. ],
  1410. },
  1411. {
  1412. info: {
  1413. messageId: "msg_assistant_first",
  1414. sessionId: "sess_1",
  1415. role: "assistant",
  1416. parentMessageId: "msg_goal_user",
  1417. time: { created: 200, completed: 210 },
  1418. agent: "zcode-agent",
  1419. model,
  1420. },
  1421. parts: [
  1422. {
  1423. partId: "part_assistant_first",
  1424. sessionId: "sess_1",
  1425. messageId: "msg_assistant_first",
  1426. type: "text",
  1427. text: "第一轮。",
  1428. },
  1429. ],
  1430. },
  1431. {
  1432. info: {
  1433. messageId: "msg_assistant_second",
  1434. sessionId: "sess_1",
  1435. role: "assistant",
  1436. parentMessageId: "msg_assistant_first",
  1437. time: { created: 220, completed: 230 },
  1438. agent: "zcode-agent",
  1439. model,
  1440. },
  1441. parts: [
  1442. {
  1443. partId: "part_assistant_second",
  1444. sessionId: "sess_1",
  1445. messageId: "msg_assistant_second",
  1446. type: "text",
  1447. text: "第二轮。",
  1448. },
  1449. ],
  1450. },
  1451. {
  1452. info: {
  1453. messageId: "msg_followup_user",
  1454. sessionId: "sess_1",
  1455. role: "user",
  1456. time: { created: 300 },
  1457. agent: "zcode-agent",
  1458. model,
  1459. },
  1460. parts: [
  1461. {
  1462. partId: "part_followup_user",
  1463. sessionId: "sess_1",
  1464. messageId: "msg_followup_user",
  1465. type: "text",
  1466. text: "新问题",
  1467. },
  1468. ],
  1469. },
  1470. ],
  1471. });
  1472. expect(snapshot.messages.map((message) => message.id)).toEqual([
  1473. "msg_goal_user",
  1474. "msg_assistant_first",
  1475. "zcode-goal-verification-goal_1-1",
  1476. "msg_followup_user",
  1477. ]);
  1478. expect(snapshot.messages[1]?.mergedMessageIds).toEqual([
  1479. "msg_assistant_first",
  1480. "msg_assistant_second",
  1481. ]);
  1482. });
  1483. it("uses runtime context usage when restored projection has no usage yet", () => {
  1484. const baseSnapshot = createSnapshot();
  1485. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1486. ...baseSnapshot,
  1487. projection: {
  1488. ...baseSnapshot.projection,
  1489. contextUsed: 0,
  1490. },
  1491. runtime: {
  1492. ...baseSnapshot.runtime,
  1493. contextUsage: {
  1494. used: 12345,
  1495. size: 128000,
  1496. cost: null,
  1497. cache: {
  1498. inputTokens: 12345,
  1499. cacheReadTokens: 2345,
  1500. cacheWriteTokens: 678,
  1501. hitRate: 2345 / 12345,
  1502. },
  1503. },
  1504. },
  1505. });
  1506. expect(snapshot.runtime?.contextUsage).toEqual({
  1507. used: 12345,
  1508. size: 128000,
  1509. cost: null,
  1510. cache: {
  1511. inputTokens: 12345,
  1512. cacheReadTokens: 2345,
  1513. cacheWriteTokens: 678,
  1514. hitRate: 2345 / 12345,
  1515. },
  1516. });
  1517. });
  1518. it("maps snapshot runtime apiRetry into legacy task runtime", () => {
  1519. const baseSnapshot = createSnapshot();
  1520. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1521. ...baseSnapshot,
  1522. runtime: {
  1523. ...baseSnapshot.runtime,
  1524. apiRetry: {
  1525. kind: "api_retry",
  1526. attempt: 1,
  1527. maxRetries: 3,
  1528. retryDelayMs: 2_000,
  1529. errorStatus: 429,
  1530. error: "rate limited",
  1531. },
  1532. },
  1533. });
  1534. expect(snapshot.runtime?.apiRetry).toEqual({
  1535. kind: "api_retry",
  1536. attempt: 1,
  1537. maxRetries: 3,
  1538. retryDelayMs: 2_000,
  1539. errorStatus: 429,
  1540. error: "rate limited",
  1541. });
  1542. });
  1543. it("maps projection background jobs into runtime background bash jobs", () => {
  1544. const baseSnapshot = createSnapshot();
  1545. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1546. ...baseSnapshot,
  1547. projection: {
  1548. ...baseSnapshot.projection,
  1549. backgroundJobs: [
  1550. {
  1551. id: "bg-1",
  1552. kind: "background_bash",
  1553. command: "python -m http.server 3000",
  1554. status: "running",
  1555. startedAt: 10_000,
  1556. pid: 123,
  1557. },
  1558. ],
  1559. },
  1560. });
  1561. expect(snapshot.runtime?.backgroundBashJobs).toEqual([
  1562. expect.objectContaining({
  1563. jobId: "bg-1",
  1564. command: "python -m http.server 3000",
  1565. status: "running",
  1566. startedAt: 10_000,
  1567. pid: 123,
  1568. }),
  1569. ]);
  1570. });
  1571. it("does not project legacy compact timelineText as visible assistant content", () => {
  1572. const internalSummary =
  1573. "This session is being continued from a previous conversation that was compacted.";
  1574. const baseSnapshot = createSnapshot();
  1575. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1576. ...baseSnapshot,
  1577. messages: [
  1578. {
  1579. info: {
  1580. messageId: "msg_compact",
  1581. sessionId: "sess_1",
  1582. role: "assistant",
  1583. parentMessageId: "msg_user",
  1584. time: { created: 20, completed: 21 },
  1585. agent: "zcode-agent",
  1586. model,
  1587. cost: 0,
  1588. tokens: {
  1589. input: 1,
  1590. output: 1,
  1591. reasoning: 0,
  1592. total: 2,
  1593. cache: { read: 0, write: 0 },
  1594. },
  1595. },
  1596. parts: [
  1597. {
  1598. partId: "part_compact",
  1599. sessionId: "sess_1",
  1600. messageId: "msg_compact",
  1601. type: "compaction",
  1602. auto: true,
  1603. summaryMessageId: "msg_summary",
  1604. timelineText: internalSummary,
  1605. metadata: {
  1606. operationId: "compact-legacy",
  1607. timelineStatus: "completed",
  1608. trigger: "auto",
  1609. },
  1610. } as unknown as ZCodeMessagePart,
  1611. ],
  1612. },
  1613. ],
  1614. });
  1615. expect(snapshot.messages).toHaveLength(1);
  1616. expect(snapshot.messages[0]).toMatchObject({
  1617. id: "msg_compact",
  1618. role: "assistant",
  1619. content: "",
  1620. syntheticTimeline: {
  1621. type: "context_compaction",
  1622. operationId: "compact-legacy",
  1623. status: "completed",
  1624. trigger: "auto",
  1625. },
  1626. });
  1627. expect(snapshot.messages[0]?.parts ?? []).toEqual([]);
  1628. expect(JSON.stringify(snapshot.messages)).not.toContain(internalSummary);
  1629. });
  1630. it("does not synthesize a compact divider from summary user compaction metadata", () => {
  1631. const baseSnapshot = createSnapshot();
  1632. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1633. ...baseSnapshot,
  1634. messages: [
  1635. {
  1636. info: {
  1637. messageId: "msg_summary",
  1638. sessionId: "sess_1",
  1639. role: "user",
  1640. time: { created: 30 },
  1641. agent: "zcode-agent",
  1642. model,
  1643. },
  1644. parts: [
  1645. {
  1646. partId: "part_summary_compaction",
  1647. sessionId: "sess_1",
  1648. messageId: "msg_summary",
  1649. type: "compaction",
  1650. auto: false,
  1651. metadata: {
  1652. operationId: "cmp-summary",
  1653. phase: "standalone_turn",
  1654. trigger: "manual",
  1655. },
  1656. },
  1657. ],
  1658. },
  1659. ],
  1660. });
  1661. expect(snapshot.messages).toEqual([]);
  1662. });
  1663. it("keeps compact summary messages hidden while rendering the lifecycle divider", () => {
  1664. const baseSnapshot = createSnapshot();
  1665. const summaryText =
  1666. "This session is being continued from a previous conversation that ran out of context.";
  1667. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1668. ...baseSnapshot,
  1669. messages: [
  1670. {
  1671. info: {
  1672. messageId: "msg_compact_lifecycle",
  1673. sessionId: "sess_1",
  1674. role: "assistant",
  1675. parentMessageId: "msg_user",
  1676. time: { created: 20, completed: 21 },
  1677. agent: "zcode-agent",
  1678. model,
  1679. cost: 0,
  1680. tokens: {
  1681. input: 1,
  1682. output: 1,
  1683. reasoning: 0,
  1684. total: 2,
  1685. cache: { read: 0, write: 0 },
  1686. },
  1687. },
  1688. parts: [
  1689. {
  1690. partId: "part_compact_lifecycle",
  1691. sessionId: "sess_1",
  1692. messageId: "msg_compact_lifecycle",
  1693. type: "compaction",
  1694. auto: true,
  1695. summaryMessageId: "msg_summary",
  1696. metadata: {
  1697. operationId: "cmp-visible-divider",
  1698. timelineStatus: "completed",
  1699. trigger: "auto",
  1700. replace: true,
  1701. },
  1702. },
  1703. ],
  1704. },
  1705. {
  1706. info: {
  1707. messageId: "msg_summary",
  1708. sessionId: "sess_1",
  1709. role: "user",
  1710. time: { created: 22 },
  1711. agent: "zcode-agent",
  1712. model,
  1713. summary: {
  1714. title: "Compact summary",
  1715. body: "Summary:\nEarlier work.",
  1716. diffs: [],
  1717. },
  1718. },
  1719. parts: [
  1720. {
  1721. partId: "part_summary_text",
  1722. sessionId: "sess_1",
  1723. messageId: "msg_summary",
  1724. type: "text",
  1725. text: summaryText,
  1726. synthetic: true,
  1727. },
  1728. {
  1729. partId: "part_summary_compaction",
  1730. sessionId: "sess_1",
  1731. messageId: "msg_summary",
  1732. type: "compaction",
  1733. auto: true,
  1734. metadata: {
  1735. operationId: "cmp-visible-divider",
  1736. trigger: "auto",
  1737. },
  1738. },
  1739. ],
  1740. },
  1741. ],
  1742. });
  1743. expect(snapshot.messages).toHaveLength(1);
  1744. expect(snapshot.messages[0]).toMatchObject({
  1745. id: "msg_compact_lifecycle",
  1746. role: "assistant",
  1747. content: "",
  1748. syntheticTimeline: {
  1749. type: "context_compaction",
  1750. operationId: "cmp-visible-divider",
  1751. status: "completed",
  1752. trigger: "auto",
  1753. replace: true,
  1754. summaryMessageId: "msg_summary",
  1755. },
  1756. });
  1757. expect(JSON.stringify(snapshot.messages)).not.toContain(summaryText);
  1758. });
  1759. it("adds a fallback fork divider for legacy fork snapshots without synthetic notice", () => {
  1760. const baseSnapshot = createSnapshot();
  1761. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1762. ...baseSnapshot,
  1763. session: {
  1764. ...baseSnapshot.session,
  1765. parentSessionId: "parent-session",
  1766. },
  1767. });
  1768. expect(snapshot.messages).toHaveLength(3);
  1769. expect(snapshot.messages[2]).toMatchObject({
  1770. id: "zcode-timeline-fork-parent-session-",
  1771. role: "user",
  1772. content: "",
  1773. syntheticTimeline: {
  1774. type: "session_fork",
  1775. display: "separator",
  1776. parentSessionId: "parent-session",
  1777. targetMessageId: "",
  1778. },
  1779. });
  1780. });
  1781. it("projects /goal continuation reminders back to the visible slash command query", () => {
  1782. const internalGoalPrompt = [
  1783. '<system-reminder source="goal-continuation">',
  1784. "Continue working toward the active session goal.",
  1785. "",
  1786. "<untrusted_objective>",
  1787. "优化性能到 60fps",
  1788. "</untrusted_objective>",
  1789. "</system-reminder>",
  1790. ].join("\n");
  1791. const baseSnapshot = createSnapshot();
  1792. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1793. ...baseSnapshot,
  1794. session: {
  1795. ...baseSnapshot.session,
  1796. title: internalGoalPrompt,
  1797. },
  1798. projection: {
  1799. ...baseSnapshot.projection,
  1800. target: {
  1801. sessionId: "sess_1",
  1802. targetId: "goal_1",
  1803. objective: "优化性能到 60fps",
  1804. summaryTitle: "优化性能到 60fps",
  1805. status: "active",
  1806. tokenBudget: null,
  1807. tokensUsed: 0,
  1808. timeUsedSeconds: 0,
  1809. createdAt: 1,
  1810. updatedAt: 1,
  1811. },
  1812. },
  1813. messages: [
  1814. {
  1815. info: {
  1816. messageId: "msg_goal_internal",
  1817. sessionId: "sess_1",
  1818. role: "user",
  1819. time: { created: 100 },
  1820. agent: "zcode-agent",
  1821. model,
  1822. },
  1823. parts: [
  1824. {
  1825. partId: "part_goal_internal",
  1826. sessionId: "sess_1",
  1827. messageId: "msg_goal_internal",
  1828. type: "text",
  1829. text: internalGoalPrompt,
  1830. },
  1831. ],
  1832. },
  1833. {
  1834. info: {
  1835. messageId: "msg_goal_assistant",
  1836. sessionId: "sess_1",
  1837. role: "assistant",
  1838. parentMessageId: "msg_goal_internal",
  1839. time: { created: 200, completed: 300 },
  1840. agent: "zcode-agent",
  1841. model,
  1842. path: { cwd: "/workspace/app", root: "/workspace/app" },
  1843. cost: 0,
  1844. tokens: {
  1845. input: 1,
  1846. output: 2,
  1847. reasoning: 0,
  1848. total: 3,
  1849. cache: { read: 0, write: 0 },
  1850. },
  1851. },
  1852. parts: [
  1853. {
  1854. partId: "part_goal_assistant_text",
  1855. sessionId: "sess_1",
  1856. messageId: "msg_goal_assistant",
  1857. type: "text",
  1858. text: "我会先定位渲染瓶颈。",
  1859. },
  1860. ],
  1861. },
  1862. ],
  1863. });
  1864. expect(snapshot.meta.title).toBe("优化性能到 60fps");
  1865. expect(snapshot.meta.target).toMatchObject({
  1866. objective: "优化性能到 60fps",
  1867. summaryTitle: "优化性能到 60fps",
  1868. targetID: "goal_1",
  1869. });
  1870. expect(snapshot.messages).toHaveLength(2);
  1871. expect(snapshot.messages[0]).toMatchObject({
  1872. role: "user",
  1873. content: "/goal 优化性能到 60fps",
  1874. });
  1875. expect(snapshot.messages[0]?.content).not.toContain("system-reminder");
  1876. expect(snapshot.messages[1]).toMatchObject({
  1877. role: "assistant",
  1878. content: "我会先定位渲染瓶颈。",
  1879. goalIteration: 1,
  1880. });
  1881. });
  1882. it("keeps verifier-bounded goal continuation assistant messages split by goal iteration in snapshots", () => {
  1883. const objective = "优化性能到 60fps";
  1884. const baseSnapshot = createSnapshot();
  1885. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  1886. ...baseSnapshot,
  1887. projection: {
  1888. ...baseSnapshot.projection,
  1889. target: {
  1890. sessionId: "sess_1",
  1891. targetId: "goal_1",
  1892. objective,
  1893. summaryTitle: null,
  1894. status: "active",
  1895. tokenBudget: null,
  1896. tokensUsed: 0,
  1897. timeUsedSeconds: 0,
  1898. createdAt: 100,
  1899. updatedAt: 100,
  1900. },
  1901. },
  1902. runtime: {
  1903. ...baseSnapshot.runtime,
  1904. goalVerificationTimeline: [
  1905. {
  1906. version: 1,
  1907. kind: "synthetic",
  1908. type: "goal_verification",
  1909. display: "separator",
  1910. targetId: "goal_1",
  1911. verificationId: "verify_goal_1",
  1912. status: "completed",
  1913. goalIteration: 1,
  1914. verification: {
  1915. nextAction: "继续做第二轮。",
  1916. passed: false,
  1917. reason: "第一轮还没完成。",
  1918. },
  1919. startedAt: 300,
  1920. updatedAt: 300,
  1921. },
  1922. ],
  1923. },
  1924. messages: [
  1925. {
  1926. info: {
  1927. messageId: "msg_user_goal",
  1928. sessionId: "sess_1",
  1929. role: "user",
  1930. time: { created: 100 },
  1931. agent: "zcode-agent",
  1932. model,
  1933. },
  1934. parts: [
  1935. {
  1936. partId: "part_user_goal",
  1937. sessionId: "sess_1",
  1938. messageId: "msg_user_goal",
  1939. type: "text",
  1940. text: `/goal ${objective}`,
  1941. },
  1942. ],
  1943. },
  1944. {
  1945. info: {
  1946. messageId: "msg_assistant_goal_1",
  1947. sessionId: "sess_1",
  1948. role: "assistant",
  1949. parentMessageId: "msg_user_goal",
  1950. time: { created: 200, completed: 250 },
  1951. agent: "zcode-agent",
  1952. model,
  1953. path: { cwd: "/workspace/app", root: "/workspace/app" },
  1954. cost: 0,
  1955. tokens: {
  1956. input: 1,
  1957. output: 2,
  1958. reasoning: 0,
  1959. total: 3,
  1960. cache: { read: 0, write: 0 },
  1961. },
  1962. },
  1963. parts: [
  1964. {
  1965. partId: "part_assistant_goal_1",
  1966. sessionId: "sess_1",
  1967. messageId: "msg_assistant_goal_1",
  1968. type: "text",
  1969. text: "第一轮。",
  1970. },
  1971. ],
  1972. },
  1973. {
  1974. info: {
  1975. messageId: "msg_goal_continue",
  1976. sessionId: "sess_1",
  1977. role: "user",
  1978. time: { created: 300 },
  1979. agent: "zcode-agent",
  1980. model,
  1981. synthetic: true,
  1982. source: "goal-continuation",
  1983. visibility: "model-only",
  1984. metadata: { source: "goal-continuation", visibility: "model-only" },
  1985. },
  1986. parts: [
  1987. {
  1988. partId: "part_goal_continue",
  1989. sessionId: "sess_1",
  1990. messageId: "msg_goal_continue",
  1991. type: "text",
  1992. text: "<system-reminder>\nContinue working toward the active session goal.\n</system-reminder>",
  1993. synthetic: true,
  1994. metadata: {
  1995. source: "goal-continuation",
  1996. visibility: "model-only",
  1997. },
  1998. },
  1999. ],
  2000. },
  2001. {
  2002. info: {
  2003. messageId: "msg_assistant_goal_2",
  2004. sessionId: "sess_1",
  2005. role: "assistant",
  2006. parentMessageId: "msg_goal_continue",
  2007. time: { created: 400, completed: 450 },
  2008. agent: "zcode-agent",
  2009. model,
  2010. path: { cwd: "/workspace/app", root: "/workspace/app" },
  2011. cost: 0,
  2012. tokens: {
  2013. input: 1,
  2014. output: 2,
  2015. reasoning: 0,
  2016. total: 3,
  2017. cache: { read: 0, write: 0 },
  2018. },
  2019. },
  2020. parts: [
  2021. {
  2022. partId: "part_assistant_goal_2",
  2023. sessionId: "sess_1",
  2024. messageId: "msg_assistant_goal_2",
  2025. type: "text",
  2026. text: "第二轮。",
  2027. },
  2028. ],
  2029. },
  2030. ],
  2031. });
  2032. expect(snapshot.messages).toHaveLength(4);
  2033. expect(snapshot.messages[1]).toMatchObject({
  2034. role: "assistant",
  2035. content: "第一轮。",
  2036. goalIteration: 1,
  2037. });
  2038. expect(snapshot.messages[2]).toMatchObject({
  2039. role: "assistant",
  2040. content: "",
  2041. syntheticTimeline: {
  2042. type: "goal_verification",
  2043. verificationId: "verify_goal_1",
  2044. goalIteration: 1,
  2045. },
  2046. });
  2047. expect(snapshot.messages[3]).toMatchObject({
  2048. role: "assistant",
  2049. content: "第二轮。",
  2050. goalIteration: 2,
  2051. });
  2052. });
  2053. it("restores /goal prefix for persisted objective user messages", () => {
  2054. const objective = "优化性能到 60fps";
  2055. const baseSnapshot = createSnapshot();
  2056. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  2057. ...baseSnapshot,
  2058. projection: {
  2059. ...baseSnapshot.projection,
  2060. target: {
  2061. sessionId: "sess_1",
  2062. targetId: "goal_1",
  2063. objective,
  2064. summaryTitle: null,
  2065. status: "active",
  2066. tokenBudget: null,
  2067. tokensUsed: 0,
  2068. timeUsedSeconds: 0,
  2069. createdAt: 100,
  2070. updatedAt: 100,
  2071. },
  2072. },
  2073. messages: [
  2074. {
  2075. info: {
  2076. messageId: "msg_goal_objective",
  2077. sessionId: "sess_1",
  2078. role: "user",
  2079. time: { created: 100 },
  2080. agent: "zcode-agent",
  2081. model,
  2082. },
  2083. parts: [
  2084. {
  2085. partId: "part_goal_objective",
  2086. sessionId: "sess_1",
  2087. messageId: "msg_goal_objective",
  2088. type: "text",
  2089. text: objective,
  2090. },
  2091. ],
  2092. },
  2093. ],
  2094. });
  2095. expect(snapshot.meta.title).toBe(objective);
  2096. expect(snapshot.messages).toHaveLength(1);
  2097. expect(snapshot.messages[0]).toMatchObject({
  2098. role: "user",
  2099. content: `/goal ${objective}`,
  2100. });
  2101. });
  2102. it("does not add /goal to earlier normal user messages with the same text", () => {
  2103. const objective = "优化性能到 60fps";
  2104. const baseSnapshot = createSnapshot();
  2105. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  2106. ...baseSnapshot,
  2107. projection: {
  2108. ...baseSnapshot.projection,
  2109. target: {
  2110. sessionId: "sess_1",
  2111. targetId: "goal_1",
  2112. objective,
  2113. summaryTitle: null,
  2114. status: "active",
  2115. tokenBudget: null,
  2116. tokensUsed: 0,
  2117. timeUsedSeconds: 0,
  2118. createdAt: 200,
  2119. updatedAt: 200,
  2120. },
  2121. },
  2122. messages: [
  2123. {
  2124. info: {
  2125. messageId: "msg_normal_user",
  2126. sessionId: "sess_1",
  2127. role: "user",
  2128. time: { created: 100 },
  2129. agent: "zcode-agent",
  2130. model,
  2131. },
  2132. parts: [
  2133. {
  2134. partId: "part_normal_user",
  2135. sessionId: "sess_1",
  2136. messageId: "msg_normal_user",
  2137. type: "text",
  2138. text: objective,
  2139. },
  2140. ],
  2141. },
  2142. ],
  2143. });
  2144. expect(snapshot.messages[0]).toMatchObject({
  2145. role: "user",
  2146. content: objective,
  2147. });
  2148. });
  2149. it("maps ZCode Protocol context projection updates to legacy usage_update events", () => {
  2150. expect(
  2151. zcodeSessionEventToZCodeStreamEvents({
  2152. event: {
  2153. eventId: "evt_usage",
  2154. sessionId: "sess_1",
  2155. seq: 4,
  2156. timestamp: 4,
  2157. traceId: "trace_usage",
  2158. type: "session.updated",
  2159. payload: {
  2160. contextUsed: 24000,
  2161. contextWindow: 128000,
  2162. },
  2163. },
  2164. taskId: "sess_1",
  2165. }),
  2166. ).toEqual([
  2167. {
  2168. type: "usage_update",
  2169. taskId: "sess_1",
  2170. traceId: "trace_usage",
  2171. used: 24000,
  2172. size: 128000,
  2173. cost: null,
  2174. },
  2175. ]);
  2176. });
  2177. it("preserves goal target run action patches", () => {
  2178. expect(
  2179. zcodeSessionEventToZCodeStreamEvents({
  2180. event: {
  2181. eventId: "evt_goal_run_started",
  2182. sessionId: "sess_1",
  2183. seq: 4,
  2184. timestamp: 4,
  2185. traceId: "trace_goal_run",
  2186. type: "session.updated",
  2187. payload: {
  2188. action: "run_started",
  2189. source: "runtime",
  2190. target: {
  2191. activeInputId: "input-1",
  2192. activeRunLastSeenAtMs: 4_000,
  2193. activeRunStartedAtMs: 4_000,
  2194. createdAt: 1,
  2195. objective: "Fix elapsed",
  2196. sessionId: "sess_1",
  2197. status: "active",
  2198. summaryTitle: null,
  2199. targetId: "target-1",
  2200. timeUsedSeconds: 0,
  2201. tokenBudget: null,
  2202. tokensUsed: 0,
  2203. updatedAt: 4_000,
  2204. },
  2205. },
  2206. },
  2207. taskId: "sess_1",
  2208. }),
  2209. ).toEqual([
  2210. {
  2211. target: {
  2212. action: "run_started",
  2213. source: "runtime",
  2214. target: {
  2215. activeInputId: "input-1",
  2216. activeRunLastSeenAtMs: 4_000,
  2217. activeRunStartedAtMs: 4_000,
  2218. objective: "Fix elapsed",
  2219. sessionID: "sess_1",
  2220. status: "active",
  2221. summaryTitle: null,
  2222. targetID: "target-1",
  2223. time: { created: 1, updated: 4_000 },
  2224. timeUsedSeconds: 0,
  2225. tokenBudget: null,
  2226. tokensUsed: 0,
  2227. },
  2228. },
  2229. taskId: "sess_1",
  2230. traceId: "trace_goal_run",
  2231. type: "session_info_update",
  2232. },
  2233. ]);
  2234. });
  2235. it("maps model streaming tool input into pending tool call previews", () => {
  2236. const state = {
  2237. streamingToolInputById: new Map(),
  2238. toolNameById: new Map<string, string>(),
  2239. };
  2240. const common = {
  2241. sessionId: "sess_1",
  2242. seq: 4,
  2243. timestamp: 4,
  2244. traceId: "trace_tool_input",
  2245. type: "model.streaming" as const,
  2246. };
  2247. const startEvents = zcodeSessionEventToZCodeStreamEvents({
  2248. event: {
  2249. ...common,
  2250. eventId: "evt_tool_input_start",
  2251. payload: {
  2252. kind: "tool_input_start",
  2253. toolCallId: "call_write",
  2254. toolName: "Write",
  2255. },
  2256. },
  2257. state,
  2258. taskId: "sess_1",
  2259. });
  2260. expect(startEvents).toEqual([
  2261. expect.objectContaining({
  2262. type: "tool_call",
  2263. toolId: "call_write",
  2264. toolName: "Write",
  2265. input: {},
  2266. }),
  2267. ]);
  2268. const deltaEvents = zcodeSessionEventToZCodeStreamEvents({
  2269. event: {
  2270. ...common,
  2271. eventId: "evt_tool_input_delta",
  2272. payload: {
  2273. kind: "tool_input_delta",
  2274. toolCallId: "call_write",
  2275. delta: '{"file_path":"src/app.ts","content":"line 1\\nline 2',
  2276. },
  2277. },
  2278. state,
  2279. taskId: "sess_1",
  2280. });
  2281. expect(deltaEvents).toEqual([
  2282. expect.objectContaining({
  2283. type: "tool_call_update",
  2284. toolId: "call_write",
  2285. status: "pending",
  2286. input: {
  2287. file_path: "src/app.ts",
  2288. content: "line 1\nline 2",
  2289. },
  2290. }),
  2291. ]);
  2292. const nextDeltaEvents = zcodeSessionEventToZCodeStreamEvents({
  2293. event: {
  2294. ...common,
  2295. eventId: "evt_tool_input_delta_2",
  2296. payload: {
  2297. kind: "tool_input_delta",
  2298. toolCallId: "call_write",
  2299. delta: "\\nline 3",
  2300. },
  2301. },
  2302. state,
  2303. taskId: "sess_1",
  2304. });
  2305. expect(nextDeltaEvents).toEqual([]);
  2306. expect(state.streamingToolInputById?.get("call_write")?.rawInput).toContain("\\nline 3");
  2307. const endEvents = zcodeSessionEventToZCodeStreamEvents({
  2308. event: {
  2309. ...common,
  2310. eventId: "evt_tool_input_end",
  2311. payload: {
  2312. kind: "tool_input_end",
  2313. toolCallId: "call_write",
  2314. },
  2315. },
  2316. state,
  2317. taskId: "sess_1",
  2318. });
  2319. expect(endEvents).toEqual([
  2320. expect.objectContaining({
  2321. type: "tool_call_update",
  2322. toolId: "call_write",
  2323. toolName: "Write",
  2324. raw: expect.objectContaining({
  2325. streamingRawInputLength: expect.any(Number),
  2326. }),
  2327. }),
  2328. ]);
  2329. expect(endEvents[0]).not.toHaveProperty("input");
  2330. expect(state.streamingToolInputById?.get("call_write")?.rawInput).toContain("\\nline 3");
  2331. const completeEvents = zcodeSessionEventToZCodeStreamEvents({
  2332. event: {
  2333. ...common,
  2334. eventId: "evt_tool_call",
  2335. payload: {
  2336. kind: "tool_call",
  2337. toolCallId: "call_write",
  2338. toolName: "Write",
  2339. input: {
  2340. file_path: "src/app.ts",
  2341. content: "line 1\nline 2\n",
  2342. },
  2343. },
  2344. },
  2345. state,
  2346. taskId: "sess_1",
  2347. });
  2348. expect(completeEvents).toEqual([
  2349. expect.objectContaining({
  2350. type: "tool_call_update",
  2351. toolId: "call_write",
  2352. input: {
  2353. file_path: "src/app.ts",
  2354. content: "line 1\nline 2\n",
  2355. },
  2356. }),
  2357. ]);
  2358. expect(state.streamingToolInputById?.get("call_write")?.rawInput).toBe("");
  2359. });
  2360. it("maps scheduled tool tombstones without rematerializing input", () => {
  2361. const state: ZCodeSessionEventProjectionState = {
  2362. streamingToolInputById: new Map(),
  2363. toolNameById: new Map<string, string>(),
  2364. };
  2365. const streamingToolCall = {
  2366. eventId: "evt_tool_call",
  2367. sessionId: "sess_1",
  2368. turnId: "turn_1",
  2369. seq: 4,
  2370. timestamp: 4,
  2371. traceId: "trace_tool_input",
  2372. type: "model.streaming",
  2373. payload: {
  2374. kind: "tool_call",
  2375. toolCallId: "call_write",
  2376. toolName: "Write",
  2377. input: {
  2378. content: "hello",
  2379. file_path: "/tmp/generated.html",
  2380. },
  2381. },
  2382. } satisfies ZCodeSessionEvent;
  2383. const scheduledTombstone = {
  2384. eventId: "evt_tool_scheduled",
  2385. sessionId: "sess_1",
  2386. turnId: "turn_1",
  2387. seq: 5,
  2388. timestamp: 5,
  2389. traceId: "trace_tool_input",
  2390. type: "tool.updated",
  2391. payload: {
  2392. kind: "scheduled",
  2393. toolCallId: "call_write",
  2394. toolName: "Write",
  2395. inputByteLength: 57,
  2396. inputOmitted: true,
  2397. inputRef: "model_stream",
  2398. },
  2399. } satisfies ZCodeSessionEvent;
  2400. expect(
  2401. zcodeSessionEventToZCodeStreamEvents({
  2402. event: streamingToolCall,
  2403. state,
  2404. taskId: "sess_1",
  2405. }),
  2406. ).toEqual([
  2407. expect.objectContaining({
  2408. type: "tool_call_update",
  2409. toolId: "call_write",
  2410. }),
  2411. ]);
  2412. const scheduledEvents = zcodeSessionEventToZCodeStreamEvents({
  2413. event: scheduledTombstone,
  2414. state,
  2415. taskId: "sess_1",
  2416. });
  2417. expect(scheduledEvents).toEqual([
  2418. expect.objectContaining({
  2419. raw: expect.not.objectContaining({
  2420. input: expect.anything(),
  2421. }),
  2422. status: "in_progress",
  2423. toolId: "call_write",
  2424. type: "tool_call_update",
  2425. }),
  2426. ]);
  2427. expect(Object.prototype.hasOwnProperty.call(scheduledEvents[0], "input")).toBe(false);
  2428. });
  2429. it("clears streaming raw input when complete tool input is remembered", () => {
  2430. const state: ZCodeSessionEventProjectionState = {
  2431. streamingToolInputById: new Map(),
  2432. toolNameById: new Map<string, string>(),
  2433. };
  2434. const streamingDelta = {
  2435. eventId: "evt_tool_delta",
  2436. sessionId: "sess_1",
  2437. turnId: "turn_1",
  2438. seq: 1,
  2439. timestamp: 1,
  2440. traceId: "trace_tool_input",
  2441. type: "model.streaming",
  2442. payload: {
  2443. kind: "tool_input_delta",
  2444. toolCallId: "call_write",
  2445. toolName: "Write",
  2446. delta: '{"file_path":"/tmp/generated.html","content":"hello"',
  2447. },
  2448. } satisfies ZCodeSessionEvent;
  2449. const scheduledWithCompleteInput = {
  2450. eventId: "evt_tool_scheduled",
  2451. sessionId: "sess_1",
  2452. turnId: "turn_1",
  2453. seq: 2,
  2454. timestamp: 2,
  2455. traceId: "trace_tool_input",
  2456. type: "tool.updated",
  2457. payload: {
  2458. kind: "scheduled",
  2459. toolCallId: "call_write",
  2460. toolName: "Write",
  2461. input: {
  2462. content: "hello",
  2463. file_path: "/tmp/generated.html",
  2464. },
  2465. },
  2466. } satisfies ZCodeSessionEvent;
  2467. zcodeSessionEventToZCodeStreamEvents({
  2468. event: streamingDelta,
  2469. state,
  2470. taskId: "sess_1",
  2471. });
  2472. expect(state.streamingToolInputById?.get("call_write")?.rawInput).toContain("generated.html");
  2473. zcodeSessionEventToZCodeStreamEvents({
  2474. event: scheduledWithCompleteInput,
  2475. state,
  2476. taskId: "sess_1",
  2477. });
  2478. expect(state.streamingToolInputById?.get("call_write")?.rawInput).toBe("");
  2479. expect(state.completeToolInputById?.get("call_write")).toEqual({
  2480. content: "hello",
  2481. file_path: "/tmp/generated.html",
  2482. });
  2483. });
  2484. it("creates missing streaming input state so foreground Write deltas accumulate", () => {
  2485. const state: ZCodeSessionEventProjectionState = {
  2486. toolNameById: new Map<string, string>(),
  2487. };
  2488. const common = {
  2489. sessionId: "sess_1",
  2490. seq: 4,
  2491. timestamp: 4,
  2492. traceId: "trace_tool_input",
  2493. type: "model.streaming" as const,
  2494. };
  2495. zcodeSessionEventToZCodeStreamEvents({
  2496. event: {
  2497. ...common,
  2498. eventId: "evt_tool_input_start",
  2499. payload: {
  2500. kind: "tool_input_start",
  2501. toolCallId: "call_write",
  2502. toolName: "Write",
  2503. },
  2504. },
  2505. state,
  2506. taskId: "sess_1",
  2507. });
  2508. zcodeSessionEventToZCodeStreamEvents({
  2509. event: {
  2510. ...common,
  2511. eventId: "evt_tool_input_delta",
  2512. payload: {
  2513. kind: "tool_input_delta",
  2514. toolCallId: "call_write",
  2515. delta: '{"file_path":"src/app.ts","content":"line 1\\nline 2',
  2516. },
  2517. },
  2518. state,
  2519. taskId: "sess_1",
  2520. });
  2521. const nextDeltaEvents = zcodeSessionEventToZCodeStreamEvents({
  2522. event: {
  2523. ...common,
  2524. eventId: "evt_tool_input_delta_2",
  2525. payload: {
  2526. kind: "tool_input_delta",
  2527. toolCallId: "call_write",
  2528. delta: "\\nline 3",
  2529. },
  2530. },
  2531. state,
  2532. taskId: "sess_1",
  2533. });
  2534. expect(state.streamingToolInputById?.get("call_write")?.deltaCount).toBe(2);
  2535. expect(nextDeltaEvents).toEqual([]);
  2536. const endEvents = zcodeSessionEventToZCodeStreamEvents({
  2537. event: {
  2538. ...common,
  2539. eventId: "evt_tool_input_end",
  2540. payload: {
  2541. kind: "tool_input_end",
  2542. toolCallId: "call_write",
  2543. },
  2544. },
  2545. state,
  2546. taskId: "sess_1",
  2547. });
  2548. expect(endEvents).toEqual([
  2549. expect.objectContaining({
  2550. type: "tool_call_update",
  2551. toolId: "call_write",
  2552. raw: expect.objectContaining({
  2553. streamingRawInputLength: expect.any(Number),
  2554. }),
  2555. }),
  2556. ]);
  2557. expect(endEvents[0]).not.toHaveProperty("input");
  2558. });
  2559. it("infers Write for streamed file inputs when the delta arrives without cached tool metadata", () => {
  2560. const streamEvents = zcodeSessionEventToZCodeStreamEvents({
  2561. event: {
  2562. eventId: "evt_tool_input_delta_no_name",
  2563. sessionId: "sess_1",
  2564. seq: 4,
  2565. timestamp: 4,
  2566. traceId: "trace_tool_input",
  2567. type: "model.streaming",
  2568. payload: {
  2569. kind: "tool_input_delta",
  2570. toolCallId: "call_write",
  2571. delta: '{"file_path":"src/app.ts","content":"line 1',
  2572. },
  2573. },
  2574. state: {
  2575. streamingToolInputById: new Map(),
  2576. toolNameById: new Map<string, string>(),
  2577. },
  2578. taskId: "sess_1",
  2579. });
  2580. expect(streamEvents).toEqual([
  2581. expect.objectContaining({
  2582. type: "tool_call_update",
  2583. toolId: "call_write",
  2584. toolName: "Write",
  2585. kind: "Write",
  2586. }),
  2587. ]);
  2588. });
  2589. it("keeps background streaming tool input as a tombstone until materialization", () => {
  2590. const state: ZCodeSessionEventProjectionState = {
  2591. streamingToolInputById: new Map(),
  2592. toolNameById: new Map<string, string>(),
  2593. };
  2594. const common = {
  2595. sessionId: "sess_1",
  2596. seq: 4,
  2597. timestamp: 4,
  2598. traceId: "trace_tool_input",
  2599. type: "model.streaming" as const,
  2600. };
  2601. const startEvents = zcodeSessionEventToZCodeStreamEvents({
  2602. event: {
  2603. ...common,
  2604. eventId: "evt_tool_input_start",
  2605. payload: {
  2606. kind: "tool_input_start",
  2607. toolCallId: "call_write",
  2608. toolName: "Write",
  2609. },
  2610. },
  2611. projectionMode: "background-summary",
  2612. state,
  2613. taskId: "sess_1",
  2614. });
  2615. const deltaEvents = zcodeSessionEventToZCodeStreamEvents({
  2616. event: {
  2617. ...common,
  2618. eventId: "evt_tool_input_delta",
  2619. payload: {
  2620. kind: "tool_input_delta",
  2621. toolCallId: "call_write",
  2622. delta: '{"file_path":"src/app.ts","content":"line 1\\nline 2',
  2623. },
  2624. },
  2625. projectionMode: "background-summary",
  2626. state,
  2627. taskId: "sess_1",
  2628. });
  2629. expect(startEvents).toHaveLength(1);
  2630. expect(deltaEvents).toEqual([]);
  2631. expect(state.streamingToolInputById?.get("call_write")).toMatchObject({
  2632. deltaCount: 1,
  2633. rawInput: '{"file_path":"src/app.ts","content":"line 1\\nline 2',
  2634. });
  2635. const completeEvents = zcodeSessionEventToZCodeStreamEvents({
  2636. event: {
  2637. ...common,
  2638. eventId: "evt_tool_call",
  2639. payload: {
  2640. kind: "tool_call",
  2641. toolCallId: "call_write",
  2642. toolName: "Write",
  2643. input: {
  2644. file_path: "src/app.ts",
  2645. content: "line 1\nline 2",
  2646. },
  2647. },
  2648. },
  2649. projectionMode: "background-summary",
  2650. state,
  2651. taskId: "sess_1",
  2652. });
  2653. expect(completeEvents).toEqual([
  2654. expect.objectContaining({
  2655. type: "tool_call_update",
  2656. toolId: "call_write",
  2657. input: {
  2658. file_path: "src/app.ts",
  2659. content: "line 1\nline 2",
  2660. },
  2661. }),
  2662. ]);
  2663. });
  2664. it("budgets active streaming tool input previews instead of projecting every delta", () => {
  2665. vi.useFakeTimers();
  2666. try {
  2667. vi.setSystemTime(1_000);
  2668. const state: ZCodeSessionEventProjectionState = {
  2669. streamingToolInputById: new Map(),
  2670. toolNameById: new Map<string, string>(),
  2671. };
  2672. const common = {
  2673. sessionId: "sess_1",
  2674. seq: 4,
  2675. timestamp: 4,
  2676. traceId: "trace_tool_input",
  2677. type: "model.streaming" as const,
  2678. };
  2679. zcodeSessionEventToZCodeStreamEvents({
  2680. event: {
  2681. ...common,
  2682. eventId: "evt_tool_input_start",
  2683. payload: {
  2684. kind: "tool_input_start",
  2685. toolCallId: "call_write",
  2686. toolName: "Write",
  2687. },
  2688. },
  2689. state,
  2690. taskId: "sess_1",
  2691. });
  2692. let materializedCount = 0;
  2693. for (let index = 0; index < 100; index += 1) {
  2694. const events = zcodeSessionEventToZCodeStreamEvents({
  2695. event: {
  2696. ...common,
  2697. eventId: `evt_tool_input_delta_${index}`,
  2698. payload: {
  2699. kind: "tool_input_delta",
  2700. toolCallId: "call_write",
  2701. delta: "x",
  2702. },
  2703. },
  2704. state,
  2705. taskId: "sess_1",
  2706. });
  2707. materializedCount += events.length;
  2708. }
  2709. expect(state.streamingToolInputById?.get("call_write")?.deltaCount).toBe(100);
  2710. expect(materializedCount).toBe(1);
  2711. vi.setSystemTime(2_000);
  2712. const intervalEvents = zcodeSessionEventToZCodeStreamEvents({
  2713. event: {
  2714. ...common,
  2715. eventId: "evt_tool_input_delta_interval",
  2716. payload: {
  2717. kind: "tool_input_delta",
  2718. toolCallId: "call_write",
  2719. delta: "y",
  2720. },
  2721. },
  2722. state,
  2723. taskId: "sess_1",
  2724. });
  2725. expect(intervalEvents).toHaveLength(1);
  2726. } finally {
  2727. vi.useRealTimers();
  2728. }
  2729. });
  2730. it("maps goal completion verifier model results to goal verification updates", () => {
  2731. expect(
  2732. zcodeSessionEventToZCodeStreamEvents({
  2733. event: {
  2734. eventId: "evt_goal_verify",
  2735. sessionId: "sess_1",
  2736. seq: 4,
  2737. timestamp: 4,
  2738. traceId: "trace_goal_verify",
  2739. type: "session.updated",
  2740. payload: {
  2741. content: JSON.stringify({
  2742. nextAction: "跑移动端 smoke test。",
  2743. passed: false,
  2744. reason: "第一轮证据不足。",
  2745. }),
  2746. querySource: "target_completion_verification",
  2747. stopReason: "stop",
  2748. usage: {
  2749. inputTokens: 1,
  2750. outputTokens: 1,
  2751. totalTokens: 2,
  2752. },
  2753. },
  2754. },
  2755. taskId: "sess_1",
  2756. }),
  2757. ).toEqual([
  2758. {
  2759. type: "goal_verification_update",
  2760. taskId: "sess_1",
  2761. traceId: "trace_goal_verify",
  2762. verification: {
  2763. nextAction: "跑移动端 smoke test。",
  2764. passed: false,
  2765. reason: "第一轮证据不足。",
  2766. },
  2767. },
  2768. {
  2769. type: "task_token_usage_delta",
  2770. taskId: "sess_1",
  2771. traceId: "trace_goal_verify",
  2772. eventId: "evt_goal_verify",
  2773. eventKey: "evt_goal_verify",
  2774. querySource: "target_completion_verification",
  2775. usage: {
  2776. inputTokens: 1,
  2777. outputTokens: 1,
  2778. totalTokens: 2,
  2779. },
  2780. },
  2781. ]);
  2782. });
  2783. it("does not synthesize nextAction when goal completion verifier JSON is invalid", () => {
  2784. expect(
  2785. zcodeSessionEventToZCodeStreamEvents({
  2786. event: {
  2787. eventId: "evt_goal_verify_invalid",
  2788. sessionId: "sess_1",
  2789. seq: 4,
  2790. timestamp: 4,
  2791. traceId: "trace_goal_verify",
  2792. type: "session.updated",
  2793. payload: {
  2794. content: "not json",
  2795. querySource: "target_completion_verification",
  2796. stopReason: "stop",
  2797. },
  2798. },
  2799. taskId: "sess_1",
  2800. }),
  2801. ).toEqual([
  2802. {
  2803. type: "goal_verification_update",
  2804. taskId: "sess_1",
  2805. traceId: "trace_goal_verify",
  2806. verification: {
  2807. passed: true,
  2808. reason: "The completion verifier did not return valid JSON.",
  2809. },
  2810. },
  2811. ]);
  2812. });
  2813. it("maps goal verification lifecycle payloads to synthetic divider chunks", () => {
  2814. expect(
  2815. zcodeSessionEventToZCodeStreamEvents({
  2816. event: {
  2817. eventId: "evt_goal_verify_started",
  2818. sessionId: "sess_1",
  2819. seq: 4,
  2820. timestamp: 42,
  2821. traceId: "trace_goal_verify",
  2822. type: "session.updated",
  2823. payload: {
  2824. status: "started",
  2825. targetId: "target_1",
  2826. verificationId: "verify_1",
  2827. goalIteration: 2,
  2828. anchorAssistantMessageId: "assistant_1",
  2829. anchorTurnId: "turn_1",
  2830. },
  2831. },
  2832. taskId: "sess_1",
  2833. }),
  2834. ).toEqual([
  2835. {
  2836. type: "agent_message_chunk",
  2837. taskId: "sess_1",
  2838. traceId: "trace_goal_verify",
  2839. messageId: "zcode-goal-verification-target_1-2",
  2840. content: "",
  2841. zcodeTimeline: {
  2842. version: 1,
  2843. kind: "synthetic",
  2844. type: "goal_verification",
  2845. display: "separator",
  2846. targetId: "target_1",
  2847. verificationId: "verify_1",
  2848. goalIteration: 2,
  2849. anchorAssistantMessageId: "assistant_1",
  2850. anchorTurnId: "turn_1",
  2851. status: "started",
  2852. startedAt: 42,
  2853. updatedAt: 42,
  2854. },
  2855. },
  2856. ]);
  2857. });
  2858. it("maps completed goal verification lifecycle payloads with verifier result", () => {
  2859. expect(
  2860. zcodeSessionEventToZCodeStreamEvents({
  2861. event: {
  2862. eventId: "evt_goal_verify_completed",
  2863. sessionId: "sess_1",
  2864. seq: 5,
  2865. timestamp: 52,
  2866. traceId: "trace_goal_verify",
  2867. type: "session.updated",
  2868. payload: {
  2869. status: "completed",
  2870. targetId: "target_1",
  2871. verificationId: "verify_1",
  2872. goalIteration: 3,
  2873. verification: {
  2874. nextAction: null,
  2875. passed: true,
  2876. reason: "所有目标要求都已完成。",
  2877. },
  2878. },
  2879. },
  2880. taskId: "sess_1",
  2881. }),
  2882. ).toEqual([
  2883. {
  2884. type: "agent_message_chunk",
  2885. taskId: "sess_1",
  2886. traceId: "trace_goal_verify",
  2887. messageId: "zcode-goal-verification-target_1-3",
  2888. content: "",
  2889. zcodeTimeline: {
  2890. version: 1,
  2891. kind: "synthetic",
  2892. type: "goal_verification",
  2893. display: "separator",
  2894. targetId: "target_1",
  2895. verificationId: "verify_1",
  2896. status: "completed",
  2897. goalIteration: 3,
  2898. verification: {
  2899. passed: true,
  2900. reason: "所有目标要求都已完成。",
  2901. },
  2902. updatedAt: 52,
  2903. },
  2904. },
  2905. ]);
  2906. });
  2907. it.each(["plan", "edit"] as const)("maps %s mode updates without replacing historical values", (mode) => {
  2908. const events = zcodeSessionEventToZCodeStreamEvents({
  2909. event: {
  2910. eventId: "evt_mode",
  2911. sessionId: "sess_1",
  2912. seq: 4,
  2913. timestamp: 4,
  2914. traceId: "trace_mode",
  2915. type: "session.updated",
  2916. payload: {
  2917. mode,
  2918. previousMode: "build",
  2919. source: "tool",
  2920. },
  2921. },
  2922. taskId: "sess_1",
  2923. });
  2924. expect(events).toHaveLength(1);
  2925. expect(events[0]).toEqual(
  2926. expect.objectContaining({
  2927. type: "mode_update",
  2928. taskId: "sess_1",
  2929. traceId: "trace_mode",
  2930. currentModeId: mode,
  2931. availableModes: expect.arrayContaining([
  2932. expect.objectContaining({ id: "build" }),
  2933. expect.objectContaining({ id: "guarded" }),
  2934. expect.objectContaining({ id: "plan" }),
  2935. expect.objectContaining({ id: "yolo" }),
  2936. ]),
  2937. }),
  2938. );
  2939. });
  2940. it("maps main turn model usage with context window to legacy usage_update events", () => {
  2941. expect(
  2942. zcodeSessionEventToZCodeStreamEvents({
  2943. event: {
  2944. eventId: "evt_model_usage",
  2945. sessionId: "sess_1",
  2946. seq: 5,
  2947. timestamp: 5,
  2948. traceId: "trace_model_usage",
  2949. type: "session.updated",
  2950. payload: {
  2951. contextWindow: 1_000_000,
  2952. querySource: "main_turn",
  2953. usage: {
  2954. inputTokens: 279454,
  2955. outputTokens: 177,
  2956. totalTokens: 279631,
  2957. cacheReadTokens: 1000,
  2958. cacheWriteTokens: 200,
  2959. cacheHitRate: 0.25,
  2960. },
  2961. contextUsageBreakdown: [
  2962. { source: "messages", chars: 1200 },
  2963. { source: "system_tool_schemas", chars: 300 },
  2964. ],
  2965. },
  2966. },
  2967. taskId: "sess_1",
  2968. }),
  2969. ).toEqual([
  2970. {
  2971. type: "task_token_usage_delta",
  2972. taskId: "sess_1",
  2973. traceId: "trace_model_usage",
  2974. eventKey: "evt_model_usage",
  2975. eventId: "evt_model_usage",
  2976. querySource: "main_turn",
  2977. usage: {
  2978. inputTokens: 279454,
  2979. outputTokens: 177,
  2980. totalTokens: 279631,
  2981. reasoningTokens: undefined,
  2982. cachedInputTokens: 1000,
  2983. cachedWriteInputTokens: 200,
  2984. },
  2985. },
  2986. {
  2987. type: "usage_update",
  2988. taskId: "sess_1",
  2989. traceId: "trace_model_usage",
  2990. used: 279631,
  2991. size: 1_000_000,
  2992. cost: null,
  2993. cache: {
  2994. inputTokens: 279454,
  2995. cacheReadTokens: 1000,
  2996. cacheWriteTokens: 200,
  2997. latestHitRate: 0.25,
  2998. hitRate: 0.25,
  2999. },
  3000. breakdown: [
  3001. { source: "messages", chars: 1200 },
  3002. { source: "system_tool_schemas", chars: 300 },
  3003. ],
  3004. },
  3005. ]);
  3006. });
  3007. it("maps model network status payloads to task network debug events", () => {
  3008. const events = zcodeSessionEventToZCodeStreamEvents({
  3009. event: {
  3010. eventId: "evt_network_debug",
  3011. sessionId: "sess_1",
  3012. seq: 5,
  3013. timestamp: 5,
  3014. traceId: "trace_network_debug",
  3015. type: "session.updated",
  3016. payload: {
  3017. type: "model_retry_scheduled",
  3018. requestId: "request-1",
  3019. timestamp: "2026-06-10T00:00:00.000Z",
  3020. model: {
  3021. providerId: "openai",
  3022. modelId: "model-test",
  3023. },
  3024. transport: "http",
  3025. attempt: 1,
  3026. maxAttempts: 3,
  3027. nextAttempt: 2,
  3028. delayMs: 1000,
  3029. reason: "rate_limited",
  3030. message: "rate limited",
  3031. statusCode: 429,
  3032. requestHeaders: {
  3033. authorization: "[redacted]",
  3034. },
  3035. responseHeaders: {
  3036. "retry-after": "1",
  3037. },
  3038. },
  3039. },
  3040. taskId: "sess_1",
  3041. });
  3042. expect(events).toContainEqual({
  3043. type: "task_network_debug_status",
  3044. taskId: "sess_1",
  3045. traceId: "trace_network_debug",
  3046. eventKey: "evt_network_debug",
  3047. eventId: "evt_network_debug",
  3048. statusType: "model_retry_scheduled",
  3049. requestId: "request-1",
  3050. providerId: "openai",
  3051. modelId: "model-test",
  3052. transport: "http",
  3053. attempt: 1,
  3054. maxAttempts: 3,
  3055. nextAttempt: 2,
  3056. statusCode: 429,
  3057. delayMs: 1000,
  3058. reason: "rate_limited",
  3059. message: "rate limited",
  3060. timestamp: "2026-06-10T00:00:00.000Z",
  3061. requestHeaders: {
  3062. authorization: "[redacted]",
  3063. },
  3064. responseHeaders: {
  3065. "retry-after": "1",
  3066. },
  3067. requestHeaderCount: 1,
  3068. responseHeaderCount: 1,
  3069. });
  3070. });
  3071. it("maps aggregate main turn cache hit usage from protocol payload", () => {
  3072. expect(
  3073. zcodeSessionEventToZCodeStreamEvents({
  3074. event: {
  3075. eventId: "evt_model_usage_average",
  3076. sessionId: "sess_1",
  3077. seq: 5,
  3078. timestamp: 5,
  3079. traceId: "trace_model_usage_average",
  3080. type: "session.updated",
  3081. payload: {
  3082. contextWindow: 1_000_000,
  3083. querySource: "main_turn",
  3084. cacheHit: {
  3085. inputTokens: 200,
  3086. cacheReadTokens: 80,
  3087. cacheWriteTokens: 10,
  3088. latestHitRate: 0.4,
  3089. hitRate: 0.3,
  3090. hitRateRequestCount: 2,
  3091. totalInputTokens: 500,
  3092. totalCacheReadTokens: 150,
  3093. totalCacheWriteTokens: 25,
  3094. },
  3095. usage: {
  3096. inputTokens: 200,
  3097. outputTokens: 20,
  3098. totalTokens: 220,
  3099. cacheReadTokens: 80,
  3100. cacheWriteTokens: 10,
  3101. },
  3102. },
  3103. },
  3104. taskId: "sess_1",
  3105. }),
  3106. ).toEqual([
  3107. {
  3108. type: "task_token_usage_delta",
  3109. taskId: "sess_1",
  3110. traceId: "trace_model_usage_average",
  3111. eventKey: "evt_model_usage_average",
  3112. eventId: "evt_model_usage_average",
  3113. querySource: "main_turn",
  3114. usage: {
  3115. inputTokens: 200,
  3116. outputTokens: 20,
  3117. totalTokens: 220,
  3118. reasoningTokens: undefined,
  3119. cachedInputTokens: 80,
  3120. cachedWriteInputTokens: 10,
  3121. },
  3122. },
  3123. {
  3124. type: "usage_update",
  3125. taskId: "sess_1",
  3126. traceId: "trace_model_usage_average",
  3127. used: 220,
  3128. size: 1_000_000,
  3129. cost: null,
  3130. cache: {
  3131. inputTokens: 200,
  3132. cacheReadTokens: 80,
  3133. cacheWriteTokens: 10,
  3134. latestHitRate: 0.4,
  3135. hitRate: 0.3,
  3136. hitRateRequestCount: 2,
  3137. totalInputTokens: 500,
  3138. totalCacheReadTokens: 150,
  3139. totalCacheWriteTokens: 25,
  3140. },
  3141. },
  3142. ]);
  3143. });
  3144. it("prefers real main turn model usage over projected context used", () => {
  3145. expect(
  3146. zcodeSessionEventToZCodeStreamEvents({
  3147. event: {
  3148. eventId: "evt_model_usage_projection",
  3149. sessionId: "sess_1",
  3150. seq: 5,
  3151. timestamp: 5,
  3152. traceId: "trace_model_usage_projection",
  3153. type: "session.updated",
  3154. payload: {
  3155. contextUsed: 64000,
  3156. contextWindow: 1_000_000,
  3157. querySource: "main_turn",
  3158. usage: {
  3159. inputTokens: 12345,
  3160. outputTokens: 77,
  3161. totalTokens: 12422,
  3162. },
  3163. },
  3164. },
  3165. taskId: "sess_1",
  3166. }),
  3167. ).toEqual([
  3168. {
  3169. type: "task_token_usage_delta",
  3170. taskId: "sess_1",
  3171. traceId: "trace_model_usage_projection",
  3172. eventKey: "evt_model_usage_projection",
  3173. eventId: "evt_model_usage_projection",
  3174. querySource: "main_turn",
  3175. usage: {
  3176. inputTokens: 12345,
  3177. outputTokens: 77,
  3178. totalTokens: 12422,
  3179. reasoningTokens: undefined,
  3180. cachedInputTokens: undefined,
  3181. cachedWriteInputTokens: undefined,
  3182. },
  3183. },
  3184. {
  3185. type: "usage_update",
  3186. taskId: "sess_1",
  3187. traceId: "trace_model_usage_projection",
  3188. used: 12422,
  3189. size: 1_000_000,
  3190. cost: null,
  3191. },
  3192. ]);
  3193. });
  3194. it("does not map sidecar model usage to context usage", () => {
  3195. expect(
  3196. zcodeSessionEventToZCodeStreamEvents({
  3197. event: {
  3198. eventId: "evt_title_usage",
  3199. sessionId: "sess_1",
  3200. seq: 6,
  3201. timestamp: 6,
  3202. traceId: "trace_title_usage",
  3203. type: "session.updated",
  3204. payload: {
  3205. contextWindow: 1_000_000,
  3206. querySource: "session_title",
  3207. usage: {
  3208. inputTokens: 89,
  3209. outputTokens: 84,
  3210. totalTokens: 173,
  3211. },
  3212. },
  3213. },
  3214. taskId: "sess_1",
  3215. }),
  3216. ).toEqual([
  3217. {
  3218. type: "task_token_usage_delta",
  3219. taskId: "sess_1",
  3220. traceId: "trace_title_usage",
  3221. eventKey: "evt_title_usage",
  3222. eventId: "evt_title_usage",
  3223. querySource: "session_title",
  3224. usage: {
  3225. inputTokens: 89,
  3226. outputTokens: 84,
  3227. totalTokens: 173,
  3228. reasoningTokens: undefined,
  3229. cachedInputTokens: undefined,
  3230. cachedWriteInputTokens: undefined,
  3231. },
  3232. },
  3233. ]);
  3234. });
  3235. it("maps ZCode model retry status updates to apiRetry events", () => {
  3236. const events = zcodeSessionEventToZCodeStreamEvents({
  3237. event: {
  3238. eventId: "evt_retry",
  3239. sessionId: "sess_1",
  3240. seq: 5,
  3241. timestamp: 5,
  3242. traceId: "trace_retry",
  3243. type: "session.updated",
  3244. payload: {
  3245. type: "model_retry_scheduled",
  3246. attempt: 1,
  3247. maxAttempts: 4,
  3248. delayMs: 2_000,
  3249. statusCode: 429,
  3250. message: "rate limited",
  3251. },
  3252. },
  3253. taskId: "sess_1",
  3254. });
  3255. expect(events).toContainEqual(
  3256. expect.objectContaining({
  3257. type: "task_network_debug_status",
  3258. taskId: "sess_1",
  3259. traceId: "trace_retry",
  3260. eventKey: "evt_retry",
  3261. statusType: "model_retry_scheduled",
  3262. attempt: 1,
  3263. maxAttempts: 4,
  3264. delayMs: 2_000,
  3265. statusCode: 429,
  3266. }),
  3267. );
  3268. expect(events).toContainEqual({
  3269. type: "session_info_update",
  3270. taskId: "sess_1",
  3271. traceId: "trace_retry",
  3272. apiRetry: {
  3273. kind: "api_retry",
  3274. attempt: 1,
  3275. maxRetries: 3,
  3276. retryDelayMs: 2_000,
  3277. errorStatus: 429,
  3278. error: "rate limited",
  3279. },
  3280. });
  3281. });
  3282. it("keeps adapter retry visible until the retry attempt produces progress", () => {
  3283. const state: ZCodeSessionEventProjectionState = {
  3284. streamedTurnKeys: new Set<string>(),
  3285. toolNameById: new Map<string, string>(),
  3286. };
  3287. expect(
  3288. zcodeSessionEventToZCodeStreamEvents({
  3289. event: {
  3290. eventId: "evt_retry_scheduled",
  3291. sessionId: "sess_1",
  3292. seq: 5,
  3293. timestamp: 5,
  3294. traceId: "trace_retry",
  3295. type: "session.updated",
  3296. payload: {
  3297. type: "model_retry_scheduled",
  3298. attempt: 1,
  3299. maxAttempts: 4,
  3300. delayMs: 2_000,
  3301. message: "rate limited",
  3302. },
  3303. },
  3304. state,
  3305. taskId: "sess_1",
  3306. }),
  3307. ).toContainEqual({
  3308. type: "session_info_update",
  3309. taskId: "sess_1",
  3310. traceId: "trace_retry",
  3311. apiRetry: {
  3312. kind: "api_retry",
  3313. attempt: 1,
  3314. maxRetries: 3,
  3315. retryDelayMs: 2_000,
  3316. errorStatus: null,
  3317. error: "rate limited",
  3318. },
  3319. });
  3320. const retryStartedEvents = zcodeSessionEventToZCodeStreamEvents({
  3321. event: {
  3322. eventId: "evt_retry_started",
  3323. sessionId: "sess_1",
  3324. seq: 6,
  3325. timestamp: 6,
  3326. traceId: "trace_retry",
  3327. type: "session.updated",
  3328. payload: {
  3329. type: "model_request_started",
  3330. attempt: 2,
  3331. maxAttempts: 4,
  3332. requestId: "request_retry",
  3333. },
  3334. },
  3335. state,
  3336. taskId: "sess_1",
  3337. });
  3338. expect(retryStartedEvents).toContainEqual(
  3339. expect.objectContaining({
  3340. type: "task_network_debug_status",
  3341. taskId: "sess_1",
  3342. traceId: "trace_retry",
  3343. eventKey: "evt_retry_started",
  3344. statusType: "model_request_started",
  3345. attempt: 2,
  3346. maxAttempts: 4,
  3347. }),
  3348. );
  3349. expect(retryStartedEvents).not.toContainEqual({
  3350. type: "session_info_update",
  3351. taskId: "sess_1",
  3352. traceId: "trace_retry",
  3353. apiRetry: null,
  3354. });
  3355. expect(
  3356. zcodeSessionEventToZCodeStreamEvents({
  3357. event: {
  3358. eventId: "evt_retry_progress",
  3359. sessionId: "sess_1",
  3360. seq: 7,
  3361. timestamp: 7,
  3362. traceId: "trace_retry",
  3363. type: "session.updated",
  3364. payload: {
  3365. kind: "reasoning_delta",
  3366. delta: "recovered",
  3367. assistantMessageId: "msg_retry",
  3368. },
  3369. },
  3370. state,
  3371. taskId: "sess_1",
  3372. }),
  3373. ).toEqual([
  3374. {
  3375. type: "session_info_update",
  3376. taskId: "sess_1",
  3377. traceId: "trace_retry",
  3378. apiRetry: null,
  3379. },
  3380. {
  3381. type: "agent_thought_chunk",
  3382. taskId: "sess_1",
  3383. traceId: "trace_retry",
  3384. content: "recovered",
  3385. },
  3386. ]);
  3387. });
  3388. it("maps core stream recovery request starts to apiRetry events", () => {
  3389. const events = zcodeSessionEventToZCodeStreamEvents({
  3390. event: {
  3391. eventId: "evt_stream_recovery_retry",
  3392. sessionId: "sess_1",
  3393. seq: 5,
  3394. timestamp: 5,
  3395. traceId: "trace_retry",
  3396. type: "session.updated",
  3397. payload: {
  3398. type: "model_request_started",
  3399. attempt: 1,
  3400. maxAttempts: 11,
  3401. requestId: "request_recovery",
  3402. streamRecovery: {
  3403. attemptId: "stream_attempt_1",
  3404. anchorId: "anchor_1",
  3405. maxRetries: 10,
  3406. recoveredFromRequestId: "request_failed",
  3407. retryNumber: 3,
  3408. },
  3409. },
  3410. },
  3411. taskId: "sess_1",
  3412. });
  3413. expect(events).toContainEqual(
  3414. expect.objectContaining({
  3415. type: "task_network_debug_status",
  3416. taskId: "sess_1",
  3417. traceId: "trace_retry",
  3418. eventKey: "evt_stream_recovery_retry",
  3419. statusType: "model_request_started",
  3420. requestId: "request_recovery",
  3421. attempt: 1,
  3422. maxAttempts: 11,
  3423. }),
  3424. );
  3425. expect(events).toContainEqual({
  3426. type: "session_info_update",
  3427. taskId: "sess_1",
  3428. traceId: "trace_retry",
  3429. apiRetry: {
  3430. kind: "api_retry",
  3431. attempt: 3,
  3432. maxRetries: 10,
  3433. retryDelayMs: 0,
  3434. errorStatus: null,
  3435. error: "Model stream recovery retry started",
  3436. },
  3437. });
  3438. });
  3439. it("maps core stream recovery progress to apiRetry events", () => {
  3440. expect(
  3441. zcodeSessionEventToZCodeStreamEvents({
  3442. event: {
  3443. eventId: "evt_stream_recovery_progress",
  3444. sessionId: "sess_1",
  3445. seq: 5,
  3446. timestamp: 5,
  3447. traceId: "trace_retry",
  3448. type: "streamRecovery.updated",
  3449. payload: {
  3450. attemptId: "stream_attempt_2",
  3451. failedRequestId: "request_failed",
  3452. maxRetries: 10,
  3453. recoveredFromRequestId: "request_failed",
  3454. retryNumber: 4,
  3455. streamMode: "sse",
  3456. },
  3457. },
  3458. taskId: "sess_1",
  3459. }),
  3460. ).toEqual([
  3461. {
  3462. type: "session_info_update",
  3463. taskId: "sess_1",
  3464. traceId: "trace_retry",
  3465. apiRetry: {
  3466. kind: "api_retry",
  3467. attempt: 4,
  3468. maxRetries: 10,
  3469. retryDelayMs: 0,
  3470. errorStatus: null,
  3471. error: "Model stream recovery retry started",
  3472. },
  3473. },
  3474. ]);
  3475. });
  3476. it("maps private apiRetry meta updates and clear patches", () => {
  3477. expect(
  3478. zcodeSessionEventToZCodeStreamEvents({
  3479. event: {
  3480. eventId: "evt_retry_meta",
  3481. sessionId: "sess_1",
  3482. seq: 5,
  3483. timestamp: 5,
  3484. traceId: "trace_retry",
  3485. type: "session.updated",
  3486. payload: {
  3487. _meta: {
  3488. zcode: {
  3489. apiRetry: {
  3490. kind: "api_retry",
  3491. attempt: 2,
  3492. maxRetries: 5,
  3493. retryDelayMs: 4_000,
  3494. errorStatus: null,
  3495. error: "network reset",
  3496. },
  3497. },
  3498. },
  3499. },
  3500. },
  3501. taskId: "sess_1",
  3502. }),
  3503. ).toEqual([
  3504. {
  3505. type: "session_info_update",
  3506. taskId: "sess_1",
  3507. traceId: "trace_retry",
  3508. apiRetry: {
  3509. kind: "api_retry",
  3510. attempt: 2,
  3511. maxRetries: 5,
  3512. retryDelayMs: 4_000,
  3513. errorStatus: null,
  3514. error: "network reset",
  3515. },
  3516. },
  3517. ]);
  3518. const clearEvents = zcodeSessionEventToZCodeStreamEvents({
  3519. event: {
  3520. eventId: "evt_retry_clear",
  3521. sessionId: "sess_1",
  3522. seq: 6,
  3523. timestamp: 6,
  3524. traceId: "trace_retry",
  3525. type: "session.updated",
  3526. payload: {
  3527. type: "model_request_completed",
  3528. attempt: 3,
  3529. maxAttempts: 4,
  3530. },
  3531. },
  3532. taskId: "sess_1",
  3533. });
  3534. expect(clearEvents).toContainEqual(
  3535. expect.objectContaining({
  3536. type: "task_network_debug_status",
  3537. taskId: "sess_1",
  3538. traceId: "trace_retry",
  3539. eventKey: "evt_retry_clear",
  3540. statusType: "model_request_completed",
  3541. attempt: 3,
  3542. maxAttempts: 4,
  3543. }),
  3544. );
  3545. expect(clearEvents).toContainEqual({
  3546. type: "session_info_update",
  3547. taskId: "sess_1",
  3548. traceId: "trace_retry",
  3549. apiRetry: null,
  3550. });
  3551. });
  3552. it("maps projection background job updates to runtime stream events", () => {
  3553. expect(
  3554. zcodeSessionEventToZCodeStreamEvents({
  3555. event: {
  3556. eventId: "evt_background_bash",
  3557. sessionId: "sess_1",
  3558. seq: 4,
  3559. timestamp: 4,
  3560. traceId: "trace_background_bash",
  3561. type: "session.updated",
  3562. payload: {
  3563. projection: {
  3564. backgroundJobs: [
  3565. {
  3566. id: "bg-1",
  3567. kind: "background_bash",
  3568. command: "pnpm dev",
  3569. status: "running",
  3570. elapsedMs: 31_000,
  3571. },
  3572. ],
  3573. },
  3574. },
  3575. },
  3576. taskId: "sess_1",
  3577. }),
  3578. ).toEqual([
  3579. {
  3580. type: "background_bash_jobs_update",
  3581. taskId: "sess_1",
  3582. traceId: "trace_background_bash",
  3583. jobs: [
  3584. expect.objectContaining({
  3585. jobId: "bg-1",
  3586. command: "pnpm dev",
  3587. status: "running",
  3588. elapsedMs: 31_000,
  3589. }),
  3590. ],
  3591. },
  3592. ]);
  3593. });
  3594. it("maps single background task payloads into cached background job updates", () => {
  3595. const state: ZCodeSessionEventProjectionState = {};
  3596. const bashEvents = zcodeSessionEventToZCodeStreamEvents({
  3597. event: {
  3598. eventId: "evt_background_bash_started",
  3599. sessionId: "sess_1",
  3600. seq: 4,
  3601. timestamp: 4,
  3602. traceId: "trace_background_bash_started",
  3603. type: "session.updated",
  3604. payload: {
  3605. taskId: "exec_1",
  3606. terminalId: "exec_1",
  3607. toolCallId: "toolu_bash",
  3608. toolName: "Bash",
  3609. command: "sleep 999",
  3610. status: "running",
  3611. startedAt: 10_000,
  3612. },
  3613. },
  3614. state,
  3615. taskId: "sess_1",
  3616. });
  3617. const agentEvents = zcodeSessionEventToZCodeStreamEvents({
  3618. event: {
  3619. eventId: "evt_background_agent_started",
  3620. sessionId: "sess_1",
  3621. seq: 5,
  3622. timestamp: 5,
  3623. traceId: "trace_background_agent_started",
  3624. type: "session.updated",
  3625. payload: {
  3626. taskId: "agent_1",
  3627. terminalId: "agent_1",
  3628. toolCallId: "toolu_agent",
  3629. toolName: "Agent",
  3630. description: "E2E background cancel agent",
  3631. status: "running",
  3632. startedAt: 11_000,
  3633. },
  3634. },
  3635. state,
  3636. taskId: "sess_1",
  3637. });
  3638. expect(bashEvents).toEqual([
  3639. {
  3640. type: "background_bash_jobs_update",
  3641. taskId: "sess_1",
  3642. traceId: "trace_background_bash_started",
  3643. jobs: [
  3644. expect.objectContaining({
  3645. jobId: "exec_1",
  3646. command: "sleep 999",
  3647. status: "running",
  3648. toolCallId: "toolu_bash",
  3649. }),
  3650. ],
  3651. },
  3652. ]);
  3653. expect(agentEvents).toEqual([
  3654. {
  3655. type: "background_bash_jobs_update",
  3656. taskId: "sess_1",
  3657. traceId: "trace_background_agent_started",
  3658. jobs: [
  3659. expect.objectContaining({
  3660. jobId: "exec_1",
  3661. command: "sleep 999",
  3662. status: "running",
  3663. }),
  3664. expect.objectContaining({
  3665. jobId: "agent_1",
  3666. command: "E2E background cancel agent",
  3667. status: "running",
  3668. taskKind: "agent",
  3669. toolCallId: "toolu_agent",
  3670. }),
  3671. ],
  3672. },
  3673. ]);
  3674. });
  3675. it("projects live task notification turns back onto the matching background Agent tool", () => {
  3676. const events = zcodeSessionEventToZCodeStreamEvents({
  3677. event: {
  3678. eventId: "evt_task_notification_started",
  3679. sessionId: "sess_1",
  3680. seq: 6,
  3681. timestamp: 6,
  3682. traceId: "trace_task_notification",
  3683. type: "turn.started",
  3684. payload: {
  3685. input: [
  3686. "<task-notification>",
  3687. "<task-id>agent_1</task-id>",
  3688. "<tool-use-id>toolu_background_agent</tool-use-id>",
  3689. "<output-file>/tmp/background-agent.output</output-file>",
  3690. "<status>completed</status>",
  3691. "<summary>Agent general-purpose task &quot;Review&quot; completed.</summary>",
  3692. "<result>Background Agent live result</result>",
  3693. "</task-notification>",
  3694. ].join("\n"),
  3695. inputSource: "task-notification",
  3696. inputVisibility: "model-only",
  3697. },
  3698. },
  3699. taskId: "sess_1",
  3700. });
  3701. expect(events).toEqual([
  3702. expect.objectContaining({
  3703. type: "task_run_started",
  3704. taskId: "sess_1",
  3705. traceId: "trace_task_notification",
  3706. }),
  3707. expect.objectContaining({
  3708. type: "tool_call_update",
  3709. taskId: "sess_1",
  3710. toolId: "toolu_background_agent",
  3711. status: "completed",
  3712. content: "Background Agent live result",
  3713. raw: expect.objectContaining({
  3714. _meta: expect.objectContaining({
  3715. zcode: expect.objectContaining({
  3716. taskNotification: {
  3717. outputFile: "/tmp/background-agent.output",
  3718. result: "Background Agent live result",
  3719. status: "completed",
  3720. summary: 'Agent general-purpose task "Review" completed.',
  3721. taskId: "agent_1",
  3722. },
  3723. }),
  3724. }),
  3725. toolCallId: "toolu_background_agent",
  3726. }),
  3727. }),
  3728. ]);
  3729. });
  3730. it("projects failed live task notifications with the original provider error", () => {
  3731. const events = zcodeSessionEventToZCodeStreamEvents({
  3732. event: {
  3733. eventId: "evt_failed_task_notification_started",
  3734. sessionId: "sess_1",
  3735. seq: 7,
  3736. timestamp: 7,
  3737. traceId: "trace_failed_task_notification",
  3738. type: "turn.started",
  3739. payload: {
  3740. input: [
  3741. "<task-notification>",
  3742. "<task-id>agent_failed</task-id>",
  3743. "<tool-use-id>toolu_failed_background_agent</tool-use-id>",
  3744. "<output-file>/tmp/background-agent.output</output-file>",
  3745. "<status>failed</status>",
  3746. '<summary>Agent general-purpose task "Review" failed.</summary>',
  3747. `<error>${backgroundAgentProviderError}</error>`,
  3748. "</task-notification>",
  3749. ].join("\n"),
  3750. inputSource: "task-notification",
  3751. inputVisibility: "model-only",
  3752. },
  3753. },
  3754. taskId: "sess_1",
  3755. });
  3756. expect(events).toEqual([
  3757. expect.objectContaining({
  3758. type: "task_run_started",
  3759. taskId: "sess_1",
  3760. traceId: "trace_failed_task_notification",
  3761. }),
  3762. expect.objectContaining({
  3763. type: "tool_call_update",
  3764. taskId: "sess_1",
  3765. toolId: "toolu_failed_background_agent",
  3766. status: "failed",
  3767. content: 'Agent general-purpose task "Review" failed.',
  3768. error: backgroundAgentProviderError,
  3769. raw: expect.objectContaining({
  3770. _meta: expect.objectContaining({
  3771. zcode: expect.objectContaining({
  3772. taskNotification: expect.objectContaining({
  3773. error: backgroundAgentProviderError,
  3774. status: "failed",
  3775. summary: 'Agent general-purpose task "Review" failed.',
  3776. taskId: "agent_failed",
  3777. }),
  3778. }),
  3779. }),
  3780. toolCallId: "toolu_failed_background_agent",
  3781. }),
  3782. }),
  3783. ]);
  3784. });
  3785. it("projects killed task notification turns as stopped tool updates", () => {
  3786. const events = zcodeSessionEventToZCodeStreamEvents({
  3787. event: {
  3788. eventId: "evt_task_notification_stopped",
  3789. sessionId: "sess_1",
  3790. seq: 7,
  3791. timestamp: 7,
  3792. traceId: "trace_task_notification_stopped",
  3793. type: "turn.started",
  3794. payload: {
  3795. input: [
  3796. "<task-notification>",
  3797. "<task-id>agent_1</task-id>",
  3798. "<tool-use-id>toolu_background_agent</tool-use-id>",
  3799. "<output-file>/tmp/background-agent.output</output-file>",
  3800. "<status>killed</status>",
  3801. "<summary>Agent task was stopped.</summary>",
  3802. "</task-notification>",
  3803. ].join("\n"),
  3804. inputSource: "task-notification",
  3805. inputVisibility: "model-only",
  3806. },
  3807. },
  3808. taskId: "sess_1",
  3809. });
  3810. expect(events).toEqual([
  3811. expect.objectContaining({
  3812. type: "task_run_started",
  3813. taskId: "sess_1",
  3814. traceId: "trace_task_notification_stopped",
  3815. }),
  3816. expect.objectContaining({
  3817. type: "tool_call_update",
  3818. taskId: "sess_1",
  3819. toolId: "toolu_background_agent",
  3820. status: "stopped",
  3821. content: "Agent task was stopped.",
  3822. raw: expect.objectContaining({
  3823. _meta: expect.objectContaining({
  3824. zcode: expect.objectContaining({
  3825. taskNotification: expect.objectContaining({
  3826. status: "killed",
  3827. summary: "Agent task was stopped.",
  3828. taskId: "agent_1",
  3829. }),
  3830. }),
  3831. }),
  3832. }),
  3833. }),
  3834. ]);
  3835. });
  3836. it("maps direct user input requests into elicitation requests", () => {
  3837. const event = zcodeUserInputRequestToZCodeStreamEvent("sess_1", {
  3838. requestId: "ask_1",
  3839. sessionId: "sess_1",
  3840. turnId: "turn_1",
  3841. toolCallId: "tool_ask",
  3842. toolName: "AskUserQuestion",
  3843. origin: subagentOrigin,
  3844. prompt: "Need a choice",
  3845. questions: [
  3846. {
  3847. question: "Which branch should I test?",
  3848. header: "Branch",
  3849. options: [
  3850. { value: "main", label: "main", description: "Use main branch" },
  3851. {
  3852. value: "release",
  3853. label: "release",
  3854. description: "Use release branch",
  3855. },
  3856. ],
  3857. },
  3858. ],
  3859. schema: { toolName: "AskUserQuestion" },
  3860. });
  3861. expect(event).toMatchObject({
  3862. type: "elicitation_request",
  3863. taskId: "sess_1",
  3864. requestId: "ask_1",
  3865. message: "Which branch should I test?",
  3866. header: "Branch",
  3867. origin: subagentOrigin,
  3868. options: [
  3869. { value: "main", label: "main", description: "Use main branch" },
  3870. {
  3871. value: "release",
  3872. label: "release",
  3873. description: "Use release branch",
  3874. },
  3875. ],
  3876. questions: [
  3877. {
  3878. question: "Which branch should I test?",
  3879. header: "Branch",
  3880. },
  3881. ],
  3882. schema: { toolName: "AskUserQuestion" },
  3883. });
  3884. });
  3885. it("maps nested ZCode Protocol projection context usage", () => {
  3886. expect(
  3887. zcodeSessionEventToZCodeStreamEvents({
  3888. event: {
  3889. eventId: "evt_projection_usage",
  3890. sessionId: "sess_1",
  3891. seq: 5,
  3892. timestamp: 5,
  3893. traceId: "trace_projection_usage",
  3894. type: "session.updated",
  3895. payload: {
  3896. projection: {
  3897. contextUsed: 64000,
  3898. contextWindow: 128000,
  3899. },
  3900. },
  3901. },
  3902. taskId: "sess_1",
  3903. }),
  3904. ).toEqual([
  3905. {
  3906. type: "usage_update",
  3907. taskId: "sess_1",
  3908. traceId: "trace_projection_usage",
  3909. used: 64000,
  3910. size: 128000,
  3911. cost: null,
  3912. },
  3913. ]);
  3914. });
  3915. it("does not emit legacy usage_update for zero context usage", () => {
  3916. expect(
  3917. zcodeSessionEventToZCodeStreamEvents({
  3918. event: {
  3919. eventId: "evt_zero_usage",
  3920. sessionId: "sess_1",
  3921. seq: 6,
  3922. timestamp: 6,
  3923. traceId: "trace_zero_usage",
  3924. type: "session.updated",
  3925. payload: {
  3926. contextUsed: 0,
  3927. contextWindow: 128000,
  3928. },
  3929. },
  3930. taskId: "sess_1",
  3931. }),
  3932. ).toEqual([]);
  3933. });
  3934. it("merges multi-round assistant messages from the same user turn into one", () => {
  3935. const baseAssistantInfo = {
  3936. sessionId: "sess_1",
  3937. role: "assistant" as const,
  3938. parentMessageId: "msg_user",
  3939. agent: "zcode-agent",
  3940. model,
  3941. path: { cwd: "/workspace/app", root: "/workspace/app" },
  3942. cost: 0,
  3943. tokens: {
  3944. input: 1,
  3945. output: 2,
  3946. reasoning: 3,
  3947. total: 6,
  3948. cache: { read: 0, write: 0 },
  3949. },
  3950. };
  3951. const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
  3952. ...createSnapshot(),
  3953. messages: [
  3954. {
  3955. info: {
  3956. messageId: "msg_user",
  3957. sessionId: "sess_1",
  3958. role: "user",
  3959. time: { created: 100 },
  3960. agent: "zcode-agent",
  3961. model,
  3962. },
  3963. parts: [
  3964. {
  3965. partId: "part_user",
  3966. sessionId: "sess_1",
  3967. messageId: "msg_user",
  3968. type: "text",
  3969. text: "do work",
  3970. },
  3971. ],
  3972. },
  3973. {
  3974. info: {
  3975. ...baseAssistantInfo,
  3976. messageId: "msg_round1",
  3977. time: { created: 200, completed: 1_200 },
  3978. },
  3979. parts: [
  3980. {
  3981. partId: "round1_text",
  3982. sessionId: "sess_1",
  3983. messageId: "msg_round1",
  3984. type: "text",
  3985. text: "calling ls ",
  3986. },
  3987. {
  3988. partId: "round1_tool",
  3989. sessionId: "sess_1",
  3990. messageId: "msg_round1",
  3991. type: "tool",
  3992. callId: "tool_1",
  3993. tool: "Bash",
  3994. state: {
  3995. status: "completed",
  3996. input: { command: "ls" },
  3997. output: "a b",
  3998. title: "Bash",
  3999. metadata: {},
  4000. startedAt: 300,
  4001. completedAt: 400,
  4002. },
  4003. },
  4004. ],
  4005. },
  4006. {
  4007. info: {
  4008. ...baseAssistantInfo,
  4009. messageId: "msg_round2",
  4010. parentMessageId: "msg_round1",
  4011. time: { created: 1_500, completed: 3_500 },
  4012. },
  4013. parts: [
  4014. {
  4015. partId: "round2_text",
  4016. sessionId: "sess_1",
  4017. messageId: "msg_round2",
  4018. type: "text",
  4019. text: "done",
  4020. },
  4021. {
  4022. partId: "round2_tool",
  4023. sessionId: "sess_1",
  4024. messageId: "msg_round2",
  4025. type: "tool",
  4026. callId: "tool_2",
  4027. tool: "Read",
  4028. state: {
  4029. status: "completed",
  4030. input: { path: "a" },
  4031. output: "hi",
  4032. title: "Read",
  4033. metadata: {},
  4034. startedAt: 1_600,
  4035. completedAt: 1_700,
  4036. },
  4037. },
  4038. ],
  4039. },
  4040. ],
  4041. });
  4042. expect(snapshot.messages).toHaveLength(2);
  4043. const merged = snapshot.messages[1]!;
  4044. expect(merged.role).toBe("assistant");
  4045. expect(merged.content).toBe("calling ls done");
  4046. expect(merged.timestamp).toBe(200);
  4047. // 整轮跨度 = round2.completed (3500) − round1.created (200)
  4048. expect(merged.durationMs).toBe(3_300);
  4049. expect(merged.tools).toHaveLength(2);
  4050. expect(merged.tools?.[0]?.toolName).toBe("Bash");
  4051. expect(merged.tools?.[1]?.toolName).toBe("Read");
  4052. expect(merged.parts).toEqual([
  4053. { type: "content", content: "calling ls " },
  4054. { type: "tool-call", toolIndex: 0 },
  4055. { type: "content", content: "done" },
  4056. { type: "tool-call", toolIndex: 1 },
  4057. ]);
  4058. expect(snapshot.messages[0]?.turnIndex).toBe(0);
  4059. expect(merged.turnIndex).toBe(0);
  4060. });
  4061. it("maps session events without routing through legacy task service", () => {
  4062. const state = {
  4063. streamedTurnKeys: new Set<string>(),
  4064. toolNameById: new Map<string, string>(),
  4065. };
  4066. const turnStartedEvent = {
  4067. eventId: "evt_start",
  4068. sessionId: "sess_1",
  4069. turnId: "turn_1",
  4070. seq: 0,
  4071. timestamp: 1,
  4072. traceId: "trace_session",
  4073. type: "turn.started",
  4074. payload: {
  4075. input: "hello",
  4076. turnNumber: 1,
  4077. inputId: "t-sess_1-run",
  4078. },
  4079. } satisfies ZCodeSessionEvent;
  4080. const streamingEvent = {
  4081. eventId: "evt_stream",
  4082. sessionId: "sess_1",
  4083. turnId: "turn_1",
  4084. seq: 1,
  4085. timestamp: 2,
  4086. traceId: "trace_session",
  4087. type: "session.updated",
  4088. payload: {
  4089. kind: "text_delta",
  4090. delta: "hel",
  4091. assistantMessageId: "msg_a",
  4092. },
  4093. } satisfies ZCodeSessionEvent;
  4094. const completeEvent = {
  4095. eventId: "evt_done",
  4096. sessionId: "sess_1",
  4097. turnId: "turn_1",
  4098. seq: 2,
  4099. timestamp: 3,
  4100. traceId: "trace_session",
  4101. type: "turn.completed",
  4102. payload: {
  4103. response: "hello",
  4104. tokenCount: 1,
  4105. toolCallCount: 0,
  4106. duration: 10,
  4107. inputId: "t-sess_1-run",
  4108. resultType: "success",
  4109. },
  4110. } satisfies ZCodeSessionEvent;
  4111. const toolEvent = {
  4112. eventId: "evt_tool",
  4113. sessionId: "sess_1",
  4114. turnId: "turn_1",
  4115. seq: 2,
  4116. timestamp: 3,
  4117. traceId: "trace_session",
  4118. type: "tool.updated",
  4119. payload: {
  4120. kind: "scheduled",
  4121. toolCallId: "call_1",
  4122. toolName: "Read",
  4123. input: { filePath: "/repo/app.ts" },
  4124. },
  4125. } satisfies ZCodeSessionEvent;
  4126. expect(
  4127. zcodeSessionEventToZCodeStreamEvents({
  4128. event: turnStartedEvent,
  4129. state,
  4130. taskId: "sess_1",
  4131. }),
  4132. ).toEqual([
  4133. {
  4134. type: "task_run_started",
  4135. taskId: "sess_1",
  4136. traceId: "t-sess_1-run",
  4137. inputId: "t-sess_1-run",
  4138. turnId: "turn_1",
  4139. startedAt: 1,
  4140. },
  4141. ]);
  4142. // 修复原因:turn.started 是首 token 前唯一可靠的运行态边界。
  4143. // projection 需要记录 active input,后续 chunk/tool/complete 才能归到同一轮 trace。
  4144. expect(state.activePromptInputIdBySession?.get("sess_1")).toBe("t-sess_1-run");
  4145. expect(
  4146. zcodeSessionEventToZCodeStreamEvents({
  4147. event: streamingEvent,
  4148. state,
  4149. taskId: "sess_1",
  4150. }),
  4151. ).toEqual([
  4152. {
  4153. type: "agent_message_chunk",
  4154. taskId: "sess_1",
  4155. traceId: "t-sess_1-run",
  4156. inputId: "t-sess_1-run",
  4157. messageId: "msg_a",
  4158. content: "hel",
  4159. },
  4160. ]);
  4161. expect(
  4162. zcodeSessionEventToZCodeStreamEvents({
  4163. event: {
  4164. ...streamingEvent,
  4165. eventId: "evt_parent_stream",
  4166. payload: {
  4167. kind: "text_delta",
  4168. delta: "child",
  4169. parentToolUseId: "call_parent",
  4170. },
  4171. },
  4172. state,
  4173. taskId: "sess_1",
  4174. }),
  4175. ).toEqual([
  4176. {
  4177. type: "agent_message_chunk",
  4178. taskId: "sess_1",
  4179. traceId: "t-sess_1-run",
  4180. inputId: "t-sess_1-run",
  4181. parentToolUseId: "call_parent",
  4182. content: "child",
  4183. },
  4184. ]);
  4185. expect(
  4186. zcodeSessionEventToZCodeStreamEvents({
  4187. event: toolEvent,
  4188. state,
  4189. taskId: "sess_1",
  4190. }),
  4191. ).toMatchObject([
  4192. {
  4193. type: "tool_call",
  4194. taskId: "sess_1",
  4195. traceId: "t-sess_1-run",
  4196. inputId: "t-sess_1-run",
  4197. toolId: "call_1",
  4198. toolName: "Read",
  4199. },
  4200. ]);
  4201. expect(
  4202. zcodeSessionEventToZCodeStreamEvents({
  4203. event: completeEvent,
  4204. state,
  4205. taskId: "sess_1",
  4206. }),
  4207. ).toEqual([
  4208. {
  4209. type: "task_complete",
  4210. taskId: "sess_1",
  4211. traceId: "t-sess_1-run",
  4212. inputId: "t-sess_1-run",
  4213. stopReason: "success",
  4214. usage: undefined,
  4215. },
  4216. ]);
  4217. expect(state.activePromptInputIdBySession?.get("sess_1")).toBeUndefined();
  4218. });
  4219. it("does not render conversation rewind command ack as an assistant chunk", () => {
  4220. const state: ZCodeSessionEventProjectionState = {
  4221. activePromptInputIdBySession: new Map<string, string>(),
  4222. streamedTurnKeys: new Set<string>(),
  4223. };
  4224. const started = {
  4225. eventId: "evt_rewind_start",
  4226. sessionId: "sess_1",
  4227. turnId: "turn_rewind",
  4228. seq: 0,
  4229. timestamp: 10,
  4230. traceId: "trace_rewind",
  4231. type: "turn.started",
  4232. payload: {
  4233. input: "/rewind conversation msg_old_user",
  4234. inputId: "input_rewind",
  4235. turnNumber: 2,
  4236. },
  4237. } satisfies ZCodeSessionEvent;
  4238. const completed = {
  4239. eventId: "evt_rewind_done",
  4240. sessionId: "sess_1",
  4241. turnId: "turn_rewind",
  4242. seq: 1,
  4243. timestamp: 11,
  4244. traceId: "trace_rewind",
  4245. type: "turn.completed",
  4246. payload: {
  4247. response: "Rewound conversation to before message msg_old_user.",
  4248. inputId: "input_rewind",
  4249. resultType: "success",
  4250. },
  4251. } satisfies ZCodeSessionEvent;
  4252. expect(
  4253. zcodeSessionEventToZCodeStreamEvents({
  4254. event: started,
  4255. state,
  4256. taskId: "sess_1",
  4257. }),
  4258. ).toMatchObject([{ type: "task_run_started" }]);
  4259. expect(state.rewindControlTurnKeys?.has("sess_1:turn_rewind")).toBe(true);
  4260. expect(
  4261. zcodeSessionEventToZCodeStreamEvents({
  4262. event: completed,
  4263. state,
  4264. taskId: "sess_1",
  4265. }),
  4266. ).toEqual([
  4267. {
  4268. type: "task_complete",
  4269. taskId: "sess_1",
  4270. traceId: "input_rewind",
  4271. inputId: "input_rewind",
  4272. stopReason: "success",
  4273. usage: undefined,
  4274. },
  4275. ]);
  4276. expect(state.rewindControlTurnKeys?.has("sess_1:turn_rewind")).toBe(false);
  4277. });
  4278. it("maps denied tool permissions to failed tool updates", () => {
  4279. const state = {
  4280. activePromptInputIdBySession: new Map([["sess_1", "input_1"]]),
  4281. toolNameById: new Map([["call_bash", "Bash"]]),
  4282. };
  4283. const payload = {
  4284. toolCallId: "call_bash",
  4285. toolName: "Bash",
  4286. decision: "deny",
  4287. reason: "Plan mode only allows read-only, non-destructive tools",
  4288. };
  4289. expect(
  4290. zcodeSessionEventToZCodeStreamEvents({
  4291. taskId: "sess_1",
  4292. state,
  4293. event: {
  4294. eventId: "evt_permission_denied",
  4295. sessionId: "sess_1",
  4296. turnId: "turn_1",
  4297. seq: 4,
  4298. timestamp: 4,
  4299. traceId: "trace_session",
  4300. type: "permission.resolved",
  4301. payload,
  4302. } satisfies ZCodeSessionEvent,
  4303. }),
  4304. ).toEqual([
  4305. {
  4306. type: "permission_response",
  4307. taskId: "sess_1",
  4308. traceId: "input_1",
  4309. inputId: "input_1",
  4310. requestId: "call_bash",
  4311. optionId: "deny",
  4312. response: { decision: "deny" },
  4313. },
  4314. {
  4315. type: "tool_call_update",
  4316. taskId: "sess_1",
  4317. traceId: "input_1",
  4318. inputId: "input_1",
  4319. toolId: "call_bash",
  4320. parentToolUseId: null,
  4321. status: "failed",
  4322. toolName: "Bash",
  4323. kind: "Bash",
  4324. title: "Bash",
  4325. error: "Plan mode only allows read-only, non-destructive tools",
  4326. raw: payload,
  4327. },
  4328. ]);
  4329. });
  4330. it("remembers tool names from started events for later result-only updates", () => {
  4331. const state = {
  4332. activePromptInputIdBySession: new Map([["sess_1", "input_1"]]),
  4333. toolNameById: new Map<string, string>(),
  4334. } satisfies ZCodeSessionEventProjectionState;
  4335. const startedPayload = {
  4336. toolCallId: "tool_subagent_agent_1_call_search",
  4337. parentToolCallId: "call_parent_agent",
  4338. source: "subagent",
  4339. agentId: "agent_1",
  4340. toolName: "WebSearch",
  4341. };
  4342. const resultPayload = {
  4343. toolCallId: "tool_subagent_agent_1_call_search",
  4344. parentToolCallId: "call_parent_agent",
  4345. source: "subagent",
  4346. agentId: "agent_1",
  4347. result: {
  4348. success: true,
  4349. content: "Web search results for query: test",
  4350. },
  4351. };
  4352. expect(
  4353. zcodeSessionEventToZCodeStreamEvents({
  4354. taskId: "sess_1",
  4355. state,
  4356. event: {
  4357. eventId: "evt_tool_started",
  4358. sessionId: "sess_1",
  4359. turnId: "turn_1",
  4360. seq: 1,
  4361. timestamp: 1,
  4362. traceId: "trace_session",
  4363. type: "tool.updated",
  4364. payload: startedPayload,
  4365. } satisfies ZCodeSessionEvent,
  4366. }),
  4367. ).toEqual([
  4368. {
  4369. type: "tool_call_update",
  4370. taskId: "sess_1",
  4371. traceId: "input_1",
  4372. inputId: "input_1",
  4373. toolId: "tool_subagent_agent_1_call_search",
  4374. parentToolUseId: "call_parent_agent",
  4375. toolName: "WebSearch",
  4376. kind: "WebSearch",
  4377. title: "WebSearch",
  4378. status: "in_progress",
  4379. raw: startedPayload,
  4380. },
  4381. ]);
  4382. expect(state.toolNameById.get("tool_subagent_agent_1_call_search")).toBe("WebSearch");
  4383. expect(
  4384. zcodeSessionEventToZCodeStreamEvents({
  4385. taskId: "sess_1",
  4386. state,
  4387. event: {
  4388. eventId: "evt_tool_result",
  4389. sessionId: "sess_1",
  4390. turnId: "turn_1",
  4391. seq: 2,
  4392. timestamp: 2,
  4393. traceId: "trace_session",
  4394. type: "tool.updated",
  4395. payload: resultPayload,
  4396. } satisfies ZCodeSessionEvent,
  4397. }),
  4398. ).toEqual([
  4399. {
  4400. type: "tool_call_update",
  4401. taskId: "sess_1",
  4402. traceId: "input_1",
  4403. inputId: "input_1",
  4404. toolId: "tool_subagent_agent_1_call_search",
  4405. parentToolUseId: "call_parent_agent",
  4406. toolName: "WebSearch",
  4407. kind: "WebSearch",
  4408. title: "WebSearch",
  4409. status: "completed",
  4410. content: "Web search results for query: test",
  4411. error: undefined,
  4412. raw: resultPayload,
  4413. },
  4414. ]);
  4415. });
  4416. it("remembers tool metadata for later result-only updates across tool renderers", () => {
  4417. const cases = [
  4418. {
  4419. input: { command: "curl -s https://example.com" },
  4420. toolName: "Bash",
  4421. },
  4422. {
  4423. input: { file_path: "package.json" },
  4424. toolName: "Read",
  4425. },
  4426. {
  4427. input: { search_query: "2026 World Cup winner odds" },
  4428. toolName: "WebSearch",
  4429. },
  4430. {
  4431. input: { path: "src", pattern: "TODO" },
  4432. toolName: "Grep",
  4433. },
  4434. ] as const;
  4435. for (const [index, testCase] of cases.entries()) {
  4436. const state = {
  4437. activePromptInputIdBySession: new Map([["sess_1", "input_1"]]),
  4438. streamingToolInputById: new Map(),
  4439. toolNameById: new Map<string, string>(),
  4440. } satisfies ZCodeSessionEventProjectionState;
  4441. const toolCallId = `tool_subagent_agent_1_call_${testCase.toolName.toLowerCase()}`;
  4442. const scheduledPayload = {
  4443. toolCallId,
  4444. parentToolCallId: "call_parent_agent",
  4445. source: "subagent",
  4446. agentId: "agent_1",
  4447. toolName: testCase.toolName,
  4448. input: testCase.input,
  4449. };
  4450. const resultPayload = {
  4451. toolCallId,
  4452. parentToolCallId: "call_parent_agent",
  4453. source: "subagent",
  4454. agentId: "agent_1",
  4455. result: {
  4456. success: true,
  4457. content: "ok",
  4458. },
  4459. };
  4460. expect(
  4461. zcodeSessionEventToZCodeStreamEvents({
  4462. taskId: "sess_1",
  4463. state,
  4464. event: {
  4465. eventId: `evt_tool_scheduled_${index}`,
  4466. sessionId: "sess_1",
  4467. turnId: "turn_1",
  4468. seq: index * 2 + 1,
  4469. timestamp: index * 2 + 1,
  4470. traceId: "trace_session",
  4471. type: "tool.updated",
  4472. payload: scheduledPayload,
  4473. } satisfies ZCodeSessionEvent,
  4474. }),
  4475. ).toEqual([
  4476. expect.objectContaining({
  4477. type: "tool_call",
  4478. toolId: toolCallId,
  4479. input: testCase.input,
  4480. toolName: testCase.toolName,
  4481. kind: testCase.toolName,
  4482. title: testCase.toolName,
  4483. }),
  4484. ]);
  4485. expect(
  4486. zcodeSessionEventToZCodeStreamEvents({
  4487. taskId: "sess_1",
  4488. state,
  4489. event: {
  4490. eventId: `evt_tool_result_${index}`,
  4491. sessionId: "sess_1",
  4492. turnId: "turn_1",
  4493. seq: index * 2 + 2,
  4494. timestamp: index * 2 + 2,
  4495. traceId: "trace_session",
  4496. type: "tool.updated",
  4497. payload: resultPayload,
  4498. } satisfies ZCodeSessionEvent,
  4499. }),
  4500. ).toEqual([
  4501. expect.objectContaining({
  4502. type: "tool_call_update",
  4503. toolId: toolCallId,
  4504. parentToolUseId: "call_parent_agent",
  4505. toolName: testCase.toolName,
  4506. kind: testCase.toolName,
  4507. title: testCase.toolName,
  4508. input: testCase.input,
  4509. status: "completed",
  4510. content: "ok",
  4511. raw: resultPayload,
  4512. }),
  4513. ]);
  4514. }
  4515. });
  4516. it("preserves child tool metadata across progress and parent turn completion", () => {
  4517. const state = {
  4518. activePromptInputIdBySession: new Map([["sess_1", "input_1"]]),
  4519. streamingToolInputById: new Map(),
  4520. toolNameById: new Map<string, string>(),
  4521. } satisfies ZCodeSessionEventProjectionState;
  4522. const scheduledPayload = {
  4523. toolCallId: "tool_subagent_agent_1_call_bash",
  4524. parentToolCallId: "call_parent_agent",
  4525. source: "subagent",
  4526. agentId: "agent_1",
  4527. toolName: "Bash",
  4528. input: {
  4529. command: "printf done",
  4530. description: "Print completion marker",
  4531. },
  4532. };
  4533. const progressPayload = {
  4534. toolCallId: scheduledPayload.toolCallId,
  4535. parentToolCallId: scheduledPayload.parentToolCallId,
  4536. source: "subagent",
  4537. agentId: "agent_1",
  4538. toolName: "Bash",
  4539. kind: "started",
  4540. };
  4541. const project = (event: ZCodeSessionEvent) =>
  4542. zcodeSessionEventToZCodeStreamEvents({
  4543. taskId: "sess_1",
  4544. state,
  4545. event,
  4546. });
  4547. project({
  4548. eventId: "evt_tool_scheduled",
  4549. sessionId: "sess_1",
  4550. turnId: "turn_parent",
  4551. seq: 1,
  4552. timestamp: 1,
  4553. traceId: "trace_session",
  4554. type: "tool.updated",
  4555. payload: scheduledPayload,
  4556. });
  4557. expect(
  4558. project({
  4559. eventId: "evt_tool_progress",
  4560. sessionId: "sess_1",
  4561. turnId: "turn_parent",
  4562. seq: 2,
  4563. timestamp: 2,
  4564. traceId: "trace_session",
  4565. type: "tool.updated",
  4566. payload: progressPayload,
  4567. }),
  4568. ).toEqual([
  4569. expect.objectContaining({
  4570. type: "tool_call_update",
  4571. toolId: scheduledPayload.toolCallId,
  4572. input: scheduledPayload.input,
  4573. status: "in_progress",
  4574. }),
  4575. ]);
  4576. project({
  4577. eventId: "evt_parent_completed",
  4578. sessionId: "sess_1",
  4579. turnId: "turn_parent",
  4580. seq: 3,
  4581. timestamp: 3,
  4582. traceId: "trace_session",
  4583. type: "turn.completed",
  4584. payload: {
  4585. inputId: "input_1",
  4586. resultType: "success",
  4587. },
  4588. });
  4589. // parent turn 已完成后,background child tool 仍可能继续接收输入流。
  4590. state.streamingToolInputById?.set(scheduledPayload.toolCallId, {
  4591. rawInput: JSON.stringify(scheduledPayload.input),
  4592. });
  4593. expect(
  4594. project({
  4595. eventId: "evt_tool_result",
  4596. sessionId: "sess_1",
  4597. turnId: "turn_child",
  4598. seq: 4,
  4599. timestamp: 4,
  4600. traceId: "trace_session",
  4601. type: "tool.updated",
  4602. payload: {
  4603. toolCallId: scheduledPayload.toolCallId,
  4604. parentToolCallId: scheduledPayload.parentToolCallId,
  4605. source: "subagent",
  4606. agentId: "agent_1",
  4607. result: {
  4608. success: true,
  4609. content: "done",
  4610. },
  4611. },
  4612. }),
  4613. ).toEqual([
  4614. expect.objectContaining({
  4615. type: "tool_call_update",
  4616. toolId: scheduledPayload.toolCallId,
  4617. toolName: "Bash",
  4618. input: scheduledPayload.input,
  4619. status: "completed",
  4620. content: "done",
  4621. }),
  4622. ]);
  4623. expect(state.streamingToolInputById?.has(scheduledPayload.toolCallId)).toBe(false);
  4624. expect(state.completeToolInputById?.has(scheduledPayload.toolCallId)).toBe(false);
  4625. expect(state.toolNameById?.has(scheduledPayload.toolCallId)).toBe(false);
  4626. });
  4627. it("keeps AskUserQuestion permission responses on the elicitation path", () => {
  4628. const state = {
  4629. activePromptInputIdBySession: new Map([["sess_1", "input_1"]]),
  4630. toolNameById: new Map([["call_ask", "AskUserQuestion"]]),
  4631. };
  4632. expect(
  4633. zcodeSessionEventToZCodeStreamEvents({
  4634. taskId: "sess_1",
  4635. state,
  4636. event: {
  4637. eventId: "evt_ask_declined",
  4638. sessionId: "sess_1",
  4639. turnId: "turn_1",
  4640. seq: 5,
  4641. timestamp: 5,
  4642. traceId: "trace_session",
  4643. type: "permission.resolved",
  4644. payload: {
  4645. toolCallId: "call_ask",
  4646. decision: "deny",
  4647. reason: "User declined",
  4648. },
  4649. } satisfies ZCodeSessionEvent,
  4650. }),
  4651. ).toEqual([
  4652. {
  4653. type: "elicitation_response",
  4654. taskId: "sess_1",
  4655. traceId: "input_1",
  4656. inputId: "input_1",
  4657. requestId: "call_ask",
  4658. action: "decline",
  4659. },
  4660. ]);
  4661. });
  4662. it("keeps ExitPlanMode permission requests on the elicitation path", () => {
  4663. const state = {
  4664. activePromptInputIdBySession: new Map([["sess_1", "input_1"]]),
  4665. toolNameById: new Map<string, string>(),
  4666. };
  4667. expect(
  4668. zcodeSessionEventToZCodeStreamEvents({
  4669. taskId: "sess_1",
  4670. state,
  4671. event: {
  4672. eventId: "evt_exit_plan_requested",
  4673. sessionId: "sess_1",
  4674. turnId: "turn_1",
  4675. seq: 4,
  4676. timestamp: 4,
  4677. traceId: "trace_session",
  4678. type: "permission.requested",
  4679. payload: {
  4680. requestId: "exit_plan_1",
  4681. toolCallId: "call_exit_plan",
  4682. toolName: "ExitPlanMode",
  4683. reason: "Exit plan mode",
  4684. },
  4685. } satisfies ZCodeSessionEvent,
  4686. }),
  4687. ).toEqual([]);
  4688. expect(state.toolNameById.get("call_exit_plan")).toBe("ExitPlanMode");
  4689. });
  4690. it("keeps ExitPlanMode permission responses on the elicitation path", () => {
  4691. const state = {
  4692. activePromptInputIdBySession: new Map([["sess_1", "input_1"]]),
  4693. toolNameById: new Map([["call_exit_plan", "ExitPlanMode"]]),
  4694. };
  4695. expect(
  4696. zcodeSessionEventToZCodeStreamEvents({
  4697. taskId: "sess_1",
  4698. state,
  4699. event: {
  4700. eventId: "evt_exit_plan_denied",
  4701. sessionId: "sess_1",
  4702. turnId: "turn_1",
  4703. seq: 5,
  4704. timestamp: 5,
  4705. traceId: "trace_session",
  4706. type: "permission.resolved",
  4707. payload: {
  4708. toolCallId: "call_exit_plan",
  4709. decision: "deny",
  4710. reason: "Please add tests first",
  4711. },
  4712. } satisfies ZCodeSessionEvent,
  4713. }),
  4714. ).toEqual([
  4715. {
  4716. type: "elicitation_response",
  4717. taskId: "sess_1",
  4718. traceId: "input_1",
  4719. inputId: "input_1",
  4720. requestId: "call_exit_plan",
  4721. action: "decline",
  4722. },
  4723. ]);
  4724. });
  4725. it("maps model-only goal continuation turn starts to goal iteration boundaries", () => {
  4726. const events = zcodeSessionEventToZCodeStreamEvents({
  4727. taskId: "task-goal",
  4728. event: {
  4729. eventId: "evt_goal_start",
  4730. sessionId: "sess_goal",
  4731. turnId: "turn_goal_2",
  4732. seq: 10,
  4733. timestamp: 1_234,
  4734. traceId: "trace_goal",
  4735. type: "turn.started",
  4736. payload: {
  4737. input:
  4738. "<system-reminder>\nContinue working toward the active session goal.\n</system-reminder>",
  4739. inputId: "input-goal",
  4740. inputSource: "goal-continuation",
  4741. inputVisibility: "model-only",
  4742. targetId: "goal-1",
  4743. turnNumber: 2,
  4744. },
  4745. },
  4746. });
  4747. expect(events).toEqual([
  4748. {
  4749. type: "task_run_started",
  4750. taskId: "task-goal",
  4751. traceId: "input-goal",
  4752. inputId: "input-goal",
  4753. turnId: "turn_goal_2",
  4754. startedAt: 1_234,
  4755. },
  4756. {
  4757. type: "goal_iteration_started",
  4758. taskId: "task-goal",
  4759. traceId: "input-goal",
  4760. inputId: "input-goal",
  4761. turnId: "turn_goal_2",
  4762. targetId: "goal-1",
  4763. startedAt: 1_234,
  4764. },
  4765. ]);
  4766. });
  4767. it("maps subagent tool updates into parented tool calls and agent activity", () => {
  4768. const state = {
  4769. streamedTurnKeys: new Set<string>(),
  4770. toolNameById: new Map<string, string>(),
  4771. };
  4772. const parentToolCall = {
  4773. eventId: "evt_parent_agent",
  4774. sessionId: "sess_1",
  4775. turnId: "turn_1",
  4776. seq: 10,
  4777. timestamp: 10,
  4778. traceId: "trace_session",
  4779. type: "tool.updated",
  4780. payload: {
  4781. kind: "scheduled",
  4782. toolCallId: "call_parent_agent",
  4783. toolName: "Agent",
  4784. input: {
  4785. description: "Inspect workspace",
  4786. prompt: "Find the project shape",
  4787. },
  4788. },
  4789. } satisfies ZCodeSessionEvent;
  4790. const subagentToolCall = {
  4791. eventId: "evt_subagent_tool",
  4792. sessionId: "sess_1",
  4793. turnId: "turn_1",
  4794. seq: 11,
  4795. timestamp: 11,
  4796. traceId: "trace_session",
  4797. type: "tool.updated",
  4798. payload: {
  4799. kind: "scheduled",
  4800. toolCallId: "tool_subagent_agent_1_call_1",
  4801. toolName: "Read",
  4802. input: { filePath: "/workspace/package.json" },
  4803. parentToolCallId: "call_parent_agent",
  4804. source: "subagent",
  4805. agentId: "agent_1",
  4806. agentType: "Explore",
  4807. childSessionId: "sess_subagent_agent_1",
  4808. childToolCallId: "call_1",
  4809. description: "Inspect workspace",
  4810. },
  4811. } satisfies ZCodeSessionEvent;
  4812. const parentToolResult = {
  4813. eventId: "evt_parent_agent_result",
  4814. sessionId: "sess_1",
  4815. turnId: "turn_1",
  4816. seq: 12,
  4817. timestamp: 12,
  4818. traceId: "trace_session",
  4819. type: "tool.updated",
  4820. payload: {
  4821. kind: "result",
  4822. toolCallId: "call_parent_agent",
  4823. duration: 123,
  4824. result: {
  4825. success: true,
  4826. content: JSON.stringify({
  4827. status: "completed",
  4828. agentId: "agent_1",
  4829. agentType: "Explore",
  4830. content: [{ type: "text", text: "Subagent summary" }],
  4831. }),
  4832. },
  4833. },
  4834. } satisfies ZCodeSessionEvent;
  4835. expect(
  4836. zcodeSessionEventToZCodeStreamEvents({
  4837. event: parentToolCall,
  4838. state,
  4839. taskId: "sess_1",
  4840. }),
  4841. ).toMatchObject([
  4842. {
  4843. type: "tool_call",
  4844. toolId: "call_parent_agent",
  4845. toolName: "Agent",
  4846. parentToolUseId: null,
  4847. },
  4848. ]);
  4849. expect(
  4850. zcodeSessionEventToZCodeStreamEvents({
  4851. event: subagentToolCall,
  4852. state,
  4853. taskId: "sess_1",
  4854. }),
  4855. ).toMatchObject([
  4856. {
  4857. type: "tool_call",
  4858. toolId: "tool_subagent_agent_1_call_1",
  4859. toolName: "Read",
  4860. parentToolUseId: "call_parent_agent",
  4861. },
  4862. ]);
  4863. expect(
  4864. zcodeSessionEventToZCodeStreamEvents({
  4865. event: parentToolResult,
  4866. state,
  4867. taskId: "sess_1",
  4868. }),
  4869. ).toMatchObject([
  4870. {
  4871. type: "tool_call_update",
  4872. toolId: "call_parent_agent",
  4873. toolName: "Agent",
  4874. content: {
  4875. kind: "agent_activity",
  4876. content: "Subagent summary",
  4877. },
  4878. },
  4879. ]);
  4880. });
  4881. it("keeps background Agent launch acknowledgements in progress", () => {
  4882. const state = {
  4883. streamedTurnKeys: new Set<string>(),
  4884. toolNameById: new Map<string, string>(),
  4885. };
  4886. zcodeSessionEventToZCodeStreamEvents({
  4887. event: {
  4888. eventId: "evt_parent_agent",
  4889. sessionId: "sess_1",
  4890. turnId: "turn_1",
  4891. seq: 10,
  4892. timestamp: 10,
  4893. traceId: "trace_session",
  4894. type: "tool.updated",
  4895. payload: {
  4896. kind: "scheduled",
  4897. toolCallId: "call_parent_agent",
  4898. toolName: "Agent",
  4899. input: {
  4900. description: "Inspect workspace",
  4901. prompt: "Find the project shape",
  4902. run_in_background: true,
  4903. },
  4904. },
  4905. } satisfies ZCodeSessionEvent,
  4906. state,
  4907. taskId: "sess_1",
  4908. });
  4909. const events = zcodeSessionEventToZCodeStreamEvents({
  4910. event: {
  4911. eventId: "evt_parent_agent_result",
  4912. sessionId: "sess_1",
  4913. turnId: "turn_1",
  4914. seq: 11,
  4915. timestamp: 11,
  4916. traceId: "trace_session",
  4917. type: "tool.updated",
  4918. payload: {
  4919. kind: "result",
  4920. toolCallId: "call_parent_agent",
  4921. duration: 4,
  4922. result: {
  4923. success: true,
  4924. content: [
  4925. 'Agent Explore task "Inspect workspace" started in background.',
  4926. "agentId: agent_1",
  4927. "backgroundTaskId: agent_1",
  4928. "Runtime will wait for this background Agent before completing the current turn.",
  4929. ].join("\n"),
  4930. },
  4931. },
  4932. } satisfies ZCodeSessionEvent,
  4933. state,
  4934. taskId: "sess_1",
  4935. });
  4936. expect(events).toMatchObject([
  4937. {
  4938. type: "tool_call_update",
  4939. toolId: "call_parent_agent",
  4940. toolName: "Agent",
  4941. status: "in_progress",
  4942. },
  4943. ]);
  4944. });
  4945. it("keeps previous and current async Task launch acknowledgements in progress", () => {
  4946. const state = {
  4947. streamedTurnKeys: new Set<string>(),
  4948. toolNameById: new Map<string, string>(),
  4949. };
  4950. zcodeSessionEventToZCodeStreamEvents({
  4951. event: {
  4952. eventId: "evt_parent_task",
  4953. sessionId: "sess_1",
  4954. turnId: "turn_1",
  4955. seq: 10,
  4956. timestamp: 10,
  4957. traceId: "trace_session",
  4958. type: "tool.updated",
  4959. payload: {
  4960. kind: "scheduled",
  4961. toolCallId: "call_parent_task",
  4962. toolName: "Task",
  4963. input: {
  4964. description: "Inspect workspace",
  4965. prompt: "Find the project shape",
  4966. },
  4967. },
  4968. } satisfies ZCodeSessionEvent,
  4969. state,
  4970. taskId: "sess_1",
  4971. });
  4972. const acknowledgementContents = [
  4973. [
  4974. 'Agent general-purpose task "Inspect workspace" started in background.',
  4975. "agentId: agent_1",
  4976. "outputFile: /tmp/agent_1/output.txt",
  4977. "You will be notified when the Agent completes.",
  4978. ].join("\n"),
  4979. [
  4980. "Async agent launched successfully.",
  4981. "agentId: agent_1 (internal ID - do not mention to user. Use SendMessage with to: 'agent_1' to continue this agent.)",
  4982. "The agent is working in the background. You will be notified automatically when it completes.",
  4983. "output_file: /tmp/agent_1/output.txt",
  4984. "Do NOT Read or tail this file via the shell tool.",
  4985. ].join("\n"),
  4986. ];
  4987. for (const [index, content] of acknowledgementContents.entries()) {
  4988. const events = zcodeSessionEventToZCodeStreamEvents({
  4989. event: {
  4990. eventId: `evt_parent_task_result_${index}`,
  4991. sessionId: "sess_1",
  4992. turnId: "turn_1",
  4993. seq: 11 + index,
  4994. timestamp: 11 + index,
  4995. traceId: "trace_session",
  4996. type: "tool.updated",
  4997. payload: {
  4998. kind: "result",
  4999. toolCallId: "call_parent_task",
  5000. duration: 4,
  5001. result: {
  5002. success: true,
  5003. content,
  5004. },
  5005. },
  5006. } satisfies ZCodeSessionEvent,
  5007. state,
  5008. taskId: "sess_1",
  5009. });
  5010. expect(events).toMatchObject([
  5011. {
  5012. type: "tool_call_update",
  5013. toolId: "call_parent_task",
  5014. toolName: "Task",
  5015. status: "in_progress",
  5016. },
  5017. ]);
  5018. }
  5019. });
  5020. it("does not project subagent TodoWrite updates as the main runtime plan", () => {
  5021. const state = {
  5022. streamedTurnKeys: new Set<string>(),
  5023. toolNameById: new Map<string, string>(),
  5024. };
  5025. const mainTodoCall = {
  5026. eventId: "evt_main_todo",
  5027. sessionId: "sess_1",
  5028. turnId: "turn_1",
  5029. seq: 20,
  5030. timestamp: 20,
  5031. traceId: "trace_session",
  5032. type: "tool.updated",
  5033. payload: {
  5034. kind: "scheduled",
  5035. toolCallId: "call_main_todo",
  5036. toolName: "TodoWrite",
  5037. input: {
  5038. todos: [
  5039. { content: "Main inspect logs", status: "completed" },
  5040. { content: "Main patch projection", status: "in_progress" },
  5041. ],
  5042. },
  5043. },
  5044. } satisfies ZCodeSessionEvent;
  5045. const subagentTodoCall = {
  5046. eventId: "evt_subagent_todo",
  5047. sessionId: "sess_1",
  5048. turnId: "turn_1",
  5049. seq: 21,
  5050. timestamp: 21,
  5051. traceId: "trace_session",
  5052. type: "tool.updated",
  5053. payload: {
  5054. kind: "scheduled",
  5055. toolCallId: "tool_subagent_agent_1_call_todo",
  5056. toolName: "TodoWrite",
  5057. input: {
  5058. todos: [
  5059. { content: "Subagent search market", status: "in_progress" },
  5060. { content: "Subagent summarize sources", status: "pending" },
  5061. ],
  5062. },
  5063. parentToolCallId: "call_parent_agent",
  5064. source: "subagent",
  5065. agentId: "agent_1",
  5066. agentType: "Explore",
  5067. childSessionId: "sess_subagent_agent_1",
  5068. childToolCallId: "call_todo",
  5069. description: "Inspect workspace",
  5070. },
  5071. } satisfies ZCodeSessionEvent;
  5072. const subagentTodoResult = {
  5073. eventId: "evt_subagent_todo_result",
  5074. sessionId: "sess_1",
  5075. turnId: "turn_1",
  5076. seq: 22,
  5077. timestamp: 22,
  5078. traceId: "trace_session",
  5079. type: "tool.updated",
  5080. payload: {
  5081. kind: "result",
  5082. toolCallId: "tool_subagent_agent_1_call_todo",
  5083. result: {
  5084. success: true,
  5085. content: JSON.stringify({
  5086. todos: [
  5087. { content: "Subagent search market", status: "completed" },
  5088. { content: "Subagent summarize sources", status: "in_progress" },
  5089. ],
  5090. }),
  5091. },
  5092. parentToolCallId: "call_parent_agent",
  5093. source: "subagent",
  5094. agentId: "agent_1",
  5095. agentType: "Explore",
  5096. childSessionId: "sess_subagent_agent_1",
  5097. childToolCallId: "call_todo",
  5098. description: "Inspect workspace",
  5099. },
  5100. } satisfies ZCodeSessionEvent;
  5101. expect(
  5102. zcodeSessionEventToZCodeStreamEvents({
  5103. event: mainTodoCall,
  5104. state,
  5105. taskId: "sess_1",
  5106. }).map((event) => event.type),
  5107. ).toEqual(["tool_call", "plan"]);
  5108. expect(
  5109. zcodeSessionEventToZCodeStreamEvents({
  5110. event: subagentTodoCall,
  5111. state,
  5112. taskId: "sess_1",
  5113. }),
  5114. ).toMatchObject([
  5115. {
  5116. type: "tool_call",
  5117. toolId: "tool_subagent_agent_1_call_todo",
  5118. parentToolUseId: "call_parent_agent",
  5119. },
  5120. ]);
  5121. expect(
  5122. zcodeSessionEventToZCodeStreamEvents({
  5123. event: subagentTodoResult,
  5124. state,
  5125. taskId: "sess_1",
  5126. }),
  5127. ).toMatchObject([
  5128. {
  5129. type: "tool_call_update",
  5130. toolId: "tool_subagent_agent_1_call_todo",
  5131. parentToolUseId: "call_parent_agent",
  5132. },
  5133. ]);
  5134. });
  5135. it("keeps per-prompt inputId correlation scoped by session", () => {
  5136. const state = {
  5137. streamedTurnKeys: new Set<string>(),
  5138. toolNameById: new Map<string, string>(),
  5139. };
  5140. zcodeSessionEventToZCodeStreamEvents({
  5141. event: {
  5142. eventId: "evt_start",
  5143. sessionId: "sess_1",
  5144. turnId: "turn_1",
  5145. seq: 0,
  5146. timestamp: 1,
  5147. traceId: "trace_session_1",
  5148. type: "turn.started",
  5149. payload: {
  5150. input: "hello",
  5151. turnNumber: 1,
  5152. inputId: "t-sess_1-run",
  5153. },
  5154. },
  5155. state,
  5156. taskId: "sess_1",
  5157. });
  5158. expect(
  5159. zcodeSessionEventToZCodeStreamEvents({
  5160. event: {
  5161. eventId: "evt_stream_other",
  5162. sessionId: "sess_2",
  5163. turnId: "turn_2",
  5164. seq: 1,
  5165. timestamp: 2,
  5166. traceId: "trace_session_2",
  5167. type: "session.updated",
  5168. payload: {
  5169. kind: "text_delta",
  5170. delta: "other",
  5171. assistantMessageId: "msg_b",
  5172. },
  5173. },
  5174. state,
  5175. taskId: "sess_2",
  5176. }),
  5177. ).toEqual([
  5178. {
  5179. type: "agent_message_chunk",
  5180. taskId: "sess_2",
  5181. traceId: "trace_session_2",
  5182. messageId: "msg_b",
  5183. content: "other",
  5184. },
  5185. ]);
  5186. });
  5187. it("projects compact lifecycle payloads to context compaction timeline chunks", () => {
  5188. const state = {
  5189. activePromptInputIdBySession: new Map([["sess_1", "input-compact"]]),
  5190. streamedTurnKeys: new Set<string>(),
  5191. toolNameById: new Map<string, string>(),
  5192. };
  5193. const events = zcodeSessionEventToZCodeStreamEvents({
  5194. event: {
  5195. eventId: "evt_compact_started",
  5196. sessionId: "sess_1",
  5197. turnId: "turn_compact",
  5198. seq: 1,
  5199. timestamp: 2,
  5200. traceId: "trace_compact",
  5201. type: "session.updated",
  5202. payload: {
  5203. operationId: "cmp-1",
  5204. messageId: "msg-compact-1",
  5205. status: "started",
  5206. trigger: "manual",
  5207. display: "separator",
  5208. preCompactTokenCount: 1200,
  5209. startedAt: 100,
  5210. },
  5211. } satisfies ZCodeSessionEvent,
  5212. state,
  5213. taskId: "sess_1",
  5214. });
  5215. expect(events).toEqual([
  5216. {
  5217. type: "agent_message_chunk",
  5218. taskId: "sess_1",
  5219. traceId: "input-compact",
  5220. inputId: "input-compact",
  5221. messageId: "msg-compact-1",
  5222. content: "",
  5223. zcodeTimeline: {
  5224. version: 1,
  5225. kind: "synthetic",
  5226. type: "context_compaction",
  5227. operationId: "cmp-1",
  5228. status: "started",
  5229. trigger: "manual",
  5230. display: "separator",
  5231. inputId: "input-compact",
  5232. preCompactTokenCount: 1200,
  5233. startedAt: 100,
  5234. },
  5235. },
  5236. ]);
  5237. });
  5238. it("projects compact retry payloads with attempt metadata", () => {
  5239. const state = {
  5240. activePromptInputIdBySession: new Map([["sess_1", "input-compact"]]),
  5241. streamedTurnKeys: new Set<string>(),
  5242. toolNameById: new Map<string, string>(),
  5243. };
  5244. const events = zcodeSessionEventToZCodeStreamEvents({
  5245. event: {
  5246. eventId: "evt_compact_retrying",
  5247. sessionId: "sess_1",
  5248. turnId: "turn_compact",
  5249. seq: 2,
  5250. timestamp: 3,
  5251. traceId: "trace_compact",
  5252. type: "session.updated",
  5253. payload: {
  5254. operationId: "cmp-1",
  5255. messageId: "msg-compact-1",
  5256. status: "retrying",
  5257. trigger: "auto",
  5258. display: "separator",
  5259. attempt: 2,
  5260. maxAttempts: 3,
  5261. reason: "Failed to generate compact summary",
  5262. },
  5263. } satisfies ZCodeSessionEvent,
  5264. state,
  5265. taskId: "sess_1",
  5266. });
  5267. expect(events[0]).toMatchObject({
  5268. type: "agent_message_chunk",
  5269. taskId: "sess_1",
  5270. traceId: "input-compact",
  5271. inputId: "input-compact",
  5272. messageId: "msg-compact-1",
  5273. content: "",
  5274. zcodeTimeline: {
  5275. type: "context_compaction",
  5276. operationId: "cmp-1",
  5277. status: "retrying",
  5278. trigger: "auto",
  5279. attempt: 2,
  5280. maxAttempts: 3,
  5281. reason: "Failed to generate compact summary",
  5282. },
  5283. });
  5284. });
  5285. it("projects compact skipped payloads to context compaction timeline chunks", () => {
  5286. const state = {
  5287. activePromptInputIdBySession: new Map([["sess_1", "input-compact"]]),
  5288. streamedTurnKeys: new Set<string>(),
  5289. toolNameById: new Map<string, string>(),
  5290. };
  5291. const events = zcodeSessionEventToZCodeStreamEvents({
  5292. event: {
  5293. eventId: "evt_compact_skipped",
  5294. sessionId: "sess_1",
  5295. turnId: "turn_compact",
  5296. seq: 3,
  5297. timestamp: 4,
  5298. traceId: "trace_compact",
  5299. type: "session.updated",
  5300. payload: {
  5301. operationId: "cmp-skipped",
  5302. messageId: "msg-compact-skipped",
  5303. status: "skipped",
  5304. trigger: "manual",
  5305. display: "separator",
  5306. },
  5307. } satisfies ZCodeSessionEvent,
  5308. state,
  5309. taskId: "sess_1",
  5310. });
  5311. expect(events[0]).toMatchObject({
  5312. type: "agent_message_chunk",
  5313. taskId: "sess_1",
  5314. traceId: "input-compact",
  5315. inputId: "input-compact",
  5316. messageId: "msg-compact-skipped",
  5317. content: "",
  5318. zcodeTimeline: {
  5319. type: "context_compaction",
  5320. operationId: "cmp-skipped",
  5321. status: "skipped",
  5322. trigger: "manual",
  5323. },
  5324. });
  5325. });
  5326. it("projects fork notice part upserts to session fork timeline chunks", () => {
  5327. const state = {
  5328. activePromptInputIdBySession: new Map<string, string>(),
  5329. streamedTurnKeys: new Set<string>(),
  5330. toolNameById: new Map<string, string>(),
  5331. };
  5332. const events = zcodeSessionEventToZCodeStreamEvents({
  5333. event: {
  5334. eventId: "evt_fork_notice",
  5335. sessionId: "forked-session",
  5336. seq: 1,
  5337. timestamp: 2,
  5338. traceId: "trace_fork",
  5339. type: "part.upserted",
  5340. payload: {
  5341. part: {
  5342. partId: "part_fork_notice",
  5343. sessionId: "forked-session",
  5344. messageId: "msg_fork_notice",
  5345. type: "text",
  5346. text: "Forked from parent",
  5347. metadata: {
  5348. forkContext: {
  5349. kind: "session_fork",
  5350. parentSessionId: "parent-session",
  5351. targetMessageId: "parent-message",
  5352. restoredFileCount: 2,
  5353. },
  5354. },
  5355. },
  5356. },
  5357. } satisfies ZCodeSessionEvent,
  5358. state,
  5359. taskId: "forked-session",
  5360. });
  5361. expect(events).toEqual([
  5362. {
  5363. type: "agent_message_chunk",
  5364. taskId: "forked-session",
  5365. traceId: "trace_fork",
  5366. messageId: "msg_fork_notice",
  5367. content: "",
  5368. zcodeTimeline: {
  5369. version: 1,
  5370. kind: "synthetic",
  5371. type: "session_fork",
  5372. display: "separator",
  5373. parentSessionId: "parent-session",
  5374. targetMessageId: "parent-message",
  5375. restoredFileCount: 2,
  5376. },
  5377. },
  5378. ]);
  5379. });
  5380. it("projects compact turn failures to failed timeline chunks instead of task errors", () => {
  5381. const state = {
  5382. activePromptInputIdBySession: new Map([["sess_1", "input-compact"]]),
  5383. streamedTurnKeys: new Set<string>(),
  5384. toolNameById: new Map<string, string>(),
  5385. };
  5386. const events = zcodeSessionEventToZCodeStreamEvents({
  5387. event: {
  5388. eventId: "evt_compact_failed",
  5389. sessionId: "sess_1",
  5390. turnId: "turn_compact",
  5391. seq: 2,
  5392. timestamp: 3,
  5393. traceId: "trace_compact",
  5394. type: "turn.failed",
  5395. payload: {
  5396. turnPhase: "compact",
  5397. inputId: "input-compact",
  5398. error: {
  5399. message: "No summary produced.",
  5400. type: "compact_failed",
  5401. },
  5402. },
  5403. } satisfies ZCodeSessionEvent,
  5404. state,
  5405. taskId: "sess_1",
  5406. });
  5407. expect(events).toHaveLength(1);
  5408. expect(events[0]).toMatchObject({
  5409. type: "agent_message_chunk",
  5410. taskId: "sess_1",
  5411. traceId: "input-compact",
  5412. inputId: "input-compact",
  5413. zcodeTimeline: {
  5414. type: "context_compaction",
  5415. status: "failed",
  5416. inputId: "input-compact",
  5417. reason: "No summary produced.",
  5418. },
  5419. });
  5420. });
  5421. it("projects ZCode settings updates to model and mode state events", () => {
  5422. const options = zcodeSessionSettingsToConfigOptions(settings);
  5423. const events = zcodeStateUpdatedToZCodeStreamEvents({
  5424. notification: {
  5425. type: "state.updated",
  5426. scope: "session",
  5427. sessionId: "sess_1",
  5428. revision: 2,
  5429. reason: "model_changed",
  5430. patch: settings,
  5431. },
  5432. settings,
  5433. taskId: "sess_1",
  5434. });
  5435. expect(options.find((option) => option.category === "model")).toMatchObject({
  5436. currentValue: "glm/glm-4.6",
  5437. });
  5438. expect(events.map((event) => event.type)).toEqual([
  5439. "mode_update",
  5440. "glm_agent_model_state_update",
  5441. ]);
  5442. expect(events[0]).toMatchObject({
  5443. type: "mode_update",
  5444. currentModeId: "build",
  5445. });
  5446. expect(events[1]).toMatchObject({
  5447. type: "glm_agent_model_state_update",
  5448. reason: "model_changed",
  5449. model: {
  5450. currentValue: "glm/glm-4.6",
  5451. },
  5452. thoughtLevel: {
  5453. enabled: true,
  5454. currentValue: "medium",
  5455. options: [{ value: "medium", name: "Medium" }],
  5456. },
  5457. contextWindow: {
  5458. tokens: 128000,
  5459. },
  5460. });
  5461. });
  5462. it("parses UI model values into strict ZCode model refs", () => {
  5463. expect(parseModelPickerValue("glm/glm-4.6")).toEqual({
  5464. providerId: "glm",
  5465. modelId: "glm-4.6",
  5466. });
  5467. expect(parseModelPickerValue("custom-openai/agent-model$fast")).toEqual({
  5468. providerId: "custom-openai",
  5469. modelId: "agent-model",
  5470. options: { reasoningLevel: "fast" },
  5471. });
  5472. expect(parseModelPickerValue("openrouter/nvidia/nemotron-3-ultra-550b-a55b:free")).toEqual({
  5473. providerId: "openrouter",
  5474. modelId: "nvidia/nemotron-3-ultra-550b-a55b:free",
  5475. });
  5476. expect(parseModelPickerValue(encodeCustomModelValue("my-provider", "my-model"))).toEqual({
  5477. providerId: "my-provider",
  5478. modelId: "my-model",
  5479. });
  5480. });
  5481. it("formats model variants with the reserved dollar separator", () => {
  5482. const modelSelection = {
  5483. providerId: "custom-openai",
  5484. modelId: "agent-model:free",
  5485. options: { reasoningLevel: "fast" },
  5486. };
  5487. expect(formatSharedModelSelection(modelSelection)).toBe("custom-openai/agent-model:free$fast");
  5488. expect(formatProjectedModelSelection(modelSelection)).toBe(
  5489. "custom-openai/agent-model:free$fast",
  5490. );
  5491. });
  5492. it("projects web remote user input response to elicitation response", () => {
  5493. expect(
  5494. zcodeUserInputResponseToZCodeStreamEvent("sess_1", {
  5495. requestId: "input-1",
  5496. action: "accept",
  5497. content: { answers: { answer_0: "a" } },
  5498. }),
  5499. ).toMatchObject({
  5500. type: "elicitation_response",
  5501. taskId: "sess_1",
  5502. requestId: "input-1",
  5503. action: "accept",
  5504. content: { answers: { answer_0: "a" } },
  5505. });
  5506. });
  5507. });