| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318 |
- 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,
- zcodeProviderRefreshRegistryResultSchema,
- 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,
- ZCodeProtocolSessionRecord,
- } 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]);
- 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]);
- 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("keeps project plugin roots and untrusted project MCP disconnected during refresh", 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);
- // 旧夹具仍期待项目配置自动加载插件、启动 MCP;当前合同要求用户安装与工作区信任。
- expect(connectedConfigs[0]?.["plugin:status-plugin:plugin-live"]).toBeUndefined();
- expect(connectedConfigs[0]?.["project-only"]).toBeUndefined();
- expect(result).toMatchObject({
- statuses: {
- "project-only": {
- status: "untrusted",
- toolCount: 0,
- 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("does not read or disconnect another workspace MCP lease 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).toHaveLength(0);
- // 没有为此 workspace 取得设置 lease 时,不能把原始端口中其他 owner 的连接态投过来。
- expect((result as { statuses: Record<string, unknown> }).statuses.everything).toBeUndefined();
- expect(result).toMatchObject({
- statuses: {
- "plugin:canva:canva": {
- status: "disconnected",
- 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 = await 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("accepts an assigned fresh ID and rejects replacement of the existing runtime", async () => {
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) => createFakeApp(options),
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const params = { workspace, sessionId: "host-assigned-session" };
- const first = await server.handleMessage({
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params,
- });
- expect(first).toHaveProperty("result.session.sessionId", params.sessionId);
- const again = await server.handleMessage({
- id: 2,
- method: zcodeProtocolMethods.sessionCreate,
- params,
- });
- expect(again).toMatchObject({ error: { code: -32602, message: "sessionId already exists" } });
- });
- it("rejects concurrent creation of the same assigned ID while materializing", async () => {
- let release!: () => void;
- let started!: () => void;
- const entered = new Promise<void>((resolve) => {
- started = resolve;
- });
- const gate = new Promise<void>((resolve) => {
- release = resolve;
- });
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: async (options) => {
- started();
- await gate;
- return createFakeApp(options);
- },
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const params = { workspace, sessionId: "concurrent-create" };
- const first = server.handleMessage({
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params,
- });
- await entered;
- const second = await server.handleMessage({
- id: 2,
- method: zcodeProtocolMethods.sessionCreate,
- params,
- });
- release();
- expect(second).toMatchObject({ error: { code: -32602, message: "sessionId already exists" } });
- expect(await first).toHaveProperty("result.session.sessionId", params.sessionId);
- });
- 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 = await 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);
- 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("returns per-request auth and distinct IDs for concurrent runtime header refreshes", 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",
- "CronPauseSelf",
- ]);
- }
- });
- it("reads materialization preferences once per root runtime and keeps active resumes stable", async () => {
- const createdAppOptions: ZCodeAppOptions[] = [];
- let nativeSearchEnabled = false;
- let toolSearchMode: "off" | "local" = "off";
- 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,
- toolSearchMode,
- memoryEnabled,
- modelContextBudgetStrategy,
- }));
- const disabled = zcodeSessionStateSnapshotSchema.parse(
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionCreate,
- params: { workspace },
- }),
- );
- nativeSearchEnabled = true;
- toolSearchMode = "local";
- 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?.toolSearch).toEqual({ mode: "off" });
- expect(createdAppOptions[1]?.runtimeConfig?.toolSearch).toEqual({ mode: "local" });
- 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 = await 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,
- toolSearchMode: "auto",
- memoryEnabled: false,
- modelContextBudgetStrategy: "preflight-v1",
- }));
- await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.sessionResume,
- params: { sessionId },
- });
- expect(preferenceRequests).toHaveLength(1);
- expect(createdAppOptions[0]?.runtimeConfig?.toolSearch).toEqual({ mode: "auto" });
- 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();
- }
- });
- // 远端 Host 同样持有子智能体快照:是否接入只看 Host 声明的能力,不按 workspace 身份排除远程。
- it.each([
- undefined,
- "remote:ssh:example.test:22:dev:/workspace/app",
- "remote:server:example-server:/workspace/app",
- ])(
- "injects pull access into advertised local and remote 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: {
- kind: "ready",
- // Host 返回已解析快照;磁盘文档及启停状态不再跨这个协议边界。
- profiles: [
- {
- name: "reviewer",
- description: "review",
- path: "/agents/reviewer.md",
- source: "user",
- systemPrompt: content,
- },
- ],
- 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;
- expect(reader).toBeTypeOf("function");
- const input = {
- signal: new AbortController().signal,
- traceContext: { traceId: createTraceId(), sessionId: options[0]!.sessionId! },
- };
- expect((await reader!(input)).profiles[0]?.systemPrompt).toBe("old");
- content = "new";
- expect((await reader!(input)).profiles[0]?.systemPrompt).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("stops every active Session runtime when the owning protocol transport disconnects", () => {
- const app = createFakeApp();
- const stopActiveForegroundExecution = vi.fn(() => ({
- foregroundExecutionId: "foreground-test",
- kind: "stopped" as const,
- }));
- app.runtime.stopActiveForegroundExecution = stopActiveForegroundExecution;
- const activeAbortController = new AbortController();
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: () => app,
- cwd: workspace.workspacePath,
- version: "test-version",
- });
- const context = (server as unknown as { context: ZCodeProtocolAgentServerContext }).context;
- context.sessions.set("sess_active", {
- activeAbortController,
- app,
- } as unknown as ZCodeProtocolSessionRecord);
- const disconnectError = new Error("Core owner disconnected");
- server.disconnectClient(disconnectError);
- expect(stopActiveForegroundExecution).toHaveBeenCalledOnce();
- expect(stopActiveForegroundExecution).toHaveBeenCalledWith({
- reason: "ZCode Protocol owner disconnected",
- });
- expect(activeAbortController.signal.aborted).toBe(true);
- expect(activeAbortController.signal.reason).toBe(disconnectError);
- });
- 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);
- // 新生命周期合同在 create 时发布 starting/ready;模型状态断言只读取自己的通知域。
- expect(
- notifications.filter((notification) => notification.method === "state.updated"),
- ).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 = await 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 = await 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.get("account:zai-individual-coding-plan")?.toJSON()).toEqual({
- access: { type: "zhipu-account", entitled: true },
- builtinModelIds: ["GLM-5.2"],
- });
- });
- it("在执行前刷新 Worker 自己的 Provider Registry,不接收 Desktop 快照", async () => {
- const refreshProviderRegistry = vi.fn(async (reason: string) => {
- expect(reason).toBe("before-turn");
- });
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: () => createFakeApp(),
- cwd: workspace.workspacePath,
- refreshProviderRegistry,
- });
- const result = await requestResult(server, {
- id: 1,
- method: zcodeProtocolMethods.providerRefreshRegistry,
- params: { reason: "before-turn" },
- });
- expect(zcodeProviderRefreshRegistryResultSchema.parse(result)).toEqual({
- refreshed: true,
- });
- expect(refreshProviderRegistry).toHaveBeenCalledTimes(1);
- });
- 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("legacy session/send 在 busy 入队时把显式 automation 身份交给 Core admission", async () => {
- let receivedAutomationId: string | undefined;
- let receivedToolDisallowlist: readonly string[] | undefined;
- let resolveSendInputStarted!: () => void;
- const sendInputStarted = new Promise<void>((resolve) => {
- resolveSendInputStarted = resolve;
- });
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createFakeApp(options, {
- sendInput: async (_input, sendOptions) => {
- receivedAutomationId = sendOptions?.automationId;
- receivedToolDisallowlist = sendOptions?.toolDisallowlist;
- resolveSendInputStarted();
- return {
- kind: "queued",
- pendingInputId: "pending-automation-queued",
- queueLength: 1,
- turnId: "turn-busy" as never,
- };
- },
- }),
- 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: "automation busy prompt",
- automationId: "automation-queued",
- inputId: "automation-queued:scheduled:run-1",
- expectedRevision: created.runtime.stateRevision,
- },
- });
- await sendInputStarted;
- expect(receivedAutomationId).toBe("automation-queued");
- expect(receivedToolDisallowlist).toEqual(["CronCreate"]);
- });
- it("does not restore automation identity from a caller-controlled inputId", async () => {
- let receivedAutomationId: string | undefined;
- let receivedToolDisallowlist: readonly string[] | undefined;
- let resolveSendInputStarted!: () => void;
- const sendInputStarted = new Promise<void>((resolve) => {
- resolveSendInputStarted = resolve;
- });
- const server = new ZCodeProtocolAgentServer({
- createZCodeApp: (options) =>
- createFakeApp(options, {
- sendInput: async (_input, options) => {
- receivedAutomationId = options?.automationId;
- receivedToolDisallowlist = options?.toolDisallowlist;
- resolveSendInputStarted();
- 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: "ordinary prompt",
- inputId: "automation-other-task:manual:forged-run",
- expectedRevision: created.runtime.stateRevision,
- },
- });
- await sendInputStarted;
- expect(receivedAutomationId).toBeUndefined();
- expect(receivedToolDisallowlist).toBeUndefined();
- });
- 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 = await 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,
- });
- let toolSearchMode: "local" | "off" = "local";
- const preferenceRequests = attachSessionRuntimePreferencesResponder(server, () => ({
- nativeSearchEnhancementsEnabled: false,
- toolSearchMode,
- 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",
- });
- toolSearchMode = "off";
- 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?.toolSearch).toEqual({ mode: "local" });
- 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?.toolSearch).toEqual({ mode: "local" });
- 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 = await 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,
- });
- // 两次 fork 必须像真实 core 一样生成不同身份,否则第二次会命中已初始化实例。
- const forkedSessionId = `sess_forked_${forkTargets.length}` 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 = Awaited<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;
- toolSearchMode?: "auto" | "local" | "off";
- 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);
- },
- };
- }
|