zcodeSessionProjection.test.ts 158 KB

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