| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142 |
- import { createHash } from "node:crypto";
- import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
- import { tmpdir } from "node:os";
- import { join } from "node:path";
- import { PassThrough } from "node:stream";
- import { describe, expect, it, vi } from "vitest";
- import { createSqliteSessionStore } from "@zcode/adapters/storage";
- import {
- BUILTIN_MODEL_PROVIDER_IDS,
- ZCODE_SESSION_RUNTIME_PREFERENCES_REQUEST_TIMEOUT_MS,
- zcodeProtocolMethods,
- zcodeMessagePartSchema,
- zcodeSessionCancelBackgroundTaskResultSchema,
- zcodeSessionCompactResultSchema,
- zcodeSessionEventsResultSchema,
- zcodeSessionEventSchema,
- zcodeSessionForkResultSchema,
- zcodeSessionGoalResultSchema,
- zcodeSessionListResultSchema,
- zcodeSessionStateSnapshotSchema,
- zcodeSessionSubscribeResultSchema,
- zcodeProviderTestModelConnectivityResultSchema,
- zcodeWorkspaceGenerateTextResultSchema,
- zcodeWorkspaceCancelGenerateTextResultSchema,
- zcodeWorkspacePresentationSchema,
- zcodeWorkspaceUpdateInteractionPreferencesResultSchema,
- type ZCodeProtocolMessage,
- type ZCodeProtocolNotification,
- } from "@zcode/shared";
- import {
- V4_METHODS,
- V4_NOTIFICATIONS,
- conversationTopicFrameSchema,
- reassembleTopicWireFrames,
- routedTopicFrameSchema,
- routedTopicWireFrameSchema,
- conversationTopic,
- sessionsIndexTopic,
- v4ConversationUsageResultSchema,
- v4ConversationSubscribeResultSchema,
- v4ConversationResyncResultSchema,
- v4UsageStatsResultSchema,
- workspaceConfigTopic,
- } from "@zcode/shared/zcode-protocol-v4";
- import {
- SessionEventType,
- createTraceId,
- type BackgroundTaskInfo,
- type MessageId,
- type MessagePart,
- type ModelId,
- type ModelProviderId,
- type MessageWithParts,
- type ProjectId,
- type SessionEvent,
- type SessionId,
- type LogContext,
- type Logger,
- type LoggerFactory,
- type McpPort,
- type McpServerConfig,
- type ExecutionShellSelection,
- } from "@zcode/contracts";
- import { InMemoryWorkspaceHookPolicyProvider } from "@zcode/core";
- import {
- ModelConfig,
- ModelOptionSpecsConfig,
- ModelPropertiesConfig,
- ProviderRegistry,
- type Provider,
- } from "@zcode/provider";
- import { ZCodeProtocolAgentServer } from "../src/zcode-protocol/server.js";
- import { ZCodeProtocolNdjsonConnection } from "../src/zcode-protocol/transport.js";
- import { shouldCloseSessionForExpectedPersistence } from "../src/zcode-protocol/server-operations.js";
- import type { ZCodeProtocolAgentServerContext } from "../src/zcode-protocol/server-types.js";
- import {
- buildSessionSnapshot,
- mapMessageWithParts,
- mapSessionEvent,
- mapSessionEvents,
- mapSessionSettings,
- } from "../src/zcode-protocol/mapper.js";
- import { createWorkspaceZCodeApp } from "../src/zcode-protocol/workspace-model-runtime.js";
- import { onSessionEvent } from "../src/zcode-protocol/server-operations.js";
- import type { ZCodeApp, ZCodeAppOptions } from "../src/app/types.js";
- import { createFakeApp } from "./helpers/fake-zcode-app.js";
- import { createApiKeyProviderConfig } from "./provider-config-fixtures.js";
- const workspace = {
- workspacePath: "/workspace/app",
- workspaceKey: "/workspace/app",
- };
- function currentOnlyModelOption() {
- return {
- ref: { providerId: "provider", modelId: "current-model" },
- label: "current-model",
- providerLabel: "provider",
- properties: {
- inputFormat: {
- supportsText: true,
- supportsImage: false,
- supportsVideo: false,
- supportsAudio: false,
- supportsPdf: false,
- },
- outputFormat: { supportsText: true },
- },
- } as const;
- }
- function createProtocolTestProviderRegistry(): ProviderRegistry {
- const modelConfig = new ModelConfig({
- properties: new ModelPropertiesConfig({
- requiresMfjsToolSchema: false,
- contextWindow: 128_000,
- inputFormat: {
- supportsText: true,
- supportsImage: false,
- supportsVideo: false,
- supportsAudio: false,
- supportsPdf: false,
- },
- outputFormat: { supportsText: true },
- supportsToolCall: true,
- supportsJsonSchemaOutput: true,
- supportsNativeWebSearch: false,
- supportsMidConversationSystem: false,
- }),
- optionSpecs: new ModelOptionSpecsConfig({
- maxOutputTokens: {
- max: 32_000,
- map: '{"max_completion_tokens":maxOutputTokens}',
- },
- }),
- });
- const provider: Provider = {
- providerId: "custom-openai",
- config: createApiKeyProviderConfig({
- apiFormat: "openai-chat-completions",
- apiKey: "sk-test",
- baseURL: "https://api.example.com/v1",
- models: ["agent-model", "backup-model"],
- }),
- models: [
- { modelId: "agent-model", config: modelConfig },
- { modelId: "backup-model", config: modelConfig },
- ],
- };
- return new ProviderRegistry([provider]);
- }
- describe("mapSessionSettings", () => {
- it("projects the current model default thought level separately from current", async () => {
- const app = createFakeApp(undefined, {
- getDefaultThoughtLevel: () => "max",
- getThoughtLevel: () => undefined,
- listThoughtLevels: () => ["high", "max"],
- });
- const settings = await mapSessionSettings(app);
- expect(settings.thoughtLevel).toMatchObject({
- available: [
- { value: "high", label: "high" },
- { value: "max", label: "max" },
- ],
- defaultLevel: "max",
- enabled: true,
- });
- expect(settings.thoughtLevel.current).toBeUndefined();
- });
- });
- describe("conditional session close", () => {
- it("only closes when the current persistence still matches the caller expectation", () => {
- expect(shouldCloseSessionForExpectedPersistence("deferred", "deferred")).toBe(true);
- expect(shouldCloseSessionForExpectedPersistence("immediate", "deferred")).toBe(false);
- expect(shouldCloseSessionForExpectedPersistence("immediate")).toBe(true);
- });
- });
- describe("ZCodeProtocolAgentServer", () => {
- it("所有 Entry 都不再接受旧 Workspace Provider 写协议", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- for (const [index, method] of [
- "workspace/updateProviderRegistry",
- "workspace/upsertModelProvider",
- "workspace/removeModelProvider",
- ].entries()) {
- await expect(
- server.handleMessage({
- id: `retired-provider-writer-${index}`,
- method,
- params: {},
- } as ZCodeProtocolMessage),
- ).resolves.toMatchObject({
- id: `retired-provider-writer-${index}`,
- error: { code: -32601 },
- });
- }
- });
- it("uses the Host managed policy for no-session Settings pretrust", async () => {
- const policyProvider = new InMemoryWorkspaceHookPolicyProvider({
- mode: "deny",
- reason: "managed",
- policyRevision: "test:deny:v1",
- });
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- version: "test-version",
- workspaceHookPolicyProvider: policyProvider,
- });
- await expect(
- requestResult(server, {
- id: "workspace-hook-trust-denied",
- method: zcodeProtocolMethods.workspaceHookTrustGrant,
- params: {
- workspace,
- bundleDigest: "b".repeat(64),
- hookDeclarationDigest: "a".repeat(64),
- },
- }),
- ).resolves.toEqual({
- accepted: false,
- reasonCode: "workspace_hooks_blocked_by_policy",
- });
- });
- it("injects the same Host managed policy provider into session Runtime", async () => {
- const policyProvider = new InMemoryWorkspaceHookPolicyProvider({
- mode: "user_decides",
- policyRevision: "test:user-decides:v1",
- });
- let createdOptions: ZCodeAppOptions | undefined;
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- createdOptions = options;
- return createFakeApp(options);
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- workspaceHookPolicyProvider: policyProvider,
- });
- await requestResult(server, {
- id: "session-with-shared-hook-policy",
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- });
- expect(createdOptions?.workspaceHookPolicyProvider).toBe(policyProvider);
- });
- it("applies strict workspace interaction preferences without creating a session", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const result = zcodeWorkspaceUpdateInteractionPreferencesResultSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.workspaceUpdateInteractionPreferences,
- params: {
- workspace,
- preferences: {
- askUserQuestionAutoResolutionEnabled: false,
- },
- },
- }),
- );
- expect(result).toEqual({
- workspace,
- askUserQuestionAutoResolutionEnabled: false,
- snoozedInteractionCount: 0,
- });
- });
- it("maps core tool events into typed ZCode session event payloads", () => {
- const mapped = zcodeSessionEventSchema.parse(
- mapSessionEvent({
- id: "evt_tool_1" as SessionEvent["id"],
- payload: {
- duration: 12,
- result: {
- content: "done",
- success: true,
- },
- toolCallId: "tool_1",
- toolName: "Edit",
- },
- sequenceNumber: 3,
- sessionId: "sess_1" as SessionId,
- timestamp: new Date(4),
- traceId: "trace_1" as SessionEvent["traceId"],
- type: SessionEventType.ToolCallResult,
- } satisfies SessionEvent),
- );
- expect(mapped.type).toBe("tool.updated");
- expect(mapped.payload.kind).toBe("result");
- });
- it("maps core permission denied events as denied protocol permission resolutions", () => {
- const mapped = zcodeSessionEventSchema.parse(
- mapSessionEvent({
- id: "evt_permission_denied" as SessionEvent["id"],
- payload: {
- toolCallId: "tool_write_denied",
- toolName: "Write",
- reason: "Plan mode only allows read-only, non-destructive tools",
- inputSummary: {
- file_path: "/tmp/denied.txt",
- },
- },
- sequenceNumber: 4,
- sessionId: "sess_1" as SessionId,
- timestamp: new Date(5),
- traceId: "trace_permission_denied" as SessionEvent["traceId"],
- type: SessionEventType.PermissionDenied,
- } satisfies SessionEvent),
- );
- expect(mapped.type).toBe("permission.resolved");
- expect(mapped.payload).toMatchObject({
- decision: "deny",
- reason: "Plan mode only allows read-only, non-destructive tools",
- toolCallId: "tool_write_denied",
- toolName: "Write",
- });
- });
- it("does not expose compact internal timeline text through the protocol", () => {
- const internalSummary =
- "This session is being continued from a previous conversation that was compacted.";
- const mapped = mapMessageWithParts({
- info: {
- id: "msg_compact" as MessageId,
- sessionID: "sess_1" as SessionId,
- role: "assistant",
- parentID: "msg_user" as MessageId,
- time: { created: 1, completed: 2 },
- agent: "zcode-agent",
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- cost: 0,
- },
- parts: [
- {
- id: "part_compact",
- sessionID: "sess_1",
- messageID: "msg_compact",
- type: "compaction",
- auto: true,
- summaryMessageId: "msg_summary",
- timelineText: internalSummary,
- timelineStatus: "completed",
- trigger: "auto",
- },
- ],
- } as unknown as MessageWithParts);
- expect(mapped.parts[0]).not.toHaveProperty("timelineText");
- expect(zcodeMessagePartSchema.parse(mapped.parts[0])).not.toHaveProperty("timelineText");
- expect(JSON.stringify(mapped)).not.toContain(internalSummary);
- });
- it("does not expose read-state metadata through protocol tool parts", () => {
- const fileContent = "secret file content that should stay internal";
- const mapped = mapMessageWithParts({
- info: {
- id: "msg_read" as MessageId,
- sessionID: "sess_1" as SessionId,
- role: "assistant",
- parentID: "msg_user" as MessageId,
- time: { created: 1, completed: 2 },
- agent: "zcode-agent",
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- cost: 0,
- },
- parts: [
- {
- callID: "tool_read_1",
- id: "part_read",
- messageID: "msg_read",
- sessionID: "sess_1",
- state: {
- input: { file_path: "/workspace/app/secret.txt" },
- metadata: {
- display: {
- additions: 0,
- deletions: 0,
- kind: "file_diff",
- structuredPatch: [],
- },
- readFileState: {
- content: fileContent,
- isPartialView: false,
- mtimeMs: 1,
- path: "/workspace/app/secret.txt",
- readAtMs: 2,
- revisionId: "rev-1",
- schemaVersion: 1,
- sizeBytes: fileContent.length,
- tool: "Read",
- },
- schemaVersion: 1,
- },
- output: "1\tsecret file content",
- status: "completed",
- time: { start: 1, end: 2 },
- title: "Read",
- },
- tool: "Read",
- type: "tool",
- },
- ],
- } as unknown as MessageWithParts);
- const part = zcodeMessagePartSchema.parse(mapped.parts[0]);
- expect(part.type).toBe("tool");
- if (part.type !== "tool" || part.state.status !== "completed") {
- throw new Error("expected completed tool part");
- }
- expect(part.state.metadata).toMatchObject({
- display: {
- kind: "file_diff",
- },
- schemaVersion: 1,
- });
- expect(part.state.metadata).not.toHaveProperty("readFileState");
- expect(JSON.stringify(mapped)).not.toContain(fileContent);
- });
- it("maps completed tool parts with missing metadata to an empty protocol metadata object", () => {
- const mapped = mapMessageWithParts({
- info: {
- id: "msg_tool_without_metadata" as MessageId,
- sessionID: "sess_1" as SessionId,
- role: "assistant",
- parentID: "msg_user" as MessageId,
- time: { created: 1, completed: 2 },
- agent: "zcode-agent",
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- cost: 0,
- },
- parts: [
- {
- callID: "tool_read_without_metadata",
- id: "part_read_without_metadata",
- messageID: "msg_tool_without_metadata",
- sessionID: "sess_1",
- state: {
- input: { file_path: "/workspace/app/plain.txt" },
- output: "1\tplain",
- status: "completed",
- time: { start: 1, end: 2 },
- title: "Read",
- },
- tool: "Read",
- type: "tool",
- },
- ],
- } as unknown as MessageWithParts);
- const part = zcodeMessagePartSchema.parse(mapped.parts[0]);
- expect(part.type).toBe("tool");
- if (part.type !== "tool" || part.state.status !== "completed") {
- throw new Error("expected completed tool part");
- }
- expect(part.state.metadata).toEqual({});
- });
- it("keeps model request protocol events compact", () => {
- const mapped = zcodeSessionEventSchema.parse(
- mapSessionEvent({
- id: "evt_model_request" as SessionEvent["id"],
- payload: {
- messages: [
- {
- role: "user",
- content: "large prompt body",
- },
- ],
- providerId: "provider",
- modelId: "model",
- toolCount: 3,
- iteration: 2,
- },
- sequenceNumber: 4,
- sessionId: "sess_1" as SessionId,
- timestamp: new Date(5),
- traceId: "trace_model_request" as SessionEvent["traceId"],
- type: SessionEventType.ModelRequest,
- } satisfies SessionEvent),
- );
- expect(mapped.type).toBe("session.updated");
- expect(mapped.payload).toMatchObject({
- messageCount: 1,
- providerId: "provider",
- modelId: "model",
- toolCount: 3,
- iteration: 2,
- });
- expect(mapped.payload).not.toHaveProperty("messages");
- });
- it("maps current-only session settings without enumerating the full model catalog", async () => {
- const app = createFakeApp(undefined, {
- getModel: () => "provider/current-model",
- getCurrentModelOption: () => currentOnlyModelOption(),
- getThoughtLevel: () => undefined,
- listModels: () => {
- throw new Error("listModels should not run for current-only settings");
- },
- listThoughtLevels: () => [],
- });
- vi.spyOn(app.runtime, "getSessionModelSelection").mockReturnValue({
- providerId: "provider",
- modelId: "current-model",
- });
- const settings = await mapSessionSettings(app, {
- modelAvailability: "current",
- });
- expect(settings.model.available).toEqual([
- expect.objectContaining({
- label: "current-model",
- providerLabel: "provider",
- ref: {
- modelId: "current-model",
- providerId: "provider",
- },
- properties: currentOnlyModelOption().properties,
- }),
- ]);
- expect(settings.model.current).toEqual({
- modelId: "current-model",
- providerId: "provider",
- });
- });
- it("preserves current context window in current-only session snapshots without enumerating models", async () => {
- const sessionId = "sess_current_context" as SessionId;
- const app = createFakeApp(
- { sessionId },
- {
- getModel: () => "provider/current-model",
- getCurrentModelOption: () => currentOnlyModelOption(),
- getThoughtLevel: () => undefined,
- listModels: () => {
- throw new Error("listModels should not run for current-only snapshots");
- },
- listThoughtLevels: () => [],
- runtime: {
- getSessionModelSelection: () => ({ providerId: "provider", modelId: "current-model" }),
- getProjection: async () =>
- ({
- activeToolCalls: [],
- backgroundTasks: [],
- contextUsed: 0,
- contextWindow: 256_000,
- createdAt: new Date(1),
- id: sessionId,
- mode: "build",
- pendingPermissions: [],
- pendingSteerInputs: [],
- status: "idle",
- streamingToolLedger: [],
- target: null,
- totalTokenCount: 0,
- turnCount: 0,
- updatedAt: new Date(1),
- }) as never,
- getActiveTurnInfo: () => undefined,
- subscribeEvents: () => () => {},
- } as never,
- },
- );
- const snapshot = await buildSessionSnapshot({
- app,
- eventSeq: 0,
- messages: [],
- modelAvailability: "current",
- stateRevision: 1,
- workspace,
- });
- expect(snapshot.settings.model.available).toEqual([
- expect.objectContaining({
- contextWindow: 256_000,
- ref: {
- modelId: "current-model",
- providerId: "provider",
- },
- }),
- ]);
- });
- it("preserves latest main turn context usage breakdown in session snapshots", async () => {
- const sessionId = "sess_context_breakdown" as SessionId;
- const app = createFakeApp(
- { sessionId },
- {
- runtime: {
- getSessionModelSelection: () => undefined,
- getProjection: async () =>
- ({
- activeToolCalls: [],
- backgroundTasks: [],
- contextUsed: 26_347,
- contextWindow: 1_000_000,
- createdAt: new Date(1),
- id: sessionId,
- mode: "build",
- pendingPermissions: [],
- pendingSteerInputs: [],
- status: "idle",
- streamingToolLedger: [],
- target: null,
- totalTokenCount: 0,
- turnCount: 0,
- updatedAt: new Date(1),
- }) as never,
- getActiveTurnInfo: () => undefined,
- subscribeEvents: () => () => {},
- } as never,
- },
- );
- const breakdown = [
- { source: "system_tool_schemas" as const, chars: 89_047 },
- { source: "mcp_tool_schemas" as const, chars: 43_644 },
- { source: "messages" as const, chars: 9_104 },
- ];
- const snapshot = await buildSessionSnapshot({
- app,
- eventSeq: 4,
- messages: [],
- persistedContextUsageBreakdownEvents: [
- {
- id: "event_context_breakdown",
- sessionId,
- sequenceNumber: 4,
- timestamp: new Date(4),
- traceId: "trace_context_breakdown" as never,
- type: SessionEventType.ModelComplete,
- payload: {
- content: "",
- contextUsageBreakdown: breakdown,
- contextWindow: 1_000_000,
- querySource: "main_turn",
- stopReason: "stop",
- usage: {
- inputTokens: 25_913,
- outputTokens: 434,
- totalTokens: 26_347,
- },
- },
- } as SessionEvent,
- ],
- stateRevision: 1,
- workspace,
- });
- expect(snapshot.runtime.contextUsage).toEqual({
- used: 26_347,
- size: 1_000_000,
- cost: null,
- breakdown,
- });
- });
- it("does not expose the last projected turn as an active runtime turn", async () => {
- const sessionId = "sess_completed_projection_turn" as SessionId;
- const completedTurnId = "turn_completed_projection";
- const app = createFakeApp(
- { sessionId },
- {
- runtime: {
- getSessionModelSelection: () => undefined,
- getProjection: async () =>
- ({
- activeToolCalls: [],
- backgroundTasks: [],
- contextUsed: 0,
- contextWindow: 128_000,
- createdAt: new Date(1),
- currentTurnId: completedTurnId,
- id: sessionId,
- mode: "build",
- pendingPermissions: [],
- pendingSteerInputs: [],
- status: "idle",
- streamingToolLedger: [],
- target: null,
- totalTokenCount: 0,
- turnCount: 1,
- updatedAt: new Date(2),
- }) as never,
- getActiveTurnInfo: () => undefined,
- subscribeEvents: () => () => {},
- } as never,
- },
- );
- const snapshot = await buildSessionSnapshot({
- app,
- eventSeq: 4,
- messages: [],
- stateRevision: 1,
- workspace,
- });
- expect(snapshot.projection.currentTurnId).toBe(completedTurnId);
- expect(snapshot.runtime.activeTurnId).toBeUndefined();
- expect(snapshot.runtime.activeTurnKind).toBeUndefined();
- });
- it("maps active turn runtime fields while a session active turn exists", async () => {
- const sessionId = "sess_active_runtime_turn" as SessionId;
- const activeTurnId = "turn_active_runtime";
- const app = createFakeApp(
- { sessionId },
- {
- runtime: {
- getSessionModelSelection: () => undefined,
- getProjection: async () =>
- ({
- activeToolCalls: [],
- backgroundTasks: [],
- contextUsed: 0,
- contextWindow: 128_000,
- createdAt: new Date(1),
- currentTurnId: activeTurnId,
- id: sessionId,
- mode: "build",
- pendingPermissions: [],
- pendingSteerInputs: [],
- status: "running",
- streamingToolLedger: [],
- target: null,
- totalTokenCount: 0,
- turnCount: 1,
- updatedAt: new Date(2),
- }) as never,
- getActiveTurnInfo: () =>
- ({
- kind: "regular",
- queueLength: 0,
- steerable: true,
- turnId: activeTurnId,
- }) as never,
- subscribeEvents: () => () => {},
- } as never,
- },
- );
- const snapshot = await buildSessionSnapshot({
- app,
- eventSeq: 4,
- messages: [],
- stateRevision: 1,
- workspace,
- });
- expect(snapshot.runtime.activeTurnId).toBe(activeTurnId);
- expect(snapshot.runtime.activeTurnKind).toBe("regular");
- });
- it("hydrates image artifact file parts when building session snapshots", async () => {
- const sessionId = "sess_image_artifact" as SessionId;
- const artifactUri = "zcode-artifact://sess_image_artifact/tool-result-image";
- const app = createFakeApp(
- { sessionId },
- {
- readToolResultArtifact: async (uri) => ({
- bytes: 30,
- content: "data:image/png;base64,aW1hZ2U=",
- contentType: "text/plain",
- uri,
- }),
- },
- );
- const messages = [
- {
- info: {
- id: "msg_user_image" as MessageId,
- sessionID: sessionId,
- role: "user",
- time: { created: 1 },
- agent: "zcode-agent",
- modelSelection: {
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- },
- },
- parts: [
- {
- id: "part_user_text" as never,
- sessionID: sessionId,
- messageID: "msg_user_image" as MessageId,
- text: "图片里是啥",
- type: "text",
- },
- {
- id: "part_user_image" as never,
- sessionID: sessionId,
- messageID: "msg_user_image" as MessageId,
- filename: "screen.png",
- metadata: {
- artifactUri,
- sizeBytes: 30,
- storageKind: "artifact",
- },
- mime: "image/png",
- type: "file",
- url: artifactUri,
- },
- ],
- },
- ] as unknown as MessageWithParts[];
- const snapshot = zcodeSessionStateSnapshotSchema.parse(
- await buildSessionSnapshot({
- app,
- eventSeq: 0,
- messages,
- stateRevision: 1,
- workspace,
- }),
- );
- expect(snapshot.messages[0]?.parts[1]).toMatchObject({
- type: "file",
- url: "data:image/png;base64,aW1hZ2U=",
- });
- });
- it("uses fallback record timestamps before projection timestamps in session snapshots", async () => {
- const app = createFakeApp();
- const snapshot = await buildSessionSnapshot({
- app,
- eventSeq: 0,
- fallbackCreatedAt: 8_000,
- fallbackUpdatedAt: 9_000,
- messages: [],
- stateRevision: 1,
- workspace,
- });
- expect(snapshot.session.createdAt).toBe(8_000);
- expect(snapshot.session.updatedAt).toBe(9_000);
- });
- it("emits Computer Use lifecycle metadata without a legacy deliveryKind", () => {
- const ingest = vi.fn();
- const notify = vi.fn<(notification: ZCodeProtocolNotification) => void>();
- const record = {
- app: { sessionId: "sess_cua_sideband" },
- updatedAt: 1_700,
- workspace,
- } as unknown as Parameters<typeof onSessionEvent>[1];
- const context = {
- notify,
- v4Gateway: { ingest },
- } as unknown as Parameters<typeof onSessionEvent>[0];
- const event = (
- type: SessionEvent["type"],
- sequenceNumber: number,
- payload: unknown,
- turnId?: string,
- ): SessionEvent => ({
- id: `evt-cua-${sequenceNumber}` as SessionEvent["id"],
- payload,
- sequenceNumber,
- sessionId: "sess_cua_sideband" as SessionId,
- timestamp: new Date(1_700 + sequenceNumber),
- traceId: "trace_cua_sideband" as SessionEvent["traceId"],
- ...(turnId ? { turnId: turnId as SessionEvent["turnId"] } : {}),
- type,
- });
- const events = [
- event(SessionEventType.TurnStarted, 1, { turnNumber: 1, input: "control" }, "turn-1"),
- event(
- SessionEventType.ToolCallScheduled,
- 2,
- {
- toolCallId: "call-1",
- toolName: "mcp__computer-use__left_click",
- input: { target: "Calculator" },
- },
- "turn-1",
- ),
- event(
- SessionEventType.ToolCallStarted,
- 3,
- { toolCallId: "call-1", startedAt: new Date(1_703) },
- "turn-1",
- ),
- event(
- SessionEventType.ToolCallResult,
- 4,
- { toolCallId: "call-1", result: { secret: "must-not-pass" }, duration: 1 },
- "turn-1",
- ),
- event(SessionEventType.TurnComplete, 5, { resultType: "success" }, "turn-1"),
- event(SessionEventType.SessionEnded, 6, { reason: "closed" }),
- ];
- for (const sessionEvent of events) onSessionEvent(context, record, sessionEvent);
- expect(notify.mock.calls.map(([notification]) => notification.method)).toEqual(
- Array.from({ length: 5 }, () => "computer-use/operation-event"),
- );
- const params = notify.mock.calls.map(
- ([notification]) => notification.params as Record<string, unknown>,
- );
- expect(params.map((value) => value.kind)).toEqual([
- "turn-started",
- "tool-scheduled",
- "tool-started",
- "turn-completed",
- "session-closed",
- ]);
- expect(params[1]).not.toHaveProperty("input");
- expect(params[2]).not.toHaveProperty("result");
- expect(ingest).toHaveBeenCalledTimes(events.length);
- });
- it("keeps v4 ingestion alive when the Computer Use lifecycle sideband throws", () => {
- const ingest = vi.fn();
- const warn = vi.fn();
- const record = {
- app: { sessionId: "sess_cua_sideband_failure" },
- updatedAt: 1_700,
- workspace,
- } as unknown as Parameters<typeof onSessionEvent>[1];
- const context = {
- logger: { warn },
- notify: vi.fn(() => {
- throw new Error("transport closed");
- }),
- v4Gateway: { ingest },
- } as unknown as Parameters<typeof onSessionEvent>[0];
- const event = {
- id: "evt-cua-sideband-failure" as SessionEvent["id"],
- payload: { turnNumber: 1, input: "control" },
- sequenceNumber: 1,
- sessionId: "sess_cua_sideband_failure" as SessionId,
- timestamp: new Date(1_800),
- traceId: "trace_cua_sideband_failure" as SessionEvent["traceId"],
- turnId: "turn-1" as SessionEvent["turnId"],
- type: SessionEventType.TurnStarted,
- } satisfies SessionEvent;
- expect(() => onSessionEvent(context, record, event)).not.toThrow();
- expect(ingest).toHaveBeenCalledWith("sess_cua_sideband_failure", event);
- expect(warn).toHaveBeenCalledTimes(1);
- });
- it("promotes a deferred record to immediate once the runtime reports the session persisted", () => {
- // 2026-09-14 实机:中枢直接启动的会话由 runtime 落行(controlOnly 启动轮,没有首发),record 一直
- // 是 deferred,sessions-index 视其为 draft 而跳过——侧栏永远不出现。record.persistence 是 runtime
- // 事实的镜像,在事件入口对齐一次即覆盖所有持久化路径。
- const ingest = vi.fn();
- let persisted = false;
- const record = {
- app: { sessionId: "sess_launch", runtime: { isSessionPersisted: () => persisted } },
- persistence: "deferred",
- updatedAt: 1_700,
- workspace,
- } as unknown as Parameters<typeof onSessionEvent>[1];
- const context = {
- v4Gateway: { ingest },
- } as unknown as Parameters<typeof onSessionEvent>[0];
- const event = {
- id: "evt_launch_title" as SessionEvent["id"],
- payload: { previousTitle: "", source: "first_input", title: "deep-research" },
- sequenceNumber: 1,
- sessionId: "sess_launch" as SessionId,
- timestamp: new Date(1_800),
- traceId: "trace_launch" as SessionEvent["traceId"],
- type: SessionEventType.SessionTitleUpdated,
- } satisfies SessionEvent;
- // runtime 尚未持久化:仍是 draft。
- onSessionEvent(context, record, event);
- expect(record.persistence).toBe("deferred");
- // runtime 持久化之后的第一条事件:离开 draft,且对齐发生在 ingest 之前(同一条事件就能进列表)。
- persisted = true;
- ingest.mockImplementation(() => {
- expect(record.persistence).toBe("immediate");
- });
- onSessionEvent(context, record, event);
- expect(record.persistence).toBe("immediate");
- expect(ingest).toHaveBeenCalledTimes(2);
- });
- it("does not bump record updatedAt for session title metadata events", () => {
- const ingest = vi.fn();
- const record = {
- app: { sessionId: "sess_title_sort" },
- updatedAt: 1_700,
- workspace,
- } as unknown as Parameters<typeof onSessionEvent>[1];
- const context = {
- v4Gateway: { ingest },
- } as unknown as Parameters<typeof onSessionEvent>[0];
- const event = {
- id: "evt_title_sort" as SessionEvent["id"],
- payload: {
- previousTitle: "",
- source: "generated",
- title: "Restored title",
- },
- sequenceNumber: 1,
- sessionId: "sess_title_sort" as SessionId,
- timestamp: new Date(1_800),
- traceId: "trace_title_sort" as SessionEvent["traceId"],
- type: SessionEventType.SessionTitleUpdated,
- } satisfies SessionEvent;
- onSessionEvent(context, record, event);
- expect(record.updatedAt).toBe(1_700);
- expect(ingest).toHaveBeenCalledWith("sess_title_sort", event);
- });
- it("routes raw child events to the child publisher without touching the parent record", () => {
- const ingest = vi.fn();
- const record = {
- app: { sessionId: "sess_parent" },
- updatedAt: 1_700,
- workspace,
- } as unknown as Parameters<typeof onSessionEvent>[1];
- const context = {
- v4Gateway: { ingestDetachedLiveSession: ingest },
- } as unknown as Parameters<typeof onSessionEvent>[0];
- const event = {
- id: "evt_child_delta" as SessionEvent["id"],
- payload: { kind: "text_delta", delta: "child", done: false },
- sequenceNumber: 2,
- sessionId: "sess_child" as SessionId,
- timestamp: new Date(1_800),
- traceId: "trace_child_delta" as SessionEvent["traceId"],
- type: SessionEventType.ModelStreaming,
- } satisfies SessionEvent;
- onSessionEvent(context, record, event);
- expect(record.updatedAt).toBe(1_700);
- expect(ingest).toHaveBeenCalledTimes(1);
- // 保留 source detached child publisher 生命周期:路由 child 时同时登记 parent 归属。
- expect(ingest).toHaveBeenCalledWith("sess_child", event, "sess_parent");
- });
- it("exposes model streaming tool input previews to the app protocol", () => {
- const events = mapSessionEvents(
- [
- {
- id: "evt_tool_input_delta" as SessionEvent["id"],
- payload: {
- kind: "tool_input_delta",
- delta: '{"file_path":"README.md"}',
- done: false,
- },
- sequenceNumber: 5,
- sessionId: "sess_1" as SessionId,
- timestamp: new Date(6),
- traceId: "trace_tool_input_delta" as SessionEvent["traceId"],
- type: SessionEventType.ModelStreaming,
- },
- {
- id: "evt_text_delta" as SessionEvent["id"],
- payload: {
- kind: "text_delta",
- delta: "hello",
- done: false,
- },
- sequenceNumber: 6,
- sessionId: "sess_1" as SessionId,
- timestamp: new Date(7),
- traceId: "trace_text_delta" as SessionEvent["traceId"],
- type: SessionEventType.ModelStreaming,
- },
- {
- id: "evt_tool_scheduled" as SessionEvent["id"],
- payload: {
- input: { file_path: "README.md" },
- toolCallId: "call_1",
- toolName: "Read",
- },
- sequenceNumber: 7,
- sessionId: "sess_1" as SessionId,
- timestamp: new Date(8),
- traceId: "trace_tool_scheduled" as SessionEvent["traceId"],
- type: SessionEventType.ToolCallScheduled,
- },
- ] satisfies SessionEvent[],
- "desktop-continuous",
- );
- expect(events).toHaveLength(3);
- expect(events[0]).toMatchObject({
- eventId: "evt_tool_input_delta",
- payload: { kind: "tool_input_delta", delta: '{"file_path":"README.md"}' },
- type: "model.streaming",
- });
- expect(events[1].eventId).toBe("evt_text_delta");
- expect(events[1].payload).toMatchObject({ kind: "text_delta", delta: "hello" });
- expect(events[2]).toMatchObject({
- eventId: "evt_tool_scheduled",
- payload: {
- input: { file_path: "README.md" },
- kind: "scheduled",
- toolCallId: "call_1",
- toolName: "Read",
- },
- type: "tool.updated",
- });
- });
- it("does not expose internal streaming tool ledger updates to the app protocol", () => {
- const events = mapSessionEvents([
- {
- id: "evt_tool_ledger" as SessionEvent["id"],
- payload: {
- input: { content: "large generated file" },
- status: "tool_started",
- toolCallId: "call_1",
- toolName: "Write",
- },
- sequenceNumber: 8,
- sessionId: "sess_1" as SessionId,
- timestamp: new Date(9),
- traceId: "trace_tool_ledger" as SessionEvent["traceId"],
- type: SessionEventType.StreamingToolLedgerUpdated,
- },
- ]);
- expect(events).toEqual([]);
- });
- it("logs snapshot phase timings for session create diagnostics", async () => {
- const logs: RecordedLog[] = [];
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- loggerFactory: createProtocolTestLoggerFactory(logs),
- version: "test-version",
- });
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- });
- const completed = logs.find(
- (log) => log.context.event === "zcode_protocol.session_create.completed",
- );
- expect(completed?.context.snapshotPhaseDurationsMs).toMatchObject({
- buildSnapshot: expect.any(Number),
- eventSeq: expect.any(Number),
- persistedMessages: expect.any(Number),
- persistedSession: expect.any(Number),
- rewindEvents: expect.any(Number),
- target: expect.any(Number),
- todos: expect.any(Number),
- });
- });
- // M5 ③-3:usage query 的 v4 名字空间分派(L2)。数据访问层与旧 usage/stats、
- // session/usage 共用(usage store 聚合),这里锁定 v4 方法名可达且结果过 v4 schema。
- it("serves v4/usage/stats through the usage data access layer", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const result = v4UsageStatsResultSchema.parse(
- await requestResult(server, {
- id: 1,
- method: V4_METHODS.usageStats,
- params: { range: "7d", timeZone: "UTC" },
- }),
- );
- // 无 usage store 的兜底路径:返回空快照而非抛错(与旧 op 语义一致)。
- expect(result.range).toBe("7d");
- expect(result.timeZone).toBe("UTC");
- expect(result.source).toBe("agent-db");
- expect(result.models).toEqual([]);
- });
- it("serves v4/conversation/usage keyed by sessionId", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const result = v4ConversationUsageResultSchema.parse(
- await requestResult(server, {
- id: 1,
- method: V4_METHODS.conversationUsage,
- params: { sessionId: "sess_v4_usage" },
- }),
- );
- expect(result.sessionId).toBe("sess_v4_usage");
- expect(result.totalTokens).toBe(0);
- expect(result.inputBaselineBySource).toEqual({});
- });
- it("三类 v4 subscribe response 只含 ACK,并把 initial 放入 request-scoped outbox", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: "create-for-v4-outbox",
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- const topics = [
- conversationTopic(created.session.sessionId),
- sessionsIndexTopic(workspace.workspaceKey),
- workspaceConfigTopic(workspace.workspaceKey),
- ];
- for (const [index, topic] of topics.entries()) {
- const id = `v4-subscribe-${index}`;
- const response = await server.handleMessage({
- id,
- method: V4_METHODS.conversationSubscribe,
- params: {
- topic,
- connectionId: `connection-${index}`,
- clientMode: "desktop-continuous",
- },
- });
- // staging 已在 ACK 内加入可选 openTiming 诊断;这里守住 response 仍只承载 ACK,
- // 初始 frame 仍必须进入 request-scoped outbox,不把诊断字段误判成 initial payload。
- expect(response).toMatchObject({
- id,
- result: {
- ack: {
- subscriptionId: expect.any(String),
- mode: "snapshot",
- logEpoch: expect.any(String),
- // 会话主题的 ACK 额外携带 session open 计时遥测(staging 的 ARMS 面);
- // 列表/配置主题没有会话可计时,不带这个键。
- ...(index === 0 ? { openTiming: expect.any(Object) } : {}),
- },
- },
- });
- const ack = (response as { result: { ack: { subscriptionId: string } } }).result.ack;
- const queued = server.takePostResponseMessages(id);
- expect(queued.length).toBeGreaterThan(0);
- expect(queued.every((message) => message.method === V4_NOTIFICATIONS.conversationFrame)).toBe(
- true,
- );
- const assembled = reassembleTopicWireFrames(
- queued.map((message) => routedTopicWireFrameSchema.parse(message.params)),
- routedTopicFrameSchema,
- );
- expect(assembled).toMatchObject({
- kind: "complete",
- frame: {
- topic,
- subscriptionId: ack.subscriptionId,
- payload: { kind: "snapshot" },
- },
- });
- expect(server.takePostResponseMessages(id)).toEqual([]);
- }
- });
- it("routes strict v4 connection flow control to the gateway", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- expect(
- await server.handleMessage({
- id: "flow-saturated",
- method: V4_METHODS.connectionFlow,
- params: { connectionId: "mobile-flow", state: "saturated" },
- }),
- ).toEqual({ id: "flow-saturated", result: {} });
- const invalid = await server.handleMessage({
- id: "flow-invalid",
- method: V4_METHODS.connectionFlow,
- params: { connectionId: "mobile-flow", state: "forged" },
- });
- expect(invalid).toMatchObject({ id: "flow-invalid", error: expect.any(Object) });
- });
- it("routes attachment begin/chunk/commit/abort without a full-data RPC", async () => {
- const writePromptAttachment = vi.fn(async () => ({ ref: "zcode-artifact://upload/server" }));
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options, { writePromptAttachment }),
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: "attachment-session",
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- const bytes = Buffer.from("server attachment");
- const common = {
- connectionId: "attachment-connection",
- sessionId: created.session.sessionId,
- uploadId: "upload-server",
- };
- await expect(
- requestResult(server, {
- id: "attachment-begin",
- method: V4_METHODS.attachmentBegin,
- params: {
- ...common,
- fileName: "server.txt",
- mime: "text/plain",
- totalBytes: bytes.byteLength,
- totalChunks: 1,
- checksum: `sha256:${createHash("sha256").update(bytes).digest("hex")}`,
- },
- }),
- ).resolves.toMatchObject({ state: "staging", nextChunkIndex: 0 });
- await requestResult(server, {
- id: "attachment-chunk",
- method: V4_METHODS.attachmentChunk,
- params: { ...common, chunkIndex: 0, dataBase64: bytes.toString("base64") },
- });
- await expect(
- requestResult(server, {
- id: "attachment-commit",
- method: V4_METHODS.attachmentCommit,
- params: common,
- }),
- ).resolves.toEqual({ ref: "zcode-artifact://upload/server" });
- await expect(
- requestResult(server, {
- id: "attachment-commit-retry",
- method: V4_METHODS.attachmentCommit,
- params: common,
- }),
- ).resolves.toEqual({ ref: "zcode-artifact://upload/server" });
- await expect(
- requestResult(server, {
- id: "attachment-abort",
- method: V4_METHODS.attachmentAbort,
- params: common,
- }),
- ).resolves.toEqual({});
- expect(writePromptAttachment).toHaveBeenCalledTimes(1);
- expect(writePromptAttachment).toHaveBeenCalledWith({
- fileName: "server.txt",
- mime: "text/plain",
- bytes: new Uint8Array(bytes),
- });
- await expect(
- server.handleMessage({
- id: "legacy-full-data-put",
- method: "v4/attachment/put" as never,
- params: {
- sessionId: created.session.sessionId,
- fileName: "forbidden.txt",
- mime: "text/plain",
- dataBase64: bytes.toString("base64"),
- },
- }),
- ).resolves.toMatchObject({
- id: "legacy-full-data-put",
- error: { code: -32601 },
- });
- });
- it("并发 subscribe request id 的 post-response outbox 不串线", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const topics = [
- sessionsIndexTopic(workspace.workspaceKey),
- workspaceConfigTopic(workspace.workspaceKey),
- ];
- await Promise.all(
- topics.map((topic, index) =>
- server.handleMessage({
- id: `parallel-${index}`,
- method: V4_METHODS.conversationSubscribe,
- params: {
- topic,
- connectionId: `parallel-connection-${index}`,
- clientMode: "desktop-continuous",
- },
- }),
- ),
- );
- expect(server.takePostResponseMessages("parallel-1")[0]).toMatchObject({
- params: { topic: topics[1] },
- });
- expect(server.takePostResponseMessages("parallel-0")[0]).toMatchObject({
- params: { topic: topics[0] },
- });
- });
- it("aligned resume 经真实 server/outbox/NDJSON 只写一行 ACK response", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: "create-for-aligned-resume",
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- const topic = conversationTopic(created.session.sessionId);
- const initialResponse = await server.handleMessage({
- id: "initial-subscribe",
- method: V4_METHODS.conversationSubscribe,
- params: {
- topic,
- connectionId: "aligned-connection",
- clientMode: "desktop-continuous",
- },
- });
- if (!initialResponse || !("result" in initialResponse)) {
- throw new Error("Expected initial subscribe response");
- }
- const initialResult = v4ConversationSubscribeResultSchema.parse(initialResponse.result);
- const initialMessages = server.takePostResponseMessages("initial-subscribe");
- if (initialMessages.length === 0) {
- throw new Error("Expected initial subscribe outbox frame");
- }
- const initialAssembly = reassembleTopicWireFrames(
- initialMessages.map((message) => routedTopicWireFrameSchema.parse(message.params)),
- conversationTopicFrameSchema,
- );
- if (initialAssembly.kind !== "complete") {
- throw new Error("Expected complete initial subscribe frame");
- }
- const initialFrame = initialAssembly.frame;
- const input = new PassThrough();
- const output = new PassThrough();
- let written = "";
- output.on("data", (chunk: Buffer) => {
- written += chunk.toString("utf8");
- });
- const connection = new ZCodeProtocolNdjsonConnection({
- clearPostResponseMessages: () => server.clearPostResponseMessages(),
- handleMessage: (message) => server.handleMessage(message),
- input,
- output,
- takePostResponseBatch: (requestId) => server.takePostResponseBatch(requestId),
- });
- connection.start();
- input.end(
- `${JSON.stringify({
- id: "aligned-resume",
- method: V4_METHODS.conversationSubscribe,
- params: {
- topic,
- connectionId: "aligned-connection",
- clientMode: "desktop-continuous",
- base: { logEpoch: initialResult.ack.logEpoch, seq: initialFrame.toSeq },
- },
- })}\n`,
- );
- await connection.waitForClose();
- const lines = written.trim().split("\n");
- expect(lines).toHaveLength(1);
- const response = JSON.parse(lines[0]!) as { result: unknown };
- expect(v4ConversationSubscribeResultSchema.parse(response.result).ack.mode).toBe("resume");
- expect(server.takePostResponseMessages("aligned-resume")).toEqual([]);
- });
- it("same-sub resync 经真实 server/NDJSON 严格先 ACK 再 physical recovery", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: "create-for-resync-order",
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- const topic = conversationTopic(created.session.sessionId);
- const subscribedResponse = await server.handleMessage({
- id: "subscribe-before-resync",
- method: V4_METHODS.conversationSubscribe,
- params: {
- topic,
- connectionId: "resync-connection",
- clientMode: "web-remote-replayable",
- },
- });
- if (!subscribedResponse || !("result" in subscribedResponse)) {
- throw new Error("Expected subscribe response");
- }
- const subscribed = v4ConversationSubscribeResultSchema.parse(subscribedResponse.result);
- // 初始 batch admission 后才开始 same-sub recovery。
- expect(server.takePostResponseMessages("subscribe-before-resync").length).toBeGreaterThan(0);
- const input = new PassThrough();
- const output = new PassThrough();
- let written = "";
- output.on("data", (chunk: Buffer) => {
- written += chunk.toString("utf8");
- });
- const connection = new ZCodeProtocolNdjsonConnection({
- clearPostResponseMessages: () => server.clearPostResponseMessages(),
- handleMessage: (message) => server.handleMessage(message),
- input,
- output,
- takePostResponseBatch: (requestId) => server.takePostResponseBatch(requestId),
- });
- connection.start();
- input.end(
- `${JSON.stringify({
- id: "same-sub-resync",
- method: V4_METHODS.conversationResync,
- params: {
- topic,
- connectionId: "resync-connection",
- subscriptionId: subscribed.ack.subscriptionId,
- base: null,
- forceSnapshot: true,
- },
- })}\n`,
- );
- await connection.waitForClose();
- const lines = written
- .trim()
- .split("\n")
- .map((line) => JSON.parse(line) as Record<string, unknown>);
- expect(lines.length).toBeGreaterThan(1);
- const result = v4ConversationResyncResultSchema.parse(lines[0]?.result);
- expect(result.ack.subscriptionId).toBe(subscribed.ack.subscriptionId);
- expect(result.ack.mode).toBe("snapshot");
- expect(lines.slice(1).every((line) => line.method === V4_NOTIFICATIONS.conversationFrame)).toBe(
- true,
- );
- });
- it("uses the app supplied protocol trace as the session root trace", async () => {
- const logs: RecordedLog[] = [];
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- loggerFactory: createProtocolTestLoggerFactory(logs),
- version: "test-version",
- });
- const snapshot = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- trace: { traceId: "trace_from_app" },
- }),
- );
- expect(snapshot.session.traceId).toBe("trace_from_app");
- const createRecord = logs.find(
- (log) => log.context.event === "zcode_protocol.create_record.mcp_config",
- );
- expect(createRecord?.context.rootTraceId).toBe("trace_from_app");
- });
- it("refreshes MCP list statuses through the protocol process MCP port", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-protocol-mcp-list-"));
- const workspacePath = join(root, "workspace");
- const pluginRoot = join(root, "plugin");
- const connectedConfigs: Record<string, McpServerConfig>[] = [];
- const mcpPort = createProtocolListMcpPort(connectedConfigs);
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspacePath,
- mcpPort,
- version: "test-version",
- });
- try {
- await mkdir(join(root, ".git"));
- await mkdir(join(pluginRoot, ".zcode-plugin"), { recursive: true });
- await mkdir(workspacePath, { recursive: true });
- await writeFile(
- join(root, "zcode.json"),
- JSON.stringify({
- plugins: {
- dirs: [pluginRoot],
- },
- mcp: {
- servers: {
- "project-only": {
- type: "stdio",
- command: "project-server",
- },
- },
- },
- }),
- );
- await writeFile(
- join(pluginRoot, ".zcode-plugin", "plugin.json"),
- JSON.stringify({
- name: "status-plugin",
- mcpServers: {
- "plugin-live": {
- command: "plugin-server",
- },
- },
- }),
- );
- const result = await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.mcpList,
- params: {
- workspace: {
- workspaceKey: workspacePath,
- workspacePath,
- },
- },
- });
- expect(connectedConfigs).toHaveLength(1);
- expect(connectedConfigs[0]?.["plugin:status-plugin:plugin-live"]).toMatchObject({
- command: "plugin-server",
- type: "stdio",
- });
- expect(connectedConfigs[0]?.["project-only"]).toMatchObject({
- command: "project-server",
- type: "stdio",
- });
- expect(result).toMatchObject({
- statuses: {
- "plugin:status-plugin:plugin-live": {
- status: "connected",
- toolCount: 3,
- transport: "stdio",
- },
- "project-only": {
- status: "connected",
- toolCount: 3,
- transport: "stdio",
- },
- },
- });
- } finally {
- await rm(root, { force: true, recursive: true });
- }
- });
- it("uses explicit protocol MCP servers for MCP list statuses", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-protocol-mcp-list-explicit-"));
- const workspacePath = join(root, "workspace");
- const connectedConfigs: Record<string, McpServerConfig>[] = [];
- const mcpPort = createProtocolListMcpPort(connectedConfigs);
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspacePath,
- mcpPort,
- version: "test-version",
- });
- try {
- await mkdir(join(root, ".git"));
- await mkdir(workspacePath, { recursive: true });
- await writeFile(
- join(root, "zcode.json"),
- JSON.stringify({
- mcp: {
- servers: {
- "disk-only": {
- type: "stdio",
- command: "disk-server",
- },
- },
- },
- }),
- );
- const result = await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.mcpList,
- params: {
- workspace: {
- workspaceKey: workspacePath,
- workspacePath,
- },
- mcpServers: [
- {
- name: "agents-fallback",
- command: "node",
- args: ["server.mjs"],
- env: [{ name: "TOKEN", value: "secret" }],
- timeoutMs: 3000,
- },
- ],
- },
- });
- expect(connectedConfigs).toHaveLength(1);
- expect(connectedConfigs[0]?.["agents-fallback"]).toMatchObject({
- args: ["server.mjs"],
- command: "node",
- env: { TOKEN: "secret" },
- timeoutMs: 3000,
- type: "stdio",
- });
- expect(connectedConfigs[0]?.["disk-only"]).toBeUndefined();
- expect(result).toMatchObject({
- statuses: {
- "agents-fallback": {
- status: "connected",
- toolCount: 3,
- transport: "stdio",
- },
- },
- });
- } finally {
- await rm(root, { force: true, recursive: true });
- }
- });
- it("reads MCP list statuses without replace disconnects in status mode", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-protocol-mcp-list-status-"));
- const workspacePath = join(root, "workspace");
- const connectedConfigs: Record<string, McpServerConfig>[] = [];
- const disconnectedNames: string[] = [];
- const mcpPort = createProtocolReplaceMcpPort(connectedConfigs, disconnectedNames, {
- everything: {
- status: "connected",
- transport: "stdio",
- toolCount: 9,
- updatedAt: new Date(1).toISOString(),
- },
- "plugin:canva:canva": {
- authorization: {
- authorizationUrl: "https://auth.canva.example.test/authorize",
- startedAt: new Date(1).toISOString(),
- type: "oauth_authorization_code",
- },
- status: "connecting",
- transport: "http",
- toolCount: 0,
- updatedAt: new Date(1).toISOString(),
- },
- });
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspacePath,
- mcpPort,
- version: "test-version",
- });
- try {
- await mkdir(join(root, ".git"));
- await mkdir(workspacePath, { recursive: true });
- const result = await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.mcpList,
- params: {
- workspace: {
- workspaceKey: workspacePath,
- workspacePath,
- },
- mode: "status",
- mcpServers: [
- {
- name: "plugin:canva:canva",
- type: "http",
- url: "https://mcp.canva.example.test/mcp",
- headers: [],
- oauth: {
- type: "authorization_code",
- clientName: "ZCode",
- },
- },
- ],
- },
- });
- expect(connectedConfigs).toHaveLength(0);
- expect(disconnectedNames).not.toContain("everything");
- expect(result).toMatchObject({
- statuses: {
- everything: {
- status: "connected",
- toolCount: 9,
- transport: "stdio",
- },
- "plugin:canva:canva": {
- authorization: {
- authorizationUrl: "https://auth.canva.example.test/authorize",
- },
- status: "connecting",
- transport: "http",
- },
- },
- });
- } finally {
- await rm(root, { force: true, recursive: true });
- }
- });
- it("keeps replace convergence when default connect sees pending OAuth status", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-protocol-mcp-list-connect-pending-"));
- const workspacePath = join(root, "workspace");
- const connectedConfigs: Record<string, McpServerConfig>[] = [];
- const disconnectedNames: string[] = [];
- const mcpPort = createProtocolReplaceMcpPort(connectedConfigs, disconnectedNames, {
- "plugin:canva:canva": {
- authorization: {
- authorizationUrl: "https://auth.canva.example.test/authorize",
- startedAt: new Date(1).toISOString(),
- type: "oauth_authorization_code",
- },
- status: "connecting",
- transport: "http",
- toolCount: 0,
- updatedAt: new Date(1).toISOString(),
- },
- stale: {
- status: "connected",
- transport: "stdio",
- toolCount: 1,
- updatedAt: new Date(1).toISOString(),
- },
- });
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspacePath,
- mcpPort,
- version: "test-version",
- });
- try {
- await mkdir(join(root, ".git"));
- await mkdir(workspacePath, { recursive: true });
- const result = await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.mcpList,
- params: {
- workspace: {
- workspaceKey: workspacePath,
- workspacePath,
- },
- mcpServers: [
- {
- name: "everything",
- command: "node",
- args: ["server.mjs"],
- env: [],
- },
- {
- name: "plugin:canva:canva",
- type: "http",
- url: "https://mcp.canva.example.test/mcp",
- headers: [],
- oauth: {
- type: "authorization_code",
- clientName: "ZCode",
- },
- },
- ],
- },
- });
- expect(connectedConfigs).toHaveLength(1);
- expect(connectedConfigs[0]).toMatchObject({
- everything: {
- command: "node",
- type: "stdio",
- },
- "plugin:canva:canva": {
- type: "http",
- },
- });
- expect(disconnectedNames).toContain("stale");
- expect(result).toMatchObject({
- statuses: {
- everything: {
- status: "connected",
- },
- "plugin:canva:canva": {
- status: "connected",
- },
- },
- });
- } finally {
- await rm(root, { force: true, recursive: true });
- }
- });
- it("returns pending MCP OAuth authorization status without waiting for callback", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-protocol-mcp-oauth-pending-"));
- const workspacePath = join(root, "workspace");
- const connectedConfigs: Record<string, McpServerConfig>[] = [];
- let finishConnect!: () => void;
- const mcpPort = createProtocolPendingAuthorizationMcpPort(connectedConfigs, (resolve) => {
- finishConnect = resolve;
- });
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspacePath,
- mcpPort,
- version: "test-version",
- });
- try {
- await mkdir(join(root, ".git"));
- await mkdir(workspacePath, { recursive: true });
- const result = await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.mcpList,
- params: {
- workspace: {
- workspaceKey: workspacePath,
- workspacePath,
- },
- mcpServers: [
- {
- name: "notion",
- type: "http",
- url: "https://mcp.notion.example.test/mcp",
- headers: [],
- oauth: {
- type: "authorization_code",
- clientName: "ZCode",
- },
- },
- ],
- },
- });
- expect(connectedConfigs).toHaveLength(1);
- expect(result).toMatchObject({
- statuses: {
- notion: {
- authorization: {
- authorizationUrl: "https://auth.example.test/authorize?state=state_test",
- type: "oauth_authorization_code",
- },
- status: "connecting",
- transport: "http",
- },
- },
- });
- finishConnect();
- } finally {
- finishConnect?.();
- await rm(root, { force: true, recursive: true });
- }
- });
- it("cancels background bash tasks through the session protocol", async () => {
- const notifications: ZCodeProtocolNotification[] = [];
- let cancelledTaskId: string | undefined;
- let backgroundTasks: BackgroundTaskInfo[] = [
- {
- cancellable: true,
- command: "pnpm dev",
- status: "running",
- taskId: "bg_1",
- terminalId: "bg_1",
- },
- ];
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- const app = createFakeApp(options);
- return {
- ...app,
- cancelBackgroundTask: async (taskId) => {
- cancelledTaskId = taskId;
- const currentTask = backgroundTasks[0];
- if (!currentTask) {
- throw new Error("Expected background task fixture");
- }
- backgroundTasks = [
- {
- ...currentTask,
- cancellable: false,
- status: "cancelled",
- },
- ];
- return {
- cancelled: true,
- snapshot: backgroundTasks[0],
- status: "cancelled",
- taskId,
- };
- },
- runtime: {
- ...app.runtime,
- getProjection: async () => ({
- ...(await app.runtime.getProjection()),
- backgroundTasks,
- }),
- },
- };
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- setTestNotificationSink(server, (notification) => notifications.push(notification));
- const snapshot = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- const result = zcodeSessionCancelBackgroundTaskResultSchema.parse(
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionCancelBackgroundTask,
- params: { sessionId: snapshot.session.sessionId, taskId: "bg_1" },
- }),
- );
- expect(cancelledTaskId).toBe("bg_1");
- expect(result).toMatchObject({
- cancelled: true,
- status: "cancelled",
- taskId: "bg_1",
- });
- expect(notifications.some((item) => item.method === "state.updated")).toBe(true);
- });
- it("sends contiguous protocol seq for the visible session event stream", async () => {
- const notifications: ZCodeProtocolNotification[] = [];
- const logs: RecordedLog[] = [];
- let eventStore: ZCodeAppOptions["eventStore"];
- let liveSink: ((event: SessionEvent) => void | Promise<void>) | undefined;
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- eventStore = options?.eventStore;
- const app = createFakeApp(options);
- return {
- ...app,
- runtime: {
- ...app.runtime,
- subscribeEvents: (sink: {
- onSessionEvent(event: SessionEvent): void | Promise<void>;
- }) => {
- liveSink = sink.onSessionEvent;
- return () => {};
- },
- } as never,
- };
- },
- cwd: workspace.workspacePath,
- loggerFactory: createProtocolTestLoggerFactory(logs),
- version: "test-version",
- });
- setTestNotificationSink(server, (notification) => notifications.push(notification));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSubscribe,
- params: {
- sessionId: created.session.sessionId,
- deliveryKind: "desktop-continuous",
- includeSnapshot: true,
- },
- });
- const emitStoredEvent = async (event: SessionEvent) => {
- if (!eventStore || !liveSink) {
- throw new Error("Expected fake app event sink to be wired");
- }
- const storedEvent = await eventStore.append(event);
- await liveSink(storedEvent);
- };
- const emitLiveOnlyEvent = async (event: SessionEvent) => {
- if (!liveSink) {
- throw new Error("Expected fake app event sink to be wired");
- }
- await liveSink(event);
- };
- const baseEvent = {
- sessionId: created.session.sessionId as SessionId,
- timestamp: new Date(7),
- traceId: "trace_protocol_seq" as SessionEvent["traceId"],
- type: SessionEventType.ModelStreaming,
- };
- await emitLiveOnlyEvent({
- ...baseEvent,
- id: "evt_live_text_delta_1" as SessionEvent["id"],
- payload: { delta: "live", done: false, kind: "text_delta" },
- sequenceNumber: 0,
- });
- await emitLiveOnlyEvent({
- ...baseEvent,
- id: "evt_live_text_delta_2" as SessionEvent["id"],
- payload: { delta: " only", done: false, kind: "text_delta" },
- sequenceNumber: 0,
- });
- await emitStoredEvent({
- ...baseEvent,
- id: "evt_tool_input_delta" as SessionEvent["id"],
- payload: { delta: '{"file_path":"README.md"}', done: false, kind: "tool_input_delta" },
- sequenceNumber: 0,
- });
- await emitStoredEvent({
- ...baseEvent,
- id: "evt_text_delta_1" as SessionEvent["id"],
- payload: { delta: "hello", done: false, kind: "text_delta" },
- sequenceNumber: 0,
- });
- await emitStoredEvent({
- ...baseEvent,
- id: "evt_text_delta_2" as SessionEvent["id"],
- payload: { delta: " world", done: false, kind: "text_delta" },
- sequenceNumber: 0,
- });
- await emitStoredEvent({
- ...baseEvent,
- id: "evt_turn_complete" as SessionEvent["id"],
- payload: {
- duration: 1,
- response: "done",
- resultType: "success",
- tokenCount: 2,
- toolCallCount: 0,
- },
- sequenceNumber: 0,
- type: SessionEventType.TurnComplete,
- });
- const liveEvents = notifications
- .filter((notification) => notification.method === "session/event")
- .map((notification) => zcodeSessionEventSchema.parse(notification.params));
- expect(liveEvents.map((event) => event.seq)).toEqual([1, 2, 3, 4, 5, 6]);
- expect(liveEvents.map((event) => event.eventId)).toEqual([
- "evt_live_text_delta_1",
- "evt_live_text_delta_2",
- "evt_tool_input_delta",
- "evt_text_delta_1",
- "evt_text_delta_2",
- "evt_turn_complete",
- ]);
- const subscribed = zcodeSessionSubscribeResultSchema.parse(
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.sessionSubscribe,
- params: {
- sessionId: created.session.sessionId,
- deliveryKind: "desktop-continuous",
- afterSeq: 1,
- includeSnapshot: true,
- },
- }),
- );
- expect(subscribed.eventSeq).toBe(6);
- expect(subscribed.events.map((event) => event.seq)).toEqual([3, 4, 5, 6]);
- expect(subscribed.snapshot?.runtime.eventSeq).toBe(6);
- const sentLog = logs.find(
- (log) =>
- log.context.event === "zcode_protocol.session_event.sent" &&
- log.context.eventId === "evt_text_delta_1",
- );
- expect(sentLog?.context).toMatchObject({
- event: "zcode_protocol.session_event.sent",
- eventId: "evt_text_delta_1",
- payloadKeys: ["delta", "done", "kind"],
- payloadKind: "text_delta",
- payloadSummary: {
- deltaBytes: expect.any(Number),
- done: false,
- kind: "text_delta",
- },
- protocolEventType: "model.streaming",
- protocolMessageBytes: expect.any(Number),
- protocolPayloadBytes: expect.any(Number),
- protocolSeq: 4,
- sessionEventType: SessionEventType.ModelStreaming,
- });
- expect(sentLog?.context.protocolMessage).toBeUndefined();
- expect(JSON.stringify(sentLog?.context)).not.toContain("hello");
- });
- it("omits repeated scheduled tool input after model streaming tool calls", async () => {
- const notifications: ZCodeProtocolNotification[] = [];
- let eventStore: ZCodeAppOptions["eventStore"];
- let liveSink: ((event: SessionEvent) => void | Promise<void>) | undefined;
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- eventStore = options?.eventStore;
- const app = createFakeApp(options);
- return {
- ...app,
- runtime: {
- ...app.runtime,
- subscribeEvents: (sink: {
- onSessionEvent(event: SessionEvent): void | Promise<void>;
- }) => {
- liveSink = sink.onSessionEvent;
- return () => {};
- },
- } as never,
- };
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- setTestNotificationSink(server, (notification) => notifications.push(notification));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSubscribe,
- params: {
- sessionId: created.session.sessionId,
- deliveryKind: "desktop-continuous",
- includeSnapshot: false,
- },
- });
- const emitStoredEvent = async (event: SessionEvent) => {
- if (!eventStore || !liveSink) {
- throw new Error("Expected fake app event sink to be wired");
- }
- const storedEvent = await eventStore.append(event);
- await liveSink(storedEvent);
- };
- const toolInput = {
- content: "generated content\n".repeat(512),
- file_path: "/workspace/generated.html",
- };
- const inputByteLength = Buffer.byteLength(JSON.stringify(toolInput), "utf8");
- const baseEvent = {
- sessionId: created.session.sessionId as SessionId,
- timestamp: new Date(7),
- traceId: "trace_tool_input_dedupe" as SessionEvent["traceId"],
- };
- await emitStoredEvent({
- ...baseEvent,
- id: "evt_tool_call" as SessionEvent["id"],
- payload: {
- done: true,
- input: toolInput,
- kind: "tool_call",
- toolCallId: "call_write",
- toolName: "Write",
- },
- sequenceNumber: 0,
- type: SessionEventType.ModelStreaming,
- });
- await emitStoredEvent({
- ...baseEvent,
- id: "evt_tool_scheduled" as SessionEvent["id"],
- payload: {
- input: toolInput,
- schedule: { dependencies: [] },
- toolCallId: "call_write",
- toolName: "Write",
- },
- sequenceNumber: 0,
- type: SessionEventType.ToolCallScheduled,
- });
- await emitStoredEvent({
- ...baseEvent,
- id: "evt_tool_ledger" as SessionEvent["id"],
- payload: {
- input: toolInput,
- status: "tool_started",
- toolCallId: "call_write",
- toolName: "Write",
- },
- sequenceNumber: 0,
- type: SessionEventType.StreamingToolLedgerUpdated,
- });
- const liveEvents = notifications
- .filter((notification) => notification.method === "session/event")
- .map((notification) => zcodeSessionEventSchema.parse(notification.params));
- expect(liveEvents.map((event) => event.eventId)).toEqual([
- "evt_tool_call",
- "evt_tool_scheduled",
- ]);
- expect(liveEvents.map((event) => event.seq)).toEqual([1, 2]);
- const liveScheduledPayload = liveEvents[1]?.payload as Record<string, unknown>;
- expect(liveScheduledPayload).toMatchObject({
- inputByteLength,
- inputOmitted: true,
- inputRef: "model_stream",
- kind: "scheduled",
- toolCallId: "call_write",
- toolName: "Write",
- });
- expect(Object.prototype.hasOwnProperty.call(liveScheduledPayload, "input")).toBe(false);
- const replayed = zcodeSessionEventsResultSchema.parse(
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.sessionEvents,
- params: { sessionId: created.session.sessionId, afterSeq: 0 },
- }),
- );
- expect(replayed.events.map((event) => event.eventId)).toEqual([
- "evt_tool_call",
- "evt_tool_scheduled",
- ]);
- const replayScheduledPayload = replayed.events[1]?.payload as Record<string, unknown>;
- expect(replayScheduledPayload).toMatchObject({
- inputByteLength,
- inputOmitted: true,
- inputRef: "model_stream",
- kind: "scheduled",
- toolCallId: "call_write",
- toolName: "Write",
- });
- expect(Object.prototype.hasOwnProperty.call(replayScheduledPayload, "input")).toBe(false);
- expect(JSON.stringify(liveScheduledPayload)).not.toContain("generated content");
- expect(JSON.stringify(replayScheduledPayload)).not.toContain("generated content");
- });
- it("coalesces streaming tool input deltas with eager and timestamp-budgeted flushes", async () => {
- const notifications: ZCodeProtocolNotification[] = [];
- let eventStore: ZCodeAppOptions["eventStore"];
- let liveSink: ((event: SessionEvent) => void | Promise<void>) | undefined;
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- eventStore = options?.eventStore;
- const app = createFakeApp(options);
- return {
- ...app,
- runtime: {
- ...app.runtime,
- subscribeEvents: (sink: {
- onSessionEvent(event: SessionEvent): void | Promise<void>;
- }) => {
- liveSink = sink.onSessionEvent;
- return () => {};
- },
- } as never,
- };
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- setTestNotificationSink(server, (notification) => notifications.push(notification));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSubscribe,
- params: {
- sessionId: created.session.sessionId,
- deliveryKind: "desktop-continuous",
- includeSnapshot: false,
- },
- });
- const emitStoredEvent = async (event: SessionEvent) => {
- if (!eventStore || !liveSink) {
- throw new Error("Expected fake app event sink to be wired");
- }
- const storedEvent = await eventStore.append(event);
- await liveSink(storedEvent);
- };
- const baseEvent = {
- sessionId: created.session.sessionId as SessionId,
- traceId: "trace_tool_delta_coalesce" as SessionEvent["traceId"],
- type: SessionEventType.ModelStreaming,
- };
- for (const [index, item] of [
- { delta: "a", timestamp: 7 },
- { delta: "b", timestamp: 407 },
- { delta: "c", timestamp: 758 },
- ].entries()) {
- await emitStoredEvent({
- ...baseEvent,
- id: `evt_tool_delta_${index + 1}` as SessionEvent["id"],
- payload: {
- delta: item.delta,
- done: false,
- kind: "tool_input_delta",
- toolCallId: "call_write",
- toolName: "Write",
- },
- sequenceNumber: 0,
- timestamp: new Date(item.timestamp),
- });
- }
- await emitStoredEvent({
- ...baseEvent,
- id: "evt_tool_input_end" as SessionEvent["id"],
- payload: {
- done: true,
- kind: "tool_input_end",
- toolCallId: "call_write",
- toolName: "Write",
- },
- sequenceNumber: 0,
- timestamp: new Date(759),
- });
- const liveEvents = notifications
- .filter((notification) => notification.method === "session/event")
- .map((notification) => zcodeSessionEventSchema.parse(notification.params));
- expect(liveEvents.map((event) => event.seq)).toEqual([1, 2, 3]);
- expect(liveEvents.map((event) => event.eventId)).toEqual([
- "evt_tool_delta_1",
- "evt_tool_delta_3",
- "evt_tool_input_end",
- ]);
- expect(liveEvents[0]?.payload).toMatchObject({
- delta: "a",
- kind: "tool_input_delta",
- toolCallId: "call_write",
- });
- expect(liveEvents[1]?.payload).toMatchObject({
- delta: "bc",
- kind: "tool_input_delta",
- toolCallId: "call_write",
- });
- const replayed = zcodeSessionEventsResultSchema.parse(
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.sessionEvents,
- params: { sessionId: created.session.sessionId, afterSeq: 0 },
- }),
- );
- expect(replayed.events.map((event) => event.seq)).toEqual([1, 2, 3]);
- expect(replayed.events[0]?.payload).toMatchObject({
- delta: "a",
- kind: "tool_input_delta",
- toolCallId: "call_write",
- });
- expect(replayed.events[1]?.payload).toMatchObject({
- delta: "bc",
- kind: "tool_input_delta",
- toolCallId: "call_write",
- });
- });
- it("coalesces text and reasoning streaming deltas after the first visible token", async () => {
- const notifications: ZCodeProtocolNotification[] = [];
- let eventStore: ZCodeAppOptions["eventStore"];
- let liveSink: ((event: SessionEvent) => void | Promise<void>) | undefined;
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- eventStore = options?.eventStore;
- const app = createFakeApp(options);
- return {
- ...app,
- runtime: {
- ...app.runtime,
- subscribeEvents: (sink: {
- onSessionEvent(event: SessionEvent): void | Promise<void>;
- }) => {
- liveSink = sink.onSessionEvent;
- return () => {};
- },
- } as never,
- };
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- setTestNotificationSink(server, (notification) => notifications.push(notification));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSubscribe,
- params: {
- sessionId: created.session.sessionId,
- deliveryKind: "desktop-continuous",
- includeSnapshot: false,
- },
- });
- const emitStoredEvent = async (event: SessionEvent) => {
- if (!eventStore || !liveSink) {
- throw new Error("Expected fake app event sink to be wired");
- }
- const storedEvent = await eventStore.append(event);
- await liveSink(storedEvent);
- };
- const baseEvent = {
- sessionId: created.session.sessionId as SessionId,
- traceId: "trace_text_delta_coalesce" as SessionEvent["traceId"],
- type: SessionEventType.ModelStreaming,
- };
- for (const [index, delta] of ["first", " second", " third"].entries()) {
- await emitStoredEvent({
- ...baseEvent,
- id: `evt_reasoning_delta_${index + 1}` as SessionEvent["id"],
- timestamp: new Date([0, 100, 260][index] ?? 260),
- payload: {
- assistantMessageId: "msg_reasoning",
- delta,
- done: false,
- kind: "reasoning_delta",
- },
- sequenceNumber: 0,
- });
- }
- const liveEventsBeforeTurnComplete = notifications
- .filter((notification) => notification.method === "session/event")
- .map((notification) => zcodeSessionEventSchema.parse(notification.params));
- expect(liveEventsBeforeTurnComplete.map((event) => event.eventId)).toEqual([
- "evt_reasoning_delta_1",
- "evt_reasoning_delta_3",
- ]);
- await emitStoredEvent({
- ...baseEvent,
- id: "evt_turn_complete_after_reasoning" as SessionEvent["id"],
- timestamp: new Date(300),
- payload: {
- duration: 1,
- response: "done",
- resultType: "success",
- tokenCount: 3,
- toolCallCount: 0,
- },
- sequenceNumber: 0,
- type: SessionEventType.TurnComplete,
- });
- const liveEvents = notifications
- .filter((notification) => notification.method === "session/event")
- .map((notification) => zcodeSessionEventSchema.parse(notification.params));
- expect(liveEvents.map((event) => event.seq)).toEqual([1, 2, 3]);
- expect(liveEvents.map((event) => event.eventId)).toEqual([
- "evt_reasoning_delta_1",
- "evt_reasoning_delta_3",
- "evt_turn_complete_after_reasoning",
- ]);
- expect(liveEvents[0]?.payload).toMatchObject({
- delta: "first",
- kind: "reasoning_delta",
- });
- expect(liveEvents[1]?.payload).toMatchObject({
- delta: " second third",
- kind: "reasoning_delta",
- });
- const replayed = zcodeSessionEventsResultSchema.parse(
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.sessionEvents,
- params: { sessionId: created.session.sessionId, afterSeq: 0 },
- }),
- );
- expect(replayed.events.map((event) => event.seq)).toEqual([1, 2, 3]);
- expect(replayed.events[1]?.payload).toMatchObject({
- delta: " second third",
- kind: "reasoning_delta",
- });
- });
- it("keeps separate text streaming parts in separate protocol batches", async () => {
- const notifications: ZCodeProtocolNotification[] = [];
- let eventStore: ZCodeAppOptions["eventStore"];
- let liveSink: ((event: SessionEvent) => void | Promise<void>) | undefined;
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- eventStore = options?.eventStore;
- const app = createFakeApp(options);
- return {
- ...app,
- runtime: {
- ...app.runtime,
- subscribeEvents: (sink: {
- onSessionEvent(event: SessionEvent): void | Promise<void>;
- }) => {
- liveSink = sink.onSessionEvent;
- return () => {};
- },
- } as never,
- };
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- setTestNotificationSink(server, (notification) => notifications.push(notification));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSubscribe,
- params: {
- sessionId: created.session.sessionId,
- deliveryKind: "desktop-continuous",
- includeSnapshot: false,
- },
- });
- const emitStoredEvent = async (event: SessionEvent) => {
- if (!eventStore || !liveSink) {
- throw new Error("Expected fake app event sink to be wired");
- }
- const storedEvent = await eventStore.append(event);
- await liveSink(storedEvent);
- };
- const baseEvent = {
- sessionId: created.session.sessionId as SessionId,
- timestamp: new Date(7),
- traceId: "trace_parent_text_delta_coalesce" as SessionEvent["traceId"],
- type: SessionEventType.ModelStreaming,
- };
- await emitStoredEvent({
- ...baseEvent,
- id: "evt_parent_a_text_delta" as SessionEvent["id"],
- payload: {
- delta: "from-a",
- done: false,
- kind: "text_delta",
- partId: "part_a",
- },
- sequenceNumber: 0,
- });
- await emitStoredEvent({
- ...baseEvent,
- id: "evt_parent_b_text_delta" as SessionEvent["id"],
- payload: {
- delta: "from-b",
- done: false,
- kind: "text_delta",
- partId: "part_b",
- },
- sequenceNumber: 0,
- });
- const liveEvents = notifications
- .filter((notification) => notification.method === "session/event")
- .map((notification) => zcodeSessionEventSchema.parse(notification.params));
- expect(liveEvents.map((event) => event.eventId)).toEqual([
- "evt_parent_a_text_delta",
- "evt_parent_b_text_delta",
- ]);
- expect(liveEvents.map((event) => event.payload)).toEqual([
- expect.objectContaining({
- delta: "from-a",
- kind: "text_delta",
- partId: "part_a",
- }),
- expect.objectContaining({
- delta: "from-b",
- kind: "text_delta",
- partId: "part_b",
- }),
- ]);
- });
- it("creates imported sessions as resumable protocol sessions", async () => {
- const store = createSqliteSessionStore({ dbPath: ":memory:" });
- const importedWorkspace = {
- ...workspace,
- workspaceIdentity: "ssh:example:/workspace/app",
- };
- try {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: importedWorkspace.workspacePath,
- sessionStore: store,
- version: "test-version",
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: {
- workspace: importedWorkspace,
- sessionId: "claude-import-test-session",
- importedHistory: {
- source: "claudeCode",
- title: "Imported Claude Session",
- createdAt: 1_700_000_000_000,
- updatedAt: 1_700_000_001_000,
- messages: [
- {
- role: "user",
- content: "继续这个导入会话",
- timestamp: 1_700_000_001_000,
- },
- {
- role: "assistant",
- content: "可以继续。",
- timestamp: 1_700_000_000_500,
- },
- ],
- },
- },
- }),
- );
- expect(created.session.title).toBe("Imported Claude Session");
- expect(created.session.sessionId).toBe("claude-import-test-session");
- await expect(
- store.getSession("claude-import-test-session" as SessionId),
- ).resolves.toMatchObject({
- workspaceID: importedWorkspace.workspaceIdentity,
- });
- expect(messageTexts(created.messages)).toEqual(["继续这个导入会话", "可以继续。"]);
- const switched = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSetModel,
- params: {
- sessionId: created.session.sessionId,
- model: { providerId: "glm", modelId: "glm-4-air" },
- },
- }),
- );
- expect(switched.session.sessionId).toBe(created.session.sessionId);
- expect(switched.settings.model.current).toMatchObject({
- providerId: "glm",
- modelId: "glm-4-air",
- });
- expect(messageTexts(switched.messages)).toEqual(["继续这个导入会话", "可以继续。"]);
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.sessionCreate,
- params: {
- workspace: importedWorkspace,
- sessionId: "claude-import-second-session",
- importedHistory: {
- source: "claudeCode",
- title: "Second Imported Claude Session",
- messages: [
- {
- role: "user",
- content: "第二个导入会话",
- timestamp: 1_700_000_003_000,
- },
- {
- role: "assistant",
- content: "第二个也可以继续。",
- timestamp: 1_700_000_002_000,
- },
- ],
- },
- },
- });
- const rereadFirst = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 4,
- method: zcodeProtocolMethods.sessionRead,
- params: { sessionId: created.session.sessionId },
- }),
- );
- const secondMessages = await store.messages({
- sessionID: "claude-import-second-session" as SessionId,
- });
- expect(messageTexts(rereadFirst.messages)).toEqual(["继续这个导入会话", "可以继续。"]);
- expect(messageTexts(secondMessages)).toEqual(["第二个导入会话", "第二个也可以继续。"]);
- expect(secondMessages.map((message) => message.info.id)).toEqual([
- "msg_claude-import-second-session_import_0",
- "msg_claude-import-second-session_import_1",
- ]);
- } finally {
- store.close();
- }
- });
- it("rejects caller-provided session ids outside imported history creates", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const response = await server.handleMessage({
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: {
- workspace,
- sessionId: "external-session-id",
- },
- });
- expect(response).toMatchObject({
- error: {
- code: -32602,
- message: "sessionId is only supported for imported history creates",
- },
- });
- });
- it("keeps session title generation internals out of the visible event stream", async () => {
- const notifications: ZCodeProtocolNotification[] = [];
- let eventStore: ZCodeAppOptions["eventStore"];
- let liveSink: ((event: SessionEvent) => void | Promise<void>) | undefined;
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- eventStore = options?.eventStore;
- const app = createFakeApp(options);
- return {
- ...app,
- runtime: {
- ...app.runtime,
- subscribeEvents: (sink: {
- onSessionEvent(event: SessionEvent): void | Promise<void>;
- }) => {
- liveSink = sink.onSessionEvent;
- return () => {};
- },
- } as never,
- };
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- setTestNotificationSink(server, (notification) => notifications.push(notification));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSubscribe,
- params: {
- sessionId: created.session.sessionId,
- deliveryKind: "desktop-continuous",
- },
- });
- const emitStoredEvent = async (event: SessionEvent) => {
- if (!eventStore || !liveSink) {
- throw new Error("Expected fake app event sink to be wired");
- }
- const storedEvent = await eventStore.append(event);
- await liveSink(storedEvent);
- };
- const common = {
- sessionId: created.session.sessionId as SessionId,
- timestamp: new Date(8),
- traceId: "trace_title_generation" as SessionEvent["traceId"],
- turnId: "turn_title" as SessionEvent["turnId"],
- };
- await emitStoredEvent({
- ...common,
- id: "evt_turn_complete" as SessionEvent["id"],
- payload: {
- response: "done",
- tokenCount: 1,
- toolCallCount: 0,
- duration: 1,
- resultType: "success",
- },
- sequenceNumber: 0,
- type: SessionEventType.TurnComplete,
- });
- await emitStoredEvent({
- ...common,
- id: "evt_title_model_request" as SessionEvent["id"],
- payload: {
- messages: [],
- model: "glm/glm-4.6",
- querySource: "session_title",
- toolCount: 0,
- },
- sequenceNumber: 0,
- type: SessionEventType.ModelRequest,
- });
- await emitStoredEvent({
- ...common,
- id: "evt_title_model_status_started" as SessionEvent["id"],
- payload: {
- attempt: 1,
- maxAttempts: 11,
- model: { modelId: "glm-0606", providerId: "zai" },
- querySource: "session_title",
- requestId: "request_title",
- timestamp: "2026-06-03T10:33:41.048Z",
- traceId: "trace_title_generation",
- transport: "http",
- type: "model_request_started",
- },
- sequenceNumber: 0,
- type: SessionEventType.ModelNetworkStatus,
- });
- await emitStoredEvent({
- ...common,
- id: "evt_main_model_retry" as SessionEvent["id"],
- payload: {
- attempt: 2,
- delayMs: 1234,
- maxAttempts: 11,
- message: "Provider returned a server error.",
- model: { modelId: "glm-0606", providerId: "zai" },
- nextAttempt: 3,
- querySource: "main_turn",
- reason: "server_error",
- requestId: "request_main",
- statusCode: 502,
- timestamp: "2026-06-03T10:33:43.048Z",
- traceId: "trace_title_generation",
- transport: "http",
- type: "model_retry_scheduled",
- },
- sequenceNumber: 0,
- type: SessionEventType.ModelNetworkStatus,
- });
- await emitStoredEvent({
- ...common,
- id: "evt_title_model_complete" as SessionEvent["id"],
- payload: {
- content: '{"title":"Done"}',
- querySource: "session_title",
- stopReason: "stop",
- toolCallCount: 0,
- },
- sequenceNumber: 0,
- type: SessionEventType.ModelComplete,
- });
- await emitStoredEvent({
- ...common,
- id: "evt_title_updated" as SessionEvent["id"],
- payload: {
- previousTitle: "Old title",
- source: "generated",
- title: "Done",
- },
- sequenceNumber: 0,
- type: SessionEventType.SessionTitleUpdated,
- });
- const liveEvents = notifications
- .filter((notification) => notification.method === "session/event")
- .map((notification) => zcodeSessionEventSchema.parse(notification.params));
- expect(liveEvents.map((event) => [event.seq, event.type])).toEqual([
- [1, "turn.completed"],
- [2, "session.updated"],
- [3, "session.titleUpdated"],
- ]);
- expect(liveEvents[1]?.payload).toMatchObject({
- _meta: {
- zcode: {
- apiRetry: {
- attempt: 2,
- errorStatus: 502,
- kind: "api_retry",
- maxRetries: 10,
- retryDelayMs: 1234,
- },
- },
- },
- querySource: "main_turn",
- type: "model_retry_scheduled",
- });
- });
- it("publishes core stream recovery retry counts as apiRetry meta", async () => {
- const notifications: Array<{ method: string; params: unknown }> = [];
- let eventStore: SessionEventStore | undefined;
- let liveSink: ((event: SessionEvent) => void | Promise<void>) | undefined;
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- eventStore = options?.eventStore;
- const app = createFakeApp(options);
- return {
- ...app,
- runtime: {
- ...app.runtime,
- subscribeEvents: (sink: {
- onSessionEvent(event: SessionEvent): void | Promise<void>;
- }) => {
- liveSink = sink.onSessionEvent;
- return () => {};
- },
- } as never,
- };
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- setTestNotificationSink(server, (notification) => notifications.push(notification));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSubscribe,
- params: {
- sessionId: created.session.sessionId,
- deliveryKind: "desktop-continuous",
- },
- });
- if (!eventStore || !liveSink) {
- throw new Error("Expected fake app event sink to be wired");
- }
- const storedEvent = await eventStore.append({
- id: "evt_stream_recovery_retry" as SessionEvent["id"],
- payload: {
- attempt: 1,
- maxAttempts: 11,
- model: { modelId: "glm-0606", providerId: "zai" },
- requestId: "request_recovery",
- streamRecovery: {
- attemptId: "stream_attempt_1",
- anchorId: "anchor_1",
- maxRetries: 10,
- recoveredFromRequestId: "request_failed",
- retryNumber: 3,
- },
- timestamp: "2026-06-03T10:33:43.048Z",
- traceId: "trace_stream_recovery",
- transport: "http",
- type: "model_request_started",
- },
- sequenceNumber: 0,
- sessionId: created.session.sessionId as SessionId,
- timestamp: new Date(8),
- traceId: "trace_stream_recovery" as SessionEvent["traceId"],
- turnId: "turn_stream_recovery" as SessionEvent["turnId"],
- type: SessionEventType.ModelNetworkStatus,
- });
- await liveSink(storedEvent);
- const liveEvents = notifications
- .filter((notification) => notification.method === "session/event")
- .map((notification) => zcodeSessionEventSchema.parse(notification.params));
- expect(liveEvents.at(-1)?.payload).toMatchObject({
- _meta: {
- zcode: {
- apiRetry: {
- attempt: 3,
- errorStatus: null,
- kind: "api_retry",
- maxRetries: 10,
- retryDelayMs: 0,
- },
- },
- },
- streamRecovery: {
- recoveredFromRequestId: "request_failed",
- retryNumber: 3,
- },
- type: "model_request_started",
- });
- const progressEvent = await eventStore.append({
- id: "evt_stream_recovery_progress" as SessionEvent["id"],
- payload: {
- attemptId: "stream_attempt_2",
- failedRequestId: "request_recovery",
- maxRetries: 10,
- recoveredFromRequestId: "request_recovery",
- retryNumber: 4,
- streamMode: "sse",
- },
- sequenceNumber: 0,
- sessionId: created.session.sessionId as SessionId,
- timestamp: new Date(9),
- traceId: "trace_stream_recovery" as SessionEvent["traceId"],
- turnId: "turn_stream_recovery" as SessionEvent["turnId"],
- type: SessionEventType.StreamRecoveryRetryStarted,
- });
- await liveSink(progressEvent);
- const progressEvents = notifications
- .filter((notification) => notification.method === "session/event")
- .map((notification) => zcodeSessionEventSchema.parse(notification.params));
- expect(progressEvents.at(-1)).toMatchObject({
- type: "streamRecovery.updated",
- payload: {
- _meta: {
- zcode: {
- apiRetry: {
- attempt: 4,
- errorStatus: null,
- kind: "api_retry",
- maxRetries: 10,
- retryDelayMs: 0,
- },
- },
- },
- recoveredFromRequestId: "request_recovery",
- retryNumber: 4,
- },
- });
- });
- it("returns direct session snapshots for create/read and wrapped subscribe results", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- expect(created.protocol).toEqual({ name: "ZCode Protocol", version: 1 });
- expect(created.session.workspace.workspaceKey).toBe(workspace.workspaceKey);
- const read = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionRead,
- params: { sessionId: created.session.sessionId },
- }),
- );
- expect(read.session.sessionId).toBe(created.session.sessionId);
- const subscribed = zcodeSessionSubscribeResultSchema.parse(
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.sessionSubscribe,
- params: {
- sessionId: created.session.sessionId,
- deliveryKind: "desktop-continuous",
- includeSnapshot: true,
- },
- }),
- );
- expect(subscribed.sessionId).toBe(created.session.sessionId);
- expect(subscribed.snapshot?.session.sessionId).toBe(created.session.sessionId);
- });
- it("session/read contentProfile=index 剥离大载荷,缺省仍返回完整历史", async () => {
- const store = createSqliteSessionStore({ dbPath: ":memory:" });
- const big = "y".repeat(512 * 1024);
- try {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- sessionStore: store,
- version: "test-version",
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- const sessionID = created.session.sessionId as SessionId;
- if (!(await store.getSession(sessionID))) {
- await store.createSession({
- id: sessionID,
- projectID: "project_index_profile" as ProjectId,
- slug: "index-profile",
- directory: workspace.workspacePath,
- path: workspace.workspacePath,
- title: "Index profile",
- version: "test-version",
- time: { created: 1, updated: 1 },
- });
- }
- const userId = "msg_index_user" as MessageId;
- const assistantId = "msg_index_assistant" as MessageId;
- await store.saveMessage({
- id: userId,
- sessionID,
- role: "user",
- agent: "zcode-agent",
- time: { created: 10 },
- modelSelection: { providerId: "glm" as ModelProviderId, modelId: "glm-4.6" as ModelId },
- });
- await store.savePart({
- id: "part_index_user" as never,
- messageID: userId,
- sessionID,
- type: "text",
- text: "查一下订单",
- });
- await store.saveMessage({
- id: assistantId,
- sessionID,
- role: "assistant",
- parentID: userId,
- agent: "zcode-agent",
- time: { created: 20, completed: 30 },
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- mode: "build",
- path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
- cost: 0,
- tokens: { input: 1, output: 1, reasoning: 0, total: 2, cache: { read: 0, write: 0 } },
- } as never);
- await store.savePart({
- id: "part_index_reasoning" as never,
- messageID: assistantId,
- sessionID,
- type: "reasoning",
- text: big,
- time: { start: 21, end: 22 },
- } as never);
- await store.savePart({
- id: "part_index_tool" as never,
- messageID: assistantId,
- sessionID,
- type: "tool",
- callID: "call_index_tool",
- tool: "Bash",
- state: {
- status: "completed",
- input: { command: big },
- output: big,
- title: "Bash",
- metadata: {},
- time: { start: 23, end: 24 },
- },
- } as never);
- await store.savePart({
- id: "part_index_text" as never,
- messageID: assistantId,
- sessionID,
- type: "text",
- text: "订单在 orderService",
- });
- const readWith = async (id: number, extra: Record<string, unknown>) =>
- zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id,
- method: zcodeProtocolMethods.sessionRead,
- params: { sessionId: sessionID, ...extra },
- }),
- );
- const full = await readWith(2, {});
- const index = await readWith(3, { contentProfile: "index" });
- expect(JSON.stringify(full).length).toBeGreaterThan(big.length * 2);
- expect(JSON.stringify(index).length).toBeLessThan(big.length / 4);
- const shape = (snapshot: typeof full) =>
- snapshot.messages.map((message) => ({
- id: message.info.messageId,
- parts: message.parts.map((part) => `${part.partId}:${part.type}`),
- }));
- expect(shape(index)).toEqual(shape(full));
- expect(messageTexts(index.messages)).toEqual(messageTexts(full.messages));
- const indexTool = index.messages
- .flatMap((message) => message.parts)
- .find((part) => part.type === "tool");
- expect(indexTool).toMatchObject({ state: { status: "completed", input: {}, output: "" } });
- // index 读取不能污染后续 full 读取(CLI 侧不得原地改写缓存消息)。
- const fullAgain = await readWith(4, { contentProfile: "full" });
- expect(JSON.stringify(fullAgain.messages)).toBe(JSON.stringify(full.messages));
- } finally {
- store.close();
- }
- });
- it("returns built-in slash commands for workspace and session snapshots", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const presentation = zcodeWorkspacePresentationSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.workspaceReadPresentation,
- params: { workspace },
- }),
- );
- expect(presentation.slashCommands).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- inputHint: "/compact [instructions]",
- name: "compact",
- }),
- expect.objectContaining({
- inputHint: "/goal [pause|resume|clear|replace <objective>|<objective>]",
- name: "goal",
- }),
- ]),
- );
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- const createdCommandNames = created.slashCommands?.map((command) => command.name) ?? [];
- expect(createdCommandNames).toEqual(expect.arrayContaining(["compact", "goal"]));
- expect(createdCommandNames).not.toContain("model");
- });
- it("enables model streaming by default for protocol workspace apps", async () => {
- const createdAppOptions: ZCodeAppOptions[] = [];
- await createWorkspaceZCodeApp(
- {
- deps: {
- createZCodeApp: (options) => {
- createdAppOptions.push(options ?? {});
- return createFakeApp(options);
- },
- },
- notify: () => undefined,
- sessions: new Map(),
- },
- workspace,
- {
- runtimeConfig: {
- workingDirectory: workspace.workspacePath,
- },
- },
- );
- expect(createdAppOptions[0]?.runtimeConfig?.modelStreaming).toBe("on");
- });
- it("passes the opaque workspace identity into protocol app Memory config", async () => {
- const createdAppOptions: ZCodeAppOptions[] = [];
- const remoteWorkspace = {
- workspaceIdentity: "ssh:example:/workspace/app",
- workspaceKey: "ssh:example:/workspace/app",
- workspacePath: "/workspace/app",
- remoteSessionId: "remote-session-1",
- };
- await createWorkspaceZCodeApp(
- {
- deps: {
- createZCodeApp: (options) => {
- createdAppOptions.push(options ?? {});
- return createFakeApp(options);
- },
- },
- notify: () => undefined,
- sessions: new Map(),
- },
- remoteWorkspace,
- {
- runtimeConfig: {
- workingDirectory: remoteWorkspace.workspacePath,
- },
- },
- );
- expect(createdAppOptions[0]?.runtimeConfig?.memory?.workspaceIdentity).toBe(
- remoteWorkspace.workspaceIdentity,
- );
- expect(createdAppOptions[0]?.runtimeConfig?.remoteSessionId).toBe(
- remoteWorkspace.remoteSessionId,
- );
- });
- it("preserves unapplied zcode-plan runtime headers original failure", async () => {
- const createdAppOptions: ZCodeAppOptions[] = [];
- const requestClient = vi.fn(async () => ({
- headersApplied: false,
- errorMessage: "Runtime headers helper timed out after 5000ms.",
- }));
- await createWorkspaceZCodeApp(
- {
- deps: {
- createZCodeApp: (options) => {
- createdAppOptions.push(options ?? {});
- return createFakeApp(options);
- },
- },
- notify: () => undefined,
- requestClient,
- sessions: new Map(),
- },
- workspace,
- {
- runtimeConfig: {
- workingDirectory: workspace.workspacePath,
- },
- },
- );
- const runtimeHeadersPort = createdAppOptions[0]?.providerRuntimeHeadersPort;
- expect(
- runtimeHeadersPort?.shouldRefreshBeforeModelRequest?.({
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
- modelId: "glm-5.1",
- }),
- ).toBe(true);
- expect(
- runtimeHeadersPort?.shouldRefreshBeforeModelRequest?.({
- providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
- modelId: "glm-5.1",
- }),
- ).toBe(true);
- expect(
- runtimeHeadersPort?.shouldRefreshBeforeModelRequest?.({
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- modelId: "glm-5.1",
- }),
- ).toBe(true);
- await expect(
- runtimeHeadersPort?.refreshBeforeModelRequest({
- accountAccess: {
- type: "zhipu-account",
- family: "zai",
- mode: "start-plan",
- },
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
- modelId: "glm-5.1",
- reason: "model-request",
- sessionId: "sess_test" as never,
- traceContext: {} as never,
- }),
- ).rejects.toThrow("Runtime headers helper timed out after 5000ms.");
- expect(requestClient).toHaveBeenCalledWith(
- zcodeProtocolMethods.interactionRequestProviderRuntimeHeaders,
- expect.objectContaining({
- accountAccess: expect.objectContaining({
- mode: "start-plan",
- }),
- }),
- expect.anything(),
- expect.anything(),
- );
- });
- it("does not fail refreshed runtime headers when provider registry revision advances concurrently", async () => {
- const createdAppOptions: ZCodeAppOptions[] = [];
- const requestClient = vi.fn(async () => ({
- headersApplied: true,
- requestAuth: {
- apiKey: "request-key",
- apiKeyId: "real-key-id",
- headers: { "X-Request": "request-header" },
- },
- }));
- await createWorkspaceZCodeApp(
- {
- deps: {
- createZCodeApp: (options) => {
- createdAppOptions.push(options ?? {});
- return createFakeApp(options);
- },
- },
- notify: () => undefined,
- requestClient,
- sessions: new Map(),
- },
- workspace,
- {
- runtimeConfig: {
- workingDirectory: workspace.workspacePath,
- },
- },
- );
- await expect(
- createdAppOptions[0]?.providerRuntimeHeadersPort?.refreshBeforeModelRequest({
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
- modelId: "glm-5.1",
- reason: "model-request",
- sessionId: "sess_test" as never,
- traceContext: {} as never,
- }),
- ).resolves.toMatchObject({
- headersApplied: true,
- requestAuth: {
- apiKey: "request-key",
- apiKeyId: "real-key-id",
- headers: { "X-Request": "request-header" },
- },
- });
- const clock = vi.spyOn(Date, "now").mockReturnValue(1234);
- try {
- const port = createdAppOptions[0]!.providerRuntimeHeadersPort!;
- const input = {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
- modelId: "glm-5.1",
- reason: "model-request" as const,
- sessionId: "sess_test" as never,
- traceContext: {} as never,
- };
- const results = await Promise.all([
- port.refreshBeforeModelRequest(input),
- port.refreshBeforeModelRequest(input),
- ]);
- expect(results.map((result) => result.requestAuth)).toEqual([
- {
- apiKey: "request-key",
- apiKeyId: "real-key-id",
- headers: { "X-Request": "request-header" },
- },
- {
- apiKey: "request-key",
- apiKeyId: "real-key-id",
- headers: { "X-Request": "request-header" },
- },
- ]);
- const requests = (
- requestClient.mock.calls as unknown as Array<
- [string, { requestId: string; reason: string }]
- >
- ).slice(-2);
- expect(requests[0][1].requestId).not.toBe(requests[1][1].requestId);
- expect(requests.map(([, request]) => request.reason)).toEqual([
- "model-request",
- "model-request",
- ]);
- } finally {
- clock.mockRestore();
- }
- });
- it("injects protocol MCP servers into session runtime config", async () => {
- const createdAppOptions: ZCodeAppOptions[] = [];
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- createdAppOptions.push(options);
- return createFakeApp(options);
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: {
- workspace,
- mcpServers: [
- {
- name: "chrome-devtools",
- command: "npx",
- args: ["-y", "chrome-devtools-mcp@latest"],
- env: [],
- timeoutMs: 3,
- },
- {
- name: "linear",
- type: "http",
- url: "https://mcp.example.test",
- headers: [{ name: "X-Test", value: "1" }],
- timeoutMs: 5000,
- },
- {
- name: "events",
- type: "sse",
- url: "https://mcp.example.test/sse",
- headers: [],
- timeoutMs: 8000,
- },
- ],
- },
- });
- expect(createdAppOptions[0]?.runtimeConfig?.mcp).toEqual({
- enabled: true,
- servers: {
- "chrome-devtools": {
- type: "stdio",
- command: "npx",
- args: ["-y", "chrome-devtools-mcp@latest"],
- env: {},
- timeoutMs: 3,
- },
- linear: {
- type: "http",
- url: "https://mcp.example.test",
- headers: { "X-Test": "1" },
- timeoutMs: 5000,
- },
- events: {
- type: "sse",
- url: "https://mcp.example.test/sse",
- headers: {},
- timeoutMs: 8000,
- },
- },
- });
- });
- it("injects protocol tool allow and deny lists into session runtime config", async () => {
- const createdAppOptions: ZCodeAppOptions[] = [];
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- createdAppOptions.push(options);
- return createFakeApp(options);
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: {
- workspace,
- toolAllowlist: ["mcp__zcode_cua__get_app_state"],
- toolDenylist: ["Bash"],
- },
- });
- expect(createdAppOptions[0]?.runtimeConfig?.toolAllowlist).toEqual([
- "mcp__zcode_cua__get_app_state",
- ]);
- expect(createdAppOptions[0]?.runtimeConfig?.toolDisallowlist).toEqual(["Bash"]);
- });
- it("远程 SSH/WSL workspace 默认禁用全部 Cron 工具并保留调用方 denylist", async () => {
- const createdAppOptions: ZCodeAppOptions[] = [];
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- createdAppOptions.push(options);
- return createFakeApp(options);
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- for (const [index, workspaceIdentity] of [
- "remote:ssh:example.test:22:dev:/workspace/app",
- "remote:wsl:Ubuntu-24.04:dev:/workspace/app",
- ].entries()) {
- await requestResult(server, {
- id: index + 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: {
- workspace: {
- ...workspace,
- workspaceIdentity,
- workspaceKey: workspaceIdentity,
- },
- toolDenylist: ["Bash"],
- },
- });
- expect(createdAppOptions[index]?.runtimeConfig?.toolDisallowlist).toEqual([
- "Bash",
- "CronCreate",
- "CronList",
- "CronUpdate",
- "CronDelete",
- ]);
- }
- });
- it("reads materialization preferences once per root runtime and keeps active resumes stable", async () => {
- const createdAppOptions: ZCodeAppOptions[] = [];
- let nativeSearchEnabled = false;
- let memoryEnabled = false;
- let modelContextBudgetStrategy: "legacy" | "preflight-v1" = "legacy";
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- createdAppOptions.push(options);
- return createFakeApp(options);
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const preferenceRequests = attachSessionRuntimePreferencesResponder(server, () => ({
- nativeSearchEnhancementsEnabled: nativeSearchEnabled,
- memoryEnabled,
- modelContextBudgetStrategy,
- }));
- const disabled = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- nativeSearchEnabled = true;
- memoryEnabled = true;
- modelContextBudgetStrategy = "preflight-v1";
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionResume,
- params: { sessionId: disabled.session.sessionId },
- });
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- });
- expect(
- preferenceRequests.map((request) => (request.params as { scope: string }).scope),
- ).toEqual(["runtime-materialization", "runtime-materialization"]);
- expect(createdAppOptions).toHaveLength(2);
- expect(createdAppOptions[0]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(false);
- expect(createdAppOptions[0]?.runtimeConfig?.memory?.enabled).toBe(false);
- expect(createdAppOptions[0]?.runtimeConfig?.modelContextBudgetStrategy).toBe("preflight-v1");
- expect(createdAppOptions[1]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(true);
- expect(createdAppOptions[1]?.runtimeConfig?.modelContextBudgetStrategy).toBe("preflight-v1");
- // 开启 Settings 只解除总开关,不覆盖底层 features.memory/use 配置。
- expect(createdAppOptions[1]?.runtimeConfig?.memory?.enabled).toBeUndefined();
- });
- it("reads the latest materialization preferences for a cold resume", async () => {
- const store = createSqliteSessionStore({ dbPath: ":memory:" });
- const sessionId = "sess_native_search_cold_resume" as SessionId;
- const createdAppOptions: ZCodeAppOptions[] = [];
- try {
- await store.createSession({
- id: sessionId,
- projectID: "project_native_search_cold_resume" as ProjectId,
- slug: "native-search-cold-resume",
- directory: workspace.workspacePath,
- path: workspace.workspacePath,
- title: "Native search cold resume",
- version: "test-version",
- time: { created: 1, updated: 1 },
- });
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- createdAppOptions.push(options);
- return createFakeApp(options);
- },
- cwd: workspace.workspacePath,
- sessionStore: store,
- version: "test-version",
- });
- const preferenceRequests = attachSessionRuntimePreferencesResponder(server, () => ({
- nativeSearchEnhancementsEnabled: false,
- memoryEnabled: false,
- modelContextBudgetStrategy: "preflight-v1",
- }));
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionResume,
- params: { sessionId },
- });
- expect(preferenceRequests).toHaveLength(1);
- expect(createdAppOptions[0]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(false);
- expect(createdAppOptions[0]?.runtimeConfig?.memory?.enabled).toBe(false);
- expect(createdAppOptions[0]?.runtimeConfig?.modelContextBudgetStrategy).toBe("preflight-v1");
- } finally {
- await store.close();
- }
- });
- it.each([undefined, "remote:ssh:example.test:22:dev:/workspace/app"])(
- "injects pull access only into advertised local sessions (%s)",
- async (workspaceIdentity) => {
- const options: ZCodeAppOptions[] = [];
- const reads: unknown[] = [];
- let content = "old";
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (input) => {
- options.push(input);
- return createFakeApp(input);
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- server.setNotificationSink((message) => {
- if (!("id" in message)) return;
- if (message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences) {
- void server.handleMessage({
- id: message.id,
- result: {
- nativeSearchEnhancementsEnabled: true,
- memoryEnabled: false,
- subagentRuntimeConfigEnabled: true,
- },
- });
- }
- if (message.method === zcodeProtocolMethods.subagentsReadRuntimeConfig) {
- reads.push(message.params);
- void server.handleMessage({
- id: message.id,
- result: {
- documents: [{ path: "/agents/reviewer.md", source: "user", content }],
- state: {
- disabledAgentIds: [],
- builtInModelSelectionOverrides: {},
- pluginAgentModelSelectionOverrides: {},
- },
- },
- });
- }
- });
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: {
- workspace: {
- ...workspace,
- ...(workspaceIdentity ? { workspaceIdentity, workspaceKey: workspaceIdentity } : {}),
- },
- },
- });
- expect(reads).toEqual([]);
- const reader = options[0]?.readSubagentRuntimeConfig;
- if (workspaceIdentity) {
- expect(reader).toBeUndefined();
- return;
- }
- expect(reader).toBeTypeOf("function");
- const input = {
- signal: new AbortController().signal,
- traceContext: { traceId: createTraceId(), sessionId: options[0]!.sessionId! },
- };
- expect((await reader!(input)).documents[0]?.content).toBe("old");
- content = "new";
- expect((await reader!(input)).documents[0]?.content).toBe("new");
- expect(reads).toEqual([
- { sessionId: options[0]!.sessionId },
- { sessionId: options[0]!.sessionId },
- ]);
- },
- );
- it("keeps native search on but defaults Memory off when no Host client is attached", async () => {
- const createdAppOptions: ZCodeAppOptions[] = [];
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- createdAppOptions.push(options);
- return createFakeApp(options);
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- });
- expect(createdAppOptions[0]?.readSubagentRuntimeConfig).toBeUndefined();
- expect(createdAppOptions[0]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(true);
- expect(createdAppOptions[0]?.runtimeConfig?.memory?.enabled).toBe(false);
- expect(createdAppOptions[0]?.runtimeConfig?.modelContextBudgetStrategy).toBe("preflight-v1");
- });
- it("defaults Memory off for an old Host but rejects other preference failures", async () => {
- const oldHostOptions: ZCodeAppOptions[] = [];
- const oldHostServer = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- oldHostOptions.push(options);
- return createFakeApp(options);
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- oldHostServer.setNotificationSink((message) => {
- if (
- "id" in message &&
- message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences
- ) {
- void oldHostServer.handleMessage({
- id: message.id,
- error: { code: -32601, message: "Method not found" },
- });
- }
- });
- await requestResult(oldHostServer, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- });
- expect(oldHostOptions[0]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(true);
- expect(oldHostOptions[0]?.runtimeConfig?.memory?.enabled).toBe(false);
- expect(oldHostOptions[0]?.runtimeConfig?.modelContextBudgetStrategy).toBe("preflight-v1");
- for (const response of [
- { error: { code: -32603, message: "setting read failed" } },
- { result: { nativeSearchEnhancementsEnabled: "invalid" } },
- ]) {
- const createdAppOptions: ZCodeAppOptions[] = [];
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- createdAppOptions.push(options);
- return createFakeApp(options);
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- server.setNotificationSink((message) => {
- if (
- "id" in message &&
- message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences
- ) {
- void server.handleMessage({ id: message.id, ...response } as ZCodeProtocolMessage);
- }
- });
- const result = await server.handleMessage({
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- });
- expect(result).toMatchObject({ error: { code: -32603 } });
- expect(createdAppOptions).toHaveLength(0);
- }
- });
- it("times out runtime preference resolution while the Host remains connected", async () => {
- vi.useFakeTimers();
- const createdAppOptions: ZCodeAppOptions[] = [];
- const logs: RecordedLog[] = [];
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- createdAppOptions.push(options);
- return createFakeApp(options);
- },
- cwd: workspace.workspacePath,
- loggerFactory: createProtocolTestLoggerFactory(logs),
- version: "test-version",
- });
- server.setNotificationSink(() => {
- // 保持 Host 连接但故意不响应,覆盖 transport 不断开时的生命周期收口。
- });
- try {
- const resultPromise = server.handleMessage({
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- });
- await vi.advanceTimersByTimeAsync(ZCODE_SESSION_RUNTIME_PREFERENCES_REQUEST_TIMEOUT_MS);
- await expect(resultPromise).resolves.toMatchObject({
- error: {
- code: -32022,
- data: {
- timeoutMs: ZCODE_SESSION_RUNTIME_PREFERENCES_REQUEST_TIMEOUT_MS,
- },
- },
- });
- expect(createdAppOptions).toHaveLength(0);
- expect(logs).toContainEqual(
- expect.objectContaining({
- level: "warn",
- message: "ZCode Protocol runtime preferences request timed out",
- context: expect.objectContaining({
- errorCode: -32022,
- scope: "runtime-materialization",
- sessionId: expect.any(String),
- }),
- }),
- );
- } finally {
- vi.useRealTimers();
- }
- });
- it("defaults Memory off when an older responder omits the preference field", async () => {
- const createdAppOptions: ZCodeAppOptions[] = [];
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- createdAppOptions.push(options);
- return createFakeApp(options);
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- attachSessionRuntimePreferencesResponder(server, () => ({
- nativeSearchEnhancementsEnabled: true,
- }));
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- });
- expect(createdAppOptions[0]?.readSubagentRuntimeConfig).toBeUndefined();
- expect(createdAppOptions[0]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(true);
- expect(createdAppOptions[0]?.runtimeConfig?.memory?.enabled).toBe(false);
- });
- it("settles queued Session creation when the Host disconnects during preference resolution", async () => {
- const createdAppOptions: ZCodeAppOptions[] = [];
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- createdAppOptions.push(options);
- return createFakeApp(options);
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const input = new PassThrough();
- const output = new PassThrough();
- let written = "";
- output.on("data", (chunk: Buffer) => {
- written += chunk.toString("utf8");
- });
- const connection = new ZCodeProtocolNdjsonConnection({
- clearPostResponseMessages: () => server.clearPostResponseMessages(),
- handleMessage: (message) => server.handleMessage(message),
- input,
- onTransportClosed: (error) => server.disconnectClient(error),
- output,
- takePostResponseBatch: (requestId) => server.takePostResponseBatch(requestId),
- });
- server.setNotificationSink((message) => connection.send(message));
- connection.start();
- input.write(
- [
- {
- id: "create-before-close",
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- },
- {
- id: "create-queued",
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- },
- ]
- .map((message) => JSON.stringify(message))
- .join("\n") + "\n",
- );
- await vi.waitFor(() =>
- expect(written).toContain(zcodeProtocolMethods.sessionRequestRuntimePreferences),
- );
- input.end();
- await connection.waitForClose();
- const messages = written
- .trim()
- .split("\n")
- .map((line) => JSON.parse(line) as ZCodeProtocolMessage);
- expect(
- messages.filter(
- (message) =>
- "method" in message &&
- message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences,
- ),
- ).toHaveLength(1);
- expect(messages).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- id: "create-before-close",
- error: expect.objectContaining({ code: -32603 }),
- }),
- expect.objectContaining({
- id: "create-queued",
- error: expect.objectContaining({ code: -32603 }),
- }),
- ]),
- );
- expect(createdAppOptions).toHaveLength(0);
- });
- it("initializes the configured integrated terminal shell before the first prompt", async () => {
- const createdAppOptions: ZCodeAppOptions[] = [];
- const shellInitializations: unknown[] = [];
- const tempRoot = await mkdtemp(join(tmpdir(), "zcode-protocol-shell-"));
- const fakeGitBash = join(tempRoot, "bash.exe");
- await writeFile(fakeGitBash, "");
- await chmod(fakeGitBash, 0o755);
- try {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createShellRecordingFakeApp(options, shellInitializations, createdAppOptions),
- cwd: workspace.workspacePath,
- platform: "win32",
- version: "test-version",
- });
- const preferenceRequests = attachSessionRuntimePreferencesResponder(server, (scope) => ({
- nativeSearchEnhancementsEnabled: true,
- ...(scope === "user-execution"
- ? {
- integratedTerminalShell: {
- mode: "shell" as const,
- dialect: "git-bash" as const,
- id: `git-bash:${fakeGitBash}`,
- label: "Git Bash",
- path: fakeGitBash,
- },
- }
- : {}),
- }));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: {
- workspace,
- },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSend,
- params: {
- sessionId: created.session.sessionId,
- inputId: "input_shell_init",
- content: "first prompt",
- },
- });
- expect(
- preferenceRequests.map((request) => (request.params as { scope: string }).scope),
- ).toEqual(["runtime-materialization", "user-execution"]);
- } finally {
- await rm(tempRoot, { force: true, recursive: true });
- }
- expect(createdAppOptions[0]?.runtimeConfig?.bashShellSelection).toBeUndefined();
- expect(shellInitializations).toEqual([
- {
- display: {
- name: "Git Bash",
- },
- dialect: "git-bash",
- id: `git-bash:${fakeGitBash}`,
- label: "Git Bash",
- path: fakeGitBash,
- source: "user-config",
- },
- ]);
- });
- it("does not initialize an unavailable configured integrated terminal shell as the effective snapshot", async () => {
- const createdAppOptions: ZCodeAppOptions[] = [];
- const shellInitializations: unknown[] = [];
- const unavailablePath = "Z:\\Missing\\Git\\bin\\bash.exe";
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createShellRecordingFakeApp(options, shellInitializations, createdAppOptions),
- cwd: workspace.workspacePath,
- env: { PATH: "" },
- platform: "win32",
- version: "test-version",
- });
- attachSessionRuntimePreferencesResponder(server, (scope) => ({
- nativeSearchEnhancementsEnabled: true,
- ...(scope === "user-execution"
- ? {
- integratedTerminalShell: {
- mode: "shell" as const,
- dialect: "git-bash" as const,
- id: `git-bash:${unavailablePath}`,
- label: "Git Bash",
- path: unavailablePath,
- },
- }
- : {}),
- }));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: {
- workspace,
- },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSend,
- params: {
- sessionId: created.session.sessionId,
- inputId: "input_unavailable_shell",
- content: "first prompt",
- },
- });
- expect(createdAppOptions[0]?.runtimeConfig?.bashShellSelection).toBeUndefined();
- expect(shellInitializations[0]).toMatchObject({
- source: expect.not.stringMatching(/^user-config$/u),
- });
- expect((shellInitializations[0] as { path?: string } | undefined)?.path).not.toBe(
- unavailablePath,
- );
- });
- it("keeps an existing session on its first prompt shell when later sends carry a newer shell setting", async () => {
- const tempRoot = await mkdtemp(join(tmpdir(), "zcode-protocol-shell-static-"));
- const initialGitBash = join(tempRoot, "initial-bash.exe");
- const laterGitBash = join(tempRoot, "later-bash.exe");
- const shellInitializations: unknown[] = [];
- await writeFile(initialGitBash, "");
- await writeFile(laterGitBash, "");
- await chmod(initialGitBash, 0o755);
- await chmod(laterGitBash, 0o755);
- try {
- let selectedShell = initialGitBash;
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createShellRecordingFakeApp(options, shellInitializations),
- cwd: workspace.workspacePath,
- platform: "win32",
- version: "test-version",
- });
- const preferenceRequests = attachSessionRuntimePreferencesResponder(server, (scope) => ({
- nativeSearchEnhancementsEnabled: true,
- ...(scope === "user-execution"
- ? {
- integratedTerminalShell: {
- mode: "shell" as const,
- dialect: "git-bash" as const,
- id: `git-bash:${selectedShell}`,
- label: "Git Bash",
- path: selectedShell,
- },
- }
- : {}),
- }));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: {
- workspace,
- },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSend,
- params: {
- sessionId: created.session.sessionId,
- inputId: "input_shell_init",
- content: "first prompt",
- },
- });
- selectedShell = laterGitBash;
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.sessionResume,
- params: {
- sessionId: created.session.sessionId,
- workspace,
- },
- });
- await requestResult(server, {
- id: 4,
- method: zcodeProtocolMethods.sessionSend,
- params: {
- sessionId: created.session.sessionId,
- inputId: "input_after_shell_change",
- content: "continue",
- },
- });
- expect(
- preferenceRequests.map((request) => (request.params as { scope: string }).scope),
- ).toEqual(["runtime-materialization", "user-execution"]);
- } finally {
- await rm(tempRoot, { force: true, recursive: true });
- }
- expect(shellInitializations).toEqual([
- {
- display: {
- name: "Git Bash",
- },
- dialect: "git-bash",
- id: `git-bash:${initialGitBash}`,
- label: "Git Bash",
- path: initialGitBash,
- source: "user-config",
- },
- ]);
- });
- it("initializes a deferred draft shell before accepting its first prompt", async () => {
- const tempRoot = await mkdtemp(join(tmpdir(), "zcode-protocol-shell-deferred-"));
- const laterGitBash = join(tempRoot, "later-bash.exe");
- const createdAppOptions: ZCodeAppOptions[] = [];
- const shellInitializations: unknown[] = [];
- await writeFile(laterGitBash, "");
- await chmod(laterGitBash, 0o755);
- try {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createShellRecordingFakeApp(options, shellInitializations, createdAppOptions),
- cwd: workspace.workspacePath,
- platform: "win32",
- version: "test-version",
- });
- attachSessionRuntimePreferencesResponder(server, (scope) => ({
- nativeSearchEnhancementsEnabled: true,
- ...(scope === "user-execution"
- ? {
- integratedTerminalShell: {
- mode: "shell" as const,
- dialect: "git-bash" as const,
- id: `git-bash:${laterGitBash}`,
- label: "Git Bash",
- path: laterGitBash,
- },
- }
- : {}),
- }));
- const draft = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: {
- workspace,
- persistence: "deferred",
- },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSend,
- params: {
- sessionId: draft.session.sessionId,
- inputId: "input_deferred_shell_change",
- content: "first prompt",
- },
- });
- } finally {
- await rm(tempRoot, { force: true, recursive: true });
- }
- expect(createdAppOptions[0]?.runtimeConfig?.bashShellSelection).toBeUndefined();
- expect(shellInitializations).toEqual([
- {
- display: { name: "Git Bash" },
- dialect: "git-bash",
- id: `git-bash:${laterGitBash}`,
- label: "Git Bash",
- path: laterGitBash,
- source: "user-config",
- },
- ]);
- });
- it("rejects integrated terminal shell params on create, resume, and send", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- platform: "win32",
- version: "test-version",
- });
- const integratedTerminalShell = {
- mode: "shell",
- dialect: "git-bash",
- id: "git-bash:/tmp/bash.exe",
- label: "Git Bash",
- path: "/tmp/bash.exe",
- };
- await expect(
- server.handleMessage({
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: {
- workspace,
- integratedTerminalShell,
- } as never,
- }),
- ).resolves.toMatchObject({
- error: {
- code: -32602,
- },
- });
- await expect(
- server.handleMessage({
- id: 2,
- method: zcodeProtocolMethods.sessionResume,
- params: {
- sessionId: "sess_shell_resume_schema",
- workspace,
- integratedTerminalShell,
- } as never,
- }),
- ).resolves.toMatchObject({
- error: {
- code: -32602,
- },
- });
- await expect(
- server.handleMessage({
- id: 3,
- method: zcodeProtocolMethods.sessionSend,
- params: {
- sessionId: "sess_shell_send_schema",
- content: "hello",
- integratedTerminalShell,
- } as never,
- }),
- ).resolves.toMatchObject({
- error: {
- code: -32602,
- },
- });
- });
- it("keeps deferred draft sessions out of session/list until the first send", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- });
- const draft = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace, persistence: "deferred" },
- }),
- );
- const hiddenList = zcodeSessionListResultSchema.parse(
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionList,
- params: { workspace },
- }),
- );
- expect(hiddenList.sessions.map((session) => session.sessionId)).not.toContain(
- draft.session.sessionId,
- );
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.sessionSend,
- params: { sessionId: draft.session.sessionId, content: "hello" },
- });
- const visibleList = zcodeSessionListResultSchema.parse(
- await requestResult(server, {
- id: 4,
- method: zcodeProtocolMethods.sessionList,
- params: { workspace },
- }),
- );
- expect(visibleList.sessions.map((session) => session.sessionId)).toContain(
- draft.session.sessionId,
- );
- });
- it("keeps server-owned model state and emits state update notifications", async () => {
- const notifications: ZCodeProtocolNotification[] = [];
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- });
- setTestNotificationSink(server, (notification) => notifications.push(notification));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- const updated = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSetModel,
- params: {
- sessionId: created.session.sessionId,
- model: { providerId: "glm", modelId: "glm-4-air" },
- expectedRevision: created.runtime.stateRevision,
- },
- }),
- );
- expect(updated.settings.model.current).toEqual({ providerId: "glm", modelId: "glm-4-air" });
- expect(updated.runtime.stateRevision).toBe(created.runtime.stateRevision + 1);
- expect(notifications).toMatchObject([
- {
- method: "state.updated",
- params: {
- type: "state.updated",
- scope: "session",
- sessionId: created.session.sessionId,
- reason: "model_changed",
- },
- },
- ]);
- });
- it("maps a protocol session model to structured Runtime Selection", async () => {
- const createdAppOptions: ZCodeAppOptions[] = [];
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- createdAppOptions.push(options);
- return createFakeApp(options);
- },
- cwd: workspace.workspacePath,
- });
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: {
- workspace,
- model: {
- providerId: "glm",
- modelId: "glm-4-air",
- options: { reasoningLevel: "deep" },
- },
- },
- });
- expect(createdAppOptions[0]?.runtimeConfig?.modelSelection).toEqual({
- providerId: "glm",
- modelId: "glm-4-air",
- options: { reasoningLevel: "deep" },
- });
- });
- it("resumes persisted sessions with the latest historical model and mode", async () => {
- const store = createSqliteSessionStore({ dbPath: ":memory:" });
- const sessionId = "sess_history" as SessionId;
- const userMessageId = "msg_user_history" as MessageId;
- const assistantMessageId = "msg_assistant_history" as MessageId;
- try {
- await store.createSession({
- id: sessionId,
- projectID: "project_history" as ProjectId,
- slug: "history-session",
- directory: workspace.workspacePath,
- path: workspace.workspacePath,
- title: "History session",
- version: "test-version",
- time: { created: 1, updated: 4 },
- });
- await store.saveMessage({
- id: userMessageId,
- sessionID: sessionId,
- role: "user",
- time: { created: 2 },
- agent: "zcode-agent",
- modelSelection: {
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4-air" as ModelId,
- },
- tools: {},
- });
- await store.saveMessage({
- id: assistantMessageId,
- sessionID: sessionId,
- role: "assistant",
- time: { created: 3, completed: 4 },
- parentID: userMessageId,
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4-air" as ModelId,
- mode: "plan",
- agent: "zcode-agent",
- path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
- cost: 0,
- tokens: { input: 12345, output: 67, reasoning: 0, cache: { read: 2345, write: 678 } },
- });
- const appOptions: ZCodeAppOptions[] = [];
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- appOptions.push(options ?? {});
- return createFakeApp(options);
- },
- cwd: workspace.workspacePath,
- sessionStore: store,
- });
- const resumed = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionResume,
- params: { sessionId, workspace },
- }),
- );
- expect(appOptions[0]?.runtimeConfig).toMatchObject({ mode: "plan" });
- // 当前结构只能来自 Session 当前选择 entry;Protocol 不再把历史消息伪装成当前选择。
- expect(appOptions[0]?.runtimeConfig?.modelSelection).toBeUndefined();
- // Process Registry 在协议入口启动时已经就绪,冷恢复不再创建旧 deferred adapter。
- expect(appOptions[0]?.modelAdapter).toBeUndefined();
- expect(resumed.settings).toMatchObject({
- mode: { current: "plan" },
- model: { current: { providerId: "glm", modelId: "glm-4.6" } },
- });
- expect(resumed.projection.lastError).toBeUndefined();
- expect(resumed.runtime.contextUsage).toEqual({
- used: 12412,
- size: 128000,
- cost: null,
- cache: {
- inputTokens: 12345,
- cacheReadTokens: 2345,
- cacheWriteTokens: 678,
- latestHitRate: 2345 / 12345,
- hitRate: 2345 / 12345,
- hitRateRequestCount: 1,
- totalInputTokens: 12345,
- totalCacheReadTokens: 2345,
- totalCacheWriteTokens: 678,
- },
- });
- expect(resumed.messages.map((message) => message.info.model)).toEqual([
- { providerId: "glm", modelId: "glm-4-air" },
- { providerId: "glm", modelId: "glm-4-air" },
- ]);
- const sendResult = await server.handleMessage({
- id: 2,
- method: zcodeProtocolMethods.sessionSend,
- params: { sessionId, content: "continue" },
- });
- expect(sendResult).toMatchObject({ id: 2, result: expect.any(Object) });
- } finally {
- store.close();
- }
- });
- it("resume 回填持久化 taskType:workflow_child 绝不落回缺省 interactive", async () => {
- // Bug 根因(2026-08-24 实测):resume 物化 record 时丢掉了持久化的 taskType(fork 路径
- // 一直带着,resume 路径没带),createRecord 落回缺省 "interactive"。于是被 resume 的
- // dwf actor 会话通过 isTaskListSessionType 的筛,经 getSessionWorkspaceId 漏进
- // sessions-index,desktop 任务列表里长出 25 条「workflow actor actor#N@k」假任务。
- const store = createSqliteSessionStore({ dbPath: ":memory:" });
- const sessionId = "sess_dwf_actor_tasktype" as SessionId;
- try {
- await store.createSession({
- id: sessionId,
- projectID: "project_tasktype" as ProjectId,
- slug: "dwf-actor-tasktype",
- directory: workspace.workspacePath,
- path: workspace.workspacePath,
- title: "workflow actor actor#1@1",
- version: "test-version",
- taskType: "workflow_child",
- time: { created: 1, updated: 2 },
- });
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- sessionStore: store,
- });
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionResume,
- params: { sessionId, workspace },
- });
- const record = (
- server as unknown as { context: ZCodeProtocolAgentServerContext }
- ).context.sessions.get(sessionId);
- expect(record?.taskType).toBe("workflow_child");
- } finally {
- store.close();
- }
- });
- it("workspace presentation omits model facts", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- });
- const presentation = zcodeWorkspacePresentationSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.workspaceReadPresentation,
- params: { workspace },
- }),
- );
- expect(presentation.mode).toBe("build");
- expect("model" in presentation).toBe(false);
- expect("settings" in presentation).toBe(false);
- });
- it("通过独立协议同步 Account Config,不再从 Workspace Snapshot 反向投影", async () => {
- const syncAccountProviderConfig = vi.fn(async () => true);
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: () => createFakeApp(),
- cwd: workspace.workspacePath,
- syncAccountProviderConfig,
- });
- const result = await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.providerUpdateAccountConfig,
- params: {
- revision: "account-1",
- basedOnZCodeBuiltinRevision: "zcode-builtin:1",
- states: {
- "account:zai-individual-coding-plan": {
- availability: "available",
- entitled: true,
- current: false,
- },
- },
- providers: {
- "account:zai-individual-coding-plan": {
- access: { type: "zhipu-account", entitled: true },
- builtinModelIds: ["GLM-5.2"],
- },
- },
- },
- });
- expect(result).toEqual({
- receivedRevision: "account-1",
- providerCount: 1,
- status: "received",
- });
- expect(syncAccountProviderConfig).toHaveBeenCalledTimes(1);
- const snapshot = syncAccountProviderConfig.mock.calls[0]?.[0];
- expect(snapshot?.revision).toBe("account-1");
- expect(snapshot?.basedOnZCodeBuiltinRevision).toBe("zcode-builtin:1");
- expect(snapshot?.states?.["account:zai-individual-coding-plan"].current).toBe(false);
- expect(snapshot?.providers.toJSON()).toEqual({
- "account:zai-individual-coding-plan": {
- access: { type: "zhipu-account", entitled: true },
- builtinModelIds: ["GLM-5.2"],
- },
- });
- });
- it("workspace presentation rejects legacy runtimeModel", async () => {
- const firstProviderRuntimeModel = {
- generatedAt: 2,
- model: {
- modelId: "first-model",
- providerId: "provider-first",
- },
- provider: {
- baseURL: "https://first.example.com/v1",
- kind: "openai-compatible" as const,
- models: [
- {
- label: "First Model",
- modelId: "first-model",
- reasoning: {
- defaultLevel: "max",
- enabled: true,
- levels: [
- { label: "High", value: "high" },
- { label: "Max", value: "max" },
- ],
- },
- },
- ],
- providerId: "provider-first",
- },
- revision: "model-runtime:first-provider-default",
- thoughtLevel: "max",
- };
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- });
- const rejected = await server.handleMessage({
- id: 2,
- method: zcodeProtocolMethods.workspaceReadPresentation,
- params: {
- runtimeModel: firstProviderRuntimeModel,
- workspace,
- },
- });
- expect(rejected).toMatchObject({
- error: { code: -32602 },
- id: 2,
- });
- });
- it("uses app-provided thought level when creating a session", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: {
- workspace,
- model: { providerId: "glm", modelId: "glm-4-air" },
- thoughtLevel: "deep",
- },
- }),
- );
- expect(created.settings).toMatchObject({
- model: { current: { providerId: "glm", modelId: "glm-4-air" } },
- thoughtLevel: { current: "deep" },
- });
- });
- it("acks session/send before the prompt turn finishes", async () => {
- let resolveSendInput!: () => void;
- let sendInputSettled = false;
- let receivedInputId: string | undefined;
- let receivedBrowserAmbientContext: unknown;
- let receivedOffPeakTaskId: string | undefined;
- let receivedOffPeakRunType: string | undefined;
- const sendInputCompletion = new Promise<void>((resolve) => {
- resolveSendInput = resolve;
- });
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createFakeApp(options, {
- sendInput: async (_input, options) => {
- receivedInputId = options?.inputId;
- receivedBrowserAmbientContext = options?.browserAmbientContext;
- receivedOffPeakTaskId = options?.offPeakTaskId;
- receivedOffPeakRunType = options?.offPeakRunType;
- await sendInputCompletion;
- sendInputSettled = true;
- return { kind: "rejected", reason: "no_active_turn" };
- },
- }),
- cwd: workspace.workspacePath,
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- const sendResponse = server.handleMessage({
- id: 2,
- method: zcodeProtocolMethods.sessionSend,
- params: {
- sessionId: created.session.sessionId,
- content: "hello",
- inputId: "t-sess_test-run",
- offPeakTaskId: "off-peak-task-1",
- offPeakRunType: "resume",
- browserAmbientContext: {
- tabCount: 1,
- currentUrl: "https://example.com/current",
- },
- expectedRevision: created.runtime.stateRevision,
- },
- });
- const raceResult = await Promise.race([
- sendResponse.then((response) => ({ response, status: "resolved" as const })),
- new Promise<{ status: "timeout" }>((resolve) =>
- setTimeout(() => resolve({ status: "timeout" }), 20),
- ),
- ]);
- expect(raceResult.status).toBe("resolved");
- expect(receivedInputId).toBe("t-sess_test-run");
- expect(receivedBrowserAmbientContext).toEqual({
- tabCount: 1,
- currentUrl: "https://example.com/current",
- });
- expect(receivedOffPeakTaskId).toBe("off-peak-task-1");
- expect(receivedOffPeakRunType).toBe("resume");
- expect(sendInputSettled).toBe(false);
- resolveSendInput();
- await sendInputCompletion;
- });
- it("emits prompt_completed after the active prompt lock is released", async () => {
- let sessionId = "";
- let secondSendDuringCompleted: Promise<unknown> | undefined;
- let finalizationCountDuringCompleted: number | undefined;
- let activeLockDuringCompleted: AbortController | undefined;
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createFakeApp(options, {
- sendInput: async () => ({
- kind: "started_turn",
- turnId: "completed-fixture" as never,
- completion: Promise.resolve({} as never),
- }),
- }),
- cwd: workspace.workspacePath,
- });
- setTestNotificationSink(server, (notification) => {
- if (
- notification.method === "state.updated" &&
- (notification.params as { reason?: string }).reason === "prompt_completed" &&
- !secondSendDuringCompleted
- ) {
- const record = (
- server as unknown as { context: ZCodeProtocolAgentServerContext }
- ).context.sessions.get(sessionId);
- finalizationCountDuringCompleted = record?.residencyFinalizationCount;
- activeLockDuringCompleted = record?.activeAbortController;
- secondSendDuringCompleted = server.handleMessage({
- id: 3,
- method: zcodeProtocolMethods.sessionSend,
- params: {
- sessionId,
- content: "second",
- inputId: "input_second",
- },
- });
- }
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- sessionId = created.session.sessionId;
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSend,
- params: {
- sessionId,
- content: "first",
- inputId: "input_first",
- expectedRevision: created.runtime.stateRevision,
- },
- });
- await vi.waitFor(() => {
- expect(secondSendDuringCompleted).toBeDefined();
- });
- const secondResponse = await secondSendDuringCompleted;
- expect(secondResponse).toMatchObject({
- result: {
- accepted: true,
- sessionId,
- },
- });
- expect(activeLockDuringCompleted).toBeUndefined();
- expect(finalizationCountDuringCompleted).toBe(1);
- await vi.waitFor(() => {
- const record = (
- server as unknown as { context: ZCodeProtocolAgentServerContext }
- ).context.sessions.get(sessionId);
- expect(record?.residencyFinalizationCount).toBe(0);
- });
- });
- it("maps protocol localPath attachments before sending input to core", async () => {
- let receivedInput: unknown;
- let resolveReceived!: () => void;
- const received = new Promise<void>((resolve) => {
- resolveReceived = resolve;
- });
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createFakeApp(options, {
- sendInput: async (input) => {
- receivedInput = input;
- resolveReceived();
- return { kind: "rejected", reason: "no_active_turn" };
- },
- }),
- cwd: workspace.workspacePath,
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSend,
- params: {
- sessionId: created.session.sessionId,
- content: "inspect attachments",
- expectedRevision: created.runtime.stateRevision,
- attachments: [
- {
- kind: "file",
- filename: "report.pdf",
- mimeType: "application/pdf",
- sizeBytes: 0,
- localPath: "/tmp/report.pdf",
- },
- {
- kind: "file",
- filename: "pasted-text.txt",
- mimeType: "text/plain",
- sizeBytes: 8192,
- localPath: "/tmp/.zcode/tmp/paste-attachments/2026-06-30/pasted-text.txt",
- sourceKind: "clipboard-text",
- },
- {
- kind: "image",
- filename: "diagram.png",
- mimeType: "image/png",
- localPath: "/tmp/diagram.png",
- },
- ],
- },
- });
- await received;
- expect(receivedInput).toMatchObject({
- text: "inspect attachments",
- attachments: [
- { path: "/tmp/report.pdf", type: "pdf" },
- {
- path: "/tmp/.zcode/tmp/paste-attachments/2026-06-30/pasted-text.txt",
- sourceKind: "clipboard-text",
- type: "file",
- },
- { path: "/tmp/diagram.png", type: "image" },
- ],
- });
- });
- it("bridges protocol permission requests through server-to-client JSON-RPC", async () => {
- const outgoing: ZCodeProtocolMessage[] = [];
- const origin = {
- kind: "subagent",
- agentId: "agent_perm",
- agentType: "general",
- childSessionId: "sess_child_perm",
- childTurnId: "turn_child_perm",
- parentSessionId: "sess_parent_perm",
- parentToolCallId: "tool_parent_agent",
- parentTurnId: "turn_parent_perm",
- } as const;
- let brokerResult:
- | Awaited<ReturnType<NonNullable<ZCodeAppOptions["permissionBroker"]>["requestPermission"]>>
- | undefined;
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createFakeApp(options, {
- sendInput: async () => {
- brokerResult = await options?.permissionBroker?.requestPermission({
- input: { command: "rm -rf tmp" },
- mode: "build",
- origin,
- reason: "Bash requires approval",
- requestId: "perm_1",
- requestedAt: new Date(1),
- riskLevel: "high",
- ruleId: "rule_1",
- sessionId: (options?.sessionId ?? "sess_test") as never,
- toolCallId: "tool_1" as never,
- toolName: "Bash",
- traceId: "trace_test" as never,
- });
- return { kind: "rejected", reason: "no_active_turn" };
- },
- }),
- cwd: workspace.workspacePath,
- });
- setTestNotificationSink(server, (message) => outgoing.push(message));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSend,
- params: { sessionId: created.session.sessionId, content: "run command" },
- });
- await vi.waitFor(() => {
- expect(outgoing.some((message) => message.method === "interaction/requestPermission")).toBe(
- true,
- );
- });
- const permissionRequest = outgoing.find(
- (message) => message.method === "interaction/requestPermission" && "id" in message,
- );
- expect(permissionRequest).toMatchObject({
- method: "interaction/requestPermission",
- params: {
- options: [
- {
- optionId: "allow_once",
- response: { decision: "allow" },
- },
- {
- optionId: "allow_project",
- response: {
- decision: "allow",
- permissionUpdates: [
- {
- behavior: "allow",
- rules: [{ ruleContent: "rm -rf tmp", toolName: "Bash" }],
- type: "addRules",
- },
- ],
- },
- },
- {
- optionId: "deny",
- response: { decision: "deny" },
- },
- ],
- origin,
- requestId: "perm_1",
- toolName: "Bash",
- },
- });
- await server.handleMessage({ id: permissionRequest?.id ?? "", result: { decision: "allow" } });
- await vi.waitFor(() => {
- expect(brokerResult).toMatchObject({ decision: "allow" });
- });
- });
- it("reannounces pending protocol permission requests so a later client request can be answered", async () => {
- vi.useFakeTimers();
- try {
- const outgoing: ZCodeProtocolMessage[] = [];
- let brokerResultPromise:
- | ReturnType<NonNullable<ZCodeAppOptions["permissionBroker"]>["requestPermission"]>
- | undefined;
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createFakeApp(options, {
- sendInput: async () => {
- brokerResultPromise = options?.permissionBroker?.requestPermission({
- input: { command: "rm -rf tmp" },
- mode: "build",
- reason: "Bash requires approval",
- requestId: "perm_reannounce",
- requestedAt: new Date(1),
- riskLevel: "high",
- ruleId: "rule_1",
- sessionId: (options?.sessionId ?? "sess_test") as never,
- toolCallId: "tool_1" as never,
- toolName: "Bash",
- traceId: "trace_test" as never,
- });
- await brokerResultPromise;
- return { kind: "rejected", reason: "no_active_turn" };
- },
- }),
- cwd: workspace.workspacePath,
- });
- setTestNotificationSink(server, (message) => outgoing.push(message));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSend,
- params: { sessionId: created.session.sessionId, content: "run command" },
- });
- await vi.waitFor(() => {
- expect(brokerResultPromise).toBeDefined();
- });
- const firstRequest = outgoing.find(
- (message) => message.method === "interaction/requestPermission" && "id" in message,
- );
- expect(firstRequest).toMatchObject({
- method: "interaction/requestPermission",
- params: {
- requestId: "perm_reannounce",
- toolName: "Bash",
- },
- });
- await vi.advanceTimersByTimeAsync(1_000);
- const permissionRequests = outgoing.filter(
- (message) => message.method === "interaction/requestPermission" && "id" in message,
- );
- expect(permissionRequests).toHaveLength(2);
- expect(permissionRequests[1]).toMatchObject({
- method: "interaction/requestPermission",
- params: {
- requestId: "perm_reannounce",
- toolName: "Bash",
- },
- });
- const firstProtocolRequestId =
- firstRequest && "id" in firstRequest ? firstRequest.id : undefined;
- expect(permissionRequests[1]?.id).not.toBe(firstProtocolRequestId);
- await server.handleMessage({
- id: permissionRequests[1]?.id ?? "",
- result: { decision: "allow" },
- });
- await expect(brokerResultPromise).resolves.toMatchObject({
- decision: "allow",
- });
- } finally {
- vi.useRealTimers();
- }
- });
- it("bridges AskUserQuestion through protocol user input requests", async () => {
- const outgoing: ZCodeProtocolMessage[] = [];
- const origin = {
- kind: "subagent",
- agentId: "agent_ask",
- agentType: "general",
- childSessionId: "sess_child_ask",
- childTurnId: "turn_child_ask",
- parentSessionId: "sess_parent_ask",
- parentToolCallId: "tool_parent_agent",
- parentTurnId: "turn_parent_ask",
- } as const;
- let brokerResult:
- | Awaited<ReturnType<NonNullable<ZCodeAppOptions["permissionBroker"]>["requestPermission"]>>
- | undefined;
- const askInput = {
- questions: [
- {
- question: "Which branch should I test?",
- header: "Branch",
- options: [
- { label: "main", description: "Use main branch" },
- { label: "release", description: "Use release branch" },
- ],
- },
- ],
- };
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createFakeApp(options, {
- sendInput: async () => {
- brokerResult = await options?.permissionBroker?.requestPermission({
- input: askInput,
- mode: "build",
- origin,
- reason: "AskUserQuestion pauses execution to collect answers from the user",
- requestId: "ask_1",
- requestedAt: new Date(1),
- riskLevel: "low",
- ruleId: "rule_ask",
- sessionId: (options?.sessionId ?? "sess_test") as never,
- toolCallId: "tool_ask" as never,
- toolName: "AskUserQuestion",
- traceId: "trace_test" as never,
- });
- return { kind: "rejected", reason: "no_active_turn" };
- },
- }),
- cwd: workspace.workspacePath,
- });
- setTestNotificationSink(server, (message) => outgoing.push(message));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSend,
- params: { sessionId: created.session.sessionId, content: "ask" },
- });
- await vi.waitFor(() => {
- expect(outgoing.some((message) => message.method === "interaction/requestUserInput")).toBe(
- true,
- );
- });
- const userInputRequest = outgoing.find(
- (message) => message.method === "interaction/requestUserInput" && "id" in message,
- );
- expect(userInputRequest).toMatchObject({
- method: "interaction/requestUserInput",
- params: {
- origin,
- requestId: "ask_1",
- questions: [{ question: "Which branch should I test?" }],
- },
- });
- await server.handleMessage({
- id: userInputRequest?.id ?? "",
- result: {
- action: "accept",
- content: {
- answers: { "Which branch should I test?": "release" },
- answer_0: "release",
- answer: "release",
- },
- },
- });
- await vi.waitFor(() => {
- expect(brokerResult).toMatchObject({
- decision: "modify",
- modifiedInput: {
- answers: { "Which branch should I test?": "release" },
- questions: askInput.questions,
- },
- });
- });
- expect(
- (brokerResult as { modifiedInput?: Record<string, unknown> }).modifiedInput,
- ).not.toHaveProperty("answer_0");
- expect(
- (brokerResult as { modifiedInput?: Record<string, unknown> }).modifiedInput,
- ).not.toHaveProperty("answer");
- });
- it("bridges ExitPlanMode approval through protocol user input requests", async () => {
- const outgoing: ZCodeProtocolMessage[] = [];
- const origin = {
- kind: "subagent",
- agentId: "agent_exit_plan",
- agentType: "general",
- childSessionId: "sess_child_exit_plan",
- childTurnId: "turn_child_exit_plan",
- parentSessionId: "sess_parent_exit_plan",
- parentToolCallId: "tool_parent_agent",
- parentTurnId: "turn_parent_exit_plan",
- } as const;
- let brokerResult:
- | Awaited<ReturnType<NonNullable<ZCodeAppOptions["permissionBroker"]>["requestPermission"]>>
- | undefined;
- const exitPlanInput = {
- plan: "1. Change the runtime\n2. Add tests",
- };
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createFakeApp(options, {
- sendInput: async () => {
- brokerResult = await options?.permissionBroker?.requestPermission({
- input: exitPlanInput,
- mode: "plan",
- origin,
- reason: "ExitPlanMode requires user approval before implementation",
- requestId: "exit_plan_1",
- requestedAt: new Date(1),
- riskLevel: "high",
- ruleId: "rule_exit_plan",
- sessionId: (options?.sessionId ?? "sess_test") as never,
- toolCallId: "tool_exit_plan" as never,
- toolName: "ExitPlanMode",
- traceId: "trace_test" as never,
- });
- return { kind: "rejected", reason: "no_active_turn" };
- },
- }),
- cwd: workspace.workspacePath,
- });
- setTestNotificationSink(server, (message) => outgoing.push(message));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSend,
- params: { sessionId: created.session.sessionId, content: "plan" },
- });
- await vi.waitFor(() => {
- expect(outgoing.some((message) => message.method === "interaction/requestUserInput")).toBe(
- true,
- );
- });
- expect(outgoing.some((message) => message.method === "interaction/requestPermission")).toBe(
- false,
- );
- const userInputRequest = outgoing.find(
- (message) => message.method === "interaction/requestUserInput" && "id" in message,
- );
- expect(userInputRequest).toMatchObject({
- method: "interaction/requestUserInput",
- params: {
- origin,
- requestId: "exit_plan_1",
- schema: { interaction: "plan_approval", toolName: "ExitPlanMode" },
- questions: [
- {
- header: "Plan",
- options: [{ value: "approve", label: "Approve" }],
- },
- ],
- },
- });
- await server.handleMessage({
- id: userInputRequest?.id ?? "",
- result: {
- action: "accept",
- content: {
- answer_0: "Please add tests before implementation.",
- answer: "Please add tests before implementation.",
- },
- },
- });
- await vi.waitFor(() => {
- expect(brokerResult).toMatchObject({
- decision: "deny",
- reason: "Please add tests before implementation.",
- reasonSource: "plan_approval_feedback",
- });
- });
- });
- it("reannounces pending ExitPlanMode approval so a later client request can be answered", async () => {
- vi.useFakeTimers();
- try {
- const outgoing: ZCodeProtocolMessage[] = [];
- let brokerResultPromise:
- | ReturnType<NonNullable<ZCodeAppOptions["permissionBroker"]>["requestPermission"]>
- | undefined;
- const exitPlanInput = {
- plan: "1. Change the runtime\n2. Add tests",
- };
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createFakeApp(options, {
- sendInput: async () => {
- brokerResultPromise = options?.permissionBroker?.requestPermission({
- input: exitPlanInput,
- mode: "plan",
- reason: "ExitPlanMode requires user approval before implementation",
- requestId: "exit_plan_reannounce",
- requestedAt: new Date(1),
- riskLevel: "high",
- ruleId: "rule_exit_plan",
- sessionId: (options?.sessionId ?? "sess_test") as never,
- toolCallId: "tool_exit_plan" as never,
- toolName: "ExitPlanMode",
- traceId: "trace_test" as never,
- });
- await brokerResultPromise;
- return { kind: "rejected", reason: "no_active_turn" };
- },
- }),
- cwd: workspace.workspacePath,
- });
- setTestNotificationSink(server, (message) => outgoing.push(message));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSend,
- params: { sessionId: created.session.sessionId, content: "plan" },
- });
- await vi.waitFor(() => {
- expect(brokerResultPromise).toBeDefined();
- });
- const firstRequest = outgoing.find(
- (message) => message.method === "interaction/requestUserInput" && "id" in message,
- );
- expect(firstRequest).toMatchObject({
- method: "interaction/requestUserInput",
- params: {
- requestId: "exit_plan_reannounce",
- schema: { interaction: "plan_approval", toolName: "ExitPlanMode" },
- },
- });
- await vi.advanceTimersByTimeAsync(1_000);
- const userInputRequests = outgoing.filter(
- (message) => message.method === "interaction/requestUserInput" && "id" in message,
- );
- expect(userInputRequests).toHaveLength(2);
- expect(userInputRequests[1]).toMatchObject({
- method: "interaction/requestUserInput",
- params: {
- requestId: "exit_plan_reannounce",
- schema: { interaction: "plan_approval", toolName: "ExitPlanMode" },
- },
- });
- const firstProtocolRequestId =
- firstRequest && "id" in firstRequest ? firstRequest.id : undefined;
- expect(userInputRequests[1]?.id).not.toBe(firstProtocolRequestId);
- await server.handleMessage({
- id: userInputRequests[1]?.id ?? "",
- result: {
- action: "accept",
- content: {
- answer_0: "approve",
- answer: "approve",
- },
- },
- });
- await expect(brokerResultPromise).resolves.toMatchObject({
- decision: "allow",
- });
- } finally {
- vi.useRealTimers();
- }
- });
- // M5 ③-4:session/rewind、session/rewindCascade 旧协议词已删除(v4 fork/edit/retry
- // 经原生 handler 直发 `/rewind conversation <messageId>` slash command,见
- // zcode-protocol-v4/commands/handlers/fork-edit-retry.ts);本用例收敛为 compact 单验证。
- it("runs compact through the explicit session protocol method", async () => {
- const submittedPrompts: string[] = [];
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createFakeApp(options, {
- submitPrompt: async (prompt) => {
- submittedPrompts.push(typeof prompt === "string" ? prompt : prompt.text);
- return { response: `ok:${submittedPrompts.at(-1)}` } as never;
- },
- }),
- cwd: workspace.workspacePath,
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- const compacted = zcodeSessionCompactResultSchema.parse(
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionCompact,
- params: {
- sessionId: created.session.sessionId,
- instructions: "keep recent files",
- },
- }),
- );
- expect(submittedPrompts).toEqual(["/compact keep recent files"]);
- expect(compacted.response).toBe("");
- expect(compacted.compact?.state).toBe("accepted");
- });
- it("aborts in-flight compact requests when the session is stopped", async () => {
- let resolveCompactStarted!: () => void;
- let resolveCompactAborted!: () => void;
- let compactSignal: AbortSignal | undefined;
- const compactStarted = new Promise<void>((resolve) => {
- resolveCompactStarted = resolve;
- });
- const compactAborted = new Promise<void>((resolve) => {
- resolveCompactAborted = resolve;
- });
- const submitPrompt = vi.fn(async (_prompt, options) => {
- compactSignal = options?.abortSignal;
- resolveCompactStarted();
- return await new Promise<never>((_resolve, reject) => {
- const abort = () => {
- resolveCompactAborted();
- reject(options?.abortSignal?.reason ?? new Error("compact aborted"));
- };
- if (options?.abortSignal?.aborted) {
- abort();
- return;
- }
- options?.abortSignal?.addEventListener("abort", abort, { once: true });
- });
- });
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options, { submitPrompt }),
- cwd: workspace.workspacePath,
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- const compactResponse = server.handleMessage({
- id: 2,
- method: zcodeProtocolMethods.sessionCompact,
- params: {
- sessionId: created.session.sessionId,
- inputId: "input-compact",
- instructions: "keep recent files",
- },
- });
- await compactStarted;
- expect(compactSignal?.aborted).toBe(false);
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.sessionStop,
- params: { sessionId: created.session.sessionId },
- });
- await compactAborted;
- expect(compactSignal?.aborted).toBe(true);
- expect(submitPrompt).toHaveBeenCalledWith(
- "/compact keep recent files",
- expect.objectContaining({
- abortSignal: compactSignal,
- inputId: "input-compact",
- }),
- );
- const response = await compactResponse;
- const result = zcodeSessionCompactResultSchema.parse(
- response && "result" in response ? response.result : undefined,
- );
- expect(result.compact?.state).toBe("accepted");
- });
- it("generates workspace text through an active app", async () => {
- const generateWorkspaceText = vi.fn(async (input: { prompt: string; querySource: string }) => ({
- text: `generated:${input.querySource}:${input.prompt}`,
- selection: { providerId: "glm", modelId: "glm-4.6" },
- finishReason: "length",
- usage: { inputTokens: 3, outputTokens: 256, totalTokens: 259 },
- }));
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options, { generateWorkspaceText }),
- cwd: workspace.workspacePath,
- });
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- });
- const result = zcodeWorkspaceGenerateTextResultSchema.parse(
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.workspaceGenerateText,
- params: {
- workspace,
- selection: { providerId: "glm", modelId: "glm-4.6" },
- prompt: "write a commit message",
- querySource: "git_commit_message",
- maxOutputTokens: 256,
- },
- }),
- );
- expect(result).toEqual({
- text: "generated:git_commit_message:write a commit message",
- selection: { providerId: "glm", modelId: "glm-4.6" },
- finishReason: "length",
- usage: { inputTokens: 3, outputTokens: 256, totalTokens: 259 },
- });
- expect(generateWorkspaceText).toHaveBeenCalledWith(
- expect.objectContaining({
- selection: { providerId: "glm", modelId: "glm-4.6" },
- prompt: "write a commit message",
- querySource: "git_commit_message",
- maxOutputTokens: 256,
- }),
- { abortSignal: undefined },
- );
- expect(generateWorkspaceText.mock.calls[0]?.[0]).not.toHaveProperty("modelSelection");
- });
- it("tests provider connectivity through the selected formal Model", async () => {
- const calls: string[] = [];
- const refreshProviderRegistry = vi.fn(async () => {
- calls.push("refresh");
- });
- const testModelConnectivity = vi.fn(async () => {});
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createFakeApp(options, {
- testModelConnectivity: async (...args) => {
- calls.push("connectivity");
- await testModelConnectivity(...args);
- },
- }),
- cwd: workspace.workspacePath,
- refreshProviderRegistry,
- });
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- });
- const result = zcodeProviderTestModelConnectivityResultSchema.parse(
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.providerTestModelConnectivity,
- params: {
- workspace,
- selection: {
- providerId: "custom-openai",
- modelId: "agent-model",
- options: { reasoningLevel: "high" },
- },
- },
- }),
- );
- expect(result).toEqual({ success: true });
- expect(refreshProviderRegistry).toHaveBeenCalledWith("provider-connectivity");
- expect(calls).toEqual(["refresh", "connectivity"]);
- expect(testModelConnectivity).toHaveBeenCalledWith(
- {
- selection: {
- providerId: "custom-openai",
- modelId: "agent-model",
- options: { reasoningLevel: "high" },
- },
- },
- { abortSignal: undefined },
- );
- });
- it("closes the temporary app after provider connectivity testing", async () => {
- const close = vi.fn(async () => {});
- const testModelConnectivity = vi.fn(async () => {});
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options, { close, testModelConnectivity }),
- cwd: workspace.workspacePath,
- });
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.providerTestModelConnectivity,
- params: {
- workspace,
- selection: { providerId: "custom-openai", modelId: "agent-model" },
- },
- });
- expect(testModelConnectivity).toHaveBeenCalledOnce();
- expect(close).toHaveBeenCalledOnce();
- });
- it("cancels an active workspace text generation by operation id", async () => {
- let generatedSignal: AbortSignal | undefined;
- let resolveStarted: (() => void) | undefined;
- const started = new Promise<void>((resolve) => {
- resolveStarted = resolve;
- });
- const generateWorkspaceText = vi.fn(
- async (...[, options]: Parameters<ZCodeApp["generateWorkspaceText"]>) => {
- generatedSignal = options?.abortSignal;
- resolveStarted?.();
- await new Promise<never>((_resolve, reject) => {
- generatedSignal?.addEventListener("abort", () => reject(generatedSignal?.reason), {
- once: true,
- });
- });
- },
- );
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options, { generateWorkspaceText }),
- cwd: workspace.workspacePath,
- });
- const generateResponse = server.handleMessage({
- id: 1,
- method: zcodeProtocolMethods.workspaceGenerateText,
- params: {
- workspace,
- selection: { providerId: "glm", modelId: "glm-4.6" },
- prompt: "generate text",
- querySource: "test_sidecar",
- operationId: "workspace_model_1",
- },
- });
- await started;
- const cancelResult = zcodeWorkspaceCancelGenerateTextResultSchema.parse(
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.workspaceCancelGenerateText,
- params: { operationId: "workspace_model_1" },
- }),
- );
- expect(cancelResult).toEqual({ operationId: "workspace_model_1", cancelled: true });
- expect(generatedSignal?.aborted).toBe(true);
- await expect(generateResponse).resolves.toMatchObject({
- id: 1,
- error: expect.objectContaining({ message: expect.any(String) }),
- });
- });
- it("rejects a duplicate active workspace text operation id without replacing its controller", async () => {
- let firstSignal: AbortSignal | undefined;
- let resolveStarted: (() => void) | undefined;
- const started = new Promise<void>((resolve) => {
- resolveStarted = resolve;
- });
- let invocation = 0;
- const generateWorkspaceText = vi.fn(
- async (...[, options]: Parameters<ZCodeApp["generateWorkspaceText"]>) => {
- invocation += 1;
- if (invocation > 1) {
- return {
- text: "reused",
- selection: { providerId: "glm", modelId: "glm-4.6" },
- finishReason: "stop",
- };
- }
- firstSignal = options?.abortSignal;
- resolveStarted?.();
- await new Promise<never>((_resolve, reject) => {
- firstSignal?.addEventListener("abort", () => reject(firstSignal?.reason), { once: true });
- });
- },
- );
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options, { generateWorkspaceText }),
- cwd: workspace.workspacePath,
- });
- const params = {
- workspace,
- selection: { providerId: "glm", modelId: "glm-4.6" },
- prompt: "generate text",
- querySource: "test_sidecar",
- operationId: "workspace_model_duplicate",
- } as const;
- const firstResponse = server.handleMessage({
- id: 1,
- method: zcodeProtocolMethods.workspaceGenerateText,
- params,
- });
- await started;
- await expect(
- server.handleMessage({
- id: 2,
- method: zcodeProtocolMethods.workspaceGenerateText,
- params,
- }),
- ).resolves.toMatchObject({
- id: 2,
- error: expect.objectContaining({
- code: -32600,
- message: expect.stringContaining("already active"),
- }),
- });
- expect(generateWorkspaceText).toHaveBeenCalledOnce();
- const cancelResult = zcodeWorkspaceCancelGenerateTextResultSchema.parse(
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.workspaceCancelGenerateText,
- params: { operationId: params.operationId },
- }),
- );
- expect(cancelResult.cancelled).toBe(true);
- expect(firstSignal?.aborted).toBe(true);
- await expect(firstResponse).resolves.toMatchObject({
- id: 1,
- error: expect.objectContaining({ message: expect.any(String) }),
- });
- const reused = await requestResult(server, {
- id: 4,
- method: zcodeProtocolMethods.workspaceGenerateText,
- params: { ...params, operationId: params.operationId, prompt: "reuse id after completion" },
- });
- expect(reused).toMatchObject({ text: expect.any(String) });
- });
- it("closes the temporary app after draft workspace text generation", async () => {
- const close = vi.fn(async () => {});
- const appOptions: ZCodeAppOptions[] = [];
- const generateWorkspaceText = vi.fn(async () => ({
- text: "fix(git): generate message",
- selection: { providerId: "custom-openai", modelId: "backup-model" },
- finishReason: "stop",
- }));
- const providerRegistry = createProtocolTestProviderRegistry();
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- const effectiveOptions = { ...options, providerRegistry };
- appOptions.push(effectiveOptions);
- return createFakeApp(effectiveOptions, { close, generateWorkspaceText });
- },
- cwd: workspace.workspacePath,
- });
- const result = zcodeWorkspaceGenerateTextResultSchema.parse(
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.workspaceGenerateText,
- params: {
- workspace,
- selection: { providerId: "custom-openai", modelId: "backup-model" },
- prompt: "write a commit message",
- querySource: "git_commit_message",
- },
- }),
- );
- expect(result.text).toBe("fix(git): generate message");
- expect(generateWorkspaceText).toHaveBeenCalledOnce();
- expect(close).toHaveBeenCalledOnce();
- const temporaryAppOptions = appOptions.at(-1);
- expect(temporaryAppOptions?.providerRegistry).toBe(providerRegistry);
- expect(temporaryAppOptions?.modelAdapter).toBeUndefined();
- });
- it("drops duplicate compact requests while the same session is compacting", async () => {
- const submitPrompt = vi.fn();
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- const app = createFakeApp(options);
- return {
- ...app,
- runtime: {
- ...app.runtime,
- getActiveTurnInfo: () =>
- ({
- kind: "compact",
- queueLength: 0,
- steerable: false,
- turnId: "turn_compact",
- }) as never,
- },
- submitPrompt,
- };
- },
- cwd: workspace.workspacePath,
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- const compacted = zcodeSessionCompactResultSchema.parse(
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionCompact,
- params: {
- sessionId: created.session.sessionId,
- instructions: "keep recent files",
- },
- }),
- );
- expect(submitPrompt).not.toHaveBeenCalled();
- expect(compacted.response).toBe("");
- expect(compacted.snapshot.runtime.activeTurnKind).toBe("compact");
- });
- it("runs goal through target APIs instead of submitPrompt", async () => {
- let target: Awaited<ReturnType<NonNullable<ZCodeApp["readTarget"]>>> = null;
- const submitPrompt = vi.fn();
- const continueActiveTarget = vi.fn(async () => ({ response: "continued" }) as never);
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- const app = createFakeApp(options);
- return {
- ...app,
- clearTarget: async () => {
- const hadTarget = target !== null;
- target = null;
- return hadTarget;
- },
- continueActiveTarget,
- readTarget: async () => target,
- runtime: {
- ...app.runtime,
- getProjection: async () =>
- ({
- activeToolCalls: [],
- backgroundTasks: [],
- contextUsed: 0,
- contextWindow: 128_000,
- createdAt: new Date(1),
- id: app.sessionId,
- mode: "build",
- pendingPermissions: [],
- pendingSteerInputs: [],
- status: "idle",
- streamingToolLedger: [],
- target,
- totalTokenCount: 0,
- turnCount: 0,
- updatedAt: new Date(1),
- }) as never,
- } as never,
- setTarget: async (input) => {
- target = {
- objective: input.objective,
- sessionID: app.sessionId,
- status: input.status ?? "active",
- summaryTitle: null,
- targetID: "goal_1" as never,
- time: {
- created: 1,
- updated: 2,
- },
- tokenBudget: input.tokenBudget,
- tokensUsed: 0,
- };
- return target;
- },
- submitPrompt,
- updateTargetStatus: async (status) => {
- if (!target) return null;
- target = { ...target, status, time: { ...target.time, updated: 3 } };
- return target;
- },
- } satisfies ZCodeApp;
- },
- cwd: workspace.workspacePath,
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- const setResult = zcodeSessionGoalResultSchema.parse(
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionGoal,
- params: {
- sessionId: created.session.sessionId,
- action: "set",
- objective: "Ship slash command routing",
- inputId: "input_goal_1",
- },
- }),
- );
- const replaceBySetResult = zcodeSessionGoalResultSchema.parse(
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.sessionGoal,
- params: {
- sessionId: created.session.sessionId,
- action: "set",
- objective: "Replace without explicit keyword",
- inputId: "input_goal_2",
- },
- }),
- );
- const clearResult = zcodeSessionGoalResultSchema.parse(
- await requestResult(server, {
- id: 4,
- method: zcodeProtocolMethods.sessionGoal,
- params: {
- sessionId: created.session.sessionId,
- action: "clear",
- },
- }),
- );
- expect(submitPrompt).not.toHaveBeenCalled();
- expect(continueActiveTarget).toHaveBeenCalledWith(
- expect.objectContaining({ inputId: "input_goal_1" }),
- );
- expect(continueActiveTarget).toHaveBeenCalledWith(
- expect.objectContaining({ inputId: "input_goal_2" }),
- );
- expect(setResult).toMatchObject({
- response: expect.stringContaining("Goal active"),
- startedTurn: true,
- snapshot: {
- projection: {
- target: expect.objectContaining({ objective: "Ship slash command routing" }),
- },
- },
- });
- expect(replaceBySetResult).toMatchObject({
- response: expect.stringContaining("Goal active"),
- startedTurn: true,
- snapshot: {
- projection: {
- target: expect.objectContaining({ objective: "Replace without explicit keyword" }),
- },
- },
- });
- expect(clearResult).toMatchObject({
- response: "Goal cleared.",
- startedTurn: false,
- snapshot: { projection: { target: null } },
- });
- });
- it("rejects session goal commands while a prompt is running", async () => {
- const sendInput = vi.fn(async () => await new Promise<never>(() => {}));
- const setTarget = vi.fn(async () => ({
- objective: "Should wait",
- sessionID: "sess_test" as SessionId,
- status: "active" as const,
- targetID: "goal_running",
- time: { created: 1, updated: 1 },
- }));
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options, { sendInput, setTarget }),
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSend,
- params: {
- sessionId: created.session.sessionId,
- content: "keep running",
- inputId: "input_running",
- },
- });
- const response = await server.handleMessage({
- id: 3,
- method: zcodeProtocolMethods.sessionGoal,
- params: {
- sessionId: created.session.sessionId,
- action: "set",
- objective: "Should wait",
- inputId: "input_goal_blocked",
- },
- });
- expect(response).toMatchObject({
- error: {
- code: -32010,
- message: "Cannot manage goals while a prompt is running",
- },
- id: 3,
- });
- expect(setTarget).not.toHaveBeenCalled();
- });
- it("allows session goal pause to stop a running prompt", async () => {
- const abortReasons: string[] = [];
- let target: Awaited<ReturnType<NonNullable<ZCodeApp["readTarget"]>>> = null;
- const sendInput = vi.fn<ZCodeApp["sendInput"]>(
- async (_input, options) =>
- await new Promise<never>((_resolve, reject) => {
- const signal = options.abortSignal;
- const rejectFromAbort = () => {
- const reason = signal.reason;
- abortReasons.push(reason instanceof Error ? reason.message : String(reason));
- reject(reason instanceof Error ? reason : new Error(String(reason)));
- };
- if (signal.aborted) {
- rejectFromAbort();
- return;
- }
- signal.addEventListener("abort", rejectFromAbort, { once: true });
- }),
- );
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- const app = createFakeApp(options, { sendInput });
- target = {
- objective: "Pause current goal immediately",
- sessionID: app.sessionId,
- status: "active",
- targetID: "goal_pause_running",
- time: { created: 1, updated: 1 },
- };
- return {
- ...app,
- readTarget: async () => target,
- runtime: {
- ...app.runtime,
- getProjection: async () =>
- ({
- activeToolCalls: [],
- backgroundTasks: [],
- contextUsed: 0,
- contextWindow: 128_000,
- createdAt: new Date(1),
- id: app.sessionId,
- mode: "build",
- pendingPermissions: [],
- pendingSteerInputs: [],
- status: "running",
- streamingToolLedger: [],
- target,
- totalTokenCount: 0,
- turnCount: 1,
- updatedAt: new Date(2),
- }) as never,
- } as never,
- updateTargetStatus: async (status) => {
- if (!target) return null;
- target = { ...target, status, time: { ...target.time, updated: 3 } };
- return target;
- },
- } satisfies ZCodeApp;
- },
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSend,
- params: {
- sessionId: created.session.sessionId,
- content: "keep running",
- inputId: "input_pause_running",
- },
- });
- const pauseResult = zcodeSessionGoalResultSchema.parse(
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.sessionGoal,
- params: {
- sessionId: created.session.sessionId,
- action: "pause",
- inputId: "input_goal_pause_running",
- },
- }),
- );
- await vi.waitFor(() => {
- expect(abortReasons).toContain("ZCode Protocol goal paused");
- });
- expect(target?.status).toBe("paused");
- expect(pauseResult).toMatchObject({
- response: "",
- startedTurn: false,
- snapshot: {
- projection: {
- target: expect.objectContaining({ status: "paused" }),
- },
- },
- });
- });
- it("pauses an active goal when session stop cancels goal continuation", async () => {
- const notifications: ZCodeProtocolNotification[] = [];
- const abortReasons: string[] = [];
- let resolveContinuationStarted!: () => void;
- const continuationStarted = new Promise<void>((resolve) => {
- resolveContinuationStarted = resolve;
- });
- let target: Awaited<ReturnType<NonNullable<ZCodeApp["readTarget"]>>> = null;
- const continueActiveTarget = vi.fn<ZCodeApp["continueActiveTarget"]>(
- async (options) =>
- await new Promise<never>((_resolve, reject) => {
- const signal = options?.abortSignal;
- resolveContinuationStarted();
- const rejectFromAbort = () => {
- const reason = signal?.reason;
- abortReasons.push(reason instanceof Error ? reason.message : String(reason));
- reject(reason instanceof Error ? reason : new Error(String(reason)));
- };
- if (signal?.aborted) {
- rejectFromAbort();
- return;
- }
- signal?.addEventListener("abort", rejectFromAbort, { once: true });
- }),
- );
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- const app = createFakeApp(options, { continueActiveTarget });
- return {
- ...app,
- readTarget: async () => target,
- runtime: {
- ...app.runtime,
- getProjection: async () =>
- ({
- activeToolCalls: [],
- backgroundTasks: [],
- contextUsed: 0,
- contextWindow: 128_000,
- createdAt: new Date(1),
- id: app.sessionId,
- mode: "build",
- pendingPermissions: [],
- pendingSteerInputs: [],
- status: continueActiveTarget.mock.calls.length > 0 ? "running" : "idle",
- streamingToolLedger: [],
- target,
- totalTokenCount: 0,
- turnCount: continueActiveTarget.mock.calls.length,
- updatedAt: new Date(2),
- }) as never,
- } as never,
- setTarget: async (input) => {
- target = {
- objective: input.objective,
- sessionID: app.sessionId,
- status: input.status ?? "active",
- summaryTitle: null,
- targetID: "goal_stop_running",
- time: { created: 1, updated: 2 },
- timeUsedSeconds: 0,
- tokenBudget: input.tokenBudget ?? null,
- tokensUsed: 0,
- };
- return target;
- },
- updateTargetStatus: async (status) => {
- if (!target) return null;
- target = { ...target, status, time: { ...target.time, updated: 3 } };
- return target;
- },
- } satisfies ZCodeApp;
- },
- cwd: workspace.workspacePath,
- });
- setTestNotificationSink(server, (notification) => notifications.push(notification));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- const goalResult = zcodeSessionGoalResultSchema.parse(
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionGoal,
- params: {
- sessionId: created.session.sessionId,
- action: "set",
- objective: "Stop should pause this goal",
- inputId: "input_goal_stop_running",
- },
- }),
- );
- await continuationStarted;
- const notificationCountBeforeStop = notifications.length;
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.sessionStop,
- params: { sessionId: created.session.sessionId },
- });
- await vi.waitFor(() => {
- expect(abortReasons).toContain("ZCode Protocol session stopped");
- });
- expect(goalResult.startedTurn).toBe(true);
- expect(target?.status).toBe("paused");
- expect(
- notifications
- .slice(notificationCountBeforeStop)
- .some((item) => item.method === "state.updated"),
- ).toBe(true);
- });
- it("includes persisted goal and todos in protocol snapshots", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- const app = createFakeApp(options);
- const persistedTarget = {
- objective: "Restore parser goal",
- sessionID: app.sessionId,
- status: "paused" as const,
- summaryTitle: "Restore parser goal",
- targetID: "goal_db",
- time: { created: 10, updated: 20 },
- timeUsedSeconds: 7,
- tokenBudget: null,
- tokensUsed: 123,
- };
- return {
- ...app,
- readTarget: async () => persistedTarget,
- readTodos: async () => [
- { content: "Implement lexer", priority: "high", status: "completed" },
- { content: "Implement parser", priority: "high", status: "in_progress" },
- ],
- };
- },
- cwd: workspace.workspacePath,
- });
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- expect(created.projection.target).toMatchObject({
- objective: "Restore parser goal",
- status: "paused",
- summaryTitle: "Restore parser goal",
- targetId: "goal_db",
- });
- expect(created.session.target).toMatchObject({
- objective: "Restore parser goal",
- summaryTitle: "Restore parser goal",
- targetId: "goal_db",
- });
- expect(created.todos).toEqual([
- { content: "Implement lexer", priority: "high", status: "completed" },
- { content: "Implement parser", priority: "high", status: "in_progress" },
- ]);
- });
- it("derives goal stats and todo groups from persisted verifier boundaries", async () => {
- const app = createFakeApp();
- const target = {
- objective: "Ship grouped todo restore",
- sessionID: app.sessionId,
- status: "active" as const,
- summaryTitle: null,
- targetID: "goal_1" as never,
- time: { created: 1_000, updated: 9_400 },
- timeUsedSeconds: 0,
- tokenBudget: 120_000,
- tokensUsed: 0,
- };
- const messages = [
- {
- info: {
- id: "msg_goal_1" as MessageId,
- sessionID: app.sessionId,
- role: "user",
- time: { created: 1_000 },
- agent: "zcode-agent",
- modelSelection: {
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- },
- source: "goal-continuation",
- synthetic: true,
- visibility: "model-only",
- metadata: { source: "goal-continuation", targetId: "goal_1" },
- },
- parts: [
- {
- id: "part_goal_1" as never,
- sessionID: app.sessionId,
- messageID: "msg_goal_1" as MessageId,
- type: "text",
- text: "continue the active goal",
- },
- ],
- },
- {
- info: {
- id: "msg_assistant_1" as MessageId,
- sessionID: app.sessionId,
- role: "assistant",
- parentID: "msg_goal_1" as MessageId,
- time: { created: 2_000, completed: 4_500 },
- agent: "zcode-agent",
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- mode: "build",
- path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
- cost: 0,
- tokens: {
- input: 100,
- output: 10,
- reasoning: 1,
- total: 111,
- cache: { read: 0, write: 0 },
- },
- },
- parts: [
- {
- id: "part_todo_1" as never,
- sessionID: app.sessionId,
- messageID: "msg_assistant_1" as MessageId,
- type: "tool",
- callID: "tool_todo_1",
- tool: "TodoWrite",
- state: {
- status: "completed",
- input: {
- todos: [
- { content: "Read existing restore flow", priority: "high", status: "completed" },
- { content: "Project grouped todos", priority: "high", status: "in_progress" },
- ],
- },
- output: "ok",
- title: "TodoWrite",
- metadata: {},
- time: { start: 2_100, end: 4_200 },
- },
- },
- ],
- },
- {
- info: {
- id: "msg_goal_2" as MessageId,
- sessionID: app.sessionId,
- role: "user",
- time: { created: 5_000 },
- agent: "zcode-agent",
- modelSelection: {
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- },
- metadata: { source: "goal-continuation", targetId: "goal_1" },
- },
- parts: [
- {
- id: "part_goal_2" as never,
- sessionID: app.sessionId,
- messageID: "msg_goal_2" as MessageId,
- type: "text",
- text: "continue again",
- },
- ],
- },
- {
- info: {
- id: "msg_assistant_2" as MessageId,
- sessionID: app.sessionId,
- role: "assistant",
- parentID: "msg_goal_2" as MessageId,
- time: { created: 5_500, completed: 8_000 },
- agent: "zcode-agent",
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- mode: "build",
- path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
- cost: 0,
- tokens: {
- input: 200,
- output: 20,
- reasoning: 2,
- total: 222,
- cache: { read: 0, write: 0 },
- },
- },
- parts: [
- {
- id: "part_bash_2" as never,
- sessionID: app.sessionId,
- messageID: "msg_assistant_2" as MessageId,
- type: "tool",
- callID: "tool_bash_2",
- tool: "Bash",
- state: {
- status: "completed",
- input: { command: "pnpm typecheck" },
- output: "passed",
- title: "Bash",
- metadata: {},
- time: { start: 5_600, end: 6_000 },
- },
- },
- {
- id: "part_todo_2" as never,
- sessionID: app.sessionId,
- messageID: "msg_assistant_2" as MessageId,
- type: "tool",
- callID: "tool_todo_2",
- tool: "todo_write",
- state: {
- status: "completed",
- input: {
- todos: [
- { content: "Project grouped todos", priority: "high", status: "completed" },
- { content: "Verify restored summary", priority: "medium", status: "in_progress" },
- ],
- },
- output: "ok",
- title: "TodoWrite",
- metadata: {},
- time: { start: 6_100, end: 7_800 },
- },
- },
- ],
- },
- {
- info: {
- id: "msg_assistant_3" as MessageId,
- sessionID: app.sessionId,
- role: "assistant",
- parentID: "msg_assistant_2" as MessageId,
- time: { created: 8_200, completed: 9_400 },
- agent: "zcode-agent",
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- mode: "build",
- path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
- cost: 0,
- tokens: {
- input: 20,
- output: 8,
- reasoning: 2,
- total: 30,
- cache: { read: 0, write: 0 },
- },
- },
- parts: [
- {
- id: "part_todo_3" as never,
- sessionID: app.sessionId,
- messageID: "msg_assistant_3" as MessageId,
- type: "tool",
- callID: "tool_todo_3",
- tool: "TodoWrite",
- state: {
- status: "completed",
- input: {
- todos: [
- { content: "Project grouped todos", priority: "high", status: "completed" },
- { content: "Verify restored summary", priority: "medium", status: "completed" },
- ],
- },
- output: "ok",
- title: "TodoWrite",
- metadata: {},
- time: { start: 8_300, end: 9_300 },
- },
- },
- ],
- },
- ] as unknown as MessageWithParts[];
- const snapshot = zcodeSessionStateSnapshotSchema.parse(
- await buildSessionSnapshot({
- app,
- eventSeq: 1,
- messages,
- persistedGoalVerificationEvents: [
- {
- id: "evt_verify_1" as SessionEvent["id"],
- payload: {
- goalIteration: 1,
- status: "completed",
- targetId: "goal_1",
- verification: {
- nextAction: "Verify restored summary",
- passed: false,
- reason: "The restored summary is not verified yet.",
- },
- verificationId: "verify_1",
- },
- sequenceNumber: 10,
- sessionId: app.sessionId,
- timestamp: new Date(4_800),
- traceId: "trace_verify_1" as SessionEvent["traceId"],
- type: SessionEventType.TargetCompletionVerification,
- },
- ],
- stateRevision: 1,
- target,
- todos: [],
- workspace,
- }),
- );
- expect(snapshot.goalStats).toEqual({
- contextUsed: 0,
- contextWindow: 128_000,
- iterationCount: 2,
- timeUsedSeconds: 8,
- tokenBudget: 120_000,
- tokensUsed: 363,
- toolCallCount: 4,
- });
- expect(snapshot.runtime.goalVerificationTimeline).toEqual([
- {
- display: "separator",
- goalIteration: 1,
- kind: "synthetic",
- status: "completed",
- targetId: "goal_1",
- type: "goal_verification",
- updatedAt: 4_800,
- verification: {
- nextAction: "Verify restored summary",
- passed: false,
- reason: "The restored summary is not verified yet.",
- },
- verificationId: "verify_1",
- version: 1,
- },
- ]);
- expect(snapshot.todoGroups).toEqual([
- {
- id: "goal-iteration-1",
- source: "goal_iteration",
- goalIteration: 1,
- targetId: "goal_1",
- startedAt: 1_000,
- updatedAt: 9_300,
- todos: [
- { content: "Read existing restore flow", priority: "high", status: "completed" },
- { content: "Project grouped todos", priority: "high", status: "completed" },
- ],
- },
- {
- id: "goal-iteration-2",
- source: "goal_iteration",
- goalIteration: 2,
- targetId: "goal_1",
- startedAt: 4_800,
- updatedAt: 9_300,
- todos: [{ content: "Verify restored summary", priority: "medium", status: "completed" }],
- },
- ]);
- });
- it("does not advance goal stats after paused verifier cancellation", async () => {
- const app = createFakeApp();
- const target = {
- objective: "Stop goal verification",
- sessionID: app.sessionId,
- status: "paused" as const,
- summaryTitle: null,
- targetID: "goal_paused_cancelled" as never,
- time: { created: 1_000, updated: 4_000 },
- timeUsedSeconds: 2,
- tokenBudget: null,
- tokensUsed: 10,
- };
- const snapshot = zcodeSessionStateSnapshotSchema.parse(
- await buildSessionSnapshot({
- app,
- eventSeq: 1,
- messages: [],
- persistedGoalVerificationEvents: [
- {
- id: "evt_verify_cancelled" as SessionEvent["id"],
- payload: {
- goalIteration: 1,
- status: "cancelled",
- targetId: "goal_paused_cancelled",
- verificationId: "verify_cancelled",
- },
- sequenceNumber: 10,
- sessionId: app.sessionId,
- timestamp: new Date(3_500),
- traceId: "trace_verify_cancelled" as SessionEvent["traceId"],
- type: SessionEventType.TargetCompletionVerification,
- },
- ],
- stateRevision: 1,
- target,
- todos: [],
- workspace,
- }),
- );
- expect(snapshot.goalStats).toMatchObject({
- iterationCount: 1,
- timeUsedSeconds: 2,
- tokensUsed: 10,
- });
- expect(snapshot.runtime.goalVerificationTimeline).toEqual([
- expect.objectContaining({
- goalIteration: 1,
- status: "cancelled",
- targetId: "goal_paused_cancelled",
- }),
- ]);
- });
- it("keeps visible user continuation todo updates in the current verifier iteration", async () => {
- const app = createFakeApp();
- const target = {
- objective: "Ship dynamic grouped todos",
- sessionID: app.sessionId,
- status: "active" as const,
- summaryTitle: null,
- targetID: "goal_visible_continue" as never,
- time: { created: 1_000, updated: 7_000 },
- timeUsedSeconds: 0,
- tokenBudget: null,
- tokensUsed: 0,
- };
- const messages = [
- {
- info: {
- id: "msg_goal_1" as MessageId,
- sessionID: app.sessionId,
- role: "user",
- time: { created: 1_000 },
- agent: "zcode-agent",
- modelSelection: {
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- },
- source: "goal-continuation",
- synthetic: true,
- visibility: "model-only",
- metadata: { source: "goal-continuation", targetId: "goal_visible_continue" },
- },
- parts: [
- {
- id: "part_goal_1" as never,
- sessionID: app.sessionId,
- messageID: "msg_goal_1" as MessageId,
- type: "text",
- text: "continue the active goal",
- },
- ],
- },
- {
- info: {
- id: "msg_assistant_1" as MessageId,
- sessionID: app.sessionId,
- role: "assistant",
- parentID: "msg_goal_1" as MessageId,
- time: { created: 2_000, completed: 3_000 },
- agent: "zcode-agent",
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- mode: "build",
- path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
- cost: 0,
- tokens: {
- input: 10,
- output: 5,
- reasoning: 0,
- total: 15,
- cache: { read: 0, write: 0 },
- },
- },
- parts: [
- {
- id: "part_todo_1" as never,
- sessionID: app.sessionId,
- messageID: "msg_assistant_1" as MessageId,
- type: "tool",
- callID: "tool_todo_1",
- tool: "TodoWrite",
- state: {
- status: "completed",
- input: {
- todos: [
- { content: "Wire UI components in App", priority: "high", status: "in_progress" },
- { content: "Wire undo/history system", priority: "medium", status: "pending" },
- ],
- },
- output: "ok",
- title: "TodoWrite",
- metadata: {},
- time: { start: 2_100, end: 2_900 },
- },
- },
- ],
- },
- {
- info: {
- id: "msg_visible_continue" as MessageId,
- sessionID: app.sessionId,
- role: "user",
- time: { created: 4_000 },
- agent: "zcode-agent",
- modelSelection: {
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- },
- },
- parts: [
- {
- id: "part_visible_continue" as never,
- sessionID: app.sessionId,
- messageID: "msg_visible_continue" as MessageId,
- type: "text",
- text: "继续",
- },
- ],
- },
- {
- info: {
- id: "msg_assistant_2" as MessageId,
- sessionID: app.sessionId,
- role: "assistant",
- parentID: "msg_visible_continue" as MessageId,
- time: { created: 4_500, completed: 5_500 },
- agent: "zcode-agent",
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- mode: "build",
- path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
- cost: 0,
- tokens: {
- input: 20,
- output: 5,
- reasoning: 0,
- total: 25,
- cache: { read: 0, write: 0 },
- },
- },
- parts: [
- {
- id: "part_todo_2" as never,
- sessionID: app.sessionId,
- messageID: "msg_assistant_2" as MessageId,
- type: "tool",
- callID: "tool_todo_2",
- tool: "todo_write",
- state: {
- status: "completed",
- input: {
- todos: [
- { content: "Wire UI components in App", priority: "high", status: "completed" },
- {
- content: "Complete remaining blend modes in WebGL shaders and Rust engine",
- priority: "high",
- status: "in_progress",
- },
- {
- content: "Wire PSD import through worker into App",
- priority: "medium",
- status: "pending",
- },
- ],
- },
- output: "ok",
- title: "TodoWrite",
- metadata: {},
- time: { start: 4_600, end: 5_300 },
- },
- },
- ],
- },
- {
- info: {
- id: "msg_assistant_3" as MessageId,
- sessionID: app.sessionId,
- role: "assistant",
- parentID: "msg_assistant_2" as MessageId,
- time: { created: 5_800, completed: 7_000 },
- agent: "zcode-agent",
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- mode: "build",
- path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
- cost: 0,
- tokens: {
- input: 30,
- output: 5,
- reasoning: 0,
- total: 35,
- cache: { read: 0, write: 0 },
- },
- },
- parts: [
- {
- id: "part_todo_3" as never,
- sessionID: app.sessionId,
- messageID: "msg_assistant_3" as MessageId,
- type: "tool",
- callID: "tool_todo_3",
- tool: "TodoWrite",
- state: {
- status: "completed",
- input: {
- todos: [
- { content: "Wire UI components in App", priority: "high", status: "completed" },
- {
- content: "Complete remaining blend modes in WebGL shaders and Rust engine",
- priority: "high",
- status: "completed",
- },
- {
- content: "Wire PSD import through worker into App",
- priority: "medium",
- status: "in_progress",
- },
- ],
- },
- output: "ok",
- title: "TodoWrite",
- metadata: {},
- time: { start: 5_900, end: 6_900 },
- },
- },
- ],
- },
- ] as unknown as MessageWithParts[];
- const snapshot = zcodeSessionStateSnapshotSchema.parse(
- await buildSessionSnapshot({
- app,
- eventSeq: 1,
- messages,
- stateRevision: 1,
- target,
- todos: [],
- workspace,
- }),
- );
- expect(snapshot.goalStats).toMatchObject({
- iterationCount: 1,
- toolCallCount: 3,
- tokensUsed: 75,
- });
- expect(snapshot.todoGroups).toEqual([
- {
- id: "goal-iteration-1",
- source: "goal_iteration",
- goalIteration: 1,
- targetId: "goal_visible_continue",
- startedAt: 1_000,
- updatedAt: 6_900,
- todos: [
- { content: "Wire UI components in App", priority: "high", status: "completed" },
- { content: "Wire undo/history system", priority: "medium", status: "pending" },
- {
- content: "Complete remaining blend modes in WebGL shaders and Rust engine",
- priority: "high",
- status: "completed",
- },
- {
- content: "Wire PSD import through worker into App",
- priority: "medium",
- status: "in_progress",
- },
- ],
- },
- ]);
- });
- it("keeps standalone non-goal todos grouped as session current todos", async () => {
- const app = createFakeApp();
- const snapshot = zcodeSessionStateSnapshotSchema.parse(
- await buildSessionSnapshot({
- app,
- eventSeq: 1,
- messages: [],
- stateRevision: 1,
- target: null,
- todos: [
- { content: "Read logs", priority: "high", status: "completed" },
- { content: "Reproduce locally", priority: "high", status: "in_progress" },
- { content: "Write fix", priority: "medium", status: "pending" },
- ],
- workspace,
- }),
- );
- expect(snapshot.goalStats).toBeUndefined();
- expect(snapshot.todoGroups).toEqual([
- {
- id: "session-current",
- source: "session",
- todos: [
- { content: "Read logs", priority: "high", status: "completed" },
- { content: "Reproduce locally", priority: "high", status: "in_progress" },
- { content: "Write fix", priority: "medium", status: "pending" },
- ],
- },
- ]);
- });
- it("ignores subagent TodoWrite parts when building main session todo groups", async () => {
- const app = createFakeApp();
- const messages = [
- {
- info: {
- id: "msg_main_todo" as MessageId,
- sessionID: app.sessionId,
- role: "assistant",
- time: { created: 1_000, completed: 1_200 },
- agent: "zcode-agent",
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- mode: "build",
- path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
- cost: 0,
- tokens: { input: 1, output: 1, reasoning: 0, total: 2, cache: { read: 0, write: 0 } },
- },
- parts: [
- {
- id: "part_main_todo" as never,
- sessionID: app.sessionId,
- messageID: "msg_main_todo" as MessageId,
- type: "tool",
- callID: "call_main_todo",
- tool: "TodoWrite",
- state: {
- status: "completed",
- input: {
- todos: [
- { content: "Main inspect logs", priority: "high", status: "completed" },
- { content: "Main patch projection", priority: "high", status: "in_progress" },
- ],
- },
- output: "ok",
- title: "TodoWrite",
- metadata: {},
- time: { start: 1_050, end: 1_100 },
- },
- },
- ],
- },
- {
- info: {
- id: "msg_subagent_todo" as MessageId,
- sessionID: app.sessionId,
- role: "assistant",
- time: { created: 2_000, completed: 2_200 },
- agent: "zcode-agent",
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4.6" as ModelId,
- mode: "build",
- path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
- cost: 0,
- tokens: { input: 1, output: 1, reasoning: 0, total: 2, cache: { read: 0, write: 0 } },
- },
- parts: [
- {
- id: "part_subagent_todo" as never,
- sessionID: app.sessionId,
- messageID: "msg_subagent_todo" as MessageId,
- type: "tool",
- callID: "tool_subagent_agent_1_call_todo",
- tool: "TodoWrite",
- metadata: { source: "subagent" },
- state: {
- status: "completed",
- input: {
- todos: [
- { content: "Subagent search market", priority: "high", status: "completed" },
- {
- content: "Subagent summarize sources",
- priority: "medium",
- status: "completed",
- },
- ],
- },
- output: "ok",
- title: "TodoWrite",
- metadata: { source: "subagent", parentToolCallId: "call_agent" },
- time: { start: 2_050, end: 2_100 },
- },
- },
- ],
- },
- ] as unknown as MessageWithParts[];
- const snapshot = zcodeSessionStateSnapshotSchema.parse(
- await buildSessionSnapshot({
- app,
- eventSeq: 1,
- messages,
- stateRevision: 1,
- target: null,
- todos: [],
- workspace,
- }),
- );
- expect(snapshot.todoGroups).toEqual([
- {
- id: "session",
- source: "session",
- startedAt: 1_000,
- updatedAt: 1_100,
- todos: [
- { content: "Main inspect logs", priority: "high", status: "completed" },
- { content: "Main patch projection", priority: "high", status: "in_progress" },
- ],
- },
- ]);
- });
- it("forks sessions and lets selection children inherit parent runtime preferences", async () => {
- const store = createSqliteSessionStore({ dbPath: ":memory:" });
- const forkTargets: Array<{ targetCheckpointId?: string; targetMessageId?: string }> = [];
- const createdAppOptions: ZCodeAppOptions[] = [];
- const selectionChildId = "sess_selection_runtime_preferences" as SessionId;
- try {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => {
- createdAppOptions.push(options);
- const app = createFakeApp(options);
- return {
- ...app,
- clearTarget: async () => await store.clearTarget({ sessionID: app.sessionId }),
- forkFromCheckpoint: async (target) => {
- forkTargets.push({
- targetCheckpointId: target?.targetCheckpointId,
- targetMessageId: target?.targetMessageId,
- });
- const forkedSessionId = "sess_forked" as SessionId;
- if (!(await store.getSession(forkedSessionId))) {
- await store.createSession({
- id: forkedSessionId,
- parentID: options?.sessionId,
- projectID: "project_fork_runtime_settings" as ProjectId,
- slug: "fork-runtime-settings",
- directory: workspace.workspacePath,
- path: workspace.workspacePath,
- title: "Fork runtime settings",
- version: "test-version",
- time: { created: 10, updated: 10 },
- });
- }
- return {
- checkpoint: {} as never,
- copiedMessageCount: 2,
- forkedSessionId,
- parentSessionId: (options?.sessionId ?? "sess_parent") as never,
- targetMessageId: "msg_assistant_1" as never,
- targetCheckpointId: "checkpoint_1",
- restoredFiles: [],
- response: "forked",
- };
- },
- readTarget: async () => await store.readTarget({ sessionID: app.sessionId }),
- runtime: {
- ...app.runtime,
- createSelectionSideConversation: async () => {
- if (!(await store.getSession(selectionChildId))) {
- await store.createSession({
- id: selectionChildId,
- parentID: app.sessionId,
- projectID: "project_selection_runtime_preferences" as ProjectId,
- slug: "selection-runtime-preferences",
- directory: workspace.workspacePath,
- path: workspace.workspacePath,
- taskType: "selection_side_chat",
- title: "Selection runtime preferences",
- version: "test-version",
- time: { created: 20, updated: 20 },
- });
- }
- return {
- forkedSessionId: selectionChildId,
- parentSessionId: app.sessionId,
- response: "selection child",
- targetMessageId: "msg_assistant_1" as MessageId,
- } as never;
- },
- } as never,
- setTarget: async (input) =>
- await store.setTarget({
- objective: input.objective,
- sessionID: app.sessionId,
- status: input.status ?? "active",
- tokenBudget: input.tokenBudget,
- }),
- updateTargetStatus: async (status) =>
- await store.updateTargetStatus({ sessionID: app.sessionId, status }),
- } satisfies ZCodeApp;
- },
- cwd: workspace.workspacePath,
- sessionStore: store,
- });
- const preferenceRequests = attachSessionRuntimePreferencesResponder(server, () => ({
- nativeSearchEnhancementsEnabled: false,
- memoryEnabled: false,
- subagentRuntimeConfigEnabled: true,
- modelContextBudgetStrategy: "preflight-v1",
- }));
- const created = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- if (!(await store.getSession(created.session.sessionId as SessionId))) {
- await store.createSession({
- id: created.session.sessionId as SessionId,
- projectID: "project_fork_runtime_settings" as ProjectId,
- slug: "fork-runtime-settings-parent",
- directory: workspace.workspacePath,
- path: workspace.workspacePath,
- title: "Fork runtime settings parent",
- version: "test-version",
- time: { created: 1, updated: 1 },
- });
- }
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionSetModel,
- params: {
- sessionId: created.session.sessionId,
- model: { providerId: "glm", modelId: "glm-4-air" },
- },
- });
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.sessionSetMode,
- params: {
- sessionId: created.session.sessionId,
- mode: "plan",
- },
- });
- await requestResult(server, {
- id: 4,
- method: zcodeProtocolMethods.sessionSetThoughtLevel,
- params: {
- sessionId: created.session.sessionId,
- thoughtLevel: "deep",
- },
- });
- const goal = zcodeSessionGoalResultSchema.parse(
- await requestResult(server, {
- id: 5,
- method: zcodeProtocolMethods.sessionGoal,
- params: {
- sessionId: created.session.sessionId,
- action: "set",
- objective: "Fork inherits parent goal target",
- },
- }),
- );
- expect(goal.snapshot.session.target).toMatchObject({
- objective: "Fork inherits parent goal target",
- sessionId: created.session.sessionId,
- status: "active",
- });
- const result = zcodeSessionForkResultSchema.parse(
- await requestResult(server, {
- id: 6,
- method: zcodeProtocolMethods.sessionFork,
- params: {
- sessionId: created.session.sessionId,
- target: { kind: "message", messageId: "msg_assistant_1" },
- },
- }),
- );
- expect(forkTargets).toEqual([
- expect.objectContaining({ targetMessageId: "msg_assistant_1" }),
- ]);
- expect(result).toMatchObject({
- forkedSessionId: "sess_forked",
- targetMessageId: "msg_assistant_1",
- targetCheckpointId: "checkpoint_1",
- });
- expect(result.snapshot.session.sessionId).toBe("sess_forked");
- expect(result.snapshot.settings).toMatchObject({
- mode: { current: "plan" },
- model: { current: { providerId: "glm", modelId: "glm-4-air" } },
- thoughtLevel: { current: "deep" },
- });
- expect(createdAppOptions).toHaveLength(2);
- expect(createdAppOptions[1]?.readSubagentRuntimeConfig).toBeTypeOf("function");
- expect(preferenceRequests).toHaveLength(1);
- expect(createdAppOptions[1]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(false);
- expect(createdAppOptions[1]?.runtimeConfig?.memory?.enabled).toBe(false);
- expect(createdAppOptions[1]?.runtimeConfig?.modelContextBudgetStrategy).toBe("preflight-v1");
- expect(result.snapshot.session.target).toMatchObject({
- objective: "Fork inherits parent goal target",
- sessionId: "sess_forked",
- status: "active",
- });
- expect(result.snapshot.projection.target).toMatchObject({
- objective: "Fork inherits parent goal target",
- sessionId: "sess_forked",
- status: "active",
- });
- expect(result.snapshot.session.target?.targetId).toBe(goal.snapshot.session.target?.targetId);
- expect(await store.readTarget({ sessionID: "sess_forked" as SessionId })).toMatchObject({
- objective: "Fork inherits parent goal target",
- });
- const selection = await requestResult(server, {
- id: 7,
- method: V4_METHODS.command,
- params: {
- clientId: "client-selection-runtime-preferences",
- commandId: "cmd-selection-runtime-preferences",
- issuedAt: 20,
- payload: {},
- sessionId: created.session.sessionId,
- type: "createSelectionSideSession",
- },
- });
- expect(selection).toMatchObject({
- status: "accepted",
- result: {
- sessionId: selectionChildId,
- type: "createSelectionSideSession",
- },
- });
- expect(createdAppOptions).toHaveLength(3);
- expect(createdAppOptions[2]?.readSubagentRuntimeConfig).toBeTypeOf("function");
- expect(preferenceRequests).toHaveLength(1);
- expect(createdAppOptions[2]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(false);
- expect(createdAppOptions[2]?.runtimeConfig?.memory?.enabled).toBe(false);
- expect(createdAppOptions[2]?.runtimeConfig?.modelContextBudgetStrategy).toBe("preflight-v1");
- expect((await store.getSession(selectionChildId))?.taskType).toBe("selection_side_chat");
- } finally {
- await store.close();
- }
- });
- it("resolves turn fork targets before later user, fork, and compact synthetic messages", async () => {
- const store = createSqliteSessionStore({ dbPath: ":memory:" });
- const sessionId = "sess_fork_turn_history" as SessionId;
- const forkTargets: Array<{ targetCheckpointId?: string; targetMessageId?: string }> = [];
- try {
- await store.createSession({
- id: sessionId,
- projectID: "project_fork_turn_history" as ProjectId,
- slug: "fork-turn-history",
- directory: workspace.workspacePath,
- path: workspace.workspacePath,
- title: "Fork turn history",
- version: "test-version",
- time: { created: 1, updated: 12 },
- });
- await saveUserTextMessage(store, sessionId, "msg_user_0" as MessageId, "第一轮", 2);
- await saveAssistantTextMessage(
- store,
- sessionId,
- "msg_assistant_0" as MessageId,
- "msg_user_0" as MessageId,
- "第一轮回复",
- 3,
- );
- await saveUserTextMessage(store, sessionId, "msg_user_1" as MessageId, "第二轮", 4);
- await saveAssistantTextMessage(
- store,
- sessionId,
- "msg_assistant_1" as MessageId,
- "msg_user_1" as MessageId,
- "第二轮回复",
- 5,
- );
- await saveSyntheticForkNotice(store, sessionId, "msg_fork_notice" as MessageId, 6);
- await saveCompactSummary(store, sessionId, "msg_compact_summary" as MessageId, 7);
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createFakeApp(options, {
- forkFromCheckpoint: async (target) => {
- forkTargets.push({
- targetCheckpointId: target?.targetCheckpointId,
- targetMessageId: target?.targetMessageId,
- });
- const forkedSessionId = "sess_forked" as SessionId;
- // fake 必须遵守 core fork 契约:返回前 child 已落 store。旧夹具只返回 id,
- // registerForkedSession 按生产语义回读时必然报 Persisted child not found。
- if (!(await store.getSession(forkedSessionId))) {
- await store.createSession({
- id: forkedSessionId,
- parentID: sessionId,
- projectID: "project_fork_turn_history" as ProjectId,
- slug: "fork-turn-history-child",
- directory: workspace.workspacePath,
- path: workspace.workspacePath,
- title: "Fork turn history child",
- version: "test-version",
- time: { created: 10, updated: 10 },
- });
- }
- return {
- checkpoint: {} as never,
- copiedMessageCount: 2,
- forkedSessionId,
- parentSessionId: sessionId,
- targetMessageId: target?.targetMessageId as never,
- restoredFiles: [],
- response: "forked",
- };
- },
- }),
- cwd: workspace.workspacePath,
- sessionStore: store,
- });
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionResume,
- params: { sessionId, workspace },
- });
- await requestResult(server, {
- id: 2,
- method: zcodeProtocolMethods.sessionFork,
- params: {
- sessionId,
- target: { kind: "turn", turnIndex: 0 },
- },
- });
- await requestResult(server, {
- id: 3,
- method: zcodeProtocolMethods.sessionFork,
- params: {
- sessionId,
- target: { kind: "turn", turnIndex: 1 },
- },
- });
- expect(forkTargets).toEqual([
- expect.objectContaining({ targetMessageId: "msg_assistant_0" }),
- expect.objectContaining({ targetMessageId: "msg_assistant_1" }),
- ]);
- } finally {
- await store.close();
- }
- });
- it("maps core session title updates into explicit protocol events", () => {
- const event = mapSessionEvent(
- {
- id: "evt_title" as never,
- payload: {
- previousTitle: "please fix the mobile login button",
- source: "generated",
- title: "Fix mobile login",
- },
- sequenceNumber: 3,
- sessionId: "sess_test" as SessionId,
- timestamp: new Date(4),
- traceId: "trace_test" as never,
- type: SessionEventType.SessionTitleUpdated,
- } satisfies SessionEvent,
- "desktop-continuous",
- );
- expect(event.type).toBe("session.titleUpdated");
- expect(event.payload).toMatchObject({ title: "Fix mobile login" });
- });
- });
- type TestSessionStore = ReturnType<typeof createSqliteSessionStore>;
- async function saveUserTextMessage(
- store: TestSessionStore,
- sessionId: SessionId,
- messageId: MessageId,
- text: string,
- created: number,
- ) {
- await store.saveMessage({
- id: messageId,
- sessionID: sessionId,
- role: "user",
- time: { created },
- agent: "zcode-agent",
- model: {
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4-air" as ModelId,
- },
- tools: {},
- });
- await saveTextPart(store, sessionId, messageId, text, created);
- }
- async function saveSyntheticForkNotice(
- store: TestSessionStore,
- sessionId: SessionId,
- messageId: MessageId,
- created: number,
- ) {
- const metadata = {
- forkContext: {
- kind: "session_fork",
- parentSessionId: "sess_parent",
- targetMessageId: "msg_assistant_1",
- },
- source: "fork",
- visibility: "user-visible",
- };
- await store.saveMessage({
- id: messageId,
- sessionID: sessionId,
- role: "user",
- time: { created },
- agent: "zcode-agent",
- metadata,
- model: {
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4-air" as ModelId,
- },
- source: "fork",
- synthetic: true,
- tools: {},
- visibility: "user-visible",
- });
- await saveTextPart(
- store,
- sessionId,
- messageId,
- "<system-reminder>\nThis session was forked from a previous session message.\n</system-reminder>",
- created,
- {
- metadata,
- synthetic: true,
- },
- );
- }
- async function saveCompactSummary(
- store: TestSessionStore,
- sessionId: SessionId,
- messageId: MessageId,
- created: number,
- ) {
- await store.saveMessage({
- id: messageId,
- sessionID: sessionId,
- role: "user",
- time: { created },
- agent: "zcode-agent",
- model: {
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4-air" as ModelId,
- },
- summary: {
- body: "历史摘要",
- diffs: [],
- title: "Compact summary",
- },
- tools: {},
- });
- await saveTextPart(store, sessionId, messageId, "compact summary context", created, {
- synthetic: true,
- });
- await store.savePart({
- id: `${messageId}_compaction` as MessagePart["id"],
- sessionID: sessionId,
- messageID: messageId,
- type: "compaction",
- auto: false,
- trigger: "manual",
- phase: "standalone_turn",
- compactReason: "user_requested",
- operationId: "cmp_test",
- } as MessagePart);
- }
- async function saveAssistantTextMessage(
- store: TestSessionStore,
- sessionId: SessionId,
- messageId: MessageId,
- parentMessageId: MessageId,
- text: string,
- created: number,
- ) {
- await store.saveMessage({
- id: messageId,
- sessionID: sessionId,
- role: "assistant",
- time: { created, completed: created },
- parentID: parentMessageId,
- providerId: "glm" as ModelProviderId,
- modelId: "glm-4-air" as ModelId,
- mode: "build",
- agent: "zcode-agent",
- path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
- cost: 0,
- tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
- });
- await saveTextPart(store, sessionId, messageId, text, created);
- }
- async function saveTextPart(
- store: TestSessionStore,
- sessionId: SessionId,
- messageId: MessageId,
- text: string,
- created: number,
- options: Pick<MessagePart, "metadata" | "synthetic"> = {},
- ) {
- await store.savePart({
- id: `${messageId}_text` as MessagePart["id"],
- sessionID: sessionId,
- messageID: messageId,
- type: "text",
- text,
- time: { start: created, end: created },
- ...options,
- });
- }
- function messageTexts(
- messages: ReadonlyArray<{ parts: ReadonlyArray<{ text?: string; type: string }> }>,
- ) {
- return messages.map((message) =>
- message.parts
- .filter((part) => part.type === "text")
- .map((part) => part.text ?? "")
- .join(""),
- );
- }
- async function requestResult(server: ZCodeProtocolAgentServer, message: ZCodeProtocolMessage) {
- const response = await server.handleMessage(message);
- if (!response || !("result" in response)) {
- throw new Error(`Expected protocol success response: ${JSON.stringify(response)}`);
- }
- return response.result;
- }
- function setTestNotificationSink(
- server: ZCodeProtocolAgentServer,
- sink: Parameters<ZCodeProtocolAgentServer["setNotificationSink"]>[0],
- ): void {
- server.setNotificationSink((message) => {
- if (
- "id" in message &&
- message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences
- ) {
- void server.handleMessage({
- id: message.id,
- result: { nativeSearchEnhancementsEnabled: true, memoryEnabled: true },
- });
- return;
- }
- sink(message);
- });
- }
- function attachSessionRuntimePreferencesResponder(
- server: ZCodeProtocolAgentServer,
- resolvePreferences: (scope: "runtime-materialization" | "user-execution") => {
- nativeSearchEnhancementsEnabled: boolean;
- memoryEnabled?: boolean;
- subagentRuntimeConfigEnabled?: boolean;
- modelContextBudgetStrategy?: "legacy" | "preflight-v1";
- integratedTerminalShell?:
- | {
- mode: "auto";
- }
- | {
- mode: "shell";
- dialect: "git-bash" | "cmd";
- id: string;
- label: string;
- path: string;
- };
- },
- ): ZCodeProtocolMessage[] {
- const requests: ZCodeProtocolMessage[] = [];
- server.setNotificationSink((message) => {
- if (
- "id" in message &&
- message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences
- ) {
- requests.push(message);
- const scope = (message.params as { scope: "runtime-materialization" | "user-execution" })
- .scope;
- void server.handleMessage({
- id: message.id,
- result: resolvePreferences(scope),
- });
- }
- });
- return requests;
- }
- interface RecordedLog {
- context: Record<string, unknown>;
- level: "debug" | "error" | "info" | "warn";
- message: string;
- }
- function createProtocolTestLoggerFactory(logs: RecordedLog[]): LoggerFactory {
- const loggerFor = (baseContext: LogContext = {}): Logger => ({
- child(childContext) {
- return loggerFor({ ...baseContext, ...childContext });
- },
- debug(message, logContext) {
- recordLog(logs, "debug", message, baseContext, logContext);
- },
- error(message, _error, logContext) {
- recordLog(logs, "error", message, baseContext, logContext);
- },
- info(message, logContext) {
- recordLog(logs, "info", message, baseContext, logContext);
- },
- warn(message, logContext) {
- recordLog(logs, "warn", message, baseContext, logContext);
- },
- });
- return {
- createLogger: () => loggerFor(),
- setLevel: () => {},
- withContext: (context) => loggerFor(context),
- };
- }
- function recordLog(
- logs: RecordedLog[],
- level: RecordedLog["level"],
- message: string,
- baseContext: LogContext,
- logContext?: LogContext,
- ): void {
- logs.push({
- level,
- message,
- context: { ...baseContext, ...logContext },
- });
- }
- function createProtocolListMcpPort(connectedConfigs: Record<string, McpServerConfig>[]): McpPort {
- const statuses: Awaited<ReturnType<McpPort["status"]>> = {};
- return {
- async callTool() {
- return { content: [] };
- },
- async close() {},
- async connectConfiguredServers(servers) {
- connectedConfigs.push(servers);
- for (const [name, config] of Object.entries(servers)) {
- statuses[name] = {
- status: config.enabled === false ? "disabled" : "connected",
- transport: config.type,
- toolCount: config.enabled === false ? 0 : 3,
- updatedAt: new Date(1).toISOString(),
- };
- }
- return {
- statuses,
- tools: [],
- };
- },
- async connectServer(name, config) {
- const status = {
- status: "connected" as const,
- transport: config.type,
- toolCount: 3,
- updatedAt: new Date(1).toISOString(),
- };
- statuses[name] = status;
- return status;
- },
- async disconnectServer(name) {
- const status = statuses[name];
- delete statuses[name];
- return status;
- },
- async listTools() {
- return [];
- },
- async status() {
- return statuses;
- },
- };
- }
- function createProtocolReplaceMcpPort(
- connectedConfigs: Record<string, McpServerConfig>[],
- disconnectedNames: string[],
- initialStatuses: Awaited<ReturnType<McpPort["status"]>>,
- ): McpPort {
- const statuses: Awaited<ReturnType<McpPort["status"]>> = { ...initialStatuses };
- return {
- async callTool() {
- return { content: [] };
- },
- async close() {},
- async connectConfiguredServers(servers) {
- connectedConfigs.push(servers);
- for (const name of Object.keys(statuses)) {
- if (!(name in servers)) {
- disconnectedNames.push(name);
- delete statuses[name];
- }
- }
- for (const [name, config] of Object.entries(servers)) {
- statuses[name] = {
- status: config.enabled === false ? "disabled" : "connected",
- transport: config.type,
- toolCount: config.enabled === false ? 0 : 3,
- updatedAt: new Date(2).toISOString(),
- };
- }
- return {
- statuses,
- tools: [],
- };
- },
- async connectServer(name, config) {
- const status = {
- status: "connected" as const,
- transport: config.type,
- toolCount: 3,
- updatedAt: new Date(2).toISOString(),
- };
- statuses[name] = status;
- return status;
- },
- async disconnectServer(name) {
- disconnectedNames.push(name);
- const status = statuses[name];
- delete statuses[name];
- return status;
- },
- async listTools() {
- return [];
- },
- async status() {
- return statuses;
- },
- };
- }
- function createProtocolPendingAuthorizationMcpPort(
- connectedConfigs: Record<string, McpServerConfig>[],
- onConnectWaiter: (resolve: () => void) => void,
- ): McpPort {
- const statuses: Awaited<ReturnType<McpPort["status"]>> = {};
- return {
- async callTool() {
- return { content: [] };
- },
- async close() {},
- async connectConfiguredServers(servers) {
- connectedConfigs.push(servers);
- statuses.notion = {
- authorization: {
- authorizationUrl: "https://auth.example.test/authorize?state=state_test",
- startedAt: new Date(1).toISOString(),
- type: "oauth_authorization_code",
- },
- status: "connecting",
- transport: "http",
- toolCount: 0,
- updatedAt: new Date(1).toISOString(),
- };
- await new Promise<void>((resolve) => {
- onConnectWaiter(resolve);
- });
- statuses.notion = {
- status: "connected",
- transport: "http",
- toolCount: 3,
- updatedAt: new Date(2).toISOString(),
- };
- return {
- statuses,
- tools: [],
- };
- },
- async connectServer(name, config) {
- const status = {
- status: "connecting" as const,
- transport: config.type,
- toolCount: 0,
- updatedAt: new Date(1).toISOString(),
- };
- statuses[name] = status;
- return status;
- },
- async disconnectServer(name) {
- const status = statuses[name];
- delete statuses[name];
- return status;
- },
- async listTools() {
- return [];
- },
- async status() {
- return statuses;
- },
- };
- }
- type ShellInitializationCandidate = Parameters<
- ZCodeApp["runtime"]["initializeSessionShellEnvironmentIfNeeded"]
- >[0];
- function resolveShellInitializationCandidate(
- candidate: ShellInitializationCandidate,
- ): ExecutionShellSelection {
- return typeof candidate === "function" ? candidate() : candidate;
- }
- function createShellRecordingFakeApp(
- options: ZCodeAppOptions,
- shellInitializations: unknown[],
- createdAppOptions?: ZCodeAppOptions[],
- ): ZCodeApp {
- createdAppOptions?.push(options);
- const app = createFakeApp(options);
- let effectiveShellSelection = options.runtimeConfig?.bashShellSelection;
- let shellInitialized = effectiveShellSelection !== undefined;
- let shellInitializationPromise: Promise<void> | undefined;
- const recordShellInitialization = (selection: ShellInitializationCandidate) => {
- if (shellInitialized) {
- return false;
- }
- const resolvedSelection = resolveShellInitializationCandidate(selection);
- effectiveShellSelection = resolvedSelection;
- shellInitialized = true;
- shellInitializations.push(resolvedSelection);
- return true;
- };
- const initializeFromStartupPreferences = async () => {
- if (shellInitialized) {
- return;
- }
- shellInitializationPromise ??= (async () => {
- const selection = await options.resolveInitialBashShellSelection?.();
- if (selection) {
- recordShellInitialization(selection);
- }
- })();
- await shellInitializationPromise;
- };
- return {
- ...app,
- resume: async (resumeOptions) => {
- await initializeFromStartupPreferences();
- return app.resume(resumeOptions);
- },
- runtime: {
- ...app.runtime,
- getSessionShellSelection: () => effectiveShellSelection,
- initializeSessionShellEnvironmentIfNeeded: recordShellInitialization,
- } as never,
- sendInput: async (input, sendOptions) => {
- await initializeFromStartupPreferences();
- return app.sendInput(input, sendOptions);
- },
- };
- }
|