| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721 |
- import { describe, expect, it, vi } from "vitest";
- import {
- encodeCustomModelValue,
- formatModelPickerValue as formatSharedModelSelection,
- ZCODE_PROTOCOL_NAME,
- ZCODE_PROTOCOL_VERSION,
- type ZCodeSessionEvent,
- type ZCodeMessagePart,
- type ZCodeMessageWithParts,
- type ZCodeSessionSettingsState,
- type ZCodeSessionStateSnapshot,
- } from "@zcode/shared";
- import {
- formatModelPickerValue as formatProjectedModelSelection,
- parseModelPickerValue,
- type ZCodeSessionEventProjectionState,
- zcodeSessionEventToZCodeStreamEvents,
- zcodeSessionSettingsToConfigOptions,
- zcodeSessionSnapshotToZCodeTaskSnapshot,
- zcodeStateUpdatedToZCodeStreamEvents,
- zcodeUserInputRequestToZCodeStreamEvent,
- zcodeUserInputResponseToZCodeStreamEvent,
- } from "@/lib/zcodeSessionProjection.js";
- const workspace = {
- workspacePath: "/workspace/app",
- workspaceIdentity: "remote:ssh:dev:/workspace/app",
- workspaceKey: "remote:ssh:dev:/workspace/app",
- };
- const subagentOrigin = {
- kind: "subagent",
- agentId: "agent_snapshot",
- agentType: "general",
- childSessionId: "sess_child_snapshot",
- childTurnId: "turn_child_snapshot",
- parentSessionId: "sess_1",
- parentToolCallId: "tool_parent_agent",
- parentTurnId: "turn_parent_snapshot",
- } as const;
- const model = { providerId: "glm", modelId: "glm-4.6" };
- const backgroundAgentProviderError =
- "Requests are too frequent. Please reduce your request frequency, wait a short moment, and retry your request. Request id: e2e-background-subagent-rate-limit";
- const settings = {
- model: {
- current: model,
- available: [{ ref: model, label: "GLM 4.6", contextWindow: 128000 }],
- lastUsed: model,
- },
- thoughtLevel: {
- enabled: true,
- current: "medium",
- available: [{ value: "medium", label: "Medium" }],
- },
- mode: {
- current: "build",
- },
- } satisfies ZCodeSessionSettingsState;
- const settingsWithDefaultThoughtLevel = {
- ...settings,
- thoughtLevel: {
- enabled: true,
- current: undefined,
- defaultLevel: "max",
- available: [
- { value: "high", label: "High" },
- { value: "max", label: "Max" },
- ],
- },
- } satisfies ZCodeSessionSettingsState;
- function createSnapshot(): ZCodeSessionStateSnapshot {
- return {
- protocol: {
- name: ZCODE_PROTOCOL_NAME,
- version: ZCODE_PROTOCOL_VERSION,
- },
- session: {
- sessionId: "sess_1",
- workspace,
- sessionKind: "interactive",
- title: "",
- mode: "build",
- status: "running",
- model,
- createdAt: 1,
- updatedAt: 2,
- },
- settings,
- projection: {
- sessionId: "sess_1",
- status: "running",
- mode: "build",
- turnCount: 1,
- totalTokenCount: 12,
- contextUsed: 12,
- contextWindow: 128000,
- pendingPermissions: [
- {
- requestId: "perm_1",
- toolCallId: "tool_1",
- toolName: "Bash",
- riskLevel: "medium",
- reason: "Run command",
- origin: subagentOrigin,
- requestedAt: 3,
- },
- ],
- activeToolCalls: [],
- backgroundJobs: [],
- },
- runtime: {
- eventSeq: 7,
- stateRevision: 3,
- deliveryKind: "desktop-continuous",
- pendingRequestIds: ["perm_1"],
- },
- messages: [
- {
- info: {
- messageId: "msg_user",
- sessionId: "sess_1",
- role: "user",
- time: { created: 1 },
- agent: "zcode-agent",
- model,
- },
- parts: [
- {
- partId: "part_user",
- sessionId: "sess_1",
- messageId: "msg_user",
- type: "text",
- text: "hello",
- },
- ],
- },
- {
- info: {
- messageId: "msg_assistant",
- sessionId: "sess_1",
- role: "assistant",
- parentMessageId: "msg_user",
- time: { created: 2, completed: 12 },
- agent: "zcode-agent",
- model,
- path: { cwd: "/workspace/app", root: "/workspace/app" },
- cost: 0,
- tokens: {
- input: 1,
- output: 2,
- reasoning: 3,
- total: 6,
- cache: { read: 0, write: 0 },
- },
- },
- parts: [
- {
- partId: "part_reasoning",
- sessionId: "sess_1",
- messageId: "msg_assistant",
- type: "reasoning",
- text: "thinking",
- },
- {
- partId: "part_tool",
- sessionId: "sess_1",
- messageId: "msg_assistant",
- type: "tool",
- callId: "tool_1",
- tool: "Bash",
- state: {
- status: "completed",
- input: { command: "pwd" },
- output: "/workspace/app",
- title: "Bash",
- metadata: {},
- startedAt: 4,
- completedAt: 5,
- },
- },
- {
- partId: "part_text",
- sessionId: "sess_1",
- messageId: "msg_assistant",
- type: "text",
- text: "done",
- },
- ],
- },
- ],
- };
- }
- describe("zcodeSessionProjection", () => {
- it.each(["desktop-continuous", "web-remote-replayable"] as const)(
- "%s 历史缺少模型来源时保留消息,不伪造模型",
- (deliveryKind) => {
- const snapshot = createSnapshot();
- snapshot.runtime.deliveryKind = deliveryKind;
- for (const message of snapshot.messages) delete message.info.model;
- const projected = zcodeSessionSnapshotToZCodeTaskSnapshot(snapshot);
- expect(projected.messages).toHaveLength(snapshot.messages.length);
- expect(projected.messages.every((message) => message.model === undefined)).toBe(true);
- expect(projected.messages[0]?.content).toBe("hello");
- },
- );
- it("preserves structured attribution when projecting a failed turn to task_error", () => {
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_turn_failed_attribution",
- seq: 8,
- sessionId: "sess_1",
- timestamp: 10,
- type: "turn.failed",
- payload: {
- turnPhase: "model",
- error: {
- type: "MODEL_ERROR",
- code: "model_request_failed",
- message: "[1301][Sensitive content rejected]",
- attribution: {
- source: "provider",
- reason: "unknown",
- providerId: "account:bigmodel-individual-coding-plan",
- providerErrorCode: "1301",
- },
- },
- },
- },
- taskId: "task_1",
- });
- expect(events).toContainEqual(
- expect.objectContaining({
- type: "task_error",
- attribution: {
- source: "provider",
- reason: "unknown",
- providerId: "account:bigmodel-individual-coding-plan",
- providerErrorCode: "1301",
- },
- }),
- );
- });
- it("preserves completed tool display metadata in snapshot raw output", () => {
- const base = createSnapshot();
- const assistant = base.messages[1]!;
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- messages: [
- base.messages[0]!,
- {
- ...assistant,
- parts: [
- {
- partId: "part_node_repl_image",
- sessionId: "sess_1",
- messageId: assistant.info.messageId,
- type: "tool",
- callId: "tool_node_repl_image",
- tool: "mcp__node_repl__js",
- state: {
- status: "completed",
- input: { code: "nodeRepl.emitImage(await tab.screenshot());" },
- output: "(no output)\n[Attached image/png: MCP image]",
- title: "截图查看",
- metadata: {
- schemaVersion: 1,
- display: {
- kind: "node_repl_images",
- images: [{ base64: "AAAA", mimeType: "image/png" }],
- },
- },
- startedAt: 4,
- completedAt: 5,
- },
- },
- ],
- },
- ],
- });
- expect(snapshot.messages[1]?.tools[0]?.raw).toMatchObject({
- toolCallId: "tool_node_repl_image",
- display: {
- kind: "node_repl_images",
- images: [{ base64: "AAAA", mimeType: "image/png" }],
- },
- });
- });
- it("falls back to a valid thought level when session settings carry a stale current value", () => {
- const options = zcodeSessionSettingsToConfigOptions({
- ...settings,
- thoughtLevel: {
- enabled: true,
- current: "high",
- available: [
- { value: "enabled", label: "Enabled" },
- { value: "disabled", label: "Disabled" },
- ],
- },
- });
- expect(options.find((option) => option.category === "thought_level")?.currentValue).toBe(
- "enabled",
- );
- });
- it("uses thought defaultLevel before the first available level when current is empty", () => {
- const options = zcodeSessionSettingsToConfigOptions(settingsWithDefaultThoughtLevel);
- expect(options.find((option) => option.category === "thought_level")?.currentValue).toBe("max");
- });
- it("uses thought defaultLevel in model state updates when current is empty", () => {
- const events = zcodeStateUpdatedToZCodeStreamEvents({
- notification: {
- type: "state.updated",
- scope: "session",
- sessionId: "sess_1",
- revision: 2,
- reason: "model_changed",
- patch: settingsWithDefaultThoughtLevel,
- },
- settings: settingsWithDefaultThoughtLevel,
- taskId: "sess_1",
- });
- expect(events.find((event) => event.type === "glm_agent_model_state_update")).toMatchObject({
- type: "glm_agent_model_state_update",
- thoughtLevel: {
- enabled: true,
- currentValue: "max",
- options: [
- { value: "high", name: "High" },
- { value: "max", name: "Max" },
- ],
- },
- });
- });
- it("maps server-owned session snapshots into the current chat projection", () => {
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot(createSnapshot());
- expect(snapshot.meta).toMatchObject({
- taskId: "sess_1",
- provider: "glm",
- title: "hello",
- status: "running",
- workspaceIdentity: workspace.workspaceIdentity,
- });
- expect(snapshot.messages).toHaveLength(2);
- expect(snapshot.messages[1]).toMatchObject({
- role: "assistant",
- content: "done",
- thought: "thinking",
- durationMs: 10,
- });
- expect(snapshot.messages[1]?.tools?.[0]).toMatchObject({
- toolName: "Bash",
- status: "completed",
- output: "/workspace/app",
- raw: {
- toolCallId: "tool_1",
- },
- });
- expect(snapshot.messages[1]?.tools?.[0]?.raw).toMatchObject({
- toolCallId: "tool_1",
- });
- expect(snapshot.runtime?.pendingPermissions?.[0]).toMatchObject({
- requestId: "perm_1",
- kind: "Bash",
- origin: subagentOrigin,
- });
- expect(snapshot.runtime?.contextUsage).toEqual({
- used: 12,
- size: 128000,
- cost: null,
- });
- });
- it("projects legacy fork synthetic user as a separator without raw text", () => {
- const base = createSnapshot();
- const forkMetadata = {
- forkContext: {
- kind: "session_fork",
- parentSessionId: "sess_parent",
- restoredFileCount: 0,
- targetMessageId: "msg_parent_assistant",
- },
- source: "fork",
- visibility: "user-visible",
- };
- const forkNotice: ZCodeMessageWithParts = {
- info: {
- messageId: "msg_fork_notice",
- sessionId: "sess_1",
- role: "user",
- time: { created: 3 },
- agent: "zcode-agent",
- model,
- metadata: forkMetadata,
- source: "fork",
- synthetic: true,
- visibility: "user-visible",
- },
- parts: [
- {
- partId: "part_fork_notice",
- sessionId: "sess_1",
- messageId: "msg_fork_notice",
- type: "text",
- text: "This session was forked from a previous session message.",
- metadata: forkMetadata,
- synthetic: true,
- },
- ],
- };
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- messages: [...base.messages, forkNotice],
- });
- const forkTimeline = snapshot.messages.find(
- (message) => message.syntheticTimeline?.type === "session_fork",
- );
- expect(forkTimeline).toMatchObject({
- content: "",
- syntheticTimeline: {
- parentSessionId: "sess_parent",
- targetMessageId: "msg_parent_assistant",
- type: "session_fork",
- },
- });
- expect(
- snapshot.messages.some((message) => message.content.includes("This session was forked")),
- ).toBe(false);
- });
- it("projects persisted session_fork timeline parts after cold snapshot restore", () => {
- const base = createSnapshot();
- const timelineMessage: ZCodeMessageWithParts = {
- info: {
- messageId: "msg_fork_timeline",
- sessionId: "sess_1",
- role: "assistant",
- parentMessageId: "msg_assistant",
- time: { created: 4, completed: 4 },
- agent: "zcode-agent",
- model,
- path: { cwd: "/workspace/app", root: "/workspace/app" },
- cost: 0,
- tokens: {
- input: 0,
- output: 0,
- reasoning: 0,
- total: 0,
- cache: { read: 0, write: 0 },
- },
- },
- parts: [
- {
- partId: "part_fork_timeline",
- sessionId: "sess_1",
- messageId: "msg_fork_timeline",
- type: "timeline",
- timelineType: "session_fork",
- display: "separator",
- status: "completed",
- parentSessionId: "sess_parent",
- targetMessageId: "msg_parent_assistant",
- restoredFileCount: 1,
- },
- ],
- };
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- messages: [...base.messages, timelineMessage],
- });
- expect(snapshot.messages.find((message) => message.id === "msg_fork_timeline")).toMatchObject({
- content: "",
- syntheticTimeline: {
- parentSessionId: "sess_parent",
- restoredFileCount: 1,
- targetMessageId: "msg_parent_assistant",
- type: "session_fork",
- },
- });
- });
- it("hides model-only fork raw notices when a structured fork timeline exists", () => {
- const base = createSnapshot();
- const forkMetadata = {
- forkContext: {
- kind: "session_fork",
- parentSessionId: "sess_parent",
- restoredFileCount: 0,
- targetMessageId: "msg_parent_assistant",
- },
- source: "fork",
- visibility: "model-only",
- };
- const timelineMessage: ZCodeMessageWithParts = {
- info: {
- messageId: "msg_fork_timeline",
- sessionId: "sess_1",
- role: "assistant",
- parentMessageId: "msg_assistant",
- time: { created: 4, completed: 4 },
- agent: "zcode-agent",
- model,
- path: { cwd: "/workspace/app", root: "/workspace/app" },
- cost: 0,
- tokens: {
- input: 0,
- output: 0,
- reasoning: 0,
- total: 0,
- cache: { read: 0, write: 0 },
- },
- },
- parts: [
- {
- partId: "part_fork_timeline",
- sessionId: "sess_1",
- messageId: "msg_fork_timeline",
- type: "timeline",
- timelineType: "session_fork",
- display: "separator",
- status: "completed",
- parentSessionId: "sess_parent",
- targetMessageId: "msg_parent_assistant",
- restoredFileCount: 0,
- },
- ],
- };
- const rawNotice: ZCodeMessageWithParts = {
- info: {
- messageId: "msg_fork_raw_notice",
- sessionId: "sess_1",
- role: "user",
- time: { created: 5 },
- agent: "zcode-agent",
- model,
- metadata: forkMetadata,
- semantics: {
- kind: "fork_notice",
- origin: "agent_runtime",
- providerVisibility: "visible",
- source: "fork",
- transcriptVisibility: "hidden",
- uiVisibility: "hidden",
- },
- source: "fork",
- synthetic: true,
- visibility: "model-only",
- },
- parts: [
- {
- partId: "part_fork_raw_notice",
- sessionId: "sess_1",
- messageId: "msg_fork_raw_notice",
- type: "text",
- text: "This session was forked from a previous session message.",
- metadata: forkMetadata,
- synthetic: true,
- },
- ],
- };
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- messages: [...base.messages, timelineMessage, rawNotice],
- });
- const forkTimelines = snapshot.messages.filter(
- (message) => message.syntheticTimeline?.type === "session_fork",
- );
- expect(forkTimelines).toHaveLength(1);
- expect(forkTimelines[0]).toMatchObject({
- id: "msg_fork_timeline",
- content: "",
- syntheticTimeline: {
- parentSessionId: "sess_parent",
- targetMessageId: "msg_parent_assistant",
- type: "session_fork",
- },
- });
- expect(JSON.stringify(snapshot.messages)).not.toContain("This session was forked");
- });
- it("attaches hidden task notification metadata to the matching background Agent tool", () => {
- const base = createSnapshot();
- const assistantMessage = {
- info: {
- messageId: "msg_assistant_agent",
- sessionId: "sess_1",
- role: "assistant",
- parentMessageId: "msg_user",
- time: { created: 2, completed: 12 },
- agent: "zcode-agent",
- model,
- },
- parts: [
- {
- partId: "part_agent_tool",
- sessionId: "sess_1",
- messageId: "msg_assistant_agent",
- type: "tool",
- callId: "toolu_background_agent",
- tool: "Agent",
- state: {
- status: "completed",
- input: {
- prompt: "run background research",
- run_in_background: true,
- },
- output: "Async agent launched successfully.\noutput_file: /tmp/background-agent.output",
- title: "Agent",
- metadata: {
- _meta: {
- zcode: {
- backgroundAgent: {
- runInBackground: true,
- outputFile: "/tmp/background-agent.output",
- },
- },
- },
- },
- startedAt: 4,
- completedAt: 5,
- },
- },
- ],
- } satisfies ZCodeSessionStateSnapshot["messages"][number];
- const notificationMessage = {
- info: {
- messageId: "msg_task_notification",
- sessionId: "sess_1",
- role: "user",
- time: { created: 13 },
- agent: "zcode-agent",
- model,
- visibility: "model-only",
- },
- parts: [
- {
- partId: "part_task_notification",
- sessionId: "sess_1",
- messageId: "msg_task_notification",
- type: "text",
- synthetic: true,
- metadata: { source: "background_task" },
- text: [
- "<task-notification>",
- "<task-id>agent_1</task-id>",
- "<tool-use-id>toolu_background_agent</tool-use-id>",
- "<output-file>/tmp/background-agent.output</output-file>",
- "<status>completed</status>",
- "<result>Background agent result & summary</result>",
- "</task-notification>",
- ].join("\n"),
- },
- ],
- } satisfies ZCodeSessionStateSnapshot["messages"][number];
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- messages: [base.messages[0]!, assistantMessage, notificationMessage],
- });
- expect(snapshot.messages).toHaveLength(2);
- expect(snapshot.messages[1]?.tools?.[0]?.raw).toMatchObject({
- _meta: {
- zcode: {
- taskNotification: {
- outputFile: "/tmp/background-agent.output",
- result: "Background agent result & summary",
- status: "completed",
- taskId: "agent_1",
- },
- },
- },
- });
- });
- it.each([
- {
- expectedError: backgroundAgentProviderError,
- expectedStatus: "failed" as const,
- notificationStatus: "failed",
- },
- {
- expectedError: undefined,
- expectedStatus: "completed" as const,
- notificationStatus: "stopped",
- },
- ])(
- "restores a $notificationStatus background Agent notification without changing unrelated launch semantics",
- ({ expectedError, expectedStatus, notificationStatus }) => {
- const base = createSnapshot();
- const assistantMessage = {
- info: {
- messageId: "msg_assistant_failed_background_agent",
- sessionId: "sess_1",
- role: "assistant",
- parentMessageId: "msg_user",
- time: { created: 2, completed: 12 },
- agent: "zcode-agent",
- model,
- },
- parts: [
- {
- partId: "part_failed_background_agent_tool",
- sessionId: "sess_1",
- messageId: "msg_assistant_failed_background_agent",
- type: "tool",
- callId: "toolu_failed_background_agent",
- tool: "Agent",
- state: {
- status: "completed",
- input: {
- prompt: "run background research",
- run_in_background: true,
- },
- output:
- "Async agent launched successfully.\noutput_file: /tmp/background-agent.output",
- title: "Agent",
- metadata: {
- _meta: {
- zcode: {
- backgroundAgent: {
- runInBackground: true,
- outputFile: "/tmp/background-agent.output",
- },
- },
- },
- },
- startedAt: 4,
- completedAt: 5,
- },
- },
- ],
- } satisfies ZCodeSessionStateSnapshot["messages"][number];
- const notificationMessage = {
- info: {
- messageId: "msg_failed_task_notification",
- sessionId: "sess_1",
- role: "user",
- time: { created: 13 },
- agent: "zcode-agent",
- model,
- visibility: "model-only",
- },
- parts: [
- {
- partId: "part_failed_task_notification",
- sessionId: "sess_1",
- messageId: "msg_failed_task_notification",
- type: "text",
- synthetic: true,
- metadata: { source: "background_task" },
- text: [
- "<task-notification>",
- "<task-id>agent_failed</task-id>",
- "<tool-use-id>toolu_failed_background_agent</tool-use-id>",
- "<output-file>/tmp/background-agent.output</output-file>",
- `<status>${notificationStatus}</status>`,
- `<summary>Agent general-purpose task "Review" ${notificationStatus}.</summary>`,
- ...(expectedError ? [`<error>${expectedError}</error>`] : []),
- "</task-notification>",
- ].join("\n"),
- },
- ],
- } satisfies ZCodeSessionStateSnapshot["messages"][number];
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- messages: [base.messages[0]!, assistantMessage, notificationMessage],
- });
- expect(snapshot.messages).toHaveLength(2);
- expect(snapshot.messages[1]?.tools?.[0]).toMatchObject({
- status: expectedStatus,
- output: "Async agent launched successfully.\noutput_file: /tmp/background-agent.output",
- raw: {
- _meta: {
- zcode: {
- taskNotification: {
- status: notificationStatus,
- summary: `Agent general-purpose task "Review" ${notificationStatus}.`,
- taskId: "agent_failed",
- },
- },
- },
- },
- });
- expect(snapshot.messages[1]?.tools?.[0]?.error).toBe(expectedError);
- },
- );
- it("maps pending ExitPlanMode approvals into pending elicitations", () => {
- const base = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- projection: {
- ...base.projection,
- pendingPermissions: [
- {
- requestId: "exit_plan_1",
- toolCallId: "tool_exit_plan",
- toolName: "ExitPlanMode",
- riskLevel: "high",
- reason: "Exit plan mode",
- origin: subagentOrigin,
- requestedAt: 4,
- input: { plan: "1. Change runtime\n2. Add tests" },
- },
- ],
- },
- runtime: {
- ...base.runtime,
- pendingRequestIds: ["exit_plan_1"],
- },
- });
- expect(snapshot.runtime?.pendingPermissions).toEqual([]);
- expect(snapshot.runtime?.pendingElicitations?.[0]).toMatchObject({
- type: "elicitation_request",
- requestId: "exit_plan_1",
- message: "Review this implementation plan.",
- header: "Plan",
- options: [{ value: "approve", label: "Approve" }],
- origin: subagentOrigin,
- schema: { interaction: "plan_approval", toolName: "ExitPlanMode" },
- });
- });
- it("keeps tools when a tool-calls assistant is followed by final text", () => {
- const base = createSnapshot();
- const toolOnlyAssistant = {
- ...base.messages[1]!,
- info: {
- ...base.messages[1]!.info,
- finish: "tool-calls",
- messageId: "msg_tool_only",
- time: { created: 2, completed: 312 },
- },
- parts: [
- {
- partId: "part_tool_only_start",
- sessionId: "sess_1",
- messageId: "msg_tool_only",
- type: "tool",
- callId: "tool_read_guard",
- tool: "Read",
- state: {
- status: "completed",
- input: { file_path: "/tmp/zcode-e2e-tool-action-guard.txt" },
- output: "E2E_TOOL_FILE_CONTENT",
- title: "Read",
- metadata: {},
- startedAt: 300,
- completedAt: 310,
- },
- },
- ],
- } satisfies ZCodeSessionStateSnapshot["messages"][number];
- const finalAssistant = {
- ...base.messages[1]!,
- info: {
- ...base.messages[1]!.info,
- finish: "stop",
- messageId: "msg_final_text",
- time: { created: 314, completed: 360 },
- },
- parts: [
- {
- partId: "part_final_text",
- sessionId: "sess_1",
- messageId: "msg_final_text",
- type: "text",
- text: "deepseek-e2e-ok",
- },
- ],
- } satisfies ZCodeSessionStateSnapshot["messages"][number];
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- session: {
- ...base.session,
- status: "idle",
- },
- projection: {
- ...base.projection,
- status: "idle",
- pendingPermissions: [],
- },
- runtime: {
- ...base.runtime,
- pendingRequestIds: [],
- },
- messages: [base.messages[0]!, toolOnlyAssistant, finalAssistant],
- });
- expect(snapshot.messages).toHaveLength(2);
- expect(snapshot.messages[1]).toMatchObject({
- id: "msg_tool_only",
- role: "assistant",
- content: "deepseek-e2e-ok",
- tools: [
- {
- toolName: "Read",
- status: "completed",
- },
- ],
- });
- expect(snapshot.messages[1]?.parts).toEqual([
- { type: "tool-call", toolIndex: 0 },
- { type: "content", content: "deepseek-e2e-ok" },
- ]);
- });
- it("restores user image, video, and PDF attachments from protocol file parts", () => {
- const base = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- messages: [
- {
- ...base.messages[0]!,
- parts: [
- ...base.messages[0]!.parts,
- {
- partId: "part_image",
- sessionId: "sess_1",
- messageId: "msg_user",
- filename: "screen.png",
- metadata: {
- sizeBytes: 30,
- storageKind: "artifact",
- },
- mime: "image/png",
- type: "file",
- url: "data:image/png;base64,aW1hZ2U=",
- } satisfies ZCodeMessagePart,
- {
- partId: "part_video",
- sessionId: "sess_1",
- messageId: "msg_user",
- filename: "demo.mp4",
- metadata: {
- originalUrl: "/workspace/app/demo.mp4",
- sizeBytes: 5,
- storageKind: "inline",
- },
- mime: "video/mp4",
- type: "file",
- url: "data:video/mp4;base64,dmlkZW8=",
- } satisfies ZCodeMessagePart,
- {
- partId: "part_pdf",
- sessionId: "sess_1",
- messageId: "msg_user",
- filename: "report.pdf",
- metadata: {
- sizeBytes: 9,
- storageKind: "artifact",
- },
- mime: "application/pdf; charset=binary",
- type: "file",
- url: "zcode-artifact://sess_1/pdf-1",
- } satisfies ZCodeMessagePart,
- ],
- },
- ],
- });
- expect(snapshot.messages[0]?.attachments).toEqual([
- {
- kind: "image",
- filename: "screen.png",
- mimeType: "image/png",
- sizeBytes: 30,
- dataBase64: "aW1hZ2U=",
- },
- {
- kind: "video",
- filename: "demo.mp4",
- mimeType: "video/mp4",
- sizeBytes: 5,
- dataBase64: "dmlkZW8=",
- localPath: "/workspace/app/demo.mp4",
- },
- {
- kind: "pdf",
- filename: "report.pdf",
- mimeType: "application/pdf",
- sizeBytes: 9,
- },
- ]);
- });
- it("projects one attachment-only raw user message without exposing the wire fallback", () => {
- const base = createSnapshot();
- const rawMessage = {
- ...base.messages[0]!,
- parts: [
- {
- partId: "part_attachment_only_text",
- sessionId: "sess_1",
- messageId: "msg_user",
- type: "text",
- text: "",
- },
- {
- partId: "part_attachment_only_file",
- sessionId: "sess_1",
- messageId: "msg_user",
- filename: "notes.md",
- metadata: {
- preview: {
- text: "# Notes\nAttachment-only content.",
- truncated: false,
- originalBytes: 32,
- },
- recoverability: "provider_ready",
- sizeBytes: 32,
- storageKind: "inline",
- },
- mime: "text/plain",
- type: "file",
- url: "inline:data-url",
- },
- ],
- } satisfies ZCodeSessionStateSnapshot["messages"][number];
- const originalParts = structuredClone(rawMessage.parts);
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- messages: [rawMessage],
- });
- expect(snapshot.messages).toHaveLength(1);
- expect(snapshot.messages[0]).toMatchObject({
- id: "msg_user",
- role: "user",
- content: "",
- attachments: [
- {
- kind: "file",
- filename: "notes.md",
- mimeType: "text/plain",
- sizeBytes: 32,
- textContent: "# Notes\nAttachment-only content.",
- },
- ],
- });
- expect(rawMessage.parts).toEqual(originalParts);
- expect(JSON.stringify(snapshot.messages)).not.toContain("(no content)");
- });
- it("maps idle session snapshots with a completed assistant turn to completed task status", () => {
- const base = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- session: {
- ...base.session,
- status: "idle",
- },
- projection: {
- ...base.projection,
- status: "idle",
- pendingPermissions: [],
- activeToolCalls: [],
- },
- runtime: {
- ...base.runtime,
- pendingRequestIds: [],
- },
- });
- expect(snapshot.meta.status).toBe("completed");
- });
- it("keeps an idle tool-calls assistant turn without a task terminal status", () => {
- const base = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- session: {
- ...base.session,
- status: "idle",
- },
- projection: {
- ...base.projection,
- status: "idle",
- pendingPermissions: [],
- activeToolCalls: [],
- },
- runtime: {
- ...base.runtime,
- pendingRequestIds: [],
- },
- messages: base.messages.map((message) =>
- message.info.role === "assistant"
- ? {
- ...message,
- info: {
- ...message.info,
- finish: "tool-calls",
- },
- }
- : message,
- ),
- });
- expect(snapshot.meta.status).toBeUndefined();
- });
- it("keeps an empty idle session without a task terminal status", () => {
- const base = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- session: {
- ...base.session,
- status: "idle",
- },
- projection: {
- ...base.projection,
- status: "idle",
- pendingPermissions: [],
- activeToolCalls: [],
- },
- runtime: {
- ...base.runtime,
- pendingRequestIds: [],
- },
- messages: [],
- });
- expect(snapshot.meta.status).toBeUndefined();
- });
- it("preserves protocol projection error type as task error code", () => {
- const base = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- projection: {
- ...base.projection,
- lastError: {
- message: "历史任务使用的模型已不可用,请从当前模型列表中选择一个可用模型后继续。",
- type: "ZCODE_RUNTIME_MODEL_UNAVAILABLE",
- },
- },
- });
- expect(snapshot.meta.lastError).toEqual({
- code: "ZCODE_RUNTIME_MODEL_UNAVAILABLE",
- message: "历史任务使用的模型已不可用,请从当前模型列表中选择一个可用模型后继续。",
- });
- });
- it("prefers structured projection error code over wrapper error type in task meta", () => {
- const base = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- projection: {
- ...base.projection,
- lastError: {
- message: "Model provider is not configured: stale-provider",
- type: "MODEL_ERROR",
- code: "provider_not_found",
- detail: "stale-provider/gpt-5.5",
- attribution: {
- source: "runtime",
- reason: "provider_not_configured",
- providerId: "account:zai-individual-coding-plan",
- },
- },
- },
- });
- expect(snapshot.meta.lastError).toEqual({
- code: "provider_not_found",
- detail: "stale-provider/gpt-5.5",
- message: "Model provider is not configured: stale-provider",
- attribution: {
- source: "runtime",
- reason: "provider_not_configured",
- providerId: "account:zai-individual-coding-plan",
- },
- });
- });
- it("prioritizes projection lastError over a completed previous assistant turn", () => {
- const base = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- session: {
- ...base.session,
- status: "idle",
- },
- projection: {
- ...base.projection,
- status: "error",
- pendingPermissions: [],
- activeToolCalls: [],
- lastError: {
- message: "messages.content.type 参数非法,取值范围 ['text']",
- type: "PROVIDER_BUSINESS_ERROR",
- },
- },
- runtime: {
- ...base.runtime,
- activeTurnId: undefined,
- pendingRequestIds: [],
- },
- });
- expect(snapshot.meta.status).toBe("error");
- expect(snapshot.meta.lastError).toEqual({
- code: "PROVIDER_BUSINESS_ERROR",
- message: "messages.content.type 参数非法,取值范围 ['text']",
- });
- });
- it("uses the latest message model for task meta when restored settings were polluted", () => {
- const pollutedModel = {
- providerId: "36965ea6-734a-46a8-8851-3dfec026589e",
- modelId: "glm-5.1-highspeed",
- };
- const historyModel = {
- providerId: "default-deepseek",
- modelId: "deepseek-v4-flash",
- };
- const base = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...base,
- settings: {
- ...base.settings,
- model: {
- ...base.settings.model,
- current: pollutedModel,
- available: [{ ref: pollutedModel, label: "glm-5.1-highspeed" }],
- },
- },
- messages: base.messages.map((message) => ({
- ...message,
- info: {
- ...message.info,
- model: historyModel,
- },
- })),
- });
- expect(snapshot.meta.model).toBe("default-deepseek/deepseek-v4-flash");
- });
- it("maps persisted session todos into task runtime plan", () => {
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...createSnapshot(),
- todos: [
- { content: "实现 Lexer", priority: "high", status: "completed" },
- { content: "实现 Parser", priority: "high", status: "in_progress" },
- ],
- });
- expect(snapshot.runtime?.plan).toEqual([
- { id: "todo-0", title: "实现 Lexer", status: "completed" },
- { id: "todo-1", title: "实现 Parser", status: "in_progress" },
- ]);
- });
- it("maps derived goal stats and grouped todos into task runtime", () => {
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...createSnapshot(),
- runtime: {
- ...createSnapshot().runtime,
- goalVerifications: [
- {
- nextAction: "补齐移动端回归。",
- passed: false,
- reason: "第一轮证据不足。",
- },
- ],
- },
- goalStats: {
- contextUsed: 38_200,
- contextWindow: 120_000,
- iterationCount: 4,
- timeUsedSeconds: 8_667,
- tokenBudget: 120_000,
- tokensUsed: 38_200,
- toolCallCount: 27,
- },
- todoGroups: [
- {
- id: "goal-iteration-1",
- source: "goal_iteration",
- goalIteration: 1,
- targetId: "goal_1",
- startedAt: 1_000,
- updatedAt: 2_000,
- todos: [
- { content: "恢复目标统计", priority: "high", status: "completed" },
- {
- content: "按目标迭代分组 todo",
- priority: "high",
- status: "in_progress",
- },
- ],
- },
- ],
- });
- expect(snapshot.runtime?.goalStats).toEqual({
- contextUsed: 38_200,
- contextWindow: 120_000,
- iterationCount: 4,
- timeUsedSeconds: 8_667,
- tokenBudget: 120_000,
- tokensUsed: 38_200,
- toolCallCount: 27,
- });
- expect(snapshot.runtime?.goalVerifications).toEqual([
- {
- nextAction: "补齐移动端回归。",
- passed: false,
- reason: "第一轮证据不足。",
- },
- ]);
- expect(snapshot.runtime?.todoGroups).toEqual([
- {
- id: "goal-iteration-1",
- source: "goal_iteration",
- goalIteration: 1,
- targetId: "goal_1",
- startedAt: 1_000,
- updatedAt: 2_000,
- todos: [
- {
- id: "goal-iteration-1-todo-0",
- title: "恢复目标统计",
- status: "completed",
- },
- {
- id: "goal-iteration-1-todo-1",
- title: "按目标迭代分组 todo",
- status: "in_progress",
- },
- ],
- },
- ]);
- });
- it("adds persisted goal verification lifecycle as a synthetic divider on snapshot restore", () => {
- const baseSnapshot = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...baseSnapshot,
- runtime: {
- ...baseSnapshot.runtime,
- goalVerificationTimeline: [
- {
- version: 1,
- kind: "synthetic",
- type: "goal_verification",
- display: "separator",
- targetId: "target_1",
- verificationId: "verify_1",
- status: "completed",
- goalIteration: 2,
- anchorAssistantMessageId: "msg_assistant",
- anchorTurnId: "turn_1",
- verification: {
- nextAction: null,
- passed: true,
- reason: "所有目标要求都已完成。",
- },
- startedAt: 20,
- updatedAt: 30,
- },
- ],
- },
- });
- expect(snapshot.runtime?.goalVerificationTimeline).toHaveLength(1);
- expect(snapshot.messages).toHaveLength(3);
- expect(snapshot.messages[2]).toMatchObject({
- id: "zcode-goal-verification-target_1-2",
- role: "assistant",
- content: "",
- timestamp: 20,
- syntheticTimeline: {
- type: "goal_verification",
- status: "completed",
- verificationId: "verify_1",
- goalIteration: 2,
- anchorAssistantMessageId: "msg_assistant",
- anchorTurnId: "turn_1",
- },
- });
- });
- it("anchors goal verification dividers to assistant messages that were coalesced", () => {
- const objective = "写一篇短篇科幻小说";
- const baseSnapshot = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...baseSnapshot,
- projection: {
- ...baseSnapshot.projection,
- target: {
- sessionId: "sess_1",
- targetId: "goal_1",
- objective,
- summaryTitle: null,
- status: "active",
- tokenBudget: null,
- tokensUsed: 0,
- timeUsedSeconds: 0,
- createdAt: 100,
- updatedAt: 100,
- },
- },
- runtime: {
- ...baseSnapshot.runtime,
- goalVerificationTimeline: [
- {
- version: 1,
- kind: "synthetic",
- type: "goal_verification",
- display: "separator",
- targetId: "goal_1",
- verificationId: "verify_goal_1",
- status: "completed",
- goalIteration: 1,
- anchorAssistantMessageId: "msg_assistant_second",
- verification: {
- nextAction: "continue",
- passed: false,
- reason: "第二轮仍未完成。",
- },
- startedAt: 400,
- updatedAt: 410,
- },
- ],
- },
- messages: [
- {
- info: {
- messageId: "msg_goal_user",
- sessionId: "sess_1",
- role: "user",
- time: { created: 100 },
- agent: "zcode-agent",
- model,
- },
- parts: [
- {
- partId: "part_goal_user",
- sessionId: "sess_1",
- messageId: "msg_goal_user",
- type: "text",
- text: `/goal ${objective}`,
- },
- ],
- },
- {
- info: {
- messageId: "msg_assistant_first",
- sessionId: "sess_1",
- role: "assistant",
- parentMessageId: "msg_goal_user",
- time: { created: 200, completed: 210 },
- agent: "zcode-agent",
- model,
- },
- parts: [
- {
- partId: "part_assistant_first",
- sessionId: "sess_1",
- messageId: "msg_assistant_first",
- type: "text",
- text: "第一轮。",
- },
- ],
- },
- {
- info: {
- messageId: "msg_assistant_second",
- sessionId: "sess_1",
- role: "assistant",
- parentMessageId: "msg_assistant_first",
- time: { created: 220, completed: 230 },
- agent: "zcode-agent",
- model,
- },
- parts: [
- {
- partId: "part_assistant_second",
- sessionId: "sess_1",
- messageId: "msg_assistant_second",
- type: "text",
- text: "第二轮。",
- },
- ],
- },
- {
- info: {
- messageId: "msg_followup_user",
- sessionId: "sess_1",
- role: "user",
- time: { created: 300 },
- agent: "zcode-agent",
- model,
- },
- parts: [
- {
- partId: "part_followup_user",
- sessionId: "sess_1",
- messageId: "msg_followup_user",
- type: "text",
- text: "新问题",
- },
- ],
- },
- ],
- });
- expect(snapshot.messages.map((message) => message.id)).toEqual([
- "msg_goal_user",
- "msg_assistant_first",
- "zcode-goal-verification-goal_1-1",
- "msg_followup_user",
- ]);
- expect(snapshot.messages[1]?.mergedMessageIds).toEqual([
- "msg_assistant_first",
- "msg_assistant_second",
- ]);
- });
- it("uses runtime context usage when restored projection has no usage yet", () => {
- const baseSnapshot = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...baseSnapshot,
- projection: {
- ...baseSnapshot.projection,
- contextUsed: 0,
- },
- runtime: {
- ...baseSnapshot.runtime,
- contextUsage: {
- used: 12345,
- size: 128000,
- cost: null,
- cache: {
- inputTokens: 12345,
- cacheReadTokens: 2345,
- cacheWriteTokens: 678,
- hitRate: 2345 / 12345,
- },
- },
- },
- });
- expect(snapshot.runtime?.contextUsage).toEqual({
- used: 12345,
- size: 128000,
- cost: null,
- cache: {
- inputTokens: 12345,
- cacheReadTokens: 2345,
- cacheWriteTokens: 678,
- hitRate: 2345 / 12345,
- },
- });
- });
- it("maps snapshot runtime apiRetry into legacy task runtime", () => {
- const baseSnapshot = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...baseSnapshot,
- runtime: {
- ...baseSnapshot.runtime,
- apiRetry: {
- kind: "api_retry",
- attempt: 1,
- maxRetries: 3,
- retryDelayMs: 2_000,
- errorStatus: 429,
- error: "rate limited",
- },
- },
- });
- expect(snapshot.runtime?.apiRetry).toEqual({
- kind: "api_retry",
- attempt: 1,
- maxRetries: 3,
- retryDelayMs: 2_000,
- errorStatus: 429,
- error: "rate limited",
- });
- });
- it("maps projection background jobs into runtime background bash jobs", () => {
- const baseSnapshot = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...baseSnapshot,
- projection: {
- ...baseSnapshot.projection,
- backgroundJobs: [
- {
- id: "bg-1",
- kind: "background_bash",
- command: "python -m http.server 3000",
- status: "running",
- startedAt: 10_000,
- pid: 123,
- },
- ],
- },
- });
- expect(snapshot.runtime?.backgroundBashJobs).toEqual([
- expect.objectContaining({
- jobId: "bg-1",
- command: "python -m http.server 3000",
- status: "running",
- startedAt: 10_000,
- pid: 123,
- }),
- ]);
- });
- it("does not project legacy compact timelineText as visible assistant content", () => {
- const internalSummary =
- "This session is being continued from a previous conversation that was compacted.";
- const baseSnapshot = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...baseSnapshot,
- messages: [
- {
- info: {
- messageId: "msg_compact",
- sessionId: "sess_1",
- role: "assistant",
- parentMessageId: "msg_user",
- time: { created: 20, completed: 21 },
- agent: "zcode-agent",
- model,
- cost: 0,
- tokens: {
- input: 1,
- output: 1,
- reasoning: 0,
- total: 2,
- cache: { read: 0, write: 0 },
- },
- },
- parts: [
- {
- partId: "part_compact",
- sessionId: "sess_1",
- messageId: "msg_compact",
- type: "compaction",
- auto: true,
- summaryMessageId: "msg_summary",
- timelineText: internalSummary,
- metadata: {
- operationId: "compact-legacy",
- timelineStatus: "completed",
- trigger: "auto",
- },
- } as unknown as ZCodeMessagePart,
- ],
- },
- ],
- });
- expect(snapshot.messages).toHaveLength(1);
- expect(snapshot.messages[0]).toMatchObject({
- id: "msg_compact",
- role: "assistant",
- content: "",
- syntheticTimeline: {
- type: "context_compaction",
- operationId: "compact-legacy",
- status: "completed",
- trigger: "auto",
- },
- });
- expect(snapshot.messages[0]?.parts ?? []).toEqual([]);
- expect(JSON.stringify(snapshot.messages)).not.toContain(internalSummary);
- });
- it("does not synthesize a compact divider from summary user compaction metadata", () => {
- const baseSnapshot = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...baseSnapshot,
- messages: [
- {
- info: {
- messageId: "msg_summary",
- sessionId: "sess_1",
- role: "user",
- time: { created: 30 },
- agent: "zcode-agent",
- model,
- },
- parts: [
- {
- partId: "part_summary_compaction",
- sessionId: "sess_1",
- messageId: "msg_summary",
- type: "compaction",
- auto: false,
- metadata: {
- operationId: "cmp-summary",
- phase: "standalone_turn",
- trigger: "manual",
- },
- },
- ],
- },
- ],
- });
- expect(snapshot.messages).toEqual([]);
- });
- it("keeps compact summary messages hidden while rendering the lifecycle divider", () => {
- const baseSnapshot = createSnapshot();
- const summaryText =
- "This session is being continued from a previous conversation that ran out of context.";
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...baseSnapshot,
- messages: [
- {
- info: {
- messageId: "msg_compact_lifecycle",
- sessionId: "sess_1",
- role: "assistant",
- parentMessageId: "msg_user",
- time: { created: 20, completed: 21 },
- agent: "zcode-agent",
- model,
- cost: 0,
- tokens: {
- input: 1,
- output: 1,
- reasoning: 0,
- total: 2,
- cache: { read: 0, write: 0 },
- },
- },
- parts: [
- {
- partId: "part_compact_lifecycle",
- sessionId: "sess_1",
- messageId: "msg_compact_lifecycle",
- type: "compaction",
- auto: true,
- summaryMessageId: "msg_summary",
- metadata: {
- operationId: "cmp-visible-divider",
- timelineStatus: "completed",
- trigger: "auto",
- replace: true,
- },
- },
- ],
- },
- {
- info: {
- messageId: "msg_summary",
- sessionId: "sess_1",
- role: "user",
- time: { created: 22 },
- agent: "zcode-agent",
- model,
- summary: {
- title: "Compact summary",
- body: "Summary:\nEarlier work.",
- diffs: [],
- },
- },
- parts: [
- {
- partId: "part_summary_text",
- sessionId: "sess_1",
- messageId: "msg_summary",
- type: "text",
- text: summaryText,
- synthetic: true,
- },
- {
- partId: "part_summary_compaction",
- sessionId: "sess_1",
- messageId: "msg_summary",
- type: "compaction",
- auto: true,
- metadata: {
- operationId: "cmp-visible-divider",
- trigger: "auto",
- },
- },
- ],
- },
- ],
- });
- expect(snapshot.messages).toHaveLength(1);
- expect(snapshot.messages[0]).toMatchObject({
- id: "msg_compact_lifecycle",
- role: "assistant",
- content: "",
- syntheticTimeline: {
- type: "context_compaction",
- operationId: "cmp-visible-divider",
- status: "completed",
- trigger: "auto",
- replace: true,
- summaryMessageId: "msg_summary",
- },
- });
- expect(JSON.stringify(snapshot.messages)).not.toContain(summaryText);
- });
- it("adds a fallback fork divider for legacy fork snapshots without synthetic notice", () => {
- const baseSnapshot = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...baseSnapshot,
- session: {
- ...baseSnapshot.session,
- parentSessionId: "parent-session",
- },
- });
- expect(snapshot.messages).toHaveLength(3);
- expect(snapshot.messages[2]).toMatchObject({
- id: "zcode-timeline-fork-parent-session-",
- role: "user",
- content: "",
- syntheticTimeline: {
- type: "session_fork",
- display: "separator",
- parentSessionId: "parent-session",
- targetMessageId: "",
- },
- });
- });
- it("projects /goal continuation reminders back to the visible slash command query", () => {
- const internalGoalPrompt = [
- '<system-reminder source="goal-continuation">',
- "Continue working toward the active session goal.",
- "",
- "<untrusted_objective>",
- "优化性能到 60fps",
- "</untrusted_objective>",
- "</system-reminder>",
- ].join("\n");
- const baseSnapshot = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...baseSnapshot,
- session: {
- ...baseSnapshot.session,
- title: internalGoalPrompt,
- },
- projection: {
- ...baseSnapshot.projection,
- target: {
- sessionId: "sess_1",
- targetId: "goal_1",
- objective: "优化性能到 60fps",
- summaryTitle: "优化性能到 60fps",
- status: "active",
- tokenBudget: null,
- tokensUsed: 0,
- timeUsedSeconds: 0,
- createdAt: 1,
- updatedAt: 1,
- },
- },
- messages: [
- {
- info: {
- messageId: "msg_goal_internal",
- sessionId: "sess_1",
- role: "user",
- time: { created: 100 },
- agent: "zcode-agent",
- model,
- },
- parts: [
- {
- partId: "part_goal_internal",
- sessionId: "sess_1",
- messageId: "msg_goal_internal",
- type: "text",
- text: internalGoalPrompt,
- },
- ],
- },
- {
- info: {
- messageId: "msg_goal_assistant",
- sessionId: "sess_1",
- role: "assistant",
- parentMessageId: "msg_goal_internal",
- time: { created: 200, completed: 300 },
- agent: "zcode-agent",
- model,
- path: { cwd: "/workspace/app", root: "/workspace/app" },
- cost: 0,
- tokens: {
- input: 1,
- output: 2,
- reasoning: 0,
- total: 3,
- cache: { read: 0, write: 0 },
- },
- },
- parts: [
- {
- partId: "part_goal_assistant_text",
- sessionId: "sess_1",
- messageId: "msg_goal_assistant",
- type: "text",
- text: "我会先定位渲染瓶颈。",
- },
- ],
- },
- ],
- });
- expect(snapshot.meta.title).toBe("优化性能到 60fps");
- expect(snapshot.meta.target).toMatchObject({
- objective: "优化性能到 60fps",
- summaryTitle: "优化性能到 60fps",
- targetID: "goal_1",
- });
- expect(snapshot.messages).toHaveLength(2);
- expect(snapshot.messages[0]).toMatchObject({
- role: "user",
- content: "/goal 优化性能到 60fps",
- });
- expect(snapshot.messages[0]?.content).not.toContain("system-reminder");
- expect(snapshot.messages[1]).toMatchObject({
- role: "assistant",
- content: "我会先定位渲染瓶颈。",
- goalIteration: 1,
- });
- });
- it("keeps verifier-bounded goal continuation assistant messages split by goal iteration in snapshots", () => {
- const objective = "优化性能到 60fps";
- const baseSnapshot = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...baseSnapshot,
- projection: {
- ...baseSnapshot.projection,
- target: {
- sessionId: "sess_1",
- targetId: "goal_1",
- objective,
- summaryTitle: null,
- status: "active",
- tokenBudget: null,
- tokensUsed: 0,
- timeUsedSeconds: 0,
- createdAt: 100,
- updatedAt: 100,
- },
- },
- runtime: {
- ...baseSnapshot.runtime,
- goalVerificationTimeline: [
- {
- version: 1,
- kind: "synthetic",
- type: "goal_verification",
- display: "separator",
- targetId: "goal_1",
- verificationId: "verify_goal_1",
- status: "completed",
- goalIteration: 1,
- verification: {
- nextAction: "继续做第二轮。",
- passed: false,
- reason: "第一轮还没完成。",
- },
- startedAt: 300,
- updatedAt: 300,
- },
- ],
- },
- messages: [
- {
- info: {
- messageId: "msg_user_goal",
- sessionId: "sess_1",
- role: "user",
- time: { created: 100 },
- agent: "zcode-agent",
- model,
- },
- parts: [
- {
- partId: "part_user_goal",
- sessionId: "sess_1",
- messageId: "msg_user_goal",
- type: "text",
- text: `/goal ${objective}`,
- },
- ],
- },
- {
- info: {
- messageId: "msg_assistant_goal_1",
- sessionId: "sess_1",
- role: "assistant",
- parentMessageId: "msg_user_goal",
- time: { created: 200, completed: 250 },
- agent: "zcode-agent",
- model,
- path: { cwd: "/workspace/app", root: "/workspace/app" },
- cost: 0,
- tokens: {
- input: 1,
- output: 2,
- reasoning: 0,
- total: 3,
- cache: { read: 0, write: 0 },
- },
- },
- parts: [
- {
- partId: "part_assistant_goal_1",
- sessionId: "sess_1",
- messageId: "msg_assistant_goal_1",
- type: "text",
- text: "第一轮。",
- },
- ],
- },
- {
- info: {
- messageId: "msg_goal_continue",
- sessionId: "sess_1",
- role: "user",
- time: { created: 300 },
- agent: "zcode-agent",
- model,
- synthetic: true,
- source: "goal-continuation",
- visibility: "model-only",
- metadata: { source: "goal-continuation", visibility: "model-only" },
- },
- parts: [
- {
- partId: "part_goal_continue",
- sessionId: "sess_1",
- messageId: "msg_goal_continue",
- type: "text",
- text: "<system-reminder>\nContinue working toward the active session goal.\n</system-reminder>",
- synthetic: true,
- metadata: {
- source: "goal-continuation",
- visibility: "model-only",
- },
- },
- ],
- },
- {
- info: {
- messageId: "msg_assistant_goal_2",
- sessionId: "sess_1",
- role: "assistant",
- parentMessageId: "msg_goal_continue",
- time: { created: 400, completed: 450 },
- agent: "zcode-agent",
- model,
- path: { cwd: "/workspace/app", root: "/workspace/app" },
- cost: 0,
- tokens: {
- input: 1,
- output: 2,
- reasoning: 0,
- total: 3,
- cache: { read: 0, write: 0 },
- },
- },
- parts: [
- {
- partId: "part_assistant_goal_2",
- sessionId: "sess_1",
- messageId: "msg_assistant_goal_2",
- type: "text",
- text: "第二轮。",
- },
- ],
- },
- ],
- });
- expect(snapshot.messages).toHaveLength(4);
- expect(snapshot.messages[1]).toMatchObject({
- role: "assistant",
- content: "第一轮。",
- goalIteration: 1,
- });
- expect(snapshot.messages[2]).toMatchObject({
- role: "assistant",
- content: "",
- syntheticTimeline: {
- type: "goal_verification",
- verificationId: "verify_goal_1",
- goalIteration: 1,
- },
- });
- expect(snapshot.messages[3]).toMatchObject({
- role: "assistant",
- content: "第二轮。",
- goalIteration: 2,
- });
- });
- it("restores /goal prefix for persisted objective user messages", () => {
- const objective = "优化性能到 60fps";
- const baseSnapshot = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...baseSnapshot,
- projection: {
- ...baseSnapshot.projection,
- target: {
- sessionId: "sess_1",
- targetId: "goal_1",
- objective,
- summaryTitle: null,
- status: "active",
- tokenBudget: null,
- tokensUsed: 0,
- timeUsedSeconds: 0,
- createdAt: 100,
- updatedAt: 100,
- },
- },
- messages: [
- {
- info: {
- messageId: "msg_goal_objective",
- sessionId: "sess_1",
- role: "user",
- time: { created: 100 },
- agent: "zcode-agent",
- model,
- },
- parts: [
- {
- partId: "part_goal_objective",
- sessionId: "sess_1",
- messageId: "msg_goal_objective",
- type: "text",
- text: objective,
- },
- ],
- },
- ],
- });
- expect(snapshot.meta.title).toBe(objective);
- expect(snapshot.messages).toHaveLength(1);
- expect(snapshot.messages[0]).toMatchObject({
- role: "user",
- content: `/goal ${objective}`,
- });
- });
- it("does not add /goal to earlier normal user messages with the same text", () => {
- const objective = "优化性能到 60fps";
- const baseSnapshot = createSnapshot();
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...baseSnapshot,
- projection: {
- ...baseSnapshot.projection,
- target: {
- sessionId: "sess_1",
- targetId: "goal_1",
- objective,
- summaryTitle: null,
- status: "active",
- tokenBudget: null,
- tokensUsed: 0,
- timeUsedSeconds: 0,
- createdAt: 200,
- updatedAt: 200,
- },
- },
- messages: [
- {
- info: {
- messageId: "msg_normal_user",
- sessionId: "sess_1",
- role: "user",
- time: { created: 100 },
- agent: "zcode-agent",
- model,
- },
- parts: [
- {
- partId: "part_normal_user",
- sessionId: "sess_1",
- messageId: "msg_normal_user",
- type: "text",
- text: objective,
- },
- ],
- },
- ],
- });
- expect(snapshot.messages[0]).toMatchObject({
- role: "user",
- content: objective,
- });
- });
- it("maps ZCode Protocol context projection updates to legacy usage_update events", () => {
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_usage",
- sessionId: "sess_1",
- seq: 4,
- timestamp: 4,
- traceId: "trace_usage",
- type: "session.updated",
- payload: {
- contextUsed: 24000,
- contextWindow: 128000,
- },
- },
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "usage_update",
- taskId: "sess_1",
- traceId: "trace_usage",
- used: 24000,
- size: 128000,
- cost: null,
- },
- ]);
- });
- it("preserves goal target run action patches", () => {
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_goal_run_started",
- sessionId: "sess_1",
- seq: 4,
- timestamp: 4,
- traceId: "trace_goal_run",
- type: "session.updated",
- payload: {
- action: "run_started",
- source: "runtime",
- target: {
- activeInputId: "input-1",
- activeRunLastSeenAtMs: 4_000,
- activeRunStartedAtMs: 4_000,
- createdAt: 1,
- objective: "Fix elapsed",
- sessionId: "sess_1",
- status: "active",
- summaryTitle: null,
- targetId: "target-1",
- timeUsedSeconds: 0,
- tokenBudget: null,
- tokensUsed: 0,
- updatedAt: 4_000,
- },
- },
- },
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- target: {
- action: "run_started",
- source: "runtime",
- target: {
- activeInputId: "input-1",
- activeRunLastSeenAtMs: 4_000,
- activeRunStartedAtMs: 4_000,
- objective: "Fix elapsed",
- sessionID: "sess_1",
- status: "active",
- summaryTitle: null,
- targetID: "target-1",
- time: { created: 1, updated: 4_000 },
- timeUsedSeconds: 0,
- tokenBudget: null,
- tokensUsed: 0,
- },
- },
- taskId: "sess_1",
- traceId: "trace_goal_run",
- type: "session_info_update",
- },
- ]);
- });
- it("maps model streaming tool input into pending tool call previews", () => {
- const state = {
- streamingToolInputById: new Map(),
- toolNameById: new Map<string, string>(),
- };
- const common = {
- sessionId: "sess_1",
- seq: 4,
- timestamp: 4,
- traceId: "trace_tool_input",
- type: "model.streaming" as const,
- };
- const startEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...common,
- eventId: "evt_tool_input_start",
- payload: {
- kind: "tool_input_start",
- toolCallId: "call_write",
- toolName: "Write",
- },
- },
- state,
- taskId: "sess_1",
- });
- expect(startEvents).toEqual([
- expect.objectContaining({
- type: "tool_call",
- toolId: "call_write",
- toolName: "Write",
- input: {},
- }),
- ]);
- const deltaEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...common,
- eventId: "evt_tool_input_delta",
- payload: {
- kind: "tool_input_delta",
- toolCallId: "call_write",
- delta: '{"file_path":"src/app.ts","content":"line 1\\nline 2',
- },
- },
- state,
- taskId: "sess_1",
- });
- expect(deltaEvents).toEqual([
- expect.objectContaining({
- type: "tool_call_update",
- toolId: "call_write",
- status: "pending",
- input: {
- file_path: "src/app.ts",
- content: "line 1\nline 2",
- },
- }),
- ]);
- const nextDeltaEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...common,
- eventId: "evt_tool_input_delta_2",
- payload: {
- kind: "tool_input_delta",
- toolCallId: "call_write",
- delta: "\\nline 3",
- },
- },
- state,
- taskId: "sess_1",
- });
- expect(nextDeltaEvents).toEqual([]);
- expect(state.streamingToolInputById?.get("call_write")?.rawInput).toContain("\\nline 3");
- const endEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...common,
- eventId: "evt_tool_input_end",
- payload: {
- kind: "tool_input_end",
- toolCallId: "call_write",
- },
- },
- state,
- taskId: "sess_1",
- });
- expect(endEvents).toEqual([
- expect.objectContaining({
- type: "tool_call_update",
- toolId: "call_write",
- toolName: "Write",
- raw: expect.objectContaining({
- streamingRawInputLength: expect.any(Number),
- }),
- }),
- ]);
- expect(endEvents[0]).not.toHaveProperty("input");
- expect(state.streamingToolInputById?.get("call_write")?.rawInput).toContain("\\nline 3");
- const completeEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...common,
- eventId: "evt_tool_call",
- payload: {
- kind: "tool_call",
- toolCallId: "call_write",
- toolName: "Write",
- input: {
- file_path: "src/app.ts",
- content: "line 1\nline 2\n",
- },
- },
- },
- state,
- taskId: "sess_1",
- });
- expect(completeEvents).toEqual([
- expect.objectContaining({
- type: "tool_call_update",
- toolId: "call_write",
- input: {
- file_path: "src/app.ts",
- content: "line 1\nline 2\n",
- },
- }),
- ]);
- expect(state.streamingToolInputById?.get("call_write")?.rawInput).toBe("");
- });
- it("maps scheduled tool tombstones without rematerializing input", () => {
- const state: ZCodeSessionEventProjectionState = {
- streamingToolInputById: new Map(),
- toolNameById: new Map<string, string>(),
- };
- const streamingToolCall = {
- eventId: "evt_tool_call",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 4,
- timestamp: 4,
- traceId: "trace_tool_input",
- type: "model.streaming",
- payload: {
- kind: "tool_call",
- toolCallId: "call_write",
- toolName: "Write",
- input: {
- content: "hello",
- file_path: "/tmp/generated.html",
- },
- },
- } satisfies ZCodeSessionEvent;
- const scheduledTombstone = {
- eventId: "evt_tool_scheduled",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 5,
- timestamp: 5,
- traceId: "trace_tool_input",
- type: "tool.updated",
- payload: {
- kind: "scheduled",
- toolCallId: "call_write",
- toolName: "Write",
- inputByteLength: 57,
- inputOmitted: true,
- inputRef: "model_stream",
- },
- } satisfies ZCodeSessionEvent;
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: streamingToolCall,
- state,
- taskId: "sess_1",
- }),
- ).toEqual([
- expect.objectContaining({
- type: "tool_call_update",
- toolId: "call_write",
- }),
- ]);
- const scheduledEvents = zcodeSessionEventToZCodeStreamEvents({
- event: scheduledTombstone,
- state,
- taskId: "sess_1",
- });
- expect(scheduledEvents).toEqual([
- expect.objectContaining({
- raw: expect.not.objectContaining({
- input: expect.anything(),
- }),
- status: "in_progress",
- toolId: "call_write",
- type: "tool_call_update",
- }),
- ]);
- expect(Object.prototype.hasOwnProperty.call(scheduledEvents[0], "input")).toBe(false);
- });
- it("clears streaming raw input when complete tool input is remembered", () => {
- const state: ZCodeSessionEventProjectionState = {
- streamingToolInputById: new Map(),
- toolNameById: new Map<string, string>(),
- };
- const streamingDelta = {
- eventId: "evt_tool_delta",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 1,
- timestamp: 1,
- traceId: "trace_tool_input",
- type: "model.streaming",
- payload: {
- kind: "tool_input_delta",
- toolCallId: "call_write",
- toolName: "Write",
- delta: '{"file_path":"/tmp/generated.html","content":"hello"',
- },
- } satisfies ZCodeSessionEvent;
- const scheduledWithCompleteInput = {
- eventId: "evt_tool_scheduled",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 2,
- timestamp: 2,
- traceId: "trace_tool_input",
- type: "tool.updated",
- payload: {
- kind: "scheduled",
- toolCallId: "call_write",
- toolName: "Write",
- input: {
- content: "hello",
- file_path: "/tmp/generated.html",
- },
- },
- } satisfies ZCodeSessionEvent;
- zcodeSessionEventToZCodeStreamEvents({
- event: streamingDelta,
- state,
- taskId: "sess_1",
- });
- expect(state.streamingToolInputById?.get("call_write")?.rawInput).toContain("generated.html");
- zcodeSessionEventToZCodeStreamEvents({
- event: scheduledWithCompleteInput,
- state,
- taskId: "sess_1",
- });
- expect(state.streamingToolInputById?.get("call_write")?.rawInput).toBe("");
- expect(state.completeToolInputById?.get("call_write")).toEqual({
- content: "hello",
- file_path: "/tmp/generated.html",
- });
- });
- it("creates missing streaming input state so foreground Write deltas accumulate", () => {
- const state: ZCodeSessionEventProjectionState = {
- toolNameById: new Map<string, string>(),
- };
- const common = {
- sessionId: "sess_1",
- seq: 4,
- timestamp: 4,
- traceId: "trace_tool_input",
- type: "model.streaming" as const,
- };
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...common,
- eventId: "evt_tool_input_start",
- payload: {
- kind: "tool_input_start",
- toolCallId: "call_write",
- toolName: "Write",
- },
- },
- state,
- taskId: "sess_1",
- });
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...common,
- eventId: "evt_tool_input_delta",
- payload: {
- kind: "tool_input_delta",
- toolCallId: "call_write",
- delta: '{"file_path":"src/app.ts","content":"line 1\\nline 2',
- },
- },
- state,
- taskId: "sess_1",
- });
- const nextDeltaEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...common,
- eventId: "evt_tool_input_delta_2",
- payload: {
- kind: "tool_input_delta",
- toolCallId: "call_write",
- delta: "\\nline 3",
- },
- },
- state,
- taskId: "sess_1",
- });
- expect(state.streamingToolInputById?.get("call_write")?.deltaCount).toBe(2);
- expect(nextDeltaEvents).toEqual([]);
- const endEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...common,
- eventId: "evt_tool_input_end",
- payload: {
- kind: "tool_input_end",
- toolCallId: "call_write",
- },
- },
- state,
- taskId: "sess_1",
- });
- expect(endEvents).toEqual([
- expect.objectContaining({
- type: "tool_call_update",
- toolId: "call_write",
- raw: expect.objectContaining({
- streamingRawInputLength: expect.any(Number),
- }),
- }),
- ]);
- expect(endEvents[0]).not.toHaveProperty("input");
- });
- it("infers Write for streamed file inputs when the delta arrives without cached tool metadata", () => {
- const streamEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_tool_input_delta_no_name",
- sessionId: "sess_1",
- seq: 4,
- timestamp: 4,
- traceId: "trace_tool_input",
- type: "model.streaming",
- payload: {
- kind: "tool_input_delta",
- toolCallId: "call_write",
- delta: '{"file_path":"src/app.ts","content":"line 1',
- },
- },
- state: {
- streamingToolInputById: new Map(),
- toolNameById: new Map<string, string>(),
- },
- taskId: "sess_1",
- });
- expect(streamEvents).toEqual([
- expect.objectContaining({
- type: "tool_call_update",
- toolId: "call_write",
- toolName: "Write",
- kind: "Write",
- }),
- ]);
- });
- it("keeps background streaming tool input as a tombstone until materialization", () => {
- const state: ZCodeSessionEventProjectionState = {
- streamingToolInputById: new Map(),
- toolNameById: new Map<string, string>(),
- };
- const common = {
- sessionId: "sess_1",
- seq: 4,
- timestamp: 4,
- traceId: "trace_tool_input",
- type: "model.streaming" as const,
- };
- const startEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...common,
- eventId: "evt_tool_input_start",
- payload: {
- kind: "tool_input_start",
- toolCallId: "call_write",
- toolName: "Write",
- },
- },
- projectionMode: "background-summary",
- state,
- taskId: "sess_1",
- });
- const deltaEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...common,
- eventId: "evt_tool_input_delta",
- payload: {
- kind: "tool_input_delta",
- toolCallId: "call_write",
- delta: '{"file_path":"src/app.ts","content":"line 1\\nline 2',
- },
- },
- projectionMode: "background-summary",
- state,
- taskId: "sess_1",
- });
- expect(startEvents).toHaveLength(1);
- expect(deltaEvents).toEqual([]);
- expect(state.streamingToolInputById?.get("call_write")).toMatchObject({
- deltaCount: 1,
- rawInput: '{"file_path":"src/app.ts","content":"line 1\\nline 2',
- });
- const completeEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...common,
- eventId: "evt_tool_call",
- payload: {
- kind: "tool_call",
- toolCallId: "call_write",
- toolName: "Write",
- input: {
- file_path: "src/app.ts",
- content: "line 1\nline 2",
- },
- },
- },
- projectionMode: "background-summary",
- state,
- taskId: "sess_1",
- });
- expect(completeEvents).toEqual([
- expect.objectContaining({
- type: "tool_call_update",
- toolId: "call_write",
- input: {
- file_path: "src/app.ts",
- content: "line 1\nline 2",
- },
- }),
- ]);
- });
- it("budgets active streaming tool input previews instead of projecting every delta", () => {
- vi.useFakeTimers();
- try {
- vi.setSystemTime(1_000);
- const state: ZCodeSessionEventProjectionState = {
- streamingToolInputById: new Map(),
- toolNameById: new Map<string, string>(),
- };
- const common = {
- sessionId: "sess_1",
- seq: 4,
- timestamp: 4,
- traceId: "trace_tool_input",
- type: "model.streaming" as const,
- };
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...common,
- eventId: "evt_tool_input_start",
- payload: {
- kind: "tool_input_start",
- toolCallId: "call_write",
- toolName: "Write",
- },
- },
- state,
- taskId: "sess_1",
- });
- let materializedCount = 0;
- for (let index = 0; index < 100; index += 1) {
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...common,
- eventId: `evt_tool_input_delta_${index}`,
- payload: {
- kind: "tool_input_delta",
- toolCallId: "call_write",
- delta: "x",
- },
- },
- state,
- taskId: "sess_1",
- });
- materializedCount += events.length;
- }
- expect(state.streamingToolInputById?.get("call_write")?.deltaCount).toBe(100);
- expect(materializedCount).toBe(1);
- vi.setSystemTime(2_000);
- const intervalEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...common,
- eventId: "evt_tool_input_delta_interval",
- payload: {
- kind: "tool_input_delta",
- toolCallId: "call_write",
- delta: "y",
- },
- },
- state,
- taskId: "sess_1",
- });
- expect(intervalEvents).toHaveLength(1);
- } finally {
- vi.useRealTimers();
- }
- });
- it("maps goal completion verifier model results to goal verification updates", () => {
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_goal_verify",
- sessionId: "sess_1",
- seq: 4,
- timestamp: 4,
- traceId: "trace_goal_verify",
- type: "session.updated",
- payload: {
- content: JSON.stringify({
- nextAction: "跑移动端 smoke test。",
- passed: false,
- reason: "第一轮证据不足。",
- }),
- querySource: "target_completion_verification",
- stopReason: "stop",
- usage: {
- inputTokens: 1,
- outputTokens: 1,
- totalTokens: 2,
- },
- },
- },
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "goal_verification_update",
- taskId: "sess_1",
- traceId: "trace_goal_verify",
- verification: {
- nextAction: "跑移动端 smoke test。",
- passed: false,
- reason: "第一轮证据不足。",
- },
- },
- {
- type: "task_token_usage_delta",
- taskId: "sess_1",
- traceId: "trace_goal_verify",
- eventId: "evt_goal_verify",
- eventKey: "evt_goal_verify",
- querySource: "target_completion_verification",
- usage: {
- inputTokens: 1,
- outputTokens: 1,
- totalTokens: 2,
- },
- },
- ]);
- });
- it("does not synthesize nextAction when goal completion verifier JSON is invalid", () => {
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_goal_verify_invalid",
- sessionId: "sess_1",
- seq: 4,
- timestamp: 4,
- traceId: "trace_goal_verify",
- type: "session.updated",
- payload: {
- content: "not json",
- querySource: "target_completion_verification",
- stopReason: "stop",
- },
- },
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "goal_verification_update",
- taskId: "sess_1",
- traceId: "trace_goal_verify",
- verification: {
- passed: true,
- reason: "The completion verifier did not return valid JSON.",
- },
- },
- ]);
- });
- it("maps goal verification lifecycle payloads to synthetic divider chunks", () => {
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_goal_verify_started",
- sessionId: "sess_1",
- seq: 4,
- timestamp: 42,
- traceId: "trace_goal_verify",
- type: "session.updated",
- payload: {
- status: "started",
- targetId: "target_1",
- verificationId: "verify_1",
- goalIteration: 2,
- anchorAssistantMessageId: "assistant_1",
- anchorTurnId: "turn_1",
- },
- },
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "agent_message_chunk",
- taskId: "sess_1",
- traceId: "trace_goal_verify",
- messageId: "zcode-goal-verification-target_1-2",
- content: "",
- zcodeTimeline: {
- version: 1,
- kind: "synthetic",
- type: "goal_verification",
- display: "separator",
- targetId: "target_1",
- verificationId: "verify_1",
- goalIteration: 2,
- anchorAssistantMessageId: "assistant_1",
- anchorTurnId: "turn_1",
- status: "started",
- startedAt: 42,
- updatedAt: 42,
- },
- },
- ]);
- });
- it("maps completed goal verification lifecycle payloads with verifier result", () => {
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_goal_verify_completed",
- sessionId: "sess_1",
- seq: 5,
- timestamp: 52,
- traceId: "trace_goal_verify",
- type: "session.updated",
- payload: {
- status: "completed",
- targetId: "target_1",
- verificationId: "verify_1",
- goalIteration: 3,
- verification: {
- nextAction: null,
- passed: true,
- reason: "所有目标要求都已完成。",
- },
- },
- },
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "agent_message_chunk",
- taskId: "sess_1",
- traceId: "trace_goal_verify",
- messageId: "zcode-goal-verification-target_1-3",
- content: "",
- zcodeTimeline: {
- version: 1,
- kind: "synthetic",
- type: "goal_verification",
- display: "separator",
- targetId: "target_1",
- verificationId: "verify_1",
- status: "completed",
- goalIteration: 3,
- verification: {
- passed: true,
- reason: "所有目标要求都已完成。",
- },
- updatedAt: 52,
- },
- },
- ]);
- });
- it.each(["plan", "edit"] as const)("maps %s mode updates without replacing historical values", (mode) => {
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_mode",
- sessionId: "sess_1",
- seq: 4,
- timestamp: 4,
- traceId: "trace_mode",
- type: "session.updated",
- payload: {
- mode,
- previousMode: "build",
- source: "tool",
- },
- },
- taskId: "sess_1",
- });
- expect(events).toHaveLength(1);
- expect(events[0]).toEqual(
- expect.objectContaining({
- type: "mode_update",
- taskId: "sess_1",
- traceId: "trace_mode",
- currentModeId: mode,
- availableModes: expect.arrayContaining([
- expect.objectContaining({ id: "build" }),
- expect.objectContaining({ id: "guarded" }),
- expect.objectContaining({ id: "plan" }),
- expect.objectContaining({ id: "yolo" }),
- ]),
- }),
- );
- });
- it("maps main turn model usage with context window to legacy usage_update events", () => {
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_model_usage",
- sessionId: "sess_1",
- seq: 5,
- timestamp: 5,
- traceId: "trace_model_usage",
- type: "session.updated",
- payload: {
- contextWindow: 1_000_000,
- querySource: "main_turn",
- usage: {
- inputTokens: 279454,
- outputTokens: 177,
- totalTokens: 279631,
- cacheReadTokens: 1000,
- cacheWriteTokens: 200,
- cacheHitRate: 0.25,
- },
- contextUsageBreakdown: [
- { source: "messages", chars: 1200 },
- { source: "system_tool_schemas", chars: 300 },
- ],
- },
- },
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "task_token_usage_delta",
- taskId: "sess_1",
- traceId: "trace_model_usage",
- eventKey: "evt_model_usage",
- eventId: "evt_model_usage",
- querySource: "main_turn",
- usage: {
- inputTokens: 279454,
- outputTokens: 177,
- totalTokens: 279631,
- reasoningTokens: undefined,
- cachedInputTokens: 1000,
- cachedWriteInputTokens: 200,
- },
- },
- {
- type: "usage_update",
- taskId: "sess_1",
- traceId: "trace_model_usage",
- used: 279631,
- size: 1_000_000,
- cost: null,
- cache: {
- inputTokens: 279454,
- cacheReadTokens: 1000,
- cacheWriteTokens: 200,
- latestHitRate: 0.25,
- hitRate: 0.25,
- },
- breakdown: [
- { source: "messages", chars: 1200 },
- { source: "system_tool_schemas", chars: 300 },
- ],
- },
- ]);
- });
- it("maps model network status payloads to task network debug events", () => {
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_network_debug",
- sessionId: "sess_1",
- seq: 5,
- timestamp: 5,
- traceId: "trace_network_debug",
- type: "session.updated",
- payload: {
- type: "model_retry_scheduled",
- requestId: "request-1",
- timestamp: "2026-06-10T00:00:00.000Z",
- model: {
- providerId: "openai",
- modelId: "model-test",
- },
- transport: "http",
- attempt: 1,
- maxAttempts: 3,
- nextAttempt: 2,
- delayMs: 1000,
- reason: "rate_limited",
- message: "rate limited",
- statusCode: 429,
- requestHeaders: {
- authorization: "[redacted]",
- },
- responseHeaders: {
- "retry-after": "1",
- },
- },
- },
- taskId: "sess_1",
- });
- expect(events).toContainEqual({
- type: "task_network_debug_status",
- taskId: "sess_1",
- traceId: "trace_network_debug",
- eventKey: "evt_network_debug",
- eventId: "evt_network_debug",
- statusType: "model_retry_scheduled",
- requestId: "request-1",
- providerId: "openai",
- modelId: "model-test",
- transport: "http",
- attempt: 1,
- maxAttempts: 3,
- nextAttempt: 2,
- statusCode: 429,
- delayMs: 1000,
- reason: "rate_limited",
- message: "rate limited",
- timestamp: "2026-06-10T00:00:00.000Z",
- requestHeaders: {
- authorization: "[redacted]",
- },
- responseHeaders: {
- "retry-after": "1",
- },
- requestHeaderCount: 1,
- responseHeaderCount: 1,
- });
- });
- it("maps aggregate main turn cache hit usage from protocol payload", () => {
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_model_usage_average",
- sessionId: "sess_1",
- seq: 5,
- timestamp: 5,
- traceId: "trace_model_usage_average",
- type: "session.updated",
- payload: {
- contextWindow: 1_000_000,
- querySource: "main_turn",
- cacheHit: {
- inputTokens: 200,
- cacheReadTokens: 80,
- cacheWriteTokens: 10,
- latestHitRate: 0.4,
- hitRate: 0.3,
- hitRateRequestCount: 2,
- totalInputTokens: 500,
- totalCacheReadTokens: 150,
- totalCacheWriteTokens: 25,
- },
- usage: {
- inputTokens: 200,
- outputTokens: 20,
- totalTokens: 220,
- cacheReadTokens: 80,
- cacheWriteTokens: 10,
- },
- },
- },
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "task_token_usage_delta",
- taskId: "sess_1",
- traceId: "trace_model_usage_average",
- eventKey: "evt_model_usage_average",
- eventId: "evt_model_usage_average",
- querySource: "main_turn",
- usage: {
- inputTokens: 200,
- outputTokens: 20,
- totalTokens: 220,
- reasoningTokens: undefined,
- cachedInputTokens: 80,
- cachedWriteInputTokens: 10,
- },
- },
- {
- type: "usage_update",
- taskId: "sess_1",
- traceId: "trace_model_usage_average",
- used: 220,
- size: 1_000_000,
- cost: null,
- cache: {
- inputTokens: 200,
- cacheReadTokens: 80,
- cacheWriteTokens: 10,
- latestHitRate: 0.4,
- hitRate: 0.3,
- hitRateRequestCount: 2,
- totalInputTokens: 500,
- totalCacheReadTokens: 150,
- totalCacheWriteTokens: 25,
- },
- },
- ]);
- });
- it("prefers real main turn model usage over projected context used", () => {
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_model_usage_projection",
- sessionId: "sess_1",
- seq: 5,
- timestamp: 5,
- traceId: "trace_model_usage_projection",
- type: "session.updated",
- payload: {
- contextUsed: 64000,
- contextWindow: 1_000_000,
- querySource: "main_turn",
- usage: {
- inputTokens: 12345,
- outputTokens: 77,
- totalTokens: 12422,
- },
- },
- },
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "task_token_usage_delta",
- taskId: "sess_1",
- traceId: "trace_model_usage_projection",
- eventKey: "evt_model_usage_projection",
- eventId: "evt_model_usage_projection",
- querySource: "main_turn",
- usage: {
- inputTokens: 12345,
- outputTokens: 77,
- totalTokens: 12422,
- reasoningTokens: undefined,
- cachedInputTokens: undefined,
- cachedWriteInputTokens: undefined,
- },
- },
- {
- type: "usage_update",
- taskId: "sess_1",
- traceId: "trace_model_usage_projection",
- used: 12422,
- size: 1_000_000,
- cost: null,
- },
- ]);
- });
- it("does not map sidecar model usage to context usage", () => {
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_title_usage",
- sessionId: "sess_1",
- seq: 6,
- timestamp: 6,
- traceId: "trace_title_usage",
- type: "session.updated",
- payload: {
- contextWindow: 1_000_000,
- querySource: "session_title",
- usage: {
- inputTokens: 89,
- outputTokens: 84,
- totalTokens: 173,
- },
- },
- },
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "task_token_usage_delta",
- taskId: "sess_1",
- traceId: "trace_title_usage",
- eventKey: "evt_title_usage",
- eventId: "evt_title_usage",
- querySource: "session_title",
- usage: {
- inputTokens: 89,
- outputTokens: 84,
- totalTokens: 173,
- reasoningTokens: undefined,
- cachedInputTokens: undefined,
- cachedWriteInputTokens: undefined,
- },
- },
- ]);
- });
- it("maps ZCode model retry status updates to apiRetry events", () => {
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_retry",
- sessionId: "sess_1",
- seq: 5,
- timestamp: 5,
- traceId: "trace_retry",
- type: "session.updated",
- payload: {
- type: "model_retry_scheduled",
- attempt: 1,
- maxAttempts: 4,
- delayMs: 2_000,
- statusCode: 429,
- message: "rate limited",
- },
- },
- taskId: "sess_1",
- });
- expect(events).toContainEqual(
- expect.objectContaining({
- type: "task_network_debug_status",
- taskId: "sess_1",
- traceId: "trace_retry",
- eventKey: "evt_retry",
- statusType: "model_retry_scheduled",
- attempt: 1,
- maxAttempts: 4,
- delayMs: 2_000,
- statusCode: 429,
- }),
- );
- expect(events).toContainEqual({
- type: "session_info_update",
- taskId: "sess_1",
- traceId: "trace_retry",
- apiRetry: {
- kind: "api_retry",
- attempt: 1,
- maxRetries: 3,
- retryDelayMs: 2_000,
- errorStatus: 429,
- error: "rate limited",
- },
- });
- });
- it("keeps adapter retry visible until the retry attempt produces progress", () => {
- const state: ZCodeSessionEventProjectionState = {
- streamedTurnKeys: new Set<string>(),
- toolNameById: new Map<string, string>(),
- };
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_retry_scheduled",
- sessionId: "sess_1",
- seq: 5,
- timestamp: 5,
- traceId: "trace_retry",
- type: "session.updated",
- payload: {
- type: "model_retry_scheduled",
- attempt: 1,
- maxAttempts: 4,
- delayMs: 2_000,
- message: "rate limited",
- },
- },
- state,
- taskId: "sess_1",
- }),
- ).toContainEqual({
- type: "session_info_update",
- taskId: "sess_1",
- traceId: "trace_retry",
- apiRetry: {
- kind: "api_retry",
- attempt: 1,
- maxRetries: 3,
- retryDelayMs: 2_000,
- errorStatus: null,
- error: "rate limited",
- },
- });
- const retryStartedEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_retry_started",
- sessionId: "sess_1",
- seq: 6,
- timestamp: 6,
- traceId: "trace_retry",
- type: "session.updated",
- payload: {
- type: "model_request_started",
- attempt: 2,
- maxAttempts: 4,
- requestId: "request_retry",
- },
- },
- state,
- taskId: "sess_1",
- });
- expect(retryStartedEvents).toContainEqual(
- expect.objectContaining({
- type: "task_network_debug_status",
- taskId: "sess_1",
- traceId: "trace_retry",
- eventKey: "evt_retry_started",
- statusType: "model_request_started",
- attempt: 2,
- maxAttempts: 4,
- }),
- );
- expect(retryStartedEvents).not.toContainEqual({
- type: "session_info_update",
- taskId: "sess_1",
- traceId: "trace_retry",
- apiRetry: null,
- });
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_retry_progress",
- sessionId: "sess_1",
- seq: 7,
- timestamp: 7,
- traceId: "trace_retry",
- type: "session.updated",
- payload: {
- kind: "reasoning_delta",
- delta: "recovered",
- assistantMessageId: "msg_retry",
- },
- },
- state,
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "session_info_update",
- taskId: "sess_1",
- traceId: "trace_retry",
- apiRetry: null,
- },
- {
- type: "agent_thought_chunk",
- taskId: "sess_1",
- traceId: "trace_retry",
- content: "recovered",
- },
- ]);
- });
- it("maps core stream recovery request starts to apiRetry events", () => {
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_stream_recovery_retry",
- sessionId: "sess_1",
- seq: 5,
- timestamp: 5,
- traceId: "trace_retry",
- type: "session.updated",
- payload: {
- type: "model_request_started",
- attempt: 1,
- maxAttempts: 11,
- requestId: "request_recovery",
- streamRecovery: {
- attemptId: "stream_attempt_1",
- anchorId: "anchor_1",
- maxRetries: 10,
- recoveredFromRequestId: "request_failed",
- retryNumber: 3,
- },
- },
- },
- taskId: "sess_1",
- });
- expect(events).toContainEqual(
- expect.objectContaining({
- type: "task_network_debug_status",
- taskId: "sess_1",
- traceId: "trace_retry",
- eventKey: "evt_stream_recovery_retry",
- statusType: "model_request_started",
- requestId: "request_recovery",
- attempt: 1,
- maxAttempts: 11,
- }),
- );
- expect(events).toContainEqual({
- type: "session_info_update",
- taskId: "sess_1",
- traceId: "trace_retry",
- apiRetry: {
- kind: "api_retry",
- attempt: 3,
- maxRetries: 10,
- retryDelayMs: 0,
- errorStatus: null,
- error: "Model stream recovery retry started",
- },
- });
- });
- it("maps core stream recovery progress to apiRetry events", () => {
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_stream_recovery_progress",
- sessionId: "sess_1",
- seq: 5,
- timestamp: 5,
- traceId: "trace_retry",
- type: "streamRecovery.updated",
- payload: {
- attemptId: "stream_attempt_2",
- failedRequestId: "request_failed",
- maxRetries: 10,
- recoveredFromRequestId: "request_failed",
- retryNumber: 4,
- streamMode: "sse",
- },
- },
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "session_info_update",
- taskId: "sess_1",
- traceId: "trace_retry",
- apiRetry: {
- kind: "api_retry",
- attempt: 4,
- maxRetries: 10,
- retryDelayMs: 0,
- errorStatus: null,
- error: "Model stream recovery retry started",
- },
- },
- ]);
- });
- it("maps private apiRetry meta updates and clear patches", () => {
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_retry_meta",
- sessionId: "sess_1",
- seq: 5,
- timestamp: 5,
- traceId: "trace_retry",
- type: "session.updated",
- payload: {
- _meta: {
- zcode: {
- apiRetry: {
- kind: "api_retry",
- attempt: 2,
- maxRetries: 5,
- retryDelayMs: 4_000,
- errorStatus: null,
- error: "network reset",
- },
- },
- },
- },
- },
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "session_info_update",
- taskId: "sess_1",
- traceId: "trace_retry",
- apiRetry: {
- kind: "api_retry",
- attempt: 2,
- maxRetries: 5,
- retryDelayMs: 4_000,
- errorStatus: null,
- error: "network reset",
- },
- },
- ]);
- const clearEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_retry_clear",
- sessionId: "sess_1",
- seq: 6,
- timestamp: 6,
- traceId: "trace_retry",
- type: "session.updated",
- payload: {
- type: "model_request_completed",
- attempt: 3,
- maxAttempts: 4,
- },
- },
- taskId: "sess_1",
- });
- expect(clearEvents).toContainEqual(
- expect.objectContaining({
- type: "task_network_debug_status",
- taskId: "sess_1",
- traceId: "trace_retry",
- eventKey: "evt_retry_clear",
- statusType: "model_request_completed",
- attempt: 3,
- maxAttempts: 4,
- }),
- );
- expect(clearEvents).toContainEqual({
- type: "session_info_update",
- taskId: "sess_1",
- traceId: "trace_retry",
- apiRetry: null,
- });
- });
- it("maps projection background job updates to runtime stream events", () => {
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_background_bash",
- sessionId: "sess_1",
- seq: 4,
- timestamp: 4,
- traceId: "trace_background_bash",
- type: "session.updated",
- payload: {
- projection: {
- backgroundJobs: [
- {
- id: "bg-1",
- kind: "background_bash",
- command: "pnpm dev",
- status: "running",
- elapsedMs: 31_000,
- },
- ],
- },
- },
- },
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "background_bash_jobs_update",
- taskId: "sess_1",
- traceId: "trace_background_bash",
- jobs: [
- expect.objectContaining({
- jobId: "bg-1",
- command: "pnpm dev",
- status: "running",
- elapsedMs: 31_000,
- }),
- ],
- },
- ]);
- });
- it("maps single background task payloads into cached background job updates", () => {
- const state: ZCodeSessionEventProjectionState = {};
- const bashEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_background_bash_started",
- sessionId: "sess_1",
- seq: 4,
- timestamp: 4,
- traceId: "trace_background_bash_started",
- type: "session.updated",
- payload: {
- taskId: "exec_1",
- terminalId: "exec_1",
- toolCallId: "toolu_bash",
- toolName: "Bash",
- command: "sleep 999",
- status: "running",
- startedAt: 10_000,
- },
- },
- state,
- taskId: "sess_1",
- });
- const agentEvents = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_background_agent_started",
- sessionId: "sess_1",
- seq: 5,
- timestamp: 5,
- traceId: "trace_background_agent_started",
- type: "session.updated",
- payload: {
- taskId: "agent_1",
- terminalId: "agent_1",
- toolCallId: "toolu_agent",
- toolName: "Agent",
- description: "E2E background cancel agent",
- status: "running",
- startedAt: 11_000,
- },
- },
- state,
- taskId: "sess_1",
- });
- expect(bashEvents).toEqual([
- {
- type: "background_bash_jobs_update",
- taskId: "sess_1",
- traceId: "trace_background_bash_started",
- jobs: [
- expect.objectContaining({
- jobId: "exec_1",
- command: "sleep 999",
- status: "running",
- toolCallId: "toolu_bash",
- }),
- ],
- },
- ]);
- expect(agentEvents).toEqual([
- {
- type: "background_bash_jobs_update",
- taskId: "sess_1",
- traceId: "trace_background_agent_started",
- jobs: [
- expect.objectContaining({
- jobId: "exec_1",
- command: "sleep 999",
- status: "running",
- }),
- expect.objectContaining({
- jobId: "agent_1",
- command: "E2E background cancel agent",
- status: "running",
- taskKind: "agent",
- toolCallId: "toolu_agent",
- }),
- ],
- },
- ]);
- });
- it("projects live task notification turns back onto the matching background Agent tool", () => {
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_task_notification_started",
- sessionId: "sess_1",
- seq: 6,
- timestamp: 6,
- traceId: "trace_task_notification",
- type: "turn.started",
- payload: {
- input: [
- "<task-notification>",
- "<task-id>agent_1</task-id>",
- "<tool-use-id>toolu_background_agent</tool-use-id>",
- "<output-file>/tmp/background-agent.output</output-file>",
- "<status>completed</status>",
- "<summary>Agent general-purpose task "Review" completed.</summary>",
- "<result>Background Agent live result</result>",
- "</task-notification>",
- ].join("\n"),
- inputSource: "task-notification",
- inputVisibility: "model-only",
- },
- },
- taskId: "sess_1",
- });
- expect(events).toEqual([
- expect.objectContaining({
- type: "task_run_started",
- taskId: "sess_1",
- traceId: "trace_task_notification",
- }),
- expect.objectContaining({
- type: "tool_call_update",
- taskId: "sess_1",
- toolId: "toolu_background_agent",
- status: "completed",
- content: "Background Agent live result",
- raw: expect.objectContaining({
- _meta: expect.objectContaining({
- zcode: expect.objectContaining({
- taskNotification: {
- outputFile: "/tmp/background-agent.output",
- result: "Background Agent live result",
- status: "completed",
- summary: 'Agent general-purpose task "Review" completed.',
- taskId: "agent_1",
- },
- }),
- }),
- toolCallId: "toolu_background_agent",
- }),
- }),
- ]);
- });
- it("projects failed live task notifications with the original provider error", () => {
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_failed_task_notification_started",
- sessionId: "sess_1",
- seq: 7,
- timestamp: 7,
- traceId: "trace_failed_task_notification",
- type: "turn.started",
- payload: {
- input: [
- "<task-notification>",
- "<task-id>agent_failed</task-id>",
- "<tool-use-id>toolu_failed_background_agent</tool-use-id>",
- "<output-file>/tmp/background-agent.output</output-file>",
- "<status>failed</status>",
- '<summary>Agent general-purpose task "Review" failed.</summary>',
- `<error>${backgroundAgentProviderError}</error>`,
- "</task-notification>",
- ].join("\n"),
- inputSource: "task-notification",
- inputVisibility: "model-only",
- },
- },
- taskId: "sess_1",
- });
- expect(events).toEqual([
- expect.objectContaining({
- type: "task_run_started",
- taskId: "sess_1",
- traceId: "trace_failed_task_notification",
- }),
- expect.objectContaining({
- type: "tool_call_update",
- taskId: "sess_1",
- toolId: "toolu_failed_background_agent",
- status: "failed",
- content: 'Agent general-purpose task "Review" failed.',
- error: backgroundAgentProviderError,
- raw: expect.objectContaining({
- _meta: expect.objectContaining({
- zcode: expect.objectContaining({
- taskNotification: expect.objectContaining({
- error: backgroundAgentProviderError,
- status: "failed",
- summary: 'Agent general-purpose task "Review" failed.',
- taskId: "agent_failed",
- }),
- }),
- }),
- toolCallId: "toolu_failed_background_agent",
- }),
- }),
- ]);
- });
- it("projects killed task notification turns as stopped tool updates", () => {
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_task_notification_stopped",
- sessionId: "sess_1",
- seq: 7,
- timestamp: 7,
- traceId: "trace_task_notification_stopped",
- type: "turn.started",
- payload: {
- input: [
- "<task-notification>",
- "<task-id>agent_1</task-id>",
- "<tool-use-id>toolu_background_agent</tool-use-id>",
- "<output-file>/tmp/background-agent.output</output-file>",
- "<status>killed</status>",
- "<summary>Agent task was stopped.</summary>",
- "</task-notification>",
- ].join("\n"),
- inputSource: "task-notification",
- inputVisibility: "model-only",
- },
- },
- taskId: "sess_1",
- });
- expect(events).toEqual([
- expect.objectContaining({
- type: "task_run_started",
- taskId: "sess_1",
- traceId: "trace_task_notification_stopped",
- }),
- expect.objectContaining({
- type: "tool_call_update",
- taskId: "sess_1",
- toolId: "toolu_background_agent",
- status: "stopped",
- content: "Agent task was stopped.",
- raw: expect.objectContaining({
- _meta: expect.objectContaining({
- zcode: expect.objectContaining({
- taskNotification: expect.objectContaining({
- status: "killed",
- summary: "Agent task was stopped.",
- taskId: "agent_1",
- }),
- }),
- }),
- }),
- }),
- ]);
- });
- it("maps direct user input requests into elicitation requests", () => {
- const event = zcodeUserInputRequestToZCodeStreamEvent("sess_1", {
- requestId: "ask_1",
- sessionId: "sess_1",
- turnId: "turn_1",
- toolCallId: "tool_ask",
- toolName: "AskUserQuestion",
- origin: subagentOrigin,
- prompt: "Need a choice",
- questions: [
- {
- question: "Which branch should I test?",
- header: "Branch",
- options: [
- { value: "main", label: "main", description: "Use main branch" },
- {
- value: "release",
- label: "release",
- description: "Use release branch",
- },
- ],
- },
- ],
- schema: { toolName: "AskUserQuestion" },
- });
- expect(event).toMatchObject({
- type: "elicitation_request",
- taskId: "sess_1",
- requestId: "ask_1",
- message: "Which branch should I test?",
- header: "Branch",
- origin: subagentOrigin,
- options: [
- { value: "main", label: "main", description: "Use main branch" },
- {
- value: "release",
- label: "release",
- description: "Use release branch",
- },
- ],
- questions: [
- {
- question: "Which branch should I test?",
- header: "Branch",
- },
- ],
- schema: { toolName: "AskUserQuestion" },
- });
- });
- it("maps nested ZCode Protocol projection context usage", () => {
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_projection_usage",
- sessionId: "sess_1",
- seq: 5,
- timestamp: 5,
- traceId: "trace_projection_usage",
- type: "session.updated",
- payload: {
- projection: {
- contextUsed: 64000,
- contextWindow: 128000,
- },
- },
- },
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "usage_update",
- taskId: "sess_1",
- traceId: "trace_projection_usage",
- used: 64000,
- size: 128000,
- cost: null,
- },
- ]);
- });
- it("does not emit legacy usage_update for zero context usage", () => {
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_zero_usage",
- sessionId: "sess_1",
- seq: 6,
- timestamp: 6,
- traceId: "trace_zero_usage",
- type: "session.updated",
- payload: {
- contextUsed: 0,
- contextWindow: 128000,
- },
- },
- taskId: "sess_1",
- }),
- ).toEqual([]);
- });
- it("merges multi-round assistant messages from the same user turn into one", () => {
- const baseAssistantInfo = {
- sessionId: "sess_1",
- role: "assistant" as const,
- parentMessageId: "msg_user",
- agent: "zcode-agent",
- model,
- path: { cwd: "/workspace/app", root: "/workspace/app" },
- cost: 0,
- tokens: {
- input: 1,
- output: 2,
- reasoning: 3,
- total: 6,
- cache: { read: 0, write: 0 },
- },
- };
- const snapshot = zcodeSessionSnapshotToZCodeTaskSnapshot({
- ...createSnapshot(),
- messages: [
- {
- info: {
- messageId: "msg_user",
- sessionId: "sess_1",
- role: "user",
- time: { created: 100 },
- agent: "zcode-agent",
- model,
- },
- parts: [
- {
- partId: "part_user",
- sessionId: "sess_1",
- messageId: "msg_user",
- type: "text",
- text: "do work",
- },
- ],
- },
- {
- info: {
- ...baseAssistantInfo,
- messageId: "msg_round1",
- time: { created: 200, completed: 1_200 },
- },
- parts: [
- {
- partId: "round1_text",
- sessionId: "sess_1",
- messageId: "msg_round1",
- type: "text",
- text: "calling ls ",
- },
- {
- partId: "round1_tool",
- sessionId: "sess_1",
- messageId: "msg_round1",
- type: "tool",
- callId: "tool_1",
- tool: "Bash",
- state: {
- status: "completed",
- input: { command: "ls" },
- output: "a b",
- title: "Bash",
- metadata: {},
- startedAt: 300,
- completedAt: 400,
- },
- },
- ],
- },
- {
- info: {
- ...baseAssistantInfo,
- messageId: "msg_round2",
- parentMessageId: "msg_round1",
- time: { created: 1_500, completed: 3_500 },
- },
- parts: [
- {
- partId: "round2_text",
- sessionId: "sess_1",
- messageId: "msg_round2",
- type: "text",
- text: "done",
- },
- {
- partId: "round2_tool",
- sessionId: "sess_1",
- messageId: "msg_round2",
- type: "tool",
- callId: "tool_2",
- tool: "Read",
- state: {
- status: "completed",
- input: { path: "a" },
- output: "hi",
- title: "Read",
- metadata: {},
- startedAt: 1_600,
- completedAt: 1_700,
- },
- },
- ],
- },
- ],
- });
- expect(snapshot.messages).toHaveLength(2);
- const merged = snapshot.messages[1]!;
- expect(merged.role).toBe("assistant");
- expect(merged.content).toBe("calling ls done");
- expect(merged.timestamp).toBe(200);
- // 整轮跨度 = round2.completed (3500) − round1.created (200)
- expect(merged.durationMs).toBe(3_300);
- expect(merged.tools).toHaveLength(2);
- expect(merged.tools?.[0]?.toolName).toBe("Bash");
- expect(merged.tools?.[1]?.toolName).toBe("Read");
- expect(merged.parts).toEqual([
- { type: "content", content: "calling ls " },
- { type: "tool-call", toolIndex: 0 },
- { type: "content", content: "done" },
- { type: "tool-call", toolIndex: 1 },
- ]);
- expect(snapshot.messages[0]?.turnIndex).toBe(0);
- expect(merged.turnIndex).toBe(0);
- });
- it("maps session events without routing through legacy task service", () => {
- const state = {
- streamedTurnKeys: new Set<string>(),
- toolNameById: new Map<string, string>(),
- };
- const turnStartedEvent = {
- eventId: "evt_start",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 0,
- timestamp: 1,
- traceId: "trace_session",
- type: "turn.started",
- payload: {
- input: "hello",
- turnNumber: 1,
- inputId: "t-sess_1-run",
- },
- } satisfies ZCodeSessionEvent;
- const streamingEvent = {
- eventId: "evt_stream",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 1,
- timestamp: 2,
- traceId: "trace_session",
- type: "session.updated",
- payload: {
- kind: "text_delta",
- delta: "hel",
- assistantMessageId: "msg_a",
- },
- } satisfies ZCodeSessionEvent;
- const completeEvent = {
- eventId: "evt_done",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 2,
- timestamp: 3,
- traceId: "trace_session",
- type: "turn.completed",
- payload: {
- response: "hello",
- tokenCount: 1,
- toolCallCount: 0,
- duration: 10,
- inputId: "t-sess_1-run",
- resultType: "success",
- },
- } satisfies ZCodeSessionEvent;
- const toolEvent = {
- eventId: "evt_tool",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 2,
- timestamp: 3,
- traceId: "trace_session",
- type: "tool.updated",
- payload: {
- kind: "scheduled",
- toolCallId: "call_1",
- toolName: "Read",
- input: { filePath: "/repo/app.ts" },
- },
- } satisfies ZCodeSessionEvent;
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: turnStartedEvent,
- state,
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "task_run_started",
- taskId: "sess_1",
- traceId: "t-sess_1-run",
- inputId: "t-sess_1-run",
- turnId: "turn_1",
- startedAt: 1,
- },
- ]);
- // 修复原因:turn.started 是首 token 前唯一可靠的运行态边界。
- // projection 需要记录 active input,后续 chunk/tool/complete 才能归到同一轮 trace。
- expect(state.activePromptInputIdBySession?.get("sess_1")).toBe("t-sess_1-run");
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: streamingEvent,
- state,
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "agent_message_chunk",
- taskId: "sess_1",
- traceId: "t-sess_1-run",
- inputId: "t-sess_1-run",
- messageId: "msg_a",
- content: "hel",
- },
- ]);
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- ...streamingEvent,
- eventId: "evt_parent_stream",
- payload: {
- kind: "text_delta",
- delta: "child",
- parentToolUseId: "call_parent",
- },
- },
- state,
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "agent_message_chunk",
- taskId: "sess_1",
- traceId: "t-sess_1-run",
- inputId: "t-sess_1-run",
- parentToolUseId: "call_parent",
- content: "child",
- },
- ]);
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: toolEvent,
- state,
- taskId: "sess_1",
- }),
- ).toMatchObject([
- {
- type: "tool_call",
- taskId: "sess_1",
- traceId: "t-sess_1-run",
- inputId: "t-sess_1-run",
- toolId: "call_1",
- toolName: "Read",
- },
- ]);
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: completeEvent,
- state,
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "task_complete",
- taskId: "sess_1",
- traceId: "t-sess_1-run",
- inputId: "t-sess_1-run",
- stopReason: "success",
- usage: undefined,
- },
- ]);
- expect(state.activePromptInputIdBySession?.get("sess_1")).toBeUndefined();
- });
- it("does not render conversation rewind command ack as an assistant chunk", () => {
- const state: ZCodeSessionEventProjectionState = {
- activePromptInputIdBySession: new Map<string, string>(),
- streamedTurnKeys: new Set<string>(),
- };
- const started = {
- eventId: "evt_rewind_start",
- sessionId: "sess_1",
- turnId: "turn_rewind",
- seq: 0,
- timestamp: 10,
- traceId: "trace_rewind",
- type: "turn.started",
- payload: {
- input: "/rewind conversation msg_old_user",
- inputId: "input_rewind",
- turnNumber: 2,
- },
- } satisfies ZCodeSessionEvent;
- const completed = {
- eventId: "evt_rewind_done",
- sessionId: "sess_1",
- turnId: "turn_rewind",
- seq: 1,
- timestamp: 11,
- traceId: "trace_rewind",
- type: "turn.completed",
- payload: {
- response: "Rewound conversation to before message msg_old_user.",
- inputId: "input_rewind",
- resultType: "success",
- },
- } satisfies ZCodeSessionEvent;
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: started,
- state,
- taskId: "sess_1",
- }),
- ).toMatchObject([{ type: "task_run_started" }]);
- expect(state.rewindControlTurnKeys?.has("sess_1:turn_rewind")).toBe(true);
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: completed,
- state,
- taskId: "sess_1",
- }),
- ).toEqual([
- {
- type: "task_complete",
- taskId: "sess_1",
- traceId: "input_rewind",
- inputId: "input_rewind",
- stopReason: "success",
- usage: undefined,
- },
- ]);
- expect(state.rewindControlTurnKeys?.has("sess_1:turn_rewind")).toBe(false);
- });
- it("maps denied tool permissions to failed tool updates", () => {
- const state = {
- activePromptInputIdBySession: new Map([["sess_1", "input_1"]]),
- toolNameById: new Map([["call_bash", "Bash"]]),
- };
- const payload = {
- toolCallId: "call_bash",
- toolName: "Bash",
- decision: "deny",
- reason: "Plan mode only allows read-only, non-destructive tools",
- };
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- taskId: "sess_1",
- state,
- event: {
- eventId: "evt_permission_denied",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 4,
- timestamp: 4,
- traceId: "trace_session",
- type: "permission.resolved",
- payload,
- } satisfies ZCodeSessionEvent,
- }),
- ).toEqual([
- {
- type: "permission_response",
- taskId: "sess_1",
- traceId: "input_1",
- inputId: "input_1",
- requestId: "call_bash",
- optionId: "deny",
- response: { decision: "deny" },
- },
- {
- type: "tool_call_update",
- taskId: "sess_1",
- traceId: "input_1",
- inputId: "input_1",
- toolId: "call_bash",
- parentToolUseId: null,
- status: "failed",
- toolName: "Bash",
- kind: "Bash",
- title: "Bash",
- error: "Plan mode only allows read-only, non-destructive tools",
- raw: payload,
- },
- ]);
- });
- it("remembers tool names from started events for later result-only updates", () => {
- const state = {
- activePromptInputIdBySession: new Map([["sess_1", "input_1"]]),
- toolNameById: new Map<string, string>(),
- } satisfies ZCodeSessionEventProjectionState;
- const startedPayload = {
- toolCallId: "tool_subagent_agent_1_call_search",
- parentToolCallId: "call_parent_agent",
- source: "subagent",
- agentId: "agent_1",
- toolName: "WebSearch",
- };
- const resultPayload = {
- toolCallId: "tool_subagent_agent_1_call_search",
- parentToolCallId: "call_parent_agent",
- source: "subagent",
- agentId: "agent_1",
- result: {
- success: true,
- content: "Web search results for query: test",
- },
- };
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- taskId: "sess_1",
- state,
- event: {
- eventId: "evt_tool_started",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 1,
- timestamp: 1,
- traceId: "trace_session",
- type: "tool.updated",
- payload: startedPayload,
- } satisfies ZCodeSessionEvent,
- }),
- ).toEqual([
- {
- type: "tool_call_update",
- taskId: "sess_1",
- traceId: "input_1",
- inputId: "input_1",
- toolId: "tool_subagent_agent_1_call_search",
- parentToolUseId: "call_parent_agent",
- toolName: "WebSearch",
- kind: "WebSearch",
- title: "WebSearch",
- status: "in_progress",
- raw: startedPayload,
- },
- ]);
- expect(state.toolNameById.get("tool_subagent_agent_1_call_search")).toBe("WebSearch");
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- taskId: "sess_1",
- state,
- event: {
- eventId: "evt_tool_result",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 2,
- timestamp: 2,
- traceId: "trace_session",
- type: "tool.updated",
- payload: resultPayload,
- } satisfies ZCodeSessionEvent,
- }),
- ).toEqual([
- {
- type: "tool_call_update",
- taskId: "sess_1",
- traceId: "input_1",
- inputId: "input_1",
- toolId: "tool_subagent_agent_1_call_search",
- parentToolUseId: "call_parent_agent",
- toolName: "WebSearch",
- kind: "WebSearch",
- title: "WebSearch",
- status: "completed",
- content: "Web search results for query: test",
- error: undefined,
- raw: resultPayload,
- },
- ]);
- });
- it("remembers tool metadata for later result-only updates across tool renderers", () => {
- const cases = [
- {
- input: { command: "curl -s https://example.com" },
- toolName: "Bash",
- },
- {
- input: { file_path: "package.json" },
- toolName: "Read",
- },
- {
- input: { search_query: "2026 World Cup winner odds" },
- toolName: "WebSearch",
- },
- {
- input: { path: "src", pattern: "TODO" },
- toolName: "Grep",
- },
- ] as const;
- for (const [index, testCase] of cases.entries()) {
- const state = {
- activePromptInputIdBySession: new Map([["sess_1", "input_1"]]),
- streamingToolInputById: new Map(),
- toolNameById: new Map<string, string>(),
- } satisfies ZCodeSessionEventProjectionState;
- const toolCallId = `tool_subagent_agent_1_call_${testCase.toolName.toLowerCase()}`;
- const scheduledPayload = {
- toolCallId,
- parentToolCallId: "call_parent_agent",
- source: "subagent",
- agentId: "agent_1",
- toolName: testCase.toolName,
- input: testCase.input,
- };
- const resultPayload = {
- toolCallId,
- parentToolCallId: "call_parent_agent",
- source: "subagent",
- agentId: "agent_1",
- result: {
- success: true,
- content: "ok",
- },
- };
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- taskId: "sess_1",
- state,
- event: {
- eventId: `evt_tool_scheduled_${index}`,
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: index * 2 + 1,
- timestamp: index * 2 + 1,
- traceId: "trace_session",
- type: "tool.updated",
- payload: scheduledPayload,
- } satisfies ZCodeSessionEvent,
- }),
- ).toEqual([
- expect.objectContaining({
- type: "tool_call",
- toolId: toolCallId,
- input: testCase.input,
- toolName: testCase.toolName,
- kind: testCase.toolName,
- title: testCase.toolName,
- }),
- ]);
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- taskId: "sess_1",
- state,
- event: {
- eventId: `evt_tool_result_${index}`,
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: index * 2 + 2,
- timestamp: index * 2 + 2,
- traceId: "trace_session",
- type: "tool.updated",
- payload: resultPayload,
- } satisfies ZCodeSessionEvent,
- }),
- ).toEqual([
- expect.objectContaining({
- type: "tool_call_update",
- toolId: toolCallId,
- parentToolUseId: "call_parent_agent",
- toolName: testCase.toolName,
- kind: testCase.toolName,
- title: testCase.toolName,
- input: testCase.input,
- status: "completed",
- content: "ok",
- raw: resultPayload,
- }),
- ]);
- }
- });
- it("preserves child tool metadata across progress and parent turn completion", () => {
- const state = {
- activePromptInputIdBySession: new Map([["sess_1", "input_1"]]),
- streamingToolInputById: new Map(),
- toolNameById: new Map<string, string>(),
- } satisfies ZCodeSessionEventProjectionState;
- const scheduledPayload = {
- toolCallId: "tool_subagent_agent_1_call_bash",
- parentToolCallId: "call_parent_agent",
- source: "subagent",
- agentId: "agent_1",
- toolName: "Bash",
- input: {
- command: "printf done",
- description: "Print completion marker",
- },
- };
- const progressPayload = {
- toolCallId: scheduledPayload.toolCallId,
- parentToolCallId: scheduledPayload.parentToolCallId,
- source: "subagent",
- agentId: "agent_1",
- toolName: "Bash",
- kind: "started",
- };
- const project = (event: ZCodeSessionEvent) =>
- zcodeSessionEventToZCodeStreamEvents({
- taskId: "sess_1",
- state,
- event,
- });
- project({
- eventId: "evt_tool_scheduled",
- sessionId: "sess_1",
- turnId: "turn_parent",
- seq: 1,
- timestamp: 1,
- traceId: "trace_session",
- type: "tool.updated",
- payload: scheduledPayload,
- });
- expect(
- project({
- eventId: "evt_tool_progress",
- sessionId: "sess_1",
- turnId: "turn_parent",
- seq: 2,
- timestamp: 2,
- traceId: "trace_session",
- type: "tool.updated",
- payload: progressPayload,
- }),
- ).toEqual([
- expect.objectContaining({
- type: "tool_call_update",
- toolId: scheduledPayload.toolCallId,
- input: scheduledPayload.input,
- status: "in_progress",
- }),
- ]);
- project({
- eventId: "evt_parent_completed",
- sessionId: "sess_1",
- turnId: "turn_parent",
- seq: 3,
- timestamp: 3,
- traceId: "trace_session",
- type: "turn.completed",
- payload: {
- inputId: "input_1",
- resultType: "success",
- },
- });
- // parent turn 已完成后,background child tool 仍可能继续接收输入流。
- state.streamingToolInputById?.set(scheduledPayload.toolCallId, {
- rawInput: JSON.stringify(scheduledPayload.input),
- });
- expect(
- project({
- eventId: "evt_tool_result",
- sessionId: "sess_1",
- turnId: "turn_child",
- seq: 4,
- timestamp: 4,
- traceId: "trace_session",
- type: "tool.updated",
- payload: {
- toolCallId: scheduledPayload.toolCallId,
- parentToolCallId: scheduledPayload.parentToolCallId,
- source: "subagent",
- agentId: "agent_1",
- result: {
- success: true,
- content: "done",
- },
- },
- }),
- ).toEqual([
- expect.objectContaining({
- type: "tool_call_update",
- toolId: scheduledPayload.toolCallId,
- toolName: "Bash",
- input: scheduledPayload.input,
- status: "completed",
- content: "done",
- }),
- ]);
- expect(state.streamingToolInputById?.has(scheduledPayload.toolCallId)).toBe(false);
- expect(state.completeToolInputById?.has(scheduledPayload.toolCallId)).toBe(false);
- expect(state.toolNameById?.has(scheduledPayload.toolCallId)).toBe(false);
- });
- it("keeps AskUserQuestion permission responses on the elicitation path", () => {
- const state = {
- activePromptInputIdBySession: new Map([["sess_1", "input_1"]]),
- toolNameById: new Map([["call_ask", "AskUserQuestion"]]),
- };
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- taskId: "sess_1",
- state,
- event: {
- eventId: "evt_ask_declined",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 5,
- timestamp: 5,
- traceId: "trace_session",
- type: "permission.resolved",
- payload: {
- toolCallId: "call_ask",
- decision: "deny",
- reason: "User declined",
- },
- } satisfies ZCodeSessionEvent,
- }),
- ).toEqual([
- {
- type: "elicitation_response",
- taskId: "sess_1",
- traceId: "input_1",
- inputId: "input_1",
- requestId: "call_ask",
- action: "decline",
- },
- ]);
- });
- it("keeps ExitPlanMode permission requests on the elicitation path", () => {
- const state = {
- activePromptInputIdBySession: new Map([["sess_1", "input_1"]]),
- toolNameById: new Map<string, string>(),
- };
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- taskId: "sess_1",
- state,
- event: {
- eventId: "evt_exit_plan_requested",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 4,
- timestamp: 4,
- traceId: "trace_session",
- type: "permission.requested",
- payload: {
- requestId: "exit_plan_1",
- toolCallId: "call_exit_plan",
- toolName: "ExitPlanMode",
- reason: "Exit plan mode",
- },
- } satisfies ZCodeSessionEvent,
- }),
- ).toEqual([]);
- expect(state.toolNameById.get("call_exit_plan")).toBe("ExitPlanMode");
- });
- it("keeps ExitPlanMode permission responses on the elicitation path", () => {
- const state = {
- activePromptInputIdBySession: new Map([["sess_1", "input_1"]]),
- toolNameById: new Map([["call_exit_plan", "ExitPlanMode"]]),
- };
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- taskId: "sess_1",
- state,
- event: {
- eventId: "evt_exit_plan_denied",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 5,
- timestamp: 5,
- traceId: "trace_session",
- type: "permission.resolved",
- payload: {
- toolCallId: "call_exit_plan",
- decision: "deny",
- reason: "Please add tests first",
- },
- } satisfies ZCodeSessionEvent,
- }),
- ).toEqual([
- {
- type: "elicitation_response",
- taskId: "sess_1",
- traceId: "input_1",
- inputId: "input_1",
- requestId: "call_exit_plan",
- action: "decline",
- },
- ]);
- });
- it("maps model-only goal continuation turn starts to goal iteration boundaries", () => {
- const events = zcodeSessionEventToZCodeStreamEvents({
- taskId: "task-goal",
- event: {
- eventId: "evt_goal_start",
- sessionId: "sess_goal",
- turnId: "turn_goal_2",
- seq: 10,
- timestamp: 1_234,
- traceId: "trace_goal",
- type: "turn.started",
- payload: {
- input:
- "<system-reminder>\nContinue working toward the active session goal.\n</system-reminder>",
- inputId: "input-goal",
- inputSource: "goal-continuation",
- inputVisibility: "model-only",
- targetId: "goal-1",
- turnNumber: 2,
- },
- },
- });
- expect(events).toEqual([
- {
- type: "task_run_started",
- taskId: "task-goal",
- traceId: "input-goal",
- inputId: "input-goal",
- turnId: "turn_goal_2",
- startedAt: 1_234,
- },
- {
- type: "goal_iteration_started",
- taskId: "task-goal",
- traceId: "input-goal",
- inputId: "input-goal",
- turnId: "turn_goal_2",
- targetId: "goal-1",
- startedAt: 1_234,
- },
- ]);
- });
- it("maps subagent tool updates into parented tool calls and agent activity", () => {
- const state = {
- streamedTurnKeys: new Set<string>(),
- toolNameById: new Map<string, string>(),
- };
- const parentToolCall = {
- eventId: "evt_parent_agent",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 10,
- timestamp: 10,
- traceId: "trace_session",
- type: "tool.updated",
- payload: {
- kind: "scheduled",
- toolCallId: "call_parent_agent",
- toolName: "Agent",
- input: {
- description: "Inspect workspace",
- prompt: "Find the project shape",
- },
- },
- } satisfies ZCodeSessionEvent;
- const subagentToolCall = {
- eventId: "evt_subagent_tool",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 11,
- timestamp: 11,
- traceId: "trace_session",
- type: "tool.updated",
- payload: {
- kind: "scheduled",
- toolCallId: "tool_subagent_agent_1_call_1",
- toolName: "Read",
- input: { filePath: "/workspace/package.json" },
- parentToolCallId: "call_parent_agent",
- source: "subagent",
- agentId: "agent_1",
- agentType: "Explore",
- childSessionId: "sess_subagent_agent_1",
- childToolCallId: "call_1",
- description: "Inspect workspace",
- },
- } satisfies ZCodeSessionEvent;
- const parentToolResult = {
- eventId: "evt_parent_agent_result",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 12,
- timestamp: 12,
- traceId: "trace_session",
- type: "tool.updated",
- payload: {
- kind: "result",
- toolCallId: "call_parent_agent",
- duration: 123,
- result: {
- success: true,
- content: JSON.stringify({
- status: "completed",
- agentId: "agent_1",
- agentType: "Explore",
- content: [{ type: "text", text: "Subagent summary" }],
- }),
- },
- },
- } satisfies ZCodeSessionEvent;
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: parentToolCall,
- state,
- taskId: "sess_1",
- }),
- ).toMatchObject([
- {
- type: "tool_call",
- toolId: "call_parent_agent",
- toolName: "Agent",
- parentToolUseId: null,
- },
- ]);
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: subagentToolCall,
- state,
- taskId: "sess_1",
- }),
- ).toMatchObject([
- {
- type: "tool_call",
- toolId: "tool_subagent_agent_1_call_1",
- toolName: "Read",
- parentToolUseId: "call_parent_agent",
- },
- ]);
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: parentToolResult,
- state,
- taskId: "sess_1",
- }),
- ).toMatchObject([
- {
- type: "tool_call_update",
- toolId: "call_parent_agent",
- toolName: "Agent",
- content: {
- kind: "agent_activity",
- content: "Subagent summary",
- },
- },
- ]);
- });
- it("keeps background Agent launch acknowledgements in progress", () => {
- const state = {
- streamedTurnKeys: new Set<string>(),
- toolNameById: new Map<string, string>(),
- };
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_parent_agent",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 10,
- timestamp: 10,
- traceId: "trace_session",
- type: "tool.updated",
- payload: {
- kind: "scheduled",
- toolCallId: "call_parent_agent",
- toolName: "Agent",
- input: {
- description: "Inspect workspace",
- prompt: "Find the project shape",
- run_in_background: true,
- },
- },
- } satisfies ZCodeSessionEvent,
- state,
- taskId: "sess_1",
- });
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_parent_agent_result",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 11,
- timestamp: 11,
- traceId: "trace_session",
- type: "tool.updated",
- payload: {
- kind: "result",
- toolCallId: "call_parent_agent",
- duration: 4,
- result: {
- success: true,
- content: [
- 'Agent Explore task "Inspect workspace" started in background.',
- "agentId: agent_1",
- "backgroundTaskId: agent_1",
- "Runtime will wait for this background Agent before completing the current turn.",
- ].join("\n"),
- },
- },
- } satisfies ZCodeSessionEvent,
- state,
- taskId: "sess_1",
- });
- expect(events).toMatchObject([
- {
- type: "tool_call_update",
- toolId: "call_parent_agent",
- toolName: "Agent",
- status: "in_progress",
- },
- ]);
- });
- it("keeps previous and current async Task launch acknowledgements in progress", () => {
- const state = {
- streamedTurnKeys: new Set<string>(),
- toolNameById: new Map<string, string>(),
- };
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_parent_task",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 10,
- timestamp: 10,
- traceId: "trace_session",
- type: "tool.updated",
- payload: {
- kind: "scheduled",
- toolCallId: "call_parent_task",
- toolName: "Task",
- input: {
- description: "Inspect workspace",
- prompt: "Find the project shape",
- },
- },
- } satisfies ZCodeSessionEvent,
- state,
- taskId: "sess_1",
- });
- const acknowledgementContents = [
- [
- 'Agent general-purpose task "Inspect workspace" started in background.',
- "agentId: agent_1",
- "outputFile: /tmp/agent_1/output.txt",
- "You will be notified when the Agent completes.",
- ].join("\n"),
- [
- "Async agent launched successfully.",
- "agentId: agent_1 (internal ID - do not mention to user. Use SendMessage with to: 'agent_1' to continue this agent.)",
- "The agent is working in the background. You will be notified automatically when it completes.",
- "output_file: /tmp/agent_1/output.txt",
- "Do NOT Read or tail this file via the shell tool.",
- ].join("\n"),
- ];
- for (const [index, content] of acknowledgementContents.entries()) {
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: `evt_parent_task_result_${index}`,
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 11 + index,
- timestamp: 11 + index,
- traceId: "trace_session",
- type: "tool.updated",
- payload: {
- kind: "result",
- toolCallId: "call_parent_task",
- duration: 4,
- result: {
- success: true,
- content,
- },
- },
- } satisfies ZCodeSessionEvent,
- state,
- taskId: "sess_1",
- });
- expect(events).toMatchObject([
- {
- type: "tool_call_update",
- toolId: "call_parent_task",
- toolName: "Task",
- status: "in_progress",
- },
- ]);
- }
- });
- it("does not project subagent TodoWrite updates as the main runtime plan", () => {
- const state = {
- streamedTurnKeys: new Set<string>(),
- toolNameById: new Map<string, string>(),
- };
- const mainTodoCall = {
- eventId: "evt_main_todo",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 20,
- timestamp: 20,
- traceId: "trace_session",
- type: "tool.updated",
- payload: {
- kind: "scheduled",
- toolCallId: "call_main_todo",
- toolName: "TodoWrite",
- input: {
- todos: [
- { content: "Main inspect logs", status: "completed" },
- { content: "Main patch projection", status: "in_progress" },
- ],
- },
- },
- } satisfies ZCodeSessionEvent;
- const subagentTodoCall = {
- eventId: "evt_subagent_todo",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 21,
- timestamp: 21,
- traceId: "trace_session",
- type: "tool.updated",
- payload: {
- kind: "scheduled",
- toolCallId: "tool_subagent_agent_1_call_todo",
- toolName: "TodoWrite",
- input: {
- todos: [
- { content: "Subagent search market", status: "in_progress" },
- { content: "Subagent summarize sources", status: "pending" },
- ],
- },
- parentToolCallId: "call_parent_agent",
- source: "subagent",
- agentId: "agent_1",
- agentType: "Explore",
- childSessionId: "sess_subagent_agent_1",
- childToolCallId: "call_todo",
- description: "Inspect workspace",
- },
- } satisfies ZCodeSessionEvent;
- const subagentTodoResult = {
- eventId: "evt_subagent_todo_result",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 22,
- timestamp: 22,
- traceId: "trace_session",
- type: "tool.updated",
- payload: {
- kind: "result",
- toolCallId: "tool_subagent_agent_1_call_todo",
- result: {
- success: true,
- content: JSON.stringify({
- todos: [
- { content: "Subagent search market", status: "completed" },
- { content: "Subagent summarize sources", status: "in_progress" },
- ],
- }),
- },
- parentToolCallId: "call_parent_agent",
- source: "subagent",
- agentId: "agent_1",
- agentType: "Explore",
- childSessionId: "sess_subagent_agent_1",
- childToolCallId: "call_todo",
- description: "Inspect workspace",
- },
- } satisfies ZCodeSessionEvent;
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: mainTodoCall,
- state,
- taskId: "sess_1",
- }).map((event) => event.type),
- ).toEqual(["tool_call", "plan"]);
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: subagentTodoCall,
- state,
- taskId: "sess_1",
- }),
- ).toMatchObject([
- {
- type: "tool_call",
- toolId: "tool_subagent_agent_1_call_todo",
- parentToolUseId: "call_parent_agent",
- },
- ]);
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: subagentTodoResult,
- state,
- taskId: "sess_1",
- }),
- ).toMatchObject([
- {
- type: "tool_call_update",
- toolId: "tool_subagent_agent_1_call_todo",
- parentToolUseId: "call_parent_agent",
- },
- ]);
- });
- it("keeps per-prompt inputId correlation scoped by session", () => {
- const state = {
- streamedTurnKeys: new Set<string>(),
- toolNameById: new Map<string, string>(),
- };
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_start",
- sessionId: "sess_1",
- turnId: "turn_1",
- seq: 0,
- timestamp: 1,
- traceId: "trace_session_1",
- type: "turn.started",
- payload: {
- input: "hello",
- turnNumber: 1,
- inputId: "t-sess_1-run",
- },
- },
- state,
- taskId: "sess_1",
- });
- expect(
- zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_stream_other",
- sessionId: "sess_2",
- turnId: "turn_2",
- seq: 1,
- timestamp: 2,
- traceId: "trace_session_2",
- type: "session.updated",
- payload: {
- kind: "text_delta",
- delta: "other",
- assistantMessageId: "msg_b",
- },
- },
- state,
- taskId: "sess_2",
- }),
- ).toEqual([
- {
- type: "agent_message_chunk",
- taskId: "sess_2",
- traceId: "trace_session_2",
- messageId: "msg_b",
- content: "other",
- },
- ]);
- });
- it("projects compact lifecycle payloads to context compaction timeline chunks", () => {
- const state = {
- activePromptInputIdBySession: new Map([["sess_1", "input-compact"]]),
- streamedTurnKeys: new Set<string>(),
- toolNameById: new Map<string, string>(),
- };
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_compact_started",
- sessionId: "sess_1",
- turnId: "turn_compact",
- seq: 1,
- timestamp: 2,
- traceId: "trace_compact",
- type: "session.updated",
- payload: {
- operationId: "cmp-1",
- messageId: "msg-compact-1",
- status: "started",
- trigger: "manual",
- display: "separator",
- preCompactTokenCount: 1200,
- startedAt: 100,
- },
- } satisfies ZCodeSessionEvent,
- state,
- taskId: "sess_1",
- });
- expect(events).toEqual([
- {
- type: "agent_message_chunk",
- taskId: "sess_1",
- traceId: "input-compact",
- inputId: "input-compact",
- messageId: "msg-compact-1",
- content: "",
- zcodeTimeline: {
- version: 1,
- kind: "synthetic",
- type: "context_compaction",
- operationId: "cmp-1",
- status: "started",
- trigger: "manual",
- display: "separator",
- inputId: "input-compact",
- preCompactTokenCount: 1200,
- startedAt: 100,
- },
- },
- ]);
- });
- it("projects compact retry payloads with attempt metadata", () => {
- const state = {
- activePromptInputIdBySession: new Map([["sess_1", "input-compact"]]),
- streamedTurnKeys: new Set<string>(),
- toolNameById: new Map<string, string>(),
- };
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_compact_retrying",
- sessionId: "sess_1",
- turnId: "turn_compact",
- seq: 2,
- timestamp: 3,
- traceId: "trace_compact",
- type: "session.updated",
- payload: {
- operationId: "cmp-1",
- messageId: "msg-compact-1",
- status: "retrying",
- trigger: "auto",
- display: "separator",
- attempt: 2,
- maxAttempts: 3,
- reason: "Failed to generate compact summary",
- },
- } satisfies ZCodeSessionEvent,
- state,
- taskId: "sess_1",
- });
- expect(events[0]).toMatchObject({
- type: "agent_message_chunk",
- taskId: "sess_1",
- traceId: "input-compact",
- inputId: "input-compact",
- messageId: "msg-compact-1",
- content: "",
- zcodeTimeline: {
- type: "context_compaction",
- operationId: "cmp-1",
- status: "retrying",
- trigger: "auto",
- attempt: 2,
- maxAttempts: 3,
- reason: "Failed to generate compact summary",
- },
- });
- });
- it("projects compact skipped payloads to context compaction timeline chunks", () => {
- const state = {
- activePromptInputIdBySession: new Map([["sess_1", "input-compact"]]),
- streamedTurnKeys: new Set<string>(),
- toolNameById: new Map<string, string>(),
- };
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_compact_skipped",
- sessionId: "sess_1",
- turnId: "turn_compact",
- seq: 3,
- timestamp: 4,
- traceId: "trace_compact",
- type: "session.updated",
- payload: {
- operationId: "cmp-skipped",
- messageId: "msg-compact-skipped",
- status: "skipped",
- trigger: "manual",
- display: "separator",
- },
- } satisfies ZCodeSessionEvent,
- state,
- taskId: "sess_1",
- });
- expect(events[0]).toMatchObject({
- type: "agent_message_chunk",
- taskId: "sess_1",
- traceId: "input-compact",
- inputId: "input-compact",
- messageId: "msg-compact-skipped",
- content: "",
- zcodeTimeline: {
- type: "context_compaction",
- operationId: "cmp-skipped",
- status: "skipped",
- trigger: "manual",
- },
- });
- });
- it("projects fork notice part upserts to session fork timeline chunks", () => {
- const state = {
- activePromptInputIdBySession: new Map<string, string>(),
- streamedTurnKeys: new Set<string>(),
- toolNameById: new Map<string, string>(),
- };
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_fork_notice",
- sessionId: "forked-session",
- seq: 1,
- timestamp: 2,
- traceId: "trace_fork",
- type: "part.upserted",
- payload: {
- part: {
- partId: "part_fork_notice",
- sessionId: "forked-session",
- messageId: "msg_fork_notice",
- type: "text",
- text: "Forked from parent",
- metadata: {
- forkContext: {
- kind: "session_fork",
- parentSessionId: "parent-session",
- targetMessageId: "parent-message",
- restoredFileCount: 2,
- },
- },
- },
- },
- } satisfies ZCodeSessionEvent,
- state,
- taskId: "forked-session",
- });
- expect(events).toEqual([
- {
- type: "agent_message_chunk",
- taskId: "forked-session",
- traceId: "trace_fork",
- messageId: "msg_fork_notice",
- content: "",
- zcodeTimeline: {
- version: 1,
- kind: "synthetic",
- type: "session_fork",
- display: "separator",
- parentSessionId: "parent-session",
- targetMessageId: "parent-message",
- restoredFileCount: 2,
- },
- },
- ]);
- });
- it("projects compact turn failures to failed timeline chunks instead of task errors", () => {
- const state = {
- activePromptInputIdBySession: new Map([["sess_1", "input-compact"]]),
- streamedTurnKeys: new Set<string>(),
- toolNameById: new Map<string, string>(),
- };
- const events = zcodeSessionEventToZCodeStreamEvents({
- event: {
- eventId: "evt_compact_failed",
- sessionId: "sess_1",
- turnId: "turn_compact",
- seq: 2,
- timestamp: 3,
- traceId: "trace_compact",
- type: "turn.failed",
- payload: {
- turnPhase: "compact",
- inputId: "input-compact",
- error: {
- message: "No summary produced.",
- type: "compact_failed",
- },
- },
- } satisfies ZCodeSessionEvent,
- state,
- taskId: "sess_1",
- });
- expect(events).toHaveLength(1);
- expect(events[0]).toMatchObject({
- type: "agent_message_chunk",
- taskId: "sess_1",
- traceId: "input-compact",
- inputId: "input-compact",
- zcodeTimeline: {
- type: "context_compaction",
- status: "failed",
- inputId: "input-compact",
- reason: "No summary produced.",
- },
- });
- });
- it("projects ZCode settings updates to model and mode state events", () => {
- const options = zcodeSessionSettingsToConfigOptions(settings);
- const events = zcodeStateUpdatedToZCodeStreamEvents({
- notification: {
- type: "state.updated",
- scope: "session",
- sessionId: "sess_1",
- revision: 2,
- reason: "model_changed",
- patch: settings,
- },
- settings,
- taskId: "sess_1",
- });
- expect(options.find((option) => option.category === "model")).toMatchObject({
- currentValue: "glm/glm-4.6",
- });
- expect(events.map((event) => event.type)).toEqual([
- "mode_update",
- "glm_agent_model_state_update",
- ]);
- expect(events[0]).toMatchObject({
- type: "mode_update",
- currentModeId: "build",
- });
- expect(events[1]).toMatchObject({
- type: "glm_agent_model_state_update",
- reason: "model_changed",
- model: {
- currentValue: "glm/glm-4.6",
- },
- thoughtLevel: {
- enabled: true,
- currentValue: "medium",
- options: [{ value: "medium", name: "Medium" }],
- },
- contextWindow: {
- tokens: 128000,
- },
- });
- });
- it("parses UI model values into strict ZCode model refs", () => {
- expect(parseModelPickerValue("glm/glm-4.6")).toEqual({
- providerId: "glm",
- modelId: "glm-4.6",
- });
- expect(parseModelPickerValue("custom-openai/agent-model$fast")).toEqual({
- providerId: "custom-openai",
- modelId: "agent-model",
- options: { reasoningLevel: "fast" },
- });
- expect(parseModelPickerValue("openrouter/nvidia/nemotron-3-ultra-550b-a55b:free")).toEqual({
- providerId: "openrouter",
- modelId: "nvidia/nemotron-3-ultra-550b-a55b:free",
- });
- expect(parseModelPickerValue(encodeCustomModelValue("my-provider", "my-model"))).toEqual({
- providerId: "my-provider",
- modelId: "my-model",
- });
- });
- it("formats model variants with the reserved dollar separator", () => {
- const modelSelection = {
- providerId: "custom-openai",
- modelId: "agent-model:free",
- options: { reasoningLevel: "fast" },
- };
- expect(formatSharedModelSelection(modelSelection)).toBe("custom-openai/agent-model:free$fast");
- expect(formatProjectedModelSelection(modelSelection)).toBe(
- "custom-openai/agent-model:free$fast",
- );
- });
- it("projects web remote user input response to elicitation response", () => {
- expect(
- zcodeUserInputResponseToZCodeStreamEvent("sess_1", {
- requestId: "input-1",
- action: "accept",
- content: { answers: { answer_0: "a" } },
- }),
- ).toMatchObject({
- type: "elicitation_response",
- taskId: "sess_1",
- requestId: "input-1",
- action: "accept",
- content: { answers: { answer_0: "a" } },
- });
- });
- });
|