zcode-protocol.test.ts 271 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372
  1. import {
  2. workspace,
  3. requestResult,
  4. attachSessionRuntimePreferencesResponder,
  5. createShellRecordingFakeApp,
  6. } from "./zcode-protocol-fixture.js";
  7. import { createHash } from "node:crypto";
  8. import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  9. import { tmpdir } from "node:os";
  10. import { join } from "node:path";
  11. import { PassThrough } from "node:stream";
  12. import { describe, expect, it, vi } from "vitest";
  13. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  14. import {
  15. BUILTIN_MODEL_PROVIDER_IDS,
  16. elideSessionSnapshotForIndex,
  17. ZCODE_SESSION_RUNTIME_PREFERENCES_REQUEST_TIMEOUT_MS,
  18. zcodeProtocolMethods,
  19. zcodeMessagePartSchema,
  20. zcodeSessionCancelBackgroundTaskResultSchema,
  21. zcodeSessionCompactResultSchema,
  22. zcodeSessionEventsResultSchema,
  23. zcodeSessionEventSchema,
  24. zcodeSessionForkResultSchema,
  25. zcodeSessionGoalResultSchema,
  26. zcodeSessionListResultSchema,
  27. zcodeSessionStateSnapshotSchema,
  28. zcodeSessionSubscribeResultSchema,
  29. zcodeProviderTestModelConnectivityResultSchema,
  30. zcodeProviderRefreshRegistryResultSchema,
  31. zcodeWorkspaceGenerateTextResultSchema,
  32. zcodeWorkspaceCancelGenerateTextResultSchema,
  33. zcodeWorkspacePresentationSchema,
  34. zcodeWorkspaceUpdateInteractionPreferencesResultSchema,
  35. type ZCodeProtocolMessage,
  36. type ZCodeProtocolNotification,
  37. } from "@zcode/shared";
  38. import {
  39. V4_METHODS,
  40. V4_NOTIFICATIONS,
  41. conversationTopicFrameSchema,
  42. reassembleTopicWireFrames,
  43. routedTopicFrameSchema,
  44. routedTopicWireFrameSchema,
  45. conversationTopic,
  46. sessionsIndexTopic,
  47. v4ConversationUsageResultSchema,
  48. v4ConversationSubscribeResultSchema,
  49. v4ConversationResyncResultSchema,
  50. v4UsageStatsResultSchema,
  51. workspaceConfigTopic,
  52. } from "@zcode/shared/zcode-protocol-v4";
  53. import {
  54. SessionEventType,
  55. createTraceId,
  56. type BackgroundTaskInfo,
  57. type MessageId,
  58. type MessagePart,
  59. type ModelId,
  60. type ModelProviderId,
  61. type MessageWithParts,
  62. type ProjectId,
  63. type SessionEvent,
  64. type SessionId,
  65. type LogContext,
  66. type Logger,
  67. type LoggerFactory,
  68. type McpPort,
  69. type McpServerConfig,
  70. } from "@zcode/contracts";
  71. import { InMemoryWorkspaceHookPolicyProvider } from "@zcode/core";
  72. import {
  73. ModelConfig,
  74. ModelOptionSpecsConfig,
  75. ModelPropertiesConfig,
  76. ProviderRegistry,
  77. type Provider,
  78. } from "@zcode/provider";
  79. import { buildRuntimeUserEntriesFromTurn } from "../../core/src/runtime/helpers/conversation.js";
  80. import type { SendInputOptions } from "../src/app/types.js";
  81. import { ZCodeProtocolAgentServer } from "../src/zcode-protocol/server.js";
  82. import { ZCodeProtocolNdjsonConnection } from "../src/zcode-protocol/transport.js";
  83. import { shouldCloseSessionForExpectedPersistence } from "../src/zcode-protocol/server-operations.js";
  84. import type {
  85. ZCodeProtocolAgentServerContext,
  86. ZCodeProtocolSessionRecord,
  87. } from "../src/zcode-protocol/server-types.js";
  88. import {
  89. buildSessionSnapshot,
  90. mapMessageWithParts,
  91. mapSessionEvent,
  92. mapSessionEvents,
  93. mapSessionSettings,
  94. } from "../src/zcode-protocol/mapper.js";
  95. import { createWorkspaceZCodeApp } from "../src/zcode-protocol/workspace-model-runtime.js";
  96. import { onSessionEvent } from "../src/zcode-protocol/server-operations.js";
  97. import type { ZCodeApp, ZCodeAppOptions } from "../src/app/types.js";
  98. import { answerReplyLanguageRequest } from "./helpers/fake-host-requests.js";
  99. import { createFakeApp } from "./helpers/fake-zcode-app.js";
  100. import { createApiKeyProviderConfig } from "./provider-config-fixtures.js";
  101. function currentOnlyModelOption() {
  102. return {
  103. ref: { providerId: "provider", modelId: "current-model" },
  104. label: "current-model",
  105. providerLabel: "provider",
  106. properties: {
  107. inputFormat: {
  108. supportsText: true,
  109. supportsImage: false,
  110. supportsVideo: false,
  111. supportsAudio: false,
  112. supportsPdf: false,
  113. },
  114. outputFormat: { supportsText: true },
  115. },
  116. } as const;
  117. }
  118. function createProtocolTestProviderRegistry(): ProviderRegistry {
  119. const modelConfig = new ModelConfig({
  120. properties: new ModelPropertiesConfig({
  121. requiresMfjsToolSchema: false,
  122. contextWindow: 128_000,
  123. inputFormat: {
  124. supportsText: true,
  125. supportsImage: false,
  126. supportsVideo: false,
  127. supportsAudio: false,
  128. supportsPdf: false,
  129. },
  130. outputFormat: { supportsText: true },
  131. supportsToolCall: true,
  132. supportsJsonSchemaOutput: true,
  133. supportsNativeWebSearch: false,
  134. supportsMidConversationSystem: false,
  135. }),
  136. optionSpecs: new ModelOptionSpecsConfig({
  137. maxOutputTokens: {
  138. max: 32_000,
  139. map: '{"max_completion_tokens":maxOutputTokens}',
  140. },
  141. }),
  142. });
  143. const provider: Provider = {
  144. providerId: "custom-openai",
  145. config: createApiKeyProviderConfig({
  146. apiFormat: "openai-chat-completions",
  147. apiKey: "sk-test",
  148. baseURL: "https://api.example.com/v1",
  149. models: ["agent-model", "backup-model"],
  150. }),
  151. models: [
  152. { modelId: "agent-model", config: modelConfig },
  153. { modelId: "backup-model", config: modelConfig },
  154. ],
  155. };
  156. return new ProviderRegistry([provider]);
  157. }
  158. describe("mapSessionSettings", () => {
  159. it("projects the current model default thought level separately from current", async () => {
  160. const app = createFakeApp(undefined, {
  161. getDefaultThoughtLevel: () => "max",
  162. getThoughtLevel: () => undefined,
  163. listThoughtLevels: () => ["high", "max"],
  164. });
  165. const settings = await mapSessionSettings(app);
  166. expect(settings.thoughtLevel).toMatchObject({
  167. available: [
  168. { value: "high", label: "high" },
  169. { value: "max", label: "max" },
  170. ],
  171. defaultLevel: "max",
  172. enabled: true,
  173. });
  174. expect(settings.thoughtLevel.current).toBeUndefined();
  175. });
  176. });
  177. describe("conditional session close", () => {
  178. it("only closes when the current persistence still matches the caller expectation", () => {
  179. expect(shouldCloseSessionForExpectedPersistence("deferred", "deferred")).toBe(true);
  180. expect(shouldCloseSessionForExpectedPersistence("immediate", "deferred")).toBe(false);
  181. expect(shouldCloseSessionForExpectedPersistence("immediate")).toBe(true);
  182. });
  183. });
  184. describe("ZCodeProtocolAgentServer", () => {
  185. it("所有 Entry 都不再接受旧 Workspace Provider 写协议", async () => {
  186. const server = new ZCodeProtocolAgentServer({
  187. createZCodeApp: (options) => createFakeApp(options),
  188. cwd: workspace.workspacePath,
  189. version: "test-version",
  190. });
  191. for (const [index, method] of [
  192. "workspace/updateProviderRegistry",
  193. "workspace/upsertModelProvider",
  194. "workspace/removeModelProvider",
  195. ].entries()) {
  196. await expect(
  197. server.handleMessage({
  198. id: `retired-provider-writer-${index}`,
  199. method,
  200. params: {},
  201. } as ZCodeProtocolMessage),
  202. ).resolves.toMatchObject({
  203. id: `retired-provider-writer-${index}`,
  204. error: { code: -32601 },
  205. });
  206. }
  207. });
  208. it("uses the Host managed policy for no-session Settings pretrust", async () => {
  209. const policyProvider = new InMemoryWorkspaceHookPolicyProvider({
  210. mode: "deny",
  211. reason: "managed",
  212. policyRevision: "test:deny:v1",
  213. });
  214. const server = new ZCodeProtocolAgentServer({
  215. createZCodeApp: (options) => createFakeApp(options),
  216. cwd: workspace.workspacePath,
  217. version: "test-version",
  218. workspaceHookPolicyProvider: policyProvider,
  219. });
  220. await expect(
  221. requestResult(server, {
  222. id: "workspace-hook-trust-denied",
  223. method: zcodeProtocolMethods.workspaceHookTrustGrant,
  224. params: {
  225. workspace,
  226. bundleDigest: "b".repeat(64),
  227. hookDeclarationDigest: "a".repeat(64),
  228. },
  229. }),
  230. ).resolves.toEqual({
  231. accepted: false,
  232. reasonCode: "workspace_hooks_blocked_by_policy",
  233. });
  234. });
  235. it("injects the same Host managed policy provider into session Runtime", async () => {
  236. const policyProvider = new InMemoryWorkspaceHookPolicyProvider({
  237. mode: "user_decides",
  238. policyRevision: "test:user-decides:v1",
  239. });
  240. let createdOptions: ZCodeAppOptions | undefined;
  241. const server = new ZCodeProtocolAgentServer({
  242. createZCodeApp: (options) => {
  243. createdOptions = options;
  244. return createFakeApp(options);
  245. },
  246. cwd: workspace.workspacePath,
  247. version: "test-version",
  248. workspaceHookPolicyProvider: policyProvider,
  249. });
  250. await requestResult(server, {
  251. id: "session-with-shared-hook-policy",
  252. method: zcodeProtocolMethods.sessionCreate,
  253. params: { workspace },
  254. });
  255. expect(createdOptions?.workspaceHookPolicyProvider).toBe(policyProvider);
  256. });
  257. it("applies strict workspace interaction preferences without creating a session", async () => {
  258. const server = new ZCodeProtocolAgentServer({
  259. createZCodeApp: (options) => createFakeApp(options),
  260. cwd: workspace.workspacePath,
  261. version: "test-version",
  262. });
  263. const result = zcodeWorkspaceUpdateInteractionPreferencesResultSchema.parse(
  264. await requestResult(server, {
  265. id: 1,
  266. method: zcodeProtocolMethods.workspaceUpdateInteractionPreferences,
  267. params: {
  268. workspace,
  269. preferences: {
  270. askUserQuestionAutoResolutionEnabled: false,
  271. },
  272. },
  273. }),
  274. );
  275. expect(result).toEqual({
  276. workspace,
  277. askUserQuestionAutoResolutionEnabled: false,
  278. snoozedInteractionCount: 0,
  279. });
  280. });
  281. it("maps core tool events into typed ZCode session event payloads", () => {
  282. const mapped = zcodeSessionEventSchema.parse(
  283. mapSessionEvent({
  284. id: "evt_tool_1" as SessionEvent["id"],
  285. payload: {
  286. duration: 12,
  287. result: {
  288. content: "done",
  289. success: true,
  290. },
  291. toolCallId: "tool_1",
  292. toolName: "Edit",
  293. },
  294. sequenceNumber: 3,
  295. sessionId: "sess_1" as SessionId,
  296. timestamp: new Date(4),
  297. traceId: "trace_1" as SessionEvent["traceId"],
  298. type: SessionEventType.ToolCallResult,
  299. } satisfies SessionEvent),
  300. );
  301. expect(mapped.type).toBe("tool.updated");
  302. expect(mapped.payload.kind).toBe("result");
  303. });
  304. it("maps core permission denied events as denied protocol permission resolutions", () => {
  305. const mapped = zcodeSessionEventSchema.parse(
  306. mapSessionEvent({
  307. id: "evt_permission_denied" as SessionEvent["id"],
  308. payload: {
  309. toolCallId: "tool_write_denied",
  310. toolName: "Write",
  311. reason: "Plan mode only allows read-only, non-destructive tools",
  312. inputSummary: {
  313. file_path: "/tmp/denied.txt",
  314. },
  315. },
  316. sequenceNumber: 4,
  317. sessionId: "sess_1" as SessionId,
  318. timestamp: new Date(5),
  319. traceId: "trace_permission_denied" as SessionEvent["traceId"],
  320. type: SessionEventType.PermissionDenied,
  321. } satisfies SessionEvent),
  322. );
  323. expect(mapped.type).toBe("permission.resolved");
  324. expect(mapped.payload).toMatchObject({
  325. decision: "deny",
  326. reason: "Plan mode only allows read-only, non-destructive tools",
  327. toolCallId: "tool_write_denied",
  328. toolName: "Write",
  329. });
  330. });
  331. it("does not expose compact internal timeline text through the protocol", () => {
  332. const internalSummary =
  333. "This session is being continued from a previous conversation that was compacted.";
  334. const mapped = mapMessageWithParts({
  335. info: {
  336. id: "msg_compact" as MessageId,
  337. sessionID: "sess_1" as SessionId,
  338. role: "assistant",
  339. parentID: "msg_user" as MessageId,
  340. time: { created: 1, completed: 2 },
  341. agent: "zcode-agent",
  342. providerId: "glm" as ModelProviderId,
  343. modelId: "glm-4.6" as ModelId,
  344. cost: 0,
  345. },
  346. parts: [
  347. {
  348. id: "part_compact",
  349. sessionID: "sess_1",
  350. messageID: "msg_compact",
  351. type: "compaction",
  352. auto: true,
  353. summaryMessageId: "msg_summary",
  354. timelineText: internalSummary,
  355. timelineStatus: "completed",
  356. trigger: "auto",
  357. },
  358. ],
  359. } as unknown as MessageWithParts);
  360. expect(mapped.parts[0]).not.toHaveProperty("timelineText");
  361. expect(zcodeMessagePartSchema.parse(mapped.parts[0])).not.toHaveProperty("timelineText");
  362. expect(JSON.stringify(mapped)).not.toContain(internalSummary);
  363. });
  364. it("does not expose read-state metadata through protocol tool parts", () => {
  365. const fileContent = "secret file content that should stay internal";
  366. const mapped = mapMessageWithParts({
  367. info: {
  368. id: "msg_read" as MessageId,
  369. sessionID: "sess_1" as SessionId,
  370. role: "assistant",
  371. parentID: "msg_user" as MessageId,
  372. time: { created: 1, completed: 2 },
  373. agent: "zcode-agent",
  374. providerId: "glm" as ModelProviderId,
  375. modelId: "glm-4.6" as ModelId,
  376. cost: 0,
  377. },
  378. parts: [
  379. {
  380. callID: "tool_read_1",
  381. id: "part_read",
  382. messageID: "msg_read",
  383. sessionID: "sess_1",
  384. state: {
  385. input: { file_path: "/workspace/app/secret.txt" },
  386. metadata: {
  387. display: {
  388. additions: 0,
  389. deletions: 0,
  390. kind: "file_diff",
  391. structuredPatch: [],
  392. },
  393. readFileState: {
  394. content: fileContent,
  395. isPartialView: false,
  396. mtimeMs: 1,
  397. path: "/workspace/app/secret.txt",
  398. readAtMs: 2,
  399. revisionId: "rev-1",
  400. schemaVersion: 1,
  401. sizeBytes: fileContent.length,
  402. tool: "Read",
  403. },
  404. schemaVersion: 1,
  405. },
  406. output: "1\tsecret file content",
  407. status: "completed",
  408. time: { start: 1, end: 2 },
  409. title: "Read",
  410. },
  411. tool: "Read",
  412. type: "tool",
  413. },
  414. ],
  415. } as unknown as MessageWithParts);
  416. const part = zcodeMessagePartSchema.parse(mapped.parts[0]);
  417. if (part.type !== "tool" || part.state.status !== "completed") {
  418. throw new Error("expected completed tool part");
  419. }
  420. expect(part.state.metadata).toMatchObject({
  421. display: {
  422. kind: "file_diff",
  423. },
  424. schemaVersion: 1,
  425. });
  426. expect(part.state.metadata).not.toHaveProperty("readFileState");
  427. expect(JSON.stringify(mapped)).not.toContain(fileContent);
  428. });
  429. it("maps completed tool parts with missing metadata to an empty protocol metadata object", () => {
  430. const mapped = mapMessageWithParts({
  431. info: {
  432. id: "msg_tool_without_metadata" as MessageId,
  433. sessionID: "sess_1" as SessionId,
  434. role: "assistant",
  435. parentID: "msg_user" as MessageId,
  436. time: { created: 1, completed: 2 },
  437. agent: "zcode-agent",
  438. providerId: "glm" as ModelProviderId,
  439. modelId: "glm-4.6" as ModelId,
  440. cost: 0,
  441. },
  442. parts: [
  443. {
  444. callID: "tool_read_without_metadata",
  445. id: "part_read_without_metadata",
  446. messageID: "msg_tool_without_metadata",
  447. sessionID: "sess_1",
  448. state: {
  449. input: { file_path: "/workspace/app/plain.txt" },
  450. output: "1\tplain",
  451. status: "completed",
  452. time: { start: 1, end: 2 },
  453. title: "Read",
  454. },
  455. tool: "Read",
  456. type: "tool",
  457. },
  458. ],
  459. } as unknown as MessageWithParts);
  460. const part = zcodeMessagePartSchema.parse(mapped.parts[0]);
  461. if (part.type !== "tool" || part.state.status !== "completed") {
  462. throw new Error("expected completed tool part");
  463. }
  464. expect(part.state.metadata).toEqual({});
  465. });
  466. it("keeps model request protocol events compact", () => {
  467. const mapped = zcodeSessionEventSchema.parse(
  468. mapSessionEvent({
  469. id: "evt_model_request" as SessionEvent["id"],
  470. payload: {
  471. messages: [
  472. {
  473. role: "user",
  474. content: "large prompt body",
  475. },
  476. ],
  477. providerId: "provider",
  478. modelId: "model",
  479. toolCount: 3,
  480. iteration: 2,
  481. },
  482. sequenceNumber: 4,
  483. sessionId: "sess_1" as SessionId,
  484. timestamp: new Date(5),
  485. traceId: "trace_model_request" as SessionEvent["traceId"],
  486. type: SessionEventType.ModelRequest,
  487. } satisfies SessionEvent),
  488. );
  489. expect(mapped.type).toBe("session.updated");
  490. expect(mapped.payload).toMatchObject({
  491. messageCount: 1,
  492. providerId: "provider",
  493. modelId: "model",
  494. toolCount: 3,
  495. iteration: 2,
  496. });
  497. expect(mapped.payload).not.toHaveProperty("messages");
  498. });
  499. it("maps current-only session settings without enumerating the full model catalog", async () => {
  500. const app = createFakeApp(undefined, {
  501. getModel: () => "provider/current-model",
  502. getCurrentModelOption: () => currentOnlyModelOption(),
  503. getThoughtLevel: () => undefined,
  504. listModels: () => {
  505. throw new Error("listModels should not run for current-only settings");
  506. },
  507. listThoughtLevels: () => [],
  508. });
  509. vi.spyOn(app.runtime, "getSessionModelSelection").mockReturnValue({
  510. providerId: "provider",
  511. modelId: "current-model",
  512. });
  513. const settings = await mapSessionSettings(app, {
  514. modelAvailability: "current",
  515. });
  516. expect(settings.model.available).toEqual([
  517. expect.objectContaining({
  518. label: "current-model",
  519. providerLabel: "provider",
  520. ref: {
  521. modelId: "current-model",
  522. providerId: "provider",
  523. },
  524. properties: currentOnlyModelOption().properties,
  525. }),
  526. ]);
  527. expect(settings.model.current).toEqual({
  528. modelId: "current-model",
  529. providerId: "provider",
  530. });
  531. });
  532. it("preserves current context window in current-only session snapshots without enumerating models", async () => {
  533. const sessionId = "sess_current_context" as SessionId;
  534. const app = createFakeApp(
  535. { sessionId },
  536. {
  537. getModel: () => "provider/current-model",
  538. getCurrentModelOption: () => currentOnlyModelOption(),
  539. getThoughtLevel: () => undefined,
  540. listModels: () => {
  541. throw new Error("listModels should not run for current-only snapshots");
  542. },
  543. listThoughtLevels: () => [],
  544. runtime: {
  545. getSessionModelSelection: () => ({ providerId: "provider", modelId: "current-model" }),
  546. getProjection: async () =>
  547. ({
  548. activeToolCalls: [],
  549. backgroundTasks: [],
  550. contextUsed: 0,
  551. contextWindow: 256_000,
  552. createdAt: new Date(1),
  553. id: sessionId,
  554. mode: "build",
  555. pendingPermissions: [],
  556. pendingSteerInputs: [],
  557. status: "idle",
  558. streamingToolLedger: [],
  559. target: null,
  560. totalTokenCount: 0,
  561. turnCount: 0,
  562. updatedAt: new Date(1),
  563. }) as never,
  564. getActiveTurnInfo: () => undefined,
  565. subscribeEvents: () => () => {},
  566. } as never,
  567. },
  568. );
  569. const snapshot = await buildSessionSnapshot({
  570. app,
  571. eventSeq: 0,
  572. messages: [],
  573. modelAvailability: "current",
  574. stateRevision: 1,
  575. workspace,
  576. });
  577. expect(snapshot.settings.model.available).toEqual([
  578. expect.objectContaining({
  579. contextWindow: 256_000,
  580. ref: {
  581. modelId: "current-model",
  582. providerId: "provider",
  583. },
  584. }),
  585. ]);
  586. });
  587. it("fills the goal first-round title past a SessionStart reminder stored before the prompt", async () => {
  588. // SessionStart hook 的上下文写在首条 prompt 之前;补首轮标题时要跳过这条隐藏提醒。
  589. const sessionId = "sess_goal_title_reminder" as SessionId;
  590. const objective = "Ship the goal title fallback";
  591. const app = createFakeApp(
  592. { sessionId },
  593. {
  594. runtime: {
  595. getSessionModelSelection: () => undefined,
  596. getProjection: async () =>
  597. ({
  598. activeToolCalls: [],
  599. backgroundTasks: [],
  600. contextUsed: 0,
  601. contextWindow: 128_000,
  602. createdAt: new Date(1),
  603. id: sessionId,
  604. mode: "build",
  605. pendingPermissions: [],
  606. pendingSteerInputs: [],
  607. status: "idle",
  608. streamingToolLedger: [],
  609. target: null,
  610. totalTokenCount: 0,
  611. turnCount: 0,
  612. updatedAt: new Date(1),
  613. }) as never,
  614. getActiveTurnInfo: () => undefined,
  615. subscribeEvents: () => () => {},
  616. } as never,
  617. },
  618. );
  619. const userRow = (id: string, created: number, text: string, hidden: boolean) =>
  620. ({
  621. info: {
  622. id,
  623. sessionID: sessionId,
  624. role: "user",
  625. time: { created },
  626. ...(hidden
  627. ? {
  628. synthetic: true,
  629. visibility: "model-only",
  630. semantics: {
  631. origin: "agent_runtime",
  632. kind: "system_reminder",
  633. source: "hook_context",
  634. uiVisibility: "hidden",
  635. providerVisibility: "visible",
  636. transcriptVisibility: "hidden",
  637. },
  638. }
  639. : {}),
  640. },
  641. parts: [{ id: `${id}-part`, sessionID: sessionId, messageID: id, type: "text", text }],
  642. }) as never;
  643. const snapshot = await buildSessionSnapshot({
  644. app,
  645. eventSeq: 0,
  646. messages: [
  647. userRow("msg_reminder", 1_000, "SessionStart hook additional context: ...", true),
  648. userRow("msg_prompt", 1_010, objective, false),
  649. ],
  650. session: { id: sessionId, title: "Goal title", time: { created: 1, updated: 1 } } as never,
  651. stateRevision: 1,
  652. target: {
  653. sessionID: sessionId,
  654. targetID: "target-title",
  655. objective,
  656. summaryTitle: null,
  657. status: "active",
  658. tokenBudget: null,
  659. tokensUsed: 0,
  660. timeUsedSeconds: 0,
  661. time: { created: 1_020, updated: 1_020 },
  662. },
  663. workspace,
  664. });
  665. expect(snapshot.projection.target?.summaryTitle).toBe("Goal title");
  666. });
  667. it("preserves latest main turn context usage breakdown in session snapshots", async () => {
  668. const sessionId = "sess_context_breakdown" as SessionId;
  669. const app = createFakeApp(
  670. { sessionId },
  671. {
  672. runtime: {
  673. getSessionModelSelection: () => undefined,
  674. getProjection: async () =>
  675. ({
  676. activeToolCalls: [],
  677. backgroundTasks: [],
  678. contextUsed: 26_347,
  679. contextWindow: 1_000_000,
  680. createdAt: new Date(1),
  681. id: sessionId,
  682. mode: "build",
  683. pendingPermissions: [],
  684. pendingSteerInputs: [],
  685. status: "idle",
  686. streamingToolLedger: [],
  687. target: null,
  688. totalTokenCount: 0,
  689. turnCount: 0,
  690. updatedAt: new Date(1),
  691. }) as never,
  692. getActiveTurnInfo: () => undefined,
  693. subscribeEvents: () => () => {},
  694. } as never,
  695. },
  696. );
  697. const breakdown = [
  698. { source: "system_tool_schemas" as const, chars: 89_047 },
  699. { source: "mcp_tool_schemas" as const, chars: 43_644 },
  700. { source: "messages" as const, chars: 9_104 },
  701. ];
  702. const snapshot = await buildSessionSnapshot({
  703. app,
  704. eventSeq: 4,
  705. messages: [],
  706. persistedContextUsageBreakdownEvents: [
  707. {
  708. id: "event_context_breakdown",
  709. sessionId,
  710. sequenceNumber: 4,
  711. timestamp: new Date(4),
  712. traceId: "trace_context_breakdown" as never,
  713. type: SessionEventType.ModelComplete,
  714. payload: {
  715. content: "",
  716. contextUsageBreakdown: breakdown,
  717. contextWindow: 1_000_000,
  718. querySource: "main_turn",
  719. stopReason: "stop",
  720. usage: {
  721. inputTokens: 25_913,
  722. outputTokens: 434,
  723. totalTokens: 26_347,
  724. },
  725. },
  726. } as SessionEvent,
  727. ],
  728. stateRevision: 1,
  729. workspace,
  730. });
  731. expect(snapshot.runtime.contextUsage).toEqual({
  732. used: 26_347,
  733. size: 1_000_000,
  734. cost: null,
  735. breakdown,
  736. });
  737. });
  738. it("does not expose the last projected turn as an active runtime turn", async () => {
  739. const sessionId = "sess_completed_projection_turn" as SessionId;
  740. const completedTurnId = "turn_completed_projection";
  741. const app = createFakeApp(
  742. { sessionId },
  743. {
  744. runtime: {
  745. getSessionModelSelection: () => undefined,
  746. getProjection: async () =>
  747. ({
  748. activeToolCalls: [],
  749. backgroundTasks: [],
  750. contextUsed: 0,
  751. contextWindow: 128_000,
  752. createdAt: new Date(1),
  753. currentTurnId: completedTurnId,
  754. id: sessionId,
  755. mode: "build",
  756. pendingPermissions: [],
  757. pendingSteerInputs: [],
  758. status: "idle",
  759. streamingToolLedger: [],
  760. target: null,
  761. totalTokenCount: 0,
  762. turnCount: 1,
  763. updatedAt: new Date(2),
  764. }) as never,
  765. getActiveTurnInfo: () => undefined,
  766. subscribeEvents: () => () => {},
  767. } as never,
  768. },
  769. );
  770. const snapshot = await buildSessionSnapshot({
  771. app,
  772. eventSeq: 4,
  773. messages: [],
  774. stateRevision: 1,
  775. workspace,
  776. });
  777. expect(snapshot.projection.currentTurnId).toBe(completedTurnId);
  778. expect(snapshot.runtime.activeTurnId).toBeUndefined();
  779. expect(snapshot.runtime.activeTurnKind).toBeUndefined();
  780. });
  781. it("maps active turn runtime fields while a session active turn exists", async () => {
  782. const sessionId = "sess_active_runtime_turn" as SessionId;
  783. const activeTurnId = "turn_active_runtime";
  784. const app = createFakeApp(
  785. { sessionId },
  786. {
  787. runtime: {
  788. getSessionModelSelection: () => undefined,
  789. getProjection: async () =>
  790. ({
  791. activeToolCalls: [],
  792. backgroundTasks: [],
  793. contextUsed: 0,
  794. contextWindow: 128_000,
  795. createdAt: new Date(1),
  796. currentTurnId: activeTurnId,
  797. id: sessionId,
  798. mode: "build",
  799. pendingPermissions: [],
  800. pendingSteerInputs: [],
  801. status: "running",
  802. streamingToolLedger: [],
  803. target: null,
  804. totalTokenCount: 0,
  805. turnCount: 1,
  806. updatedAt: new Date(2),
  807. }) as never,
  808. getActiveTurnInfo: () =>
  809. ({
  810. kind: "regular",
  811. queueLength: 0,
  812. steerable: true,
  813. turnId: activeTurnId,
  814. }) as never,
  815. subscribeEvents: () => () => {},
  816. } as never,
  817. },
  818. );
  819. const snapshot = await buildSessionSnapshot({
  820. app,
  821. eventSeq: 4,
  822. messages: [],
  823. stateRevision: 1,
  824. workspace,
  825. });
  826. expect(snapshot.runtime.activeTurnId).toBe(activeTurnId);
  827. expect(snapshot.runtime.activeTurnKind).toBe("regular");
  828. });
  829. it("hydrates image artifact file parts when building session snapshots", async () => {
  830. const sessionId = "sess_image_artifact" as SessionId;
  831. const artifactUri = "zcode-artifact://sess_image_artifact/tool-result-image";
  832. const app = createFakeApp(
  833. { sessionId },
  834. {
  835. readToolResultArtifact: async (uri) => ({
  836. bytes: 30,
  837. content: "data:image/png;base64,aW1hZ2U=",
  838. contentType: "text/plain",
  839. uri,
  840. }),
  841. },
  842. );
  843. const messages = [
  844. {
  845. info: {
  846. id: "msg_user_image" as MessageId,
  847. sessionID: sessionId,
  848. role: "user",
  849. time: { created: 1 },
  850. agent: "zcode-agent",
  851. modelSelection: {
  852. providerId: "glm" as ModelProviderId,
  853. modelId: "glm-4.6" as ModelId,
  854. },
  855. },
  856. parts: [
  857. {
  858. id: "part_user_text" as never,
  859. sessionID: sessionId,
  860. messageID: "msg_user_image" as MessageId,
  861. text: "图片里是啥",
  862. type: "text",
  863. },
  864. {
  865. id: "part_user_image" as never,
  866. sessionID: sessionId,
  867. messageID: "msg_user_image" as MessageId,
  868. filename: "screen.png",
  869. metadata: {
  870. artifactUri,
  871. sizeBytes: 30,
  872. storageKind: "artifact",
  873. },
  874. mime: "image/png",
  875. type: "file",
  876. url: artifactUri,
  877. },
  878. ],
  879. },
  880. ] as unknown as MessageWithParts[];
  881. const snapshot = zcodeSessionStateSnapshotSchema.parse(
  882. await buildSessionSnapshot({
  883. app,
  884. eventSeq: 0,
  885. messages,
  886. stateRevision: 1,
  887. workspace,
  888. }),
  889. );
  890. expect(snapshot.messages[0]?.parts[1]).toMatchObject({
  891. type: "file",
  892. url: "data:image/png;base64,aW1hZ2U=",
  893. });
  894. });
  895. it("uses fallback record timestamps before projection timestamps in session snapshots", async () => {
  896. const app = createFakeApp();
  897. const snapshot = await buildSessionSnapshot({
  898. app,
  899. eventSeq: 0,
  900. fallbackCreatedAt: 8_000,
  901. fallbackUpdatedAt: 9_000,
  902. messages: [],
  903. stateRevision: 1,
  904. workspace,
  905. });
  906. expect(snapshot.session.createdAt).toBe(8_000);
  907. expect(snapshot.session.updatedAt).toBe(9_000);
  908. });
  909. it("emits Computer Use lifecycle metadata without a legacy deliveryKind", () => {
  910. const ingest = vi.fn();
  911. const notify = vi.fn<(notification: ZCodeProtocolNotification) => void>();
  912. const record = {
  913. app: { sessionId: "sess_cua_sideband" },
  914. updatedAt: 1_700,
  915. workspace,
  916. } as unknown as Parameters<typeof onSessionEvent>[1];
  917. const context = {
  918. notify,
  919. v4Gateway: { ingest },
  920. } as unknown as Parameters<typeof onSessionEvent>[0];
  921. const event = (
  922. type: SessionEvent["type"],
  923. sequenceNumber: number,
  924. payload: unknown,
  925. turnId?: string,
  926. ): SessionEvent => ({
  927. id: `evt-cua-${sequenceNumber}` as SessionEvent["id"],
  928. payload,
  929. sequenceNumber,
  930. sessionId: "sess_cua_sideband" as SessionId,
  931. timestamp: new Date(1_700 + sequenceNumber),
  932. traceId: "trace_cua_sideband" as SessionEvent["traceId"],
  933. ...(turnId ? { turnId: turnId as SessionEvent["turnId"] } : {}),
  934. type,
  935. });
  936. const events = [
  937. event(SessionEventType.TurnStarted, 1, { turnNumber: 1, input: "control" }, "turn-1"),
  938. event(
  939. SessionEventType.ToolCallScheduled,
  940. 2,
  941. {
  942. toolCallId: "call-1",
  943. toolName: "mcp__computer-use__left_click",
  944. input: { target: "Calculator" },
  945. },
  946. "turn-1",
  947. ),
  948. event(
  949. SessionEventType.ToolCallStarted,
  950. 3,
  951. { toolCallId: "call-1", startedAt: new Date(1_703) },
  952. "turn-1",
  953. ),
  954. event(
  955. SessionEventType.ToolCallResult,
  956. 4,
  957. { toolCallId: "call-1", result: { secret: "must-not-pass" }, duration: 1 },
  958. "turn-1",
  959. ),
  960. event(SessionEventType.TurnComplete, 5, { resultType: "success" }, "turn-1"),
  961. event(SessionEventType.SessionEnded, 6, { reason: "closed" }),
  962. ];
  963. for (const sessionEvent of events) onSessionEvent(context, record, sessionEvent);
  964. expect(notify.mock.calls.map(([notification]) => notification.method)).toEqual(
  965. Array.from({ length: 5 }, () => "computer-use/operation-event"),
  966. );
  967. const params = notify.mock.calls.map(
  968. ([notification]) => notification.params as Record<string, unknown>,
  969. );
  970. expect(params.map((value) => value.kind)).toEqual([
  971. "turn-started",
  972. "tool-scheduled",
  973. "tool-started",
  974. "turn-completed",
  975. "session-closed",
  976. ]);
  977. expect(params[1]).not.toHaveProperty("input");
  978. expect(params[2]).not.toHaveProperty("result");
  979. expect(ingest).toHaveBeenCalledTimes(events.length);
  980. });
  981. it("keeps v4 ingestion alive when the Computer Use lifecycle sideband throws", () => {
  982. const ingest = vi.fn();
  983. const warn = vi.fn();
  984. const record = {
  985. app: { sessionId: "sess_cua_sideband_failure" },
  986. updatedAt: 1_700,
  987. workspace,
  988. } as unknown as Parameters<typeof onSessionEvent>[1];
  989. const context = {
  990. logger: { warn },
  991. notify: vi.fn(() => {
  992. throw new Error("transport closed");
  993. }),
  994. v4Gateway: { ingest },
  995. } as unknown as Parameters<typeof onSessionEvent>[0];
  996. const event = {
  997. id: "evt-cua-sideband-failure" as SessionEvent["id"],
  998. payload: { turnNumber: 1, input: "control" },
  999. sequenceNumber: 1,
  1000. sessionId: "sess_cua_sideband_failure" as SessionId,
  1001. timestamp: new Date(1_800),
  1002. traceId: "trace_cua_sideband_failure" as SessionEvent["traceId"],
  1003. turnId: "turn-1" as SessionEvent["turnId"],
  1004. type: SessionEventType.TurnStarted,
  1005. } satisfies SessionEvent;
  1006. expect(() => onSessionEvent(context, record, event)).not.toThrow();
  1007. expect(ingest).toHaveBeenCalledWith("sess_cua_sideband_failure", event);
  1008. expect(warn).toHaveBeenCalledTimes(1);
  1009. });
  1010. it("promotes a deferred record to immediate once the runtime reports the session persisted", () => {
  1011. // 2026-09-14 实机:中枢直接启动的会话由 runtime 落行(controlOnly 启动轮,没有首发),record 一直
  1012. // 是 deferred,sessions-index 视其为 draft 而跳过——侧栏永远不出现。record.persistence 是 runtime
  1013. // 事实的镜像,在事件入口对齐一次即覆盖所有持久化路径。
  1014. const ingest = vi.fn();
  1015. let persisted = false;
  1016. const record = {
  1017. app: { sessionId: "sess_launch", runtime: { isSessionPersisted: () => persisted } },
  1018. persistence: "deferred",
  1019. updatedAt: 1_700,
  1020. workspace,
  1021. } as unknown as Parameters<typeof onSessionEvent>[1];
  1022. const context = {
  1023. v4Gateway: { ingest },
  1024. } as unknown as Parameters<typeof onSessionEvent>[0];
  1025. const event = {
  1026. id: "evt_launch_title" as SessionEvent["id"],
  1027. payload: { previousTitle: "", source: "first_input", title: "deep-research" },
  1028. sequenceNumber: 1,
  1029. sessionId: "sess_launch" as SessionId,
  1030. timestamp: new Date(1_800),
  1031. traceId: "trace_launch" as SessionEvent["traceId"],
  1032. type: SessionEventType.SessionTitleUpdated,
  1033. } satisfies SessionEvent;
  1034. // runtime 尚未持久化:仍是 draft。
  1035. onSessionEvent(context, record, event);
  1036. expect(record.persistence).toBe("deferred");
  1037. // runtime 持久化之后的第一条事件:离开 draft,且对齐发生在 ingest 之前(同一条事件就能进列表)。
  1038. persisted = true;
  1039. ingest.mockImplementation(() => {
  1040. expect(record.persistence).toBe("immediate");
  1041. });
  1042. onSessionEvent(context, record, event);
  1043. expect(record.persistence).toBe("immediate");
  1044. expect(ingest).toHaveBeenCalledTimes(2);
  1045. });
  1046. it("does not bump record updatedAt for session title metadata events", () => {
  1047. const ingest = vi.fn();
  1048. const record = {
  1049. app: { sessionId: "sess_title_sort" },
  1050. updatedAt: 1_700,
  1051. workspace,
  1052. } as unknown as Parameters<typeof onSessionEvent>[1];
  1053. const context = {
  1054. v4Gateway: { ingest },
  1055. } as unknown as Parameters<typeof onSessionEvent>[0];
  1056. const event = {
  1057. id: "evt_title_sort" as SessionEvent["id"],
  1058. payload: {
  1059. previousTitle: "",
  1060. source: "generated",
  1061. title: "Restored title",
  1062. },
  1063. sequenceNumber: 1,
  1064. sessionId: "sess_title_sort" as SessionId,
  1065. timestamp: new Date(1_800),
  1066. traceId: "trace_title_sort" as SessionEvent["traceId"],
  1067. type: SessionEventType.SessionTitleUpdated,
  1068. } satisfies SessionEvent;
  1069. onSessionEvent(context, record, event);
  1070. expect(record.updatedAt).toBe(1_700);
  1071. expect(ingest).toHaveBeenCalledWith("sess_title_sort", event);
  1072. });
  1073. it("routes raw child events to the child publisher without touching the parent record", () => {
  1074. const ingest = vi.fn();
  1075. const record = {
  1076. app: { sessionId: "sess_parent" },
  1077. updatedAt: 1_700,
  1078. workspace,
  1079. } as unknown as Parameters<typeof onSessionEvent>[1];
  1080. const context = {
  1081. v4Gateway: { ingestDetachedLiveSession: ingest },
  1082. } as unknown as Parameters<typeof onSessionEvent>[0];
  1083. const event = {
  1084. id: "evt_child_delta" as SessionEvent["id"],
  1085. payload: { kind: "text_delta", delta: "child", done: false },
  1086. sequenceNumber: 2,
  1087. sessionId: "sess_child" as SessionId,
  1088. timestamp: new Date(1_800),
  1089. traceId: "trace_child_delta" as SessionEvent["traceId"],
  1090. type: SessionEventType.ModelStreaming,
  1091. } satisfies SessionEvent;
  1092. onSessionEvent(context, record, event);
  1093. expect(record.updatedAt).toBe(1_700);
  1094. expect(ingest).toHaveBeenCalledTimes(1);
  1095. // 保留 source detached child publisher 生命周期:路由 child 时同时登记 parent 归属。
  1096. expect(ingest).toHaveBeenCalledWith("sess_child", event, "sess_parent");
  1097. });
  1098. it("exposes model streaming tool input previews to the app protocol", () => {
  1099. const events = mapSessionEvents(
  1100. [
  1101. {
  1102. id: "evt_tool_input_delta" as SessionEvent["id"],
  1103. payload: {
  1104. kind: "tool_input_delta",
  1105. delta: '{"file_path":"README.md"}',
  1106. done: false,
  1107. },
  1108. sequenceNumber: 5,
  1109. sessionId: "sess_1" as SessionId,
  1110. timestamp: new Date(6),
  1111. traceId: "trace_tool_input_delta" as SessionEvent["traceId"],
  1112. type: SessionEventType.ModelStreaming,
  1113. },
  1114. {
  1115. id: "evt_text_delta" as SessionEvent["id"],
  1116. payload: {
  1117. kind: "text_delta",
  1118. delta: "hello",
  1119. done: false,
  1120. },
  1121. sequenceNumber: 6,
  1122. sessionId: "sess_1" as SessionId,
  1123. timestamp: new Date(7),
  1124. traceId: "trace_text_delta" as SessionEvent["traceId"],
  1125. type: SessionEventType.ModelStreaming,
  1126. },
  1127. {
  1128. id: "evt_tool_scheduled" as SessionEvent["id"],
  1129. payload: {
  1130. input: { file_path: "README.md" },
  1131. toolCallId: "call_1",
  1132. toolName: "Read",
  1133. },
  1134. sequenceNumber: 7,
  1135. sessionId: "sess_1" as SessionId,
  1136. timestamp: new Date(8),
  1137. traceId: "trace_tool_scheduled" as SessionEvent["traceId"],
  1138. type: SessionEventType.ToolCallScheduled,
  1139. },
  1140. ] satisfies SessionEvent[],
  1141. "desktop-continuous",
  1142. );
  1143. expect(events).toHaveLength(3);
  1144. expect(events[0]).toMatchObject({
  1145. eventId: "evt_tool_input_delta",
  1146. payload: { kind: "tool_input_delta", delta: '{"file_path":"README.md"}' },
  1147. type: "model.streaming",
  1148. });
  1149. expect(events[1].eventId).toBe("evt_text_delta");
  1150. expect(events[1].payload).toMatchObject({ kind: "text_delta", delta: "hello" });
  1151. expect(events[2]).toMatchObject({
  1152. eventId: "evt_tool_scheduled",
  1153. payload: {
  1154. input: { file_path: "README.md" },
  1155. kind: "scheduled",
  1156. toolCallId: "call_1",
  1157. toolName: "Read",
  1158. },
  1159. type: "tool.updated",
  1160. });
  1161. });
  1162. it("does not expose internal streaming tool ledger updates to the app protocol", () => {
  1163. const events = mapSessionEvents([
  1164. {
  1165. id: "evt_tool_ledger" as SessionEvent["id"],
  1166. payload: {
  1167. input: { content: "large generated file" },
  1168. status: "tool_started",
  1169. toolCallId: "call_1",
  1170. toolName: "Write",
  1171. },
  1172. sequenceNumber: 8,
  1173. sessionId: "sess_1" as SessionId,
  1174. timestamp: new Date(9),
  1175. traceId: "trace_tool_ledger" as SessionEvent["traceId"],
  1176. type: SessionEventType.StreamingToolLedgerUpdated,
  1177. },
  1178. ]);
  1179. expect(events).toEqual([]);
  1180. });
  1181. it("logs snapshot phase timings for session create diagnostics", async () => {
  1182. const logs: RecordedLog[] = [];
  1183. const server = new ZCodeProtocolAgentServer({
  1184. createZCodeApp: (options) => createFakeApp(options),
  1185. cwd: workspace.workspacePath,
  1186. loggerFactory: createProtocolTestLoggerFactory(logs),
  1187. version: "test-version",
  1188. });
  1189. await requestResult(server, {
  1190. id: 1,
  1191. method: zcodeProtocolMethods.sessionCreate,
  1192. params: { workspace },
  1193. });
  1194. const completed = logs.find(
  1195. (log) => log.context.event === "zcode_protocol.session_create.completed",
  1196. );
  1197. expect(completed?.context.snapshotPhaseDurationsMs).toMatchObject({
  1198. buildSnapshot: expect.any(Number),
  1199. eventSeq: expect.any(Number),
  1200. persistedMessages: expect.any(Number),
  1201. persistedSession: expect.any(Number),
  1202. rewindEvents: expect.any(Number),
  1203. target: expect.any(Number),
  1204. todos: expect.any(Number),
  1205. });
  1206. });
  1207. // M5 ③-3:usage query 的 v4 名字空间分派(L2)。数据访问层与旧 usage/stats、
  1208. // session/usage 共用(usage store 聚合),这里锁定 v4 方法名可达且结果过 v4 schema。
  1209. it("serves v4/usage/stats through the usage data access layer", async () => {
  1210. const server = new ZCodeProtocolAgentServer({
  1211. createZCodeApp: (options) => createFakeApp(options),
  1212. cwd: workspace.workspacePath,
  1213. version: "test-version",
  1214. });
  1215. const result = v4UsageStatsResultSchema.parse(
  1216. await requestResult(server, {
  1217. id: 1,
  1218. method: V4_METHODS.usageStats,
  1219. params: { range: "7d", timeZone: "UTC" },
  1220. }),
  1221. );
  1222. // 无 usage store 的兜底路径:返回空快照而非抛错(与旧 op 语义一致)。
  1223. expect(result.range).toBe("7d");
  1224. expect(result.timeZone).toBe("UTC");
  1225. expect(result.source).toBe("agent-db");
  1226. expect(result.models).toEqual([]);
  1227. });
  1228. it("serves v4/conversation/usage keyed by sessionId", async () => {
  1229. const server = new ZCodeProtocolAgentServer({
  1230. createZCodeApp: (options) => createFakeApp(options),
  1231. cwd: workspace.workspacePath,
  1232. version: "test-version",
  1233. });
  1234. const result = v4ConversationUsageResultSchema.parse(
  1235. await requestResult(server, {
  1236. id: 1,
  1237. method: V4_METHODS.conversationUsage,
  1238. params: { sessionId: "sess_v4_usage" },
  1239. }),
  1240. );
  1241. expect(result.sessionId).toBe("sess_v4_usage");
  1242. expect(result.totalTokens).toBe(0);
  1243. expect(result.inputBaselineBySource).toEqual({});
  1244. });
  1245. it("三类 v4 subscribe response 只含 ACK,并把 initial 放入 request-scoped outbox", async () => {
  1246. const server = new ZCodeProtocolAgentServer({
  1247. createZCodeApp: (options) => createFakeApp(options),
  1248. cwd: workspace.workspacePath,
  1249. version: "test-version",
  1250. });
  1251. const created = zcodeSessionStateSnapshotSchema.parse(
  1252. await requestResult(server, {
  1253. id: "create-for-v4-outbox",
  1254. method: zcodeProtocolMethods.sessionCreate,
  1255. params: { workspace },
  1256. }),
  1257. );
  1258. const topics = [
  1259. conversationTopic(created.session.sessionId),
  1260. sessionsIndexTopic(workspace.workspaceKey),
  1261. workspaceConfigTopic(workspace.workspaceKey),
  1262. ];
  1263. for (const [index, topic] of topics.entries()) {
  1264. const id = `v4-subscribe-${index}`;
  1265. const response = await server.handleMessage({
  1266. id,
  1267. method: V4_METHODS.conversationSubscribe,
  1268. params: {
  1269. topic,
  1270. connectionId: `connection-${index}`,
  1271. clientMode: "desktop-continuous",
  1272. },
  1273. });
  1274. // staging 已在 ACK 内加入可选 openTiming 诊断;这里守住 response 仍只承载 ACK,
  1275. // 初始 frame 仍必须进入 request-scoped outbox,不把诊断字段误判成 initial payload。
  1276. expect(response).toMatchObject({
  1277. id,
  1278. result: {
  1279. ack: {
  1280. subscriptionId: expect.any(String),
  1281. mode: "snapshot",
  1282. logEpoch: expect.any(String),
  1283. // 会话主题的 ACK 额外携带 session open 计时遥测(staging 的 ARMS 面);
  1284. // 列表/配置主题没有会话可计时,不带这个键。
  1285. ...(index === 0 ? { openTiming: expect.any(Object) } : {}),
  1286. },
  1287. },
  1288. });
  1289. const ack = (response as { result: { ack: { subscriptionId: string } } }).result.ack;
  1290. const queued = server.takePostResponseMessages(id);
  1291. expect(queued.length).toBeGreaterThan(0);
  1292. expect(queued.every((message) => message.method === V4_NOTIFICATIONS.conversationFrame)).toBe(
  1293. true,
  1294. );
  1295. const assembled = reassembleTopicWireFrames(
  1296. queued.map((message) => routedTopicWireFrameSchema.parse(message.params)),
  1297. routedTopicFrameSchema,
  1298. );
  1299. expect(assembled).toMatchObject({
  1300. kind: "complete",
  1301. frame: {
  1302. topic,
  1303. subscriptionId: ack.subscriptionId,
  1304. payload: { kind: "snapshot" },
  1305. },
  1306. });
  1307. expect(server.takePostResponseMessages(id)).toEqual([]);
  1308. }
  1309. });
  1310. it("routes strict v4 connection flow control to the gateway", async () => {
  1311. const server = new ZCodeProtocolAgentServer({
  1312. createZCodeApp: (options) => createFakeApp(options),
  1313. cwd: workspace.workspacePath,
  1314. version: "test-version",
  1315. });
  1316. expect(
  1317. await server.handleMessage({
  1318. id: "flow-saturated",
  1319. method: V4_METHODS.connectionFlow,
  1320. params: { connectionId: "mobile-flow", state: "saturated" },
  1321. }),
  1322. ).toEqual({ id: "flow-saturated", result: {} });
  1323. const invalid = await server.handleMessage({
  1324. id: "flow-invalid",
  1325. method: V4_METHODS.connectionFlow,
  1326. params: { connectionId: "mobile-flow", state: "forged" },
  1327. });
  1328. expect(invalid).toMatchObject({ id: "flow-invalid", error: expect.any(Object) });
  1329. });
  1330. it("routes attachment begin/chunk/commit/abort without a full-data RPC", async () => {
  1331. const writePromptAttachment = vi.fn(async () => ({ ref: "zcode-artifact://upload/server" }));
  1332. const server = new ZCodeProtocolAgentServer({
  1333. createZCodeApp: (options) => createFakeApp(options, { writePromptAttachment }),
  1334. cwd: workspace.workspacePath,
  1335. version: "test-version",
  1336. });
  1337. const created = zcodeSessionStateSnapshotSchema.parse(
  1338. await requestResult(server, {
  1339. id: "attachment-session",
  1340. method: zcodeProtocolMethods.sessionCreate,
  1341. params: { workspace },
  1342. }),
  1343. );
  1344. const bytes = Buffer.from("server attachment");
  1345. const common = {
  1346. connectionId: "attachment-connection",
  1347. sessionId: created.session.sessionId,
  1348. uploadId: "upload-server",
  1349. };
  1350. await expect(
  1351. requestResult(server, {
  1352. id: "attachment-begin",
  1353. method: V4_METHODS.attachmentBegin,
  1354. params: {
  1355. ...common,
  1356. fileName: "server.txt",
  1357. mime: "text/plain",
  1358. totalBytes: bytes.byteLength,
  1359. totalChunks: 1,
  1360. checksum: `sha256:${createHash("sha256").update(bytes).digest("hex")}`,
  1361. },
  1362. }),
  1363. ).resolves.toMatchObject({ state: "staging", nextChunkIndex: 0 });
  1364. await requestResult(server, {
  1365. id: "attachment-chunk",
  1366. method: V4_METHODS.attachmentChunk,
  1367. params: { ...common, chunkIndex: 0, dataBase64: bytes.toString("base64") },
  1368. });
  1369. await expect(
  1370. requestResult(server, {
  1371. id: "attachment-commit",
  1372. method: V4_METHODS.attachmentCommit,
  1373. params: common,
  1374. }),
  1375. ).resolves.toEqual({ ref: "zcode-artifact://upload/server" });
  1376. await expect(
  1377. requestResult(server, {
  1378. id: "attachment-commit-retry",
  1379. method: V4_METHODS.attachmentCommit,
  1380. params: common,
  1381. }),
  1382. ).resolves.toEqual({ ref: "zcode-artifact://upload/server" });
  1383. await expect(
  1384. requestResult(server, {
  1385. id: "attachment-abort",
  1386. method: V4_METHODS.attachmentAbort,
  1387. params: common,
  1388. }),
  1389. ).resolves.toEqual({});
  1390. expect(writePromptAttachment).toHaveBeenCalledTimes(1);
  1391. expect(writePromptAttachment).toHaveBeenCalledWith({
  1392. fileName: "server.txt",
  1393. mime: "text/plain",
  1394. bytes: new Uint8Array(bytes),
  1395. });
  1396. await expect(
  1397. server.handleMessage({
  1398. id: "legacy-full-data-put",
  1399. method: "v4/attachment/put" as never,
  1400. params: {
  1401. sessionId: created.session.sessionId,
  1402. fileName: "forbidden.txt",
  1403. mime: "text/plain",
  1404. dataBase64: bytes.toString("base64"),
  1405. },
  1406. }),
  1407. ).resolves.toMatchObject({
  1408. id: "legacy-full-data-put",
  1409. error: { code: -32601 },
  1410. });
  1411. });
  1412. it("并发 subscribe request id 的 post-response outbox 不串线", async () => {
  1413. const server = new ZCodeProtocolAgentServer({
  1414. createZCodeApp: (options) => createFakeApp(options),
  1415. cwd: workspace.workspacePath,
  1416. version: "test-version",
  1417. });
  1418. const topics = [
  1419. sessionsIndexTopic(workspace.workspaceKey),
  1420. workspaceConfigTopic(workspace.workspaceKey),
  1421. ];
  1422. await Promise.all(
  1423. topics.map((topic, index) =>
  1424. server.handleMessage({
  1425. id: `parallel-${index}`,
  1426. method: V4_METHODS.conversationSubscribe,
  1427. params: {
  1428. topic,
  1429. connectionId: `parallel-connection-${index}`,
  1430. clientMode: "desktop-continuous",
  1431. },
  1432. }),
  1433. ),
  1434. );
  1435. expect(server.takePostResponseMessages("parallel-1")[0]).toMatchObject({
  1436. params: { topic: topics[1] },
  1437. });
  1438. expect(server.takePostResponseMessages("parallel-0")[0]).toMatchObject({
  1439. params: { topic: topics[0] },
  1440. });
  1441. });
  1442. it("aligned resume 经真实 server/outbox/NDJSON 只写一行 ACK response", async () => {
  1443. const server = new ZCodeProtocolAgentServer({
  1444. createZCodeApp: (options) => createFakeApp(options),
  1445. cwd: workspace.workspacePath,
  1446. version: "test-version",
  1447. });
  1448. const created = zcodeSessionStateSnapshotSchema.parse(
  1449. await requestResult(server, {
  1450. id: "create-for-aligned-resume",
  1451. method: zcodeProtocolMethods.sessionCreate,
  1452. params: { workspace },
  1453. }),
  1454. );
  1455. const topic = conversationTopic(created.session.sessionId);
  1456. const initialResponse = await server.handleMessage({
  1457. id: "initial-subscribe",
  1458. method: V4_METHODS.conversationSubscribe,
  1459. params: {
  1460. topic,
  1461. connectionId: "aligned-connection",
  1462. clientMode: "desktop-continuous",
  1463. },
  1464. });
  1465. if (!initialResponse || !("result" in initialResponse)) {
  1466. throw new Error("Expected initial subscribe response");
  1467. }
  1468. const initialResult = v4ConversationSubscribeResultSchema.parse(initialResponse.result);
  1469. const initialMessages = server.takePostResponseMessages("initial-subscribe");
  1470. if (initialMessages.length === 0) {
  1471. throw new Error("Expected initial subscribe outbox frame");
  1472. }
  1473. const initialAssembly = reassembleTopicWireFrames(
  1474. initialMessages.map((message) => routedTopicWireFrameSchema.parse(message.params)),
  1475. conversationTopicFrameSchema,
  1476. );
  1477. if (initialAssembly.kind !== "complete") {
  1478. throw new Error("Expected complete initial subscribe frame");
  1479. }
  1480. const initialFrame = initialAssembly.frame;
  1481. const input = new PassThrough();
  1482. const output = new PassThrough();
  1483. let written = "";
  1484. output.on("data", (chunk: Buffer) => {
  1485. written += chunk.toString("utf8");
  1486. });
  1487. const connection = new ZCodeProtocolNdjsonConnection({
  1488. clearPostResponseMessages: () => server.clearPostResponseMessages(),
  1489. handleMessage: (message) => server.handleMessage(message),
  1490. input,
  1491. output,
  1492. takePostResponseBatch: (requestId) => server.takePostResponseBatch(requestId),
  1493. });
  1494. connection.start();
  1495. input.end(
  1496. `${JSON.stringify({
  1497. id: "aligned-resume",
  1498. method: V4_METHODS.conversationSubscribe,
  1499. params: {
  1500. topic,
  1501. connectionId: "aligned-connection",
  1502. clientMode: "desktop-continuous",
  1503. base: { logEpoch: initialResult.ack.logEpoch, seq: initialFrame.toSeq },
  1504. },
  1505. })}\n`,
  1506. );
  1507. await connection.waitForClose();
  1508. const lines = written.trim().split("\n");
  1509. expect(lines).toHaveLength(1);
  1510. const response = JSON.parse(lines[0]!) as { result: unknown };
  1511. expect(v4ConversationSubscribeResultSchema.parse(response.result).ack.mode).toBe("resume");
  1512. expect(server.takePostResponseMessages("aligned-resume")).toEqual([]);
  1513. });
  1514. it("same-sub resync 经真实 server/NDJSON 严格先 ACK 再 physical recovery", async () => {
  1515. const server = new ZCodeProtocolAgentServer({
  1516. createZCodeApp: (options) => createFakeApp(options),
  1517. cwd: workspace.workspacePath,
  1518. version: "test-version",
  1519. });
  1520. const created = zcodeSessionStateSnapshotSchema.parse(
  1521. await requestResult(server, {
  1522. id: "create-for-resync-order",
  1523. method: zcodeProtocolMethods.sessionCreate,
  1524. params: { workspace },
  1525. }),
  1526. );
  1527. const topic = conversationTopic(created.session.sessionId);
  1528. const subscribedResponse = await server.handleMessage({
  1529. id: "subscribe-before-resync",
  1530. method: V4_METHODS.conversationSubscribe,
  1531. params: {
  1532. topic,
  1533. connectionId: "resync-connection",
  1534. clientMode: "web-remote-replayable",
  1535. },
  1536. });
  1537. if (!subscribedResponse || !("result" in subscribedResponse)) {
  1538. throw new Error("Expected subscribe response");
  1539. }
  1540. const subscribed = v4ConversationSubscribeResultSchema.parse(subscribedResponse.result);
  1541. // 初始 batch admission 后才开始 same-sub recovery。
  1542. expect(server.takePostResponseMessages("subscribe-before-resync").length).toBeGreaterThan(0);
  1543. const input = new PassThrough();
  1544. const output = new PassThrough();
  1545. let written = "";
  1546. output.on("data", (chunk: Buffer) => {
  1547. written += chunk.toString("utf8");
  1548. });
  1549. const connection = new ZCodeProtocolNdjsonConnection({
  1550. clearPostResponseMessages: () => server.clearPostResponseMessages(),
  1551. handleMessage: (message) => server.handleMessage(message),
  1552. input,
  1553. output,
  1554. takePostResponseBatch: (requestId) => server.takePostResponseBatch(requestId),
  1555. });
  1556. connection.start();
  1557. input.end(
  1558. `${JSON.stringify({
  1559. id: "same-sub-resync",
  1560. method: V4_METHODS.conversationResync,
  1561. params: {
  1562. topic,
  1563. connectionId: "resync-connection",
  1564. subscriptionId: subscribed.ack.subscriptionId,
  1565. base: null,
  1566. forceSnapshot: true,
  1567. },
  1568. })}\n`,
  1569. );
  1570. await connection.waitForClose();
  1571. const lines = written
  1572. .trim()
  1573. .split("\n")
  1574. .map((line) => JSON.parse(line) as Record<string, unknown>);
  1575. expect(lines.length).toBeGreaterThan(1);
  1576. const result = v4ConversationResyncResultSchema.parse(lines[0]?.result);
  1577. expect(result.ack.subscriptionId).toBe(subscribed.ack.subscriptionId);
  1578. expect(result.ack.mode).toBe("snapshot");
  1579. expect(lines.slice(1).every((line) => line.method === V4_NOTIFICATIONS.conversationFrame)).toBe(
  1580. true,
  1581. );
  1582. });
  1583. it("uses the app supplied protocol trace as the session root trace", async () => {
  1584. const logs: RecordedLog[] = [];
  1585. const server = new ZCodeProtocolAgentServer({
  1586. createZCodeApp: (options) => createFakeApp(options),
  1587. cwd: workspace.workspacePath,
  1588. loggerFactory: createProtocolTestLoggerFactory(logs),
  1589. version: "test-version",
  1590. });
  1591. const snapshot = zcodeSessionStateSnapshotSchema.parse(
  1592. await requestResult(server, {
  1593. id: 1,
  1594. method: zcodeProtocolMethods.sessionCreate,
  1595. params: { workspace },
  1596. trace: { traceId: "trace_from_app" },
  1597. }),
  1598. );
  1599. expect(snapshot.session.traceId).toBe("trace_from_app");
  1600. const createRecord = logs.find(
  1601. (log) => log.context.event === "zcode_protocol.create_record.mcp_config",
  1602. );
  1603. expect(createRecord?.context.rootTraceId).toBe("trace_from_app");
  1604. });
  1605. it("keeps project plugin roots and untrusted project MCP disconnected during refresh", async () => {
  1606. const root = await mkdtemp(join(tmpdir(), "zcode-protocol-mcp-list-"));
  1607. const workspacePath = join(root, "workspace");
  1608. const pluginRoot = join(root, "plugin");
  1609. const connectedConfigs: Record<string, McpServerConfig>[] = [];
  1610. const mcpPort = createProtocolListMcpPort(connectedConfigs);
  1611. const server = new ZCodeProtocolAgentServer({
  1612. createZCodeApp: (options) => createFakeApp(options),
  1613. cwd: workspacePath,
  1614. mcpPort,
  1615. version: "test-version",
  1616. });
  1617. try {
  1618. await mkdir(join(root, ".git"));
  1619. await mkdir(join(pluginRoot, ".zcode-plugin"), { recursive: true });
  1620. await mkdir(workspacePath, { recursive: true });
  1621. await writeFile(
  1622. join(root, "zcode.json"),
  1623. JSON.stringify({
  1624. plugins: {
  1625. dirs: [pluginRoot],
  1626. },
  1627. mcp: {
  1628. servers: {
  1629. "project-only": {
  1630. type: "stdio",
  1631. command: "project-server",
  1632. },
  1633. },
  1634. },
  1635. }),
  1636. );
  1637. await writeFile(
  1638. join(pluginRoot, ".zcode-plugin", "plugin.json"),
  1639. JSON.stringify({
  1640. name: "status-plugin",
  1641. mcpServers: {
  1642. "plugin-live": {
  1643. command: "plugin-server",
  1644. },
  1645. },
  1646. }),
  1647. );
  1648. const result = await requestResult(server, {
  1649. id: 1,
  1650. method: zcodeProtocolMethods.mcpList,
  1651. params: {
  1652. workspace: {
  1653. workspaceKey: workspacePath,
  1654. workspacePath,
  1655. },
  1656. },
  1657. });
  1658. expect(connectedConfigs).toHaveLength(1);
  1659. // 旧夹具仍期待项目配置自动加载插件、启动 MCP;当前合同要求用户安装与工作区信任。
  1660. expect(connectedConfigs[0]?.["plugin:status-plugin:plugin-live"]).toBeUndefined();
  1661. expect(connectedConfigs[0]?.["project-only"]).toBeUndefined();
  1662. expect(result).toMatchObject({
  1663. statuses: {
  1664. "project-only": {
  1665. status: "untrusted",
  1666. toolCount: 0,
  1667. transport: "stdio",
  1668. },
  1669. },
  1670. });
  1671. } finally {
  1672. await rm(root, { force: true, recursive: true });
  1673. }
  1674. });
  1675. it("uses explicit protocol MCP servers for MCP list statuses", async () => {
  1676. const root = await mkdtemp(join(tmpdir(), "zcode-protocol-mcp-list-explicit-"));
  1677. const workspacePath = join(root, "workspace");
  1678. const connectedConfigs: Record<string, McpServerConfig>[] = [];
  1679. const mcpPort = createProtocolListMcpPort(connectedConfigs);
  1680. const server = new ZCodeProtocolAgentServer({
  1681. createZCodeApp: (options) => createFakeApp(options),
  1682. cwd: workspacePath,
  1683. mcpPort,
  1684. version: "test-version",
  1685. });
  1686. try {
  1687. await mkdir(join(root, ".git"));
  1688. await mkdir(workspacePath, { recursive: true });
  1689. await writeFile(
  1690. join(root, "zcode.json"),
  1691. JSON.stringify({
  1692. mcp: {
  1693. servers: {
  1694. "disk-only": {
  1695. type: "stdio",
  1696. command: "disk-server",
  1697. },
  1698. },
  1699. },
  1700. }),
  1701. );
  1702. const result = await requestResult(server, {
  1703. id: 1,
  1704. method: zcodeProtocolMethods.mcpList,
  1705. params: {
  1706. workspace: {
  1707. workspaceKey: workspacePath,
  1708. workspacePath,
  1709. },
  1710. mcpServers: [
  1711. {
  1712. name: "agents-fallback",
  1713. command: "node",
  1714. args: ["server.mjs"],
  1715. env: [{ name: "TOKEN", value: "secret" }],
  1716. timeoutMs: 3000,
  1717. },
  1718. ],
  1719. },
  1720. });
  1721. expect(connectedConfigs).toHaveLength(1);
  1722. expect(connectedConfigs[0]?.["agents-fallback"]).toMatchObject({
  1723. args: ["server.mjs"],
  1724. command: "node",
  1725. env: { TOKEN: "secret" },
  1726. timeoutMs: 3000,
  1727. type: "stdio",
  1728. });
  1729. expect(connectedConfigs[0]?.["disk-only"]).toBeUndefined();
  1730. expect(result).toMatchObject({
  1731. statuses: {
  1732. "agents-fallback": {
  1733. status: "connected",
  1734. toolCount: 3,
  1735. transport: "stdio",
  1736. },
  1737. },
  1738. });
  1739. } finally {
  1740. await rm(root, { force: true, recursive: true });
  1741. }
  1742. });
  1743. it("does not read or disconnect another workspace MCP lease in status mode", async () => {
  1744. const root = await mkdtemp(join(tmpdir(), "zcode-protocol-mcp-list-status-"));
  1745. const workspacePath = join(root, "workspace");
  1746. const connectedConfigs: Record<string, McpServerConfig>[] = [];
  1747. const disconnectedNames: string[] = [];
  1748. const mcpPort = createProtocolReplaceMcpPort(connectedConfigs, disconnectedNames, {
  1749. everything: {
  1750. status: "connected",
  1751. transport: "stdio",
  1752. toolCount: 9,
  1753. updatedAt: new Date(1).toISOString(),
  1754. },
  1755. "plugin:canva:canva": {
  1756. authorization: {
  1757. authorizationUrl: "https://auth.canva.example.test/authorize",
  1758. startedAt: new Date(1).toISOString(),
  1759. type: "oauth_authorization_code",
  1760. },
  1761. status: "connecting",
  1762. transport: "http",
  1763. toolCount: 0,
  1764. updatedAt: new Date(1).toISOString(),
  1765. },
  1766. });
  1767. const server = new ZCodeProtocolAgentServer({
  1768. createZCodeApp: (options) => createFakeApp(options),
  1769. cwd: workspacePath,
  1770. mcpPort,
  1771. version: "test-version",
  1772. });
  1773. try {
  1774. await mkdir(join(root, ".git"));
  1775. await mkdir(workspacePath, { recursive: true });
  1776. const result = await requestResult(server, {
  1777. id: 1,
  1778. method: zcodeProtocolMethods.mcpList,
  1779. params: {
  1780. workspace: {
  1781. workspaceKey: workspacePath,
  1782. workspacePath,
  1783. },
  1784. mode: "status",
  1785. mcpServers: [
  1786. {
  1787. name: "plugin:canva:canva",
  1788. type: "http",
  1789. url: "https://mcp.canva.example.test/mcp",
  1790. headers: [],
  1791. oauth: {
  1792. type: "authorization_code",
  1793. clientName: "ZCode",
  1794. },
  1795. },
  1796. ],
  1797. },
  1798. });
  1799. expect(connectedConfigs).toHaveLength(0);
  1800. expect(disconnectedNames).toHaveLength(0);
  1801. // 没有为此 workspace 取得设置 lease 时,不能把原始端口中其他 owner 的连接态投过来。
  1802. expect((result as { statuses: Record<string, unknown> }).statuses.everything).toBeUndefined();
  1803. expect(result).toMatchObject({
  1804. statuses: {
  1805. "plugin:canva:canva": {
  1806. status: "disconnected",
  1807. transport: "http",
  1808. },
  1809. },
  1810. });
  1811. } finally {
  1812. await rm(root, { force: true, recursive: true });
  1813. }
  1814. });
  1815. it("keeps replace convergence when default connect sees pending OAuth status", async () => {
  1816. const root = await mkdtemp(join(tmpdir(), "zcode-protocol-mcp-list-connect-pending-"));
  1817. const workspacePath = join(root, "workspace");
  1818. const connectedConfigs: Record<string, McpServerConfig>[] = [];
  1819. const disconnectedNames: string[] = [];
  1820. const mcpPort = createProtocolReplaceMcpPort(connectedConfigs, disconnectedNames, {
  1821. "plugin:canva:canva": {
  1822. authorization: {
  1823. authorizationUrl: "https://auth.canva.example.test/authorize",
  1824. startedAt: new Date(1).toISOString(),
  1825. type: "oauth_authorization_code",
  1826. },
  1827. status: "connecting",
  1828. transport: "http",
  1829. toolCount: 0,
  1830. updatedAt: new Date(1).toISOString(),
  1831. },
  1832. stale: {
  1833. status: "connected",
  1834. transport: "stdio",
  1835. toolCount: 1,
  1836. updatedAt: new Date(1).toISOString(),
  1837. },
  1838. });
  1839. const server = new ZCodeProtocolAgentServer({
  1840. createZCodeApp: (options) => createFakeApp(options),
  1841. cwd: workspacePath,
  1842. mcpPort,
  1843. version: "test-version",
  1844. });
  1845. try {
  1846. await mkdir(join(root, ".git"));
  1847. await mkdir(workspacePath, { recursive: true });
  1848. const result = await requestResult(server, {
  1849. id: 1,
  1850. method: zcodeProtocolMethods.mcpList,
  1851. params: {
  1852. workspace: {
  1853. workspaceKey: workspacePath,
  1854. workspacePath,
  1855. },
  1856. mcpServers: [
  1857. {
  1858. name: "everything",
  1859. command: "node",
  1860. args: ["server.mjs"],
  1861. env: [],
  1862. },
  1863. {
  1864. name: "plugin:canva:canva",
  1865. type: "http",
  1866. url: "https://mcp.canva.example.test/mcp",
  1867. headers: [],
  1868. oauth: {
  1869. type: "authorization_code",
  1870. clientName: "ZCode",
  1871. },
  1872. },
  1873. ],
  1874. },
  1875. });
  1876. expect(connectedConfigs).toHaveLength(1);
  1877. expect(connectedConfigs[0]).toMatchObject({
  1878. everything: {
  1879. command: "node",
  1880. type: "stdio",
  1881. },
  1882. "plugin:canva:canva": {
  1883. type: "http",
  1884. },
  1885. });
  1886. expect(disconnectedNames).toContain("stale");
  1887. expect(result).toMatchObject({
  1888. statuses: {
  1889. everything: {
  1890. status: "connected",
  1891. },
  1892. "plugin:canva:canva": {
  1893. status: "connected",
  1894. },
  1895. },
  1896. });
  1897. } finally {
  1898. await rm(root, { force: true, recursive: true });
  1899. }
  1900. });
  1901. it("returns pending MCP OAuth authorization status without waiting for callback", async () => {
  1902. const root = await mkdtemp(join(tmpdir(), "zcode-protocol-mcp-oauth-pending-"));
  1903. const workspacePath = join(root, "workspace");
  1904. const connectedConfigs: Record<string, McpServerConfig>[] = [];
  1905. let finishConnect!: () => void;
  1906. const mcpPort = createProtocolPendingAuthorizationMcpPort(connectedConfigs, (resolve) => {
  1907. finishConnect = resolve;
  1908. });
  1909. const server = new ZCodeProtocolAgentServer({
  1910. createZCodeApp: (options) => createFakeApp(options),
  1911. cwd: workspacePath,
  1912. mcpPort,
  1913. version: "test-version",
  1914. });
  1915. try {
  1916. await mkdir(join(root, ".git"));
  1917. await mkdir(workspacePath, { recursive: true });
  1918. const result = await requestResult(server, {
  1919. id: 1,
  1920. method: zcodeProtocolMethods.mcpList,
  1921. params: {
  1922. workspace: {
  1923. workspaceKey: workspacePath,
  1924. workspacePath,
  1925. },
  1926. mcpServers: [
  1927. {
  1928. name: "notion",
  1929. type: "http",
  1930. url: "https://mcp.notion.example.test/mcp",
  1931. headers: [],
  1932. oauth: {
  1933. type: "authorization_code",
  1934. clientName: "ZCode",
  1935. },
  1936. },
  1937. ],
  1938. },
  1939. });
  1940. expect(connectedConfigs).toHaveLength(1);
  1941. expect(result).toMatchObject({
  1942. statuses: {
  1943. notion: {
  1944. authorization: {
  1945. authorizationUrl: "https://auth.example.test/authorize?state=state_test",
  1946. type: "oauth_authorization_code",
  1947. },
  1948. status: "connecting",
  1949. transport: "http",
  1950. },
  1951. },
  1952. });
  1953. finishConnect();
  1954. } finally {
  1955. finishConnect?.();
  1956. await rm(root, { force: true, recursive: true });
  1957. }
  1958. });
  1959. it("cancels background bash tasks through the session protocol", async () => {
  1960. const notifications: ZCodeProtocolNotification[] = [];
  1961. let cancelledTaskId: string | undefined;
  1962. let backgroundTasks: BackgroundTaskInfo[] = [
  1963. {
  1964. cancellable: true,
  1965. command: "pnpm dev",
  1966. status: "running",
  1967. taskId: "bg_1",
  1968. terminalId: "bg_1",
  1969. },
  1970. ];
  1971. const server = new ZCodeProtocolAgentServer({
  1972. createZCodeApp: (options) => {
  1973. const app = createFakeApp(options);
  1974. return {
  1975. ...app,
  1976. cancelBackgroundTask: async (taskId) => {
  1977. cancelledTaskId = taskId;
  1978. const currentTask = backgroundTasks[0];
  1979. if (!currentTask) {
  1980. throw new Error("Expected background task fixture");
  1981. }
  1982. backgroundTasks = [
  1983. {
  1984. ...currentTask,
  1985. cancellable: false,
  1986. status: "cancelled",
  1987. },
  1988. ];
  1989. return {
  1990. cancelled: true,
  1991. snapshot: backgroundTasks[0],
  1992. status: "cancelled",
  1993. taskId,
  1994. };
  1995. },
  1996. runtime: {
  1997. ...app.runtime,
  1998. getProjection: async () => ({
  1999. ...(await app.runtime.getProjection()),
  2000. backgroundTasks,
  2001. }),
  2002. },
  2003. };
  2004. },
  2005. cwd: workspace.workspacePath,
  2006. version: "test-version",
  2007. });
  2008. setTestNotificationSink(server, (notification) => notifications.push(notification));
  2009. const snapshot = zcodeSessionStateSnapshotSchema.parse(
  2010. await requestResult(server, {
  2011. id: 1,
  2012. method: zcodeProtocolMethods.sessionCreate,
  2013. params: { workspace },
  2014. }),
  2015. );
  2016. const result = zcodeSessionCancelBackgroundTaskResultSchema.parse(
  2017. await requestResult(server, {
  2018. id: 2,
  2019. method: zcodeProtocolMethods.sessionCancelBackgroundTask,
  2020. params: { sessionId: snapshot.session.sessionId, taskId: "bg_1" },
  2021. }),
  2022. );
  2023. expect(cancelledTaskId).toBe("bg_1");
  2024. expect(result).toMatchObject({
  2025. cancelled: true,
  2026. status: "cancelled",
  2027. taskId: "bg_1",
  2028. });
  2029. expect(notifications.some((item) => item.method === "state.updated")).toBe(true);
  2030. });
  2031. it("sends contiguous protocol seq for the visible session event stream", async () => {
  2032. const notifications: ZCodeProtocolNotification[] = [];
  2033. const logs: RecordedLog[] = [];
  2034. let eventStore: ZCodeAppOptions["eventStore"];
  2035. let liveSink: ((event: SessionEvent) => void | Promise<void>) | undefined;
  2036. const server = new ZCodeProtocolAgentServer({
  2037. createZCodeApp: (options) => {
  2038. eventStore = options?.eventStore;
  2039. const app = createFakeApp(options);
  2040. return {
  2041. ...app,
  2042. runtime: {
  2043. ...app.runtime,
  2044. subscribeEvents: (sink: {
  2045. onSessionEvent(event: SessionEvent): void | Promise<void>;
  2046. }) => {
  2047. liveSink = sink.onSessionEvent;
  2048. return () => {};
  2049. },
  2050. } as never,
  2051. };
  2052. },
  2053. cwd: workspace.workspacePath,
  2054. loggerFactory: createProtocolTestLoggerFactory(logs),
  2055. version: "test-version",
  2056. });
  2057. setTestNotificationSink(server, (notification) => notifications.push(notification));
  2058. const created = zcodeSessionStateSnapshotSchema.parse(
  2059. await requestResult(server, {
  2060. id: 1,
  2061. method: zcodeProtocolMethods.sessionCreate,
  2062. params: { workspace },
  2063. }),
  2064. );
  2065. await requestResult(server, {
  2066. id: 2,
  2067. method: zcodeProtocolMethods.sessionSubscribe,
  2068. params: {
  2069. sessionId: created.session.sessionId,
  2070. deliveryKind: "desktop-continuous",
  2071. includeSnapshot: true,
  2072. },
  2073. });
  2074. const emitStoredEvent = async (event: SessionEvent) => {
  2075. if (!eventStore || !liveSink) {
  2076. throw new Error("Expected fake app event sink to be wired");
  2077. }
  2078. const storedEvent = await eventStore.append(event);
  2079. await liveSink(storedEvent);
  2080. };
  2081. const emitLiveOnlyEvent = async (event: SessionEvent) => {
  2082. if (!liveSink) {
  2083. throw new Error("Expected fake app event sink to be wired");
  2084. }
  2085. await liveSink(event);
  2086. };
  2087. const baseEvent = {
  2088. sessionId: created.session.sessionId as SessionId,
  2089. timestamp: new Date(7),
  2090. traceId: "trace_protocol_seq" as SessionEvent["traceId"],
  2091. type: SessionEventType.ModelStreaming,
  2092. };
  2093. await emitLiveOnlyEvent({
  2094. ...baseEvent,
  2095. id: "evt_live_text_delta_1" as SessionEvent["id"],
  2096. payload: { delta: "live", done: false, kind: "text_delta" },
  2097. sequenceNumber: 0,
  2098. });
  2099. await emitLiveOnlyEvent({
  2100. ...baseEvent,
  2101. id: "evt_live_text_delta_2" as SessionEvent["id"],
  2102. payload: { delta: " only", done: false, kind: "text_delta" },
  2103. sequenceNumber: 0,
  2104. });
  2105. await emitStoredEvent({
  2106. ...baseEvent,
  2107. id: "evt_tool_input_delta" as SessionEvent["id"],
  2108. payload: { delta: '{"file_path":"README.md"}', done: false, kind: "tool_input_delta" },
  2109. sequenceNumber: 0,
  2110. });
  2111. await emitStoredEvent({
  2112. ...baseEvent,
  2113. id: "evt_text_delta_1" as SessionEvent["id"],
  2114. payload: { delta: "hello", done: false, kind: "text_delta" },
  2115. sequenceNumber: 0,
  2116. });
  2117. await emitStoredEvent({
  2118. ...baseEvent,
  2119. id: "evt_text_delta_2" as SessionEvent["id"],
  2120. payload: { delta: " world", done: false, kind: "text_delta" },
  2121. sequenceNumber: 0,
  2122. });
  2123. await emitStoredEvent({
  2124. ...baseEvent,
  2125. id: "evt_turn_complete" as SessionEvent["id"],
  2126. payload: {
  2127. duration: 1,
  2128. response: "done",
  2129. resultType: "success",
  2130. tokenCount: 2,
  2131. toolCallCount: 0,
  2132. },
  2133. sequenceNumber: 0,
  2134. type: SessionEventType.TurnComplete,
  2135. });
  2136. const liveEvents = notifications
  2137. .filter((notification) => notification.method === "session/event")
  2138. .map((notification) => zcodeSessionEventSchema.parse(notification.params));
  2139. expect(liveEvents.map((event) => event.seq)).toEqual([1, 2, 3, 4, 5, 6]);
  2140. expect(liveEvents.map((event) => event.eventId)).toEqual([
  2141. "evt_live_text_delta_1",
  2142. "evt_live_text_delta_2",
  2143. "evt_tool_input_delta",
  2144. "evt_text_delta_1",
  2145. "evt_text_delta_2",
  2146. "evt_turn_complete",
  2147. ]);
  2148. const subscribed = zcodeSessionSubscribeResultSchema.parse(
  2149. await requestResult(server, {
  2150. id: 3,
  2151. method: zcodeProtocolMethods.sessionSubscribe,
  2152. params: {
  2153. sessionId: created.session.sessionId,
  2154. deliveryKind: "desktop-continuous",
  2155. afterSeq: 1,
  2156. includeSnapshot: true,
  2157. },
  2158. }),
  2159. );
  2160. expect(subscribed.eventSeq).toBe(6);
  2161. expect(subscribed.events.map((event) => event.seq)).toEqual([3, 4, 5, 6]);
  2162. expect(subscribed.snapshot?.runtime.eventSeq).toBe(6);
  2163. const sentLog = logs.find(
  2164. (log) =>
  2165. log.context.event === "zcode_protocol.session_event.sent" &&
  2166. log.context.eventId === "evt_text_delta_1",
  2167. );
  2168. expect(sentLog?.context).toMatchObject({
  2169. event: "zcode_protocol.session_event.sent",
  2170. eventId: "evt_text_delta_1",
  2171. payloadKeys: ["delta", "done", "kind"],
  2172. payloadKind: "text_delta",
  2173. payloadSummary: {
  2174. deltaBytes: expect.any(Number),
  2175. done: false,
  2176. kind: "text_delta",
  2177. },
  2178. protocolEventType: "model.streaming",
  2179. protocolMessageBytes: expect.any(Number),
  2180. protocolPayloadBytes: expect.any(Number),
  2181. protocolSeq: 4,
  2182. sessionEventType: SessionEventType.ModelStreaming,
  2183. });
  2184. expect(sentLog?.context.protocolMessage).toBeUndefined();
  2185. expect(JSON.stringify(sentLog?.context)).not.toContain("hello");
  2186. });
  2187. it("omits repeated scheduled tool input after model streaming tool calls", async () => {
  2188. const notifications: ZCodeProtocolNotification[] = [];
  2189. let eventStore: ZCodeAppOptions["eventStore"];
  2190. let liveSink: ((event: SessionEvent) => void | Promise<void>) | undefined;
  2191. const server = new ZCodeProtocolAgentServer({
  2192. createZCodeApp: (options) => {
  2193. eventStore = options?.eventStore;
  2194. const app = createFakeApp(options);
  2195. return {
  2196. ...app,
  2197. runtime: {
  2198. ...app.runtime,
  2199. subscribeEvents: (sink: {
  2200. onSessionEvent(event: SessionEvent): void | Promise<void>;
  2201. }) => {
  2202. liveSink = sink.onSessionEvent;
  2203. return () => {};
  2204. },
  2205. } as never,
  2206. };
  2207. },
  2208. cwd: workspace.workspacePath,
  2209. version: "test-version",
  2210. });
  2211. setTestNotificationSink(server, (notification) => notifications.push(notification));
  2212. const created = zcodeSessionStateSnapshotSchema.parse(
  2213. await requestResult(server, {
  2214. id: 1,
  2215. method: zcodeProtocolMethods.sessionCreate,
  2216. params: { workspace },
  2217. }),
  2218. );
  2219. await requestResult(server, {
  2220. id: 2,
  2221. method: zcodeProtocolMethods.sessionSubscribe,
  2222. params: {
  2223. sessionId: created.session.sessionId,
  2224. deliveryKind: "desktop-continuous",
  2225. includeSnapshot: false,
  2226. },
  2227. });
  2228. const emitStoredEvent = async (event: SessionEvent) => {
  2229. if (!eventStore || !liveSink) {
  2230. throw new Error("Expected fake app event sink to be wired");
  2231. }
  2232. const storedEvent = await eventStore.append(event);
  2233. await liveSink(storedEvent);
  2234. };
  2235. const toolInput = {
  2236. content: "generated content\n".repeat(512),
  2237. file_path: "/workspace/generated.html",
  2238. };
  2239. const inputByteLength = Buffer.byteLength(JSON.stringify(toolInput), "utf8");
  2240. const baseEvent = {
  2241. sessionId: created.session.sessionId as SessionId,
  2242. timestamp: new Date(7),
  2243. traceId: "trace_tool_input_dedupe" as SessionEvent["traceId"],
  2244. };
  2245. await emitStoredEvent({
  2246. ...baseEvent,
  2247. id: "evt_tool_call" as SessionEvent["id"],
  2248. payload: {
  2249. done: true,
  2250. input: toolInput,
  2251. kind: "tool_call",
  2252. toolCallId: "call_write",
  2253. toolName: "Write",
  2254. },
  2255. sequenceNumber: 0,
  2256. type: SessionEventType.ModelStreaming,
  2257. });
  2258. await emitStoredEvent({
  2259. ...baseEvent,
  2260. id: "evt_tool_scheduled" as SessionEvent["id"],
  2261. payload: {
  2262. input: toolInput,
  2263. schedule: { dependencies: [] },
  2264. toolCallId: "call_write",
  2265. toolName: "Write",
  2266. },
  2267. sequenceNumber: 0,
  2268. type: SessionEventType.ToolCallScheduled,
  2269. });
  2270. await emitStoredEvent({
  2271. ...baseEvent,
  2272. id: "evt_tool_ledger" as SessionEvent["id"],
  2273. payload: {
  2274. input: toolInput,
  2275. status: "tool_started",
  2276. toolCallId: "call_write",
  2277. toolName: "Write",
  2278. },
  2279. sequenceNumber: 0,
  2280. type: SessionEventType.StreamingToolLedgerUpdated,
  2281. });
  2282. const liveEvents = notifications
  2283. .filter((notification) => notification.method === "session/event")
  2284. .map((notification) => zcodeSessionEventSchema.parse(notification.params));
  2285. expect(liveEvents.map((event) => event.eventId)).toEqual([
  2286. "evt_tool_call",
  2287. "evt_tool_scheduled",
  2288. ]);
  2289. expect(liveEvents.map((event) => event.seq)).toEqual([1, 2]);
  2290. const liveScheduledPayload = liveEvents[1]?.payload as Record<string, unknown>;
  2291. expect(liveScheduledPayload).toMatchObject({
  2292. inputByteLength,
  2293. inputOmitted: true,
  2294. inputRef: "model_stream",
  2295. kind: "scheduled",
  2296. toolCallId: "call_write",
  2297. toolName: "Write",
  2298. });
  2299. expect(Object.prototype.hasOwnProperty.call(liveScheduledPayload, "input")).toBe(false);
  2300. const replayed = zcodeSessionEventsResultSchema.parse(
  2301. await requestResult(server, {
  2302. id: 3,
  2303. method: zcodeProtocolMethods.sessionEvents,
  2304. params: { sessionId: created.session.sessionId, afterSeq: 0 },
  2305. }),
  2306. );
  2307. expect(replayed.events.map((event) => event.eventId)).toEqual([
  2308. "evt_tool_call",
  2309. "evt_tool_scheduled",
  2310. ]);
  2311. const replayScheduledPayload = replayed.events[1]?.payload as Record<string, unknown>;
  2312. expect(replayScheduledPayload).toMatchObject({
  2313. inputByteLength,
  2314. inputOmitted: true,
  2315. inputRef: "model_stream",
  2316. kind: "scheduled",
  2317. toolCallId: "call_write",
  2318. toolName: "Write",
  2319. });
  2320. expect(Object.prototype.hasOwnProperty.call(replayScheduledPayload, "input")).toBe(false);
  2321. expect(JSON.stringify(liveScheduledPayload)).not.toContain("generated content");
  2322. expect(JSON.stringify(replayScheduledPayload)).not.toContain("generated content");
  2323. });
  2324. it("coalesces streaming tool input deltas with eager and timestamp-budgeted flushes", async () => {
  2325. const notifications: ZCodeProtocolNotification[] = [];
  2326. let eventStore: ZCodeAppOptions["eventStore"];
  2327. let liveSink: ((event: SessionEvent) => void | Promise<void>) | undefined;
  2328. const server = new ZCodeProtocolAgentServer({
  2329. createZCodeApp: (options) => {
  2330. eventStore = options?.eventStore;
  2331. const app = createFakeApp(options);
  2332. return {
  2333. ...app,
  2334. runtime: {
  2335. ...app.runtime,
  2336. subscribeEvents: (sink: {
  2337. onSessionEvent(event: SessionEvent): void | Promise<void>;
  2338. }) => {
  2339. liveSink = sink.onSessionEvent;
  2340. return () => {};
  2341. },
  2342. } as never,
  2343. };
  2344. },
  2345. cwd: workspace.workspacePath,
  2346. version: "test-version",
  2347. });
  2348. setTestNotificationSink(server, (notification) => notifications.push(notification));
  2349. const created = zcodeSessionStateSnapshotSchema.parse(
  2350. await requestResult(server, {
  2351. id: 1,
  2352. method: zcodeProtocolMethods.sessionCreate,
  2353. params: { workspace },
  2354. }),
  2355. );
  2356. await requestResult(server, {
  2357. id: 2,
  2358. method: zcodeProtocolMethods.sessionSubscribe,
  2359. params: {
  2360. sessionId: created.session.sessionId,
  2361. deliveryKind: "desktop-continuous",
  2362. includeSnapshot: false,
  2363. },
  2364. });
  2365. const emitStoredEvent = async (event: SessionEvent) => {
  2366. if (!eventStore || !liveSink) {
  2367. throw new Error("Expected fake app event sink to be wired");
  2368. }
  2369. const storedEvent = await eventStore.append(event);
  2370. await liveSink(storedEvent);
  2371. };
  2372. const baseEvent = {
  2373. sessionId: created.session.sessionId as SessionId,
  2374. traceId: "trace_tool_delta_coalesce" as SessionEvent["traceId"],
  2375. type: SessionEventType.ModelStreaming,
  2376. };
  2377. for (const [index, item] of [
  2378. { delta: "a", timestamp: 7 },
  2379. { delta: "b", timestamp: 407 },
  2380. { delta: "c", timestamp: 758 },
  2381. ].entries()) {
  2382. await emitStoredEvent({
  2383. ...baseEvent,
  2384. id: `evt_tool_delta_${index + 1}` as SessionEvent["id"],
  2385. payload: {
  2386. delta: item.delta,
  2387. done: false,
  2388. kind: "tool_input_delta",
  2389. toolCallId: "call_write",
  2390. toolName: "Write",
  2391. },
  2392. sequenceNumber: 0,
  2393. timestamp: new Date(item.timestamp),
  2394. });
  2395. }
  2396. await emitStoredEvent({
  2397. ...baseEvent,
  2398. id: "evt_tool_input_end" as SessionEvent["id"],
  2399. payload: {
  2400. done: true,
  2401. kind: "tool_input_end",
  2402. toolCallId: "call_write",
  2403. toolName: "Write",
  2404. },
  2405. sequenceNumber: 0,
  2406. timestamp: new Date(759),
  2407. });
  2408. const liveEvents = notifications
  2409. .filter((notification) => notification.method === "session/event")
  2410. .map((notification) => zcodeSessionEventSchema.parse(notification.params));
  2411. expect(liveEvents.map((event) => event.seq)).toEqual([1, 2, 3]);
  2412. expect(liveEvents.map((event) => event.eventId)).toEqual([
  2413. "evt_tool_delta_1",
  2414. "evt_tool_delta_3",
  2415. "evt_tool_input_end",
  2416. ]);
  2417. expect(liveEvents[0]?.payload).toMatchObject({
  2418. delta: "a",
  2419. kind: "tool_input_delta",
  2420. toolCallId: "call_write",
  2421. });
  2422. expect(liveEvents[1]?.payload).toMatchObject({
  2423. delta: "bc",
  2424. kind: "tool_input_delta",
  2425. toolCallId: "call_write",
  2426. });
  2427. const replayed = zcodeSessionEventsResultSchema.parse(
  2428. await requestResult(server, {
  2429. id: 3,
  2430. method: zcodeProtocolMethods.sessionEvents,
  2431. params: { sessionId: created.session.sessionId, afterSeq: 0 },
  2432. }),
  2433. );
  2434. expect(replayed.events.map((event) => event.seq)).toEqual([1, 2, 3]);
  2435. expect(replayed.events[0]?.payload).toMatchObject({
  2436. delta: "a",
  2437. kind: "tool_input_delta",
  2438. toolCallId: "call_write",
  2439. });
  2440. expect(replayed.events[1]?.payload).toMatchObject({
  2441. delta: "bc",
  2442. kind: "tool_input_delta",
  2443. toolCallId: "call_write",
  2444. });
  2445. });
  2446. it("coalesces text and reasoning streaming deltas after the first visible token", async () => {
  2447. const notifications: ZCodeProtocolNotification[] = [];
  2448. let eventStore: ZCodeAppOptions["eventStore"];
  2449. let liveSink: ((event: SessionEvent) => void | Promise<void>) | undefined;
  2450. const server = new ZCodeProtocolAgentServer({
  2451. createZCodeApp: (options) => {
  2452. eventStore = options?.eventStore;
  2453. const app = createFakeApp(options);
  2454. return {
  2455. ...app,
  2456. runtime: {
  2457. ...app.runtime,
  2458. subscribeEvents: (sink: {
  2459. onSessionEvent(event: SessionEvent): void | Promise<void>;
  2460. }) => {
  2461. liveSink = sink.onSessionEvent;
  2462. return () => {};
  2463. },
  2464. } as never,
  2465. };
  2466. },
  2467. cwd: workspace.workspacePath,
  2468. version: "test-version",
  2469. });
  2470. setTestNotificationSink(server, (notification) => notifications.push(notification));
  2471. const created = zcodeSessionStateSnapshotSchema.parse(
  2472. await requestResult(server, {
  2473. id: 1,
  2474. method: zcodeProtocolMethods.sessionCreate,
  2475. params: { workspace },
  2476. }),
  2477. );
  2478. await requestResult(server, {
  2479. id: 2,
  2480. method: zcodeProtocolMethods.sessionSubscribe,
  2481. params: {
  2482. sessionId: created.session.sessionId,
  2483. deliveryKind: "desktop-continuous",
  2484. includeSnapshot: false,
  2485. },
  2486. });
  2487. const emitStoredEvent = async (event: SessionEvent) => {
  2488. if (!eventStore || !liveSink) {
  2489. throw new Error("Expected fake app event sink to be wired");
  2490. }
  2491. const storedEvent = await eventStore.append(event);
  2492. await liveSink(storedEvent);
  2493. };
  2494. const baseEvent = {
  2495. sessionId: created.session.sessionId as SessionId,
  2496. traceId: "trace_text_delta_coalesce" as SessionEvent["traceId"],
  2497. type: SessionEventType.ModelStreaming,
  2498. };
  2499. for (const [index, delta] of ["first", " second", " third"].entries()) {
  2500. await emitStoredEvent({
  2501. ...baseEvent,
  2502. id: `evt_reasoning_delta_${index + 1}` as SessionEvent["id"],
  2503. timestamp: new Date([0, 100, 260][index] ?? 260),
  2504. payload: {
  2505. assistantMessageId: "msg_reasoning",
  2506. delta,
  2507. done: false,
  2508. kind: "reasoning_delta",
  2509. },
  2510. sequenceNumber: 0,
  2511. });
  2512. }
  2513. const liveEventsBeforeTurnComplete = notifications
  2514. .filter((notification) => notification.method === "session/event")
  2515. .map((notification) => zcodeSessionEventSchema.parse(notification.params));
  2516. expect(liveEventsBeforeTurnComplete.map((event) => event.eventId)).toEqual([
  2517. "evt_reasoning_delta_1",
  2518. "evt_reasoning_delta_3",
  2519. ]);
  2520. await emitStoredEvent({
  2521. ...baseEvent,
  2522. id: "evt_turn_complete_after_reasoning" as SessionEvent["id"],
  2523. timestamp: new Date(300),
  2524. payload: {
  2525. duration: 1,
  2526. response: "done",
  2527. resultType: "success",
  2528. tokenCount: 3,
  2529. toolCallCount: 0,
  2530. },
  2531. sequenceNumber: 0,
  2532. type: SessionEventType.TurnComplete,
  2533. });
  2534. const liveEvents = notifications
  2535. .filter((notification) => notification.method === "session/event")
  2536. .map((notification) => zcodeSessionEventSchema.parse(notification.params));
  2537. expect(liveEvents.map((event) => event.seq)).toEqual([1, 2, 3]);
  2538. expect(liveEvents.map((event) => event.eventId)).toEqual([
  2539. "evt_reasoning_delta_1",
  2540. "evt_reasoning_delta_3",
  2541. "evt_turn_complete_after_reasoning",
  2542. ]);
  2543. expect(liveEvents[0]?.payload).toMatchObject({
  2544. delta: "first",
  2545. kind: "reasoning_delta",
  2546. });
  2547. expect(liveEvents[1]?.payload).toMatchObject({
  2548. delta: " second third",
  2549. kind: "reasoning_delta",
  2550. });
  2551. const replayed = zcodeSessionEventsResultSchema.parse(
  2552. await requestResult(server, {
  2553. id: 3,
  2554. method: zcodeProtocolMethods.sessionEvents,
  2555. params: { sessionId: created.session.sessionId, afterSeq: 0 },
  2556. }),
  2557. );
  2558. expect(replayed.events.map((event) => event.seq)).toEqual([1, 2, 3]);
  2559. expect(replayed.events[1]?.payload).toMatchObject({
  2560. delta: " second third",
  2561. kind: "reasoning_delta",
  2562. });
  2563. });
  2564. it("keeps separate text streaming parts in separate protocol batches", async () => {
  2565. const notifications: ZCodeProtocolNotification[] = [];
  2566. let eventStore: ZCodeAppOptions["eventStore"];
  2567. let liveSink: ((event: SessionEvent) => void | Promise<void>) | undefined;
  2568. const server = new ZCodeProtocolAgentServer({
  2569. createZCodeApp: (options) => {
  2570. eventStore = options?.eventStore;
  2571. const app = createFakeApp(options);
  2572. return {
  2573. ...app,
  2574. runtime: {
  2575. ...app.runtime,
  2576. subscribeEvents: (sink: {
  2577. onSessionEvent(event: SessionEvent): void | Promise<void>;
  2578. }) => {
  2579. liveSink = sink.onSessionEvent;
  2580. return () => {};
  2581. },
  2582. } as never,
  2583. };
  2584. },
  2585. cwd: workspace.workspacePath,
  2586. version: "test-version",
  2587. });
  2588. setTestNotificationSink(server, (notification) => notifications.push(notification));
  2589. const created = zcodeSessionStateSnapshotSchema.parse(
  2590. await requestResult(server, {
  2591. id: 1,
  2592. method: zcodeProtocolMethods.sessionCreate,
  2593. params: { workspace },
  2594. }),
  2595. );
  2596. await requestResult(server, {
  2597. id: 2,
  2598. method: zcodeProtocolMethods.sessionSubscribe,
  2599. params: {
  2600. sessionId: created.session.sessionId,
  2601. deliveryKind: "desktop-continuous",
  2602. includeSnapshot: false,
  2603. },
  2604. });
  2605. const emitStoredEvent = async (event: SessionEvent) => {
  2606. if (!eventStore || !liveSink) {
  2607. throw new Error("Expected fake app event sink to be wired");
  2608. }
  2609. const storedEvent = await eventStore.append(event);
  2610. await liveSink(storedEvent);
  2611. };
  2612. const baseEvent = {
  2613. sessionId: created.session.sessionId as SessionId,
  2614. timestamp: new Date(7),
  2615. traceId: "trace_parent_text_delta_coalesce" as SessionEvent["traceId"],
  2616. type: SessionEventType.ModelStreaming,
  2617. };
  2618. await emitStoredEvent({
  2619. ...baseEvent,
  2620. id: "evt_parent_a_text_delta" as SessionEvent["id"],
  2621. payload: {
  2622. delta: "from-a",
  2623. done: false,
  2624. kind: "text_delta",
  2625. partId: "part_a",
  2626. },
  2627. sequenceNumber: 0,
  2628. });
  2629. await emitStoredEvent({
  2630. ...baseEvent,
  2631. id: "evt_parent_b_text_delta" as SessionEvent["id"],
  2632. payload: {
  2633. delta: "from-b",
  2634. done: false,
  2635. kind: "text_delta",
  2636. partId: "part_b",
  2637. },
  2638. sequenceNumber: 0,
  2639. });
  2640. const liveEvents = notifications
  2641. .filter((notification) => notification.method === "session/event")
  2642. .map((notification) => zcodeSessionEventSchema.parse(notification.params));
  2643. expect(liveEvents.map((event) => event.eventId)).toEqual([
  2644. "evt_parent_a_text_delta",
  2645. "evt_parent_b_text_delta",
  2646. ]);
  2647. expect(liveEvents.map((event) => event.payload)).toEqual([
  2648. expect.objectContaining({
  2649. delta: "from-a",
  2650. kind: "text_delta",
  2651. partId: "part_a",
  2652. }),
  2653. expect.objectContaining({
  2654. delta: "from-b",
  2655. kind: "text_delta",
  2656. partId: "part_b",
  2657. }),
  2658. ]);
  2659. });
  2660. it("creates imported sessions as resumable protocol sessions", async () => {
  2661. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  2662. const importedWorkspace = {
  2663. ...workspace,
  2664. workspaceIdentity: "ssh:example:/workspace/app",
  2665. };
  2666. try {
  2667. const server = new ZCodeProtocolAgentServer({
  2668. createZCodeApp: (options) => createFakeApp(options),
  2669. cwd: importedWorkspace.workspacePath,
  2670. sessionStore: store,
  2671. version: "test-version",
  2672. });
  2673. const created = zcodeSessionStateSnapshotSchema.parse(
  2674. await requestResult(server, {
  2675. id: 1,
  2676. method: zcodeProtocolMethods.sessionCreate,
  2677. params: {
  2678. workspace: importedWorkspace,
  2679. sessionId: "claude-import-test-session",
  2680. importedHistory: {
  2681. source: "claudeCode",
  2682. title: "Imported Claude Session",
  2683. createdAt: 1_700_000_000_000,
  2684. updatedAt: 1_700_000_001_000,
  2685. messages: [
  2686. {
  2687. role: "user",
  2688. content: "继续这个导入会话",
  2689. timestamp: 1_700_000_001_000,
  2690. },
  2691. {
  2692. role: "assistant",
  2693. content: "可以继续。",
  2694. timestamp: 1_700_000_000_500,
  2695. },
  2696. ],
  2697. },
  2698. },
  2699. }),
  2700. );
  2701. expect(created.session.title).toBe("Imported Claude Session");
  2702. expect(created.session.sessionId).toBe("claude-import-test-session");
  2703. await expect(
  2704. store.getSession("claude-import-test-session" as SessionId),
  2705. ).resolves.toMatchObject({
  2706. workspaceID: importedWorkspace.workspaceIdentity,
  2707. });
  2708. expect(messageTexts(created.messages)).toEqual(["继续这个导入会话", "可以继续。"]);
  2709. const switched = zcodeSessionStateSnapshotSchema.parse(
  2710. await requestResult(server, {
  2711. id: 2,
  2712. method: zcodeProtocolMethods.sessionSetModel,
  2713. params: {
  2714. sessionId: created.session.sessionId,
  2715. model: { providerId: "glm", modelId: "glm-4-air" },
  2716. },
  2717. }),
  2718. );
  2719. expect(switched.session.sessionId).toBe(created.session.sessionId);
  2720. expect(switched.settings.model.current).toMatchObject({
  2721. providerId: "glm",
  2722. modelId: "glm-4-air",
  2723. });
  2724. expect(messageTexts(switched.messages)).toEqual(["继续这个导入会话", "可以继续。"]);
  2725. await requestResult(server, {
  2726. id: 3,
  2727. method: zcodeProtocolMethods.sessionCreate,
  2728. params: {
  2729. workspace: importedWorkspace,
  2730. sessionId: "claude-import-second-session",
  2731. importedHistory: {
  2732. source: "claudeCode",
  2733. title: "Second Imported Claude Session",
  2734. messages: [
  2735. {
  2736. role: "user",
  2737. content: "第二个导入会话",
  2738. timestamp: 1_700_000_003_000,
  2739. },
  2740. {
  2741. role: "assistant",
  2742. content: "第二个也可以继续。",
  2743. timestamp: 1_700_000_002_000,
  2744. },
  2745. ],
  2746. },
  2747. },
  2748. });
  2749. const rereadFirst = zcodeSessionStateSnapshotSchema.parse(
  2750. await requestResult(server, {
  2751. id: 4,
  2752. method: zcodeProtocolMethods.sessionRead,
  2753. params: { sessionId: created.session.sessionId },
  2754. }),
  2755. );
  2756. const secondMessages = await store.messages({
  2757. sessionID: "claude-import-second-session" as SessionId,
  2758. });
  2759. expect(messageTexts(rereadFirst.messages)).toEqual(["继续这个导入会话", "可以继续。"]);
  2760. expect(messageTexts(secondMessages)).toEqual(["第二个导入会话", "第二个也可以继续。"]);
  2761. expect(secondMessages.map((message) => message.info.id)).toEqual([
  2762. "msg_claude-import-second-session_import_0",
  2763. "msg_claude-import-second-session_import_1",
  2764. ]);
  2765. } finally {
  2766. store.close();
  2767. }
  2768. });
  2769. it("accepts an assigned fresh ID and rejects replacement of the existing runtime", async () => {
  2770. const server = new ZCodeProtocolAgentServer({
  2771. createZCodeApp: (options) => createFakeApp(options),
  2772. cwd: workspace.workspacePath,
  2773. version: "test-version",
  2774. });
  2775. const params = { workspace, sessionId: "host-assigned-session" };
  2776. const first = await server.handleMessage({
  2777. id: 1,
  2778. method: zcodeProtocolMethods.sessionCreate,
  2779. params,
  2780. });
  2781. expect(first).toHaveProperty("result.session.sessionId", params.sessionId);
  2782. const again = await server.handleMessage({
  2783. id: 2,
  2784. method: zcodeProtocolMethods.sessionCreate,
  2785. params,
  2786. });
  2787. expect(again).toMatchObject({ error: { code: -32602, message: "sessionId already exists" } });
  2788. });
  2789. it("rejects concurrent creation of the same assigned ID while materializing", async () => {
  2790. let release!: () => void;
  2791. let started!: () => void;
  2792. const entered = new Promise<void>((resolve) => {
  2793. started = resolve;
  2794. });
  2795. const gate = new Promise<void>((resolve) => {
  2796. release = resolve;
  2797. });
  2798. const server = new ZCodeProtocolAgentServer({
  2799. createZCodeApp: async (options) => {
  2800. started();
  2801. await gate;
  2802. return createFakeApp(options);
  2803. },
  2804. cwd: workspace.workspacePath,
  2805. version: "test-version",
  2806. });
  2807. const params = { workspace, sessionId: "concurrent-create" };
  2808. const first = server.handleMessage({
  2809. id: 1,
  2810. method: zcodeProtocolMethods.sessionCreate,
  2811. params,
  2812. });
  2813. await entered;
  2814. const second = await server.handleMessage({
  2815. id: 2,
  2816. method: zcodeProtocolMethods.sessionCreate,
  2817. params,
  2818. });
  2819. release();
  2820. expect(second).toMatchObject({ error: { code: -32602, message: "sessionId already exists" } });
  2821. expect(await first).toHaveProperty("result.session.sessionId", params.sessionId);
  2822. });
  2823. it("keeps session title generation internals out of the visible event stream", async () => {
  2824. const notifications: ZCodeProtocolNotification[] = [];
  2825. let eventStore: ZCodeAppOptions["eventStore"];
  2826. let liveSink: ((event: SessionEvent) => void | Promise<void>) | undefined;
  2827. const server = new ZCodeProtocolAgentServer({
  2828. createZCodeApp: (options) => {
  2829. eventStore = options?.eventStore;
  2830. const app = createFakeApp(options);
  2831. return {
  2832. ...app,
  2833. runtime: {
  2834. ...app.runtime,
  2835. subscribeEvents: (sink: {
  2836. onSessionEvent(event: SessionEvent): void | Promise<void>;
  2837. }) => {
  2838. liveSink = sink.onSessionEvent;
  2839. return () => {};
  2840. },
  2841. } as never,
  2842. };
  2843. },
  2844. cwd: workspace.workspacePath,
  2845. version: "test-version",
  2846. });
  2847. setTestNotificationSink(server, (notification) => notifications.push(notification));
  2848. const created = zcodeSessionStateSnapshotSchema.parse(
  2849. await requestResult(server, {
  2850. id: 1,
  2851. method: zcodeProtocolMethods.sessionCreate,
  2852. params: { workspace },
  2853. }),
  2854. );
  2855. await requestResult(server, {
  2856. id: 2,
  2857. method: zcodeProtocolMethods.sessionSubscribe,
  2858. params: {
  2859. sessionId: created.session.sessionId,
  2860. deliveryKind: "desktop-continuous",
  2861. },
  2862. });
  2863. const emitStoredEvent = async (event: SessionEvent) => {
  2864. if (!eventStore || !liveSink) {
  2865. throw new Error("Expected fake app event sink to be wired");
  2866. }
  2867. const storedEvent = await eventStore.append(event);
  2868. await liveSink(storedEvent);
  2869. };
  2870. const common = {
  2871. sessionId: created.session.sessionId as SessionId,
  2872. timestamp: new Date(8),
  2873. traceId: "trace_title_generation" as SessionEvent["traceId"],
  2874. turnId: "turn_title" as SessionEvent["turnId"],
  2875. };
  2876. await emitStoredEvent({
  2877. ...common,
  2878. id: "evt_turn_complete" as SessionEvent["id"],
  2879. payload: {
  2880. response: "done",
  2881. tokenCount: 1,
  2882. toolCallCount: 0,
  2883. duration: 1,
  2884. resultType: "success",
  2885. },
  2886. sequenceNumber: 0,
  2887. type: SessionEventType.TurnComplete,
  2888. });
  2889. await emitStoredEvent({
  2890. ...common,
  2891. id: "evt_title_model_request" as SessionEvent["id"],
  2892. payload: {
  2893. messages: [],
  2894. model: "glm/glm-4.6",
  2895. querySource: "session_title",
  2896. toolCount: 0,
  2897. },
  2898. sequenceNumber: 0,
  2899. type: SessionEventType.ModelRequest,
  2900. });
  2901. await emitStoredEvent({
  2902. ...common,
  2903. id: "evt_title_model_status_started" as SessionEvent["id"],
  2904. payload: {
  2905. attempt: 1,
  2906. maxAttempts: 11,
  2907. model: { modelId: "glm-0606", providerId: "zai" },
  2908. querySource: "session_title",
  2909. requestId: "request_title",
  2910. timestamp: "2026-06-03T10:33:41.048Z",
  2911. traceId: "trace_title_generation",
  2912. transport: "http",
  2913. type: "model_request_started",
  2914. },
  2915. sequenceNumber: 0,
  2916. type: SessionEventType.ModelNetworkStatus,
  2917. });
  2918. await emitStoredEvent({
  2919. ...common,
  2920. id: "evt_main_model_retry" as SessionEvent["id"],
  2921. payload: {
  2922. attempt: 2,
  2923. delayMs: 1234,
  2924. maxAttempts: 11,
  2925. message: "Provider returned a server error.",
  2926. model: { modelId: "glm-0606", providerId: "zai" },
  2927. nextAttempt: 3,
  2928. querySource: "main_turn",
  2929. reason: "server_error",
  2930. requestId: "request_main",
  2931. statusCode: 502,
  2932. timestamp: "2026-06-03T10:33:43.048Z",
  2933. traceId: "trace_title_generation",
  2934. transport: "http",
  2935. type: "model_retry_scheduled",
  2936. },
  2937. sequenceNumber: 0,
  2938. type: SessionEventType.ModelNetworkStatus,
  2939. });
  2940. await emitStoredEvent({
  2941. ...common,
  2942. id: "evt_title_model_complete" as SessionEvent["id"],
  2943. payload: {
  2944. content: '{"title":"Done"}',
  2945. querySource: "session_title",
  2946. stopReason: "stop",
  2947. toolCallCount: 0,
  2948. },
  2949. sequenceNumber: 0,
  2950. type: SessionEventType.ModelComplete,
  2951. });
  2952. await emitStoredEvent({
  2953. ...common,
  2954. id: "evt_title_updated" as SessionEvent["id"],
  2955. payload: {
  2956. previousTitle: "Old title",
  2957. source: "generated",
  2958. title: "Done",
  2959. },
  2960. sequenceNumber: 0,
  2961. type: SessionEventType.SessionTitleUpdated,
  2962. });
  2963. const liveEvents = notifications
  2964. .filter((notification) => notification.method === "session/event")
  2965. .map((notification) => zcodeSessionEventSchema.parse(notification.params));
  2966. expect(liveEvents.map((event) => [event.seq, event.type])).toEqual([
  2967. [1, "turn.completed"],
  2968. [2, "session.updated"],
  2969. [3, "session.titleUpdated"],
  2970. ]);
  2971. expect(liveEvents[1]?.payload).toMatchObject({
  2972. _meta: {
  2973. zcode: {
  2974. apiRetry: {
  2975. attempt: 2,
  2976. errorStatus: 502,
  2977. kind: "api_retry",
  2978. maxRetries: 10,
  2979. retryDelayMs: 1234,
  2980. },
  2981. },
  2982. },
  2983. querySource: "main_turn",
  2984. type: "model_retry_scheduled",
  2985. });
  2986. });
  2987. it("publishes core stream recovery retry counts as apiRetry meta", async () => {
  2988. const notifications: Array<{ method: string; params: unknown }> = [];
  2989. let eventStore: SessionEventStore | undefined;
  2990. let liveSink: ((event: SessionEvent) => void | Promise<void>) | undefined;
  2991. const server = new ZCodeProtocolAgentServer({
  2992. createZCodeApp: (options) => {
  2993. eventStore = options?.eventStore;
  2994. const app = createFakeApp(options);
  2995. return {
  2996. ...app,
  2997. runtime: {
  2998. ...app.runtime,
  2999. subscribeEvents: (sink: {
  3000. onSessionEvent(event: SessionEvent): void | Promise<void>;
  3001. }) => {
  3002. liveSink = sink.onSessionEvent;
  3003. return () => {};
  3004. },
  3005. } as never,
  3006. };
  3007. },
  3008. cwd: workspace.workspacePath,
  3009. version: "test-version",
  3010. });
  3011. setTestNotificationSink(server, (notification) => notifications.push(notification));
  3012. const created = zcodeSessionStateSnapshotSchema.parse(
  3013. await requestResult(server, {
  3014. id: 1,
  3015. method: zcodeProtocolMethods.sessionCreate,
  3016. params: { workspace },
  3017. }),
  3018. );
  3019. await requestResult(server, {
  3020. id: 2,
  3021. method: zcodeProtocolMethods.sessionSubscribe,
  3022. params: {
  3023. sessionId: created.session.sessionId,
  3024. deliveryKind: "desktop-continuous",
  3025. },
  3026. });
  3027. if (!eventStore || !liveSink) {
  3028. throw new Error("Expected fake app event sink to be wired");
  3029. }
  3030. const storedEvent = await eventStore.append({
  3031. id: "evt_stream_recovery_retry" as SessionEvent["id"],
  3032. payload: {
  3033. attempt: 1,
  3034. maxAttempts: 11,
  3035. model: { modelId: "glm-0606", providerId: "zai" },
  3036. requestId: "request_recovery",
  3037. streamRecovery: {
  3038. attemptId: "stream_attempt_1",
  3039. anchorId: "anchor_1",
  3040. maxRetries: 10,
  3041. recoveredFromRequestId: "request_failed",
  3042. retryNumber: 3,
  3043. },
  3044. timestamp: "2026-06-03T10:33:43.048Z",
  3045. traceId: "trace_stream_recovery",
  3046. transport: "http",
  3047. type: "model_request_started",
  3048. },
  3049. sequenceNumber: 0,
  3050. sessionId: created.session.sessionId as SessionId,
  3051. timestamp: new Date(8),
  3052. traceId: "trace_stream_recovery" as SessionEvent["traceId"],
  3053. turnId: "turn_stream_recovery" as SessionEvent["turnId"],
  3054. type: SessionEventType.ModelNetworkStatus,
  3055. });
  3056. await liveSink(storedEvent);
  3057. const liveEvents = notifications
  3058. .filter((notification) => notification.method === "session/event")
  3059. .map((notification) => zcodeSessionEventSchema.parse(notification.params));
  3060. expect(liveEvents.at(-1)?.payload).toMatchObject({
  3061. _meta: {
  3062. zcode: {
  3063. apiRetry: {
  3064. attempt: 3,
  3065. errorStatus: null,
  3066. kind: "api_retry",
  3067. maxRetries: 10,
  3068. retryDelayMs: 0,
  3069. },
  3070. },
  3071. },
  3072. streamRecovery: {
  3073. recoveredFromRequestId: "request_failed",
  3074. retryNumber: 3,
  3075. },
  3076. type: "model_request_started",
  3077. });
  3078. const progressEvent = await eventStore.append({
  3079. id: "evt_stream_recovery_progress" as SessionEvent["id"],
  3080. payload: {
  3081. attemptId: "stream_attempt_2",
  3082. failedRequestId: "request_recovery",
  3083. maxRetries: 10,
  3084. recoveredFromRequestId: "request_recovery",
  3085. retryNumber: 4,
  3086. streamMode: "sse",
  3087. },
  3088. sequenceNumber: 0,
  3089. sessionId: created.session.sessionId as SessionId,
  3090. timestamp: new Date(9),
  3091. traceId: "trace_stream_recovery" as SessionEvent["traceId"],
  3092. turnId: "turn_stream_recovery" as SessionEvent["turnId"],
  3093. type: SessionEventType.StreamRecoveryRetryStarted,
  3094. });
  3095. await liveSink(progressEvent);
  3096. const progressEvents = notifications
  3097. .filter((notification) => notification.method === "session/event")
  3098. .map((notification) => zcodeSessionEventSchema.parse(notification.params));
  3099. expect(progressEvents.at(-1)).toMatchObject({
  3100. type: "streamRecovery.updated",
  3101. payload: {
  3102. _meta: {
  3103. zcode: {
  3104. apiRetry: {
  3105. attempt: 4,
  3106. errorStatus: null,
  3107. kind: "api_retry",
  3108. maxRetries: 10,
  3109. retryDelayMs: 0,
  3110. },
  3111. },
  3112. },
  3113. recoveredFromRequestId: "request_recovery",
  3114. retryNumber: 4,
  3115. },
  3116. });
  3117. });
  3118. it("returns direct session snapshots for create/read and wrapped subscribe results", async () => {
  3119. const server = new ZCodeProtocolAgentServer({
  3120. createZCodeApp: (options) => createFakeApp(options),
  3121. cwd: workspace.workspacePath,
  3122. version: "test-version",
  3123. });
  3124. const created = zcodeSessionStateSnapshotSchema.parse(
  3125. await requestResult(server, {
  3126. id: 1,
  3127. method: zcodeProtocolMethods.sessionCreate,
  3128. params: { workspace },
  3129. }),
  3130. );
  3131. expect(created.protocol).toEqual({ name: "ZCode Protocol", version: 1 });
  3132. expect(created.session.workspace.workspaceKey).toBe(workspace.workspaceKey);
  3133. const read = zcodeSessionStateSnapshotSchema.parse(
  3134. await requestResult(server, {
  3135. id: 2,
  3136. method: zcodeProtocolMethods.sessionRead,
  3137. params: { sessionId: created.session.sessionId },
  3138. }),
  3139. );
  3140. expect(read.session.sessionId).toBe(created.session.sessionId);
  3141. const subscribed = zcodeSessionSubscribeResultSchema.parse(
  3142. await requestResult(server, {
  3143. id: 3,
  3144. method: zcodeProtocolMethods.sessionSubscribe,
  3145. params: {
  3146. sessionId: created.session.sessionId,
  3147. deliveryKind: "desktop-continuous",
  3148. includeSnapshot: true,
  3149. },
  3150. }),
  3151. );
  3152. expect(subscribed.sessionId).toBe(created.session.sessionId);
  3153. expect(subscribed.snapshot?.session.sessionId).toBe(created.session.sessionId);
  3154. });
  3155. it("session/read contentProfile=index 剥离大载荷,缺省仍返回完整历史", async () => {
  3156. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  3157. const big = "y".repeat(512 * 1024);
  3158. try {
  3159. const server = new ZCodeProtocolAgentServer({
  3160. createZCodeApp: (options) => {
  3161. const app = createFakeApp(options);
  3162. app.readTarget = async () => ({
  3163. sessionID: app.sessionId,
  3164. targetID: "goal_index_profile" as never,
  3165. objective: "查一下订单",
  3166. summaryTitle: null,
  3167. status: "active",
  3168. tokenBudget: 100_000,
  3169. tokensUsed: 0,
  3170. timeUsedSeconds: 0,
  3171. time: { created: 10, updated: 30 },
  3172. });
  3173. return app;
  3174. },
  3175. cwd: workspace.workspacePath,
  3176. sessionStore: store,
  3177. version: "test-version",
  3178. });
  3179. const created = zcodeSessionStateSnapshotSchema.parse(
  3180. await requestResult(server, {
  3181. id: 1,
  3182. method: zcodeProtocolMethods.sessionCreate,
  3183. params: { workspace },
  3184. }),
  3185. );
  3186. const sessionID = created.session.sessionId as SessionId;
  3187. if (!(await store.getSession(sessionID))) {
  3188. await store.createSession({
  3189. id: sessionID,
  3190. projectID: "project_index_profile" as ProjectId,
  3191. slug: "index-profile",
  3192. directory: workspace.workspacePath,
  3193. path: workspace.workspacePath,
  3194. title: "Index profile",
  3195. version: "test-version",
  3196. time: { created: 1, updated: 1 },
  3197. });
  3198. }
  3199. const userId = "msg_index_user" as MessageId;
  3200. const assistantId = "msg_index_assistant" as MessageId;
  3201. await store.saveMessage({
  3202. id: userId,
  3203. sessionID,
  3204. role: "user",
  3205. agent: "zcode-agent",
  3206. time: { created: 10 },
  3207. modelSelection: { providerId: "glm" as ModelProviderId, modelId: "glm-4.6" as ModelId },
  3208. });
  3209. await store.savePart({
  3210. id: "part_index_user" as never,
  3211. messageID: userId,
  3212. sessionID,
  3213. type: "text",
  3214. text: "查一下订单",
  3215. });
  3216. await store.saveMessage({
  3217. id: assistantId,
  3218. sessionID,
  3219. role: "assistant",
  3220. parentID: userId,
  3221. agent: "zcode-agent",
  3222. time: { created: 20, completed: 30 },
  3223. providerId: "glm" as ModelProviderId,
  3224. modelId: "glm-4.6" as ModelId,
  3225. mode: "build",
  3226. path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
  3227. cost: 0,
  3228. tokens: { input: 1, output: 1, reasoning: 0, total: 2, cache: { read: 0, write: 0 } },
  3229. } as never);
  3230. await store.savePart({
  3231. id: "part_index_reasoning" as never,
  3232. messageID: assistantId,
  3233. sessionID,
  3234. type: "reasoning",
  3235. text: big,
  3236. time: { start: 21, end: 22 },
  3237. } as never);
  3238. await store.savePart({
  3239. id: "part_index_tool" as never,
  3240. messageID: assistantId,
  3241. sessionID,
  3242. type: "tool",
  3243. callID: "call_index_tool",
  3244. tool: "Bash",
  3245. state: {
  3246. status: "completed",
  3247. input: { command: big },
  3248. output: big,
  3249. title: "Bash",
  3250. metadata: {},
  3251. time: { start: 23, end: 24 },
  3252. },
  3253. } as never);
  3254. await store.savePart({
  3255. id: "part_index_text" as never,
  3256. messageID: assistantId,
  3257. sessionID,
  3258. type: "text",
  3259. text: "订单在 orderService",
  3260. });
  3261. await store.savePart({
  3262. id: "part_index_todos" as never,
  3263. messageID: assistantId,
  3264. sessionID,
  3265. type: "tool",
  3266. callID: "call_index_todos",
  3267. tool: "TodoWrite",
  3268. state: {
  3269. status: "completed",
  3270. input: { todos: [{ content: "检查订单", status: "in_progress", priority: "high" }] },
  3271. output: big,
  3272. title: "TodoWrite",
  3273. metadata: {},
  3274. time: { start: 24, end: 25 },
  3275. },
  3276. });
  3277. const messageReads = vi.spyOn(store, "messages");
  3278. const readWith = async (id: number, extra: Record<string, unknown>) =>
  3279. zcodeSessionStateSnapshotSchema.parse(
  3280. await requestResult(server, {
  3281. id,
  3282. method: zcodeProtocolMethods.sessionRead,
  3283. params: { sessionId: sessionID, ...extra },
  3284. }),
  3285. );
  3286. const full = await readWith(2, {});
  3287. const index = await readWith(3, { contentProfile: "index" });
  3288. expect(messageReads).toHaveBeenLastCalledWith({ sessionID, contentProfile: "index" });
  3289. // 不能只比较 message 形状:过早裁掉 TodoWrite input 会静默丢失历史分组。
  3290. expect(index.todoGroups.some((group) => group.todos.length > 0)).toBe(true);
  3291. expect(index.goalStats).toBeDefined();
  3292. expect(index).toEqual(elideSessionSnapshotForIndex(full));
  3293. expect(JSON.stringify(full).length).toBeGreaterThan(big.length * 2);
  3294. expect(JSON.stringify(index).length).toBeLessThan(big.length / 4);
  3295. const shape = (snapshot: typeof full) =>
  3296. snapshot.messages.map((message) => ({
  3297. id: message.info.messageId,
  3298. parts: message.parts.map((part) => `${part.partId}:${part.type}`),
  3299. }));
  3300. expect(shape(index)).toEqual(shape(full));
  3301. expect(messageTexts(index.messages)).toEqual(messageTexts(full.messages));
  3302. const indexTool = index.messages
  3303. .flatMap((message) => message.parts)
  3304. .find((part) => part.type === "tool");
  3305. expect(indexTool).toMatchObject({ state: { status: "completed", input: {}, output: "" } });
  3306. // index 读取不能污染后续 full 读取(CLI 侧不得原地改写缓存消息)。
  3307. const fullAgain = await readWith(4, { contentProfile: "full" });
  3308. expect(JSON.stringify(fullAgain.messages)).toBe(JSON.stringify(full.messages));
  3309. } finally {
  3310. store.close();
  3311. }
  3312. });
  3313. it("returns built-in slash commands for workspace and session snapshots", async () => {
  3314. const server = new ZCodeProtocolAgentServer({
  3315. createZCodeApp: (options) => createFakeApp(options),
  3316. cwd: workspace.workspacePath,
  3317. version: "test-version",
  3318. });
  3319. const presentation = zcodeWorkspacePresentationSchema.parse(
  3320. await requestResult(server, {
  3321. id: 1,
  3322. method: zcodeProtocolMethods.workspaceReadPresentation,
  3323. params: { workspace },
  3324. }),
  3325. );
  3326. expect(presentation.slashCommands).toEqual(
  3327. expect.arrayContaining([
  3328. expect.objectContaining({
  3329. inputHint: "/compact [instructions]",
  3330. name: "compact",
  3331. }),
  3332. expect.objectContaining({
  3333. inputHint: "/goal [pause|resume|clear|replace <objective>|<objective>]",
  3334. name: "goal",
  3335. }),
  3336. ]),
  3337. );
  3338. const created = zcodeSessionStateSnapshotSchema.parse(
  3339. await requestResult(server, {
  3340. id: 2,
  3341. method: zcodeProtocolMethods.sessionCreate,
  3342. params: { workspace },
  3343. }),
  3344. );
  3345. const createdCommandNames = created.slashCommands?.map((command) => command.name) ?? [];
  3346. expect(createdCommandNames).toEqual(expect.arrayContaining(["compact", "goal"]));
  3347. expect(createdCommandNames).not.toContain("model");
  3348. });
  3349. it("enables model streaming by default for protocol workspace apps", async () => {
  3350. const createdAppOptions: ZCodeAppOptions[] = [];
  3351. await createWorkspaceZCodeApp(
  3352. {
  3353. deps: {
  3354. createZCodeApp: (options) => {
  3355. createdAppOptions.push(options ?? {});
  3356. return createFakeApp(options);
  3357. },
  3358. },
  3359. notify: () => undefined,
  3360. sessions: new Map(),
  3361. },
  3362. workspace,
  3363. {
  3364. runtimeConfig: {
  3365. workingDirectory: workspace.workspacePath,
  3366. },
  3367. },
  3368. );
  3369. expect(createdAppOptions[0]?.runtimeConfig?.modelStreaming).toBe("on");
  3370. });
  3371. it("passes the opaque workspace identity into protocol app Memory config", async () => {
  3372. const createdAppOptions: ZCodeAppOptions[] = [];
  3373. const remoteWorkspace = {
  3374. workspaceIdentity: "ssh:example:/workspace/app",
  3375. workspaceKey: "ssh:example:/workspace/app",
  3376. workspacePath: "/workspace/app",
  3377. remoteSessionId: "remote-session-1",
  3378. };
  3379. await createWorkspaceZCodeApp(
  3380. {
  3381. deps: {
  3382. createZCodeApp: (options) => {
  3383. createdAppOptions.push(options ?? {});
  3384. return createFakeApp(options);
  3385. },
  3386. },
  3387. notify: () => undefined,
  3388. sessions: new Map(),
  3389. },
  3390. remoteWorkspace,
  3391. {
  3392. runtimeConfig: {
  3393. workingDirectory: remoteWorkspace.workspacePath,
  3394. },
  3395. },
  3396. );
  3397. expect(createdAppOptions[0]?.runtimeConfig?.memory?.workspaceIdentity).toBe(
  3398. remoteWorkspace.workspaceIdentity,
  3399. );
  3400. expect(createdAppOptions[0]?.runtimeConfig?.remoteSessionId).toBe(
  3401. remoteWorkspace.remoteSessionId,
  3402. );
  3403. });
  3404. it("preserves unapplied zcode-plan runtime headers original failure", async () => {
  3405. const createdAppOptions: ZCodeAppOptions[] = [];
  3406. const requestClient = vi.fn(async () => ({
  3407. headersApplied: false,
  3408. errorMessage: "Runtime headers helper timed out after 5000ms.",
  3409. }));
  3410. await createWorkspaceZCodeApp(
  3411. {
  3412. deps: {
  3413. createZCodeApp: (options) => {
  3414. createdAppOptions.push(options ?? {});
  3415. return createFakeApp(options);
  3416. },
  3417. },
  3418. notify: () => undefined,
  3419. requestClient,
  3420. sessions: new Map(),
  3421. },
  3422. workspace,
  3423. {
  3424. runtimeConfig: {
  3425. workingDirectory: workspace.workspacePath,
  3426. },
  3427. },
  3428. );
  3429. const runtimeHeadersPort = createdAppOptions[0]?.providerRuntimeHeadersPort;
  3430. expect(
  3431. runtimeHeadersPort?.shouldRefreshBeforeModelRequest?.({
  3432. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  3433. modelId: "glm-5.1",
  3434. }),
  3435. ).toBe(true);
  3436. await expect(
  3437. runtimeHeadersPort?.refreshBeforeModelRequest({
  3438. accountAccess: {
  3439. type: "zhipu-account",
  3440. family: "zai",
  3441. mode: "start-plan",
  3442. },
  3443. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  3444. modelId: "glm-5.1",
  3445. reason: "model-request",
  3446. sessionId: "sess_test" as never,
  3447. traceContext: {} as never,
  3448. }),
  3449. ).rejects.toThrow("Runtime headers helper timed out after 5000ms.");
  3450. expect(requestClient).toHaveBeenCalledWith(
  3451. zcodeProtocolMethods.interactionRequestProviderRuntimeHeaders,
  3452. expect.objectContaining({
  3453. accountAccess: expect.objectContaining({
  3454. mode: "start-plan",
  3455. }),
  3456. }),
  3457. expect.anything(),
  3458. expect.anything(),
  3459. );
  3460. });
  3461. it("returns per-request auth and distinct IDs for concurrent runtime header refreshes", async () => {
  3462. const createdAppOptions: ZCodeAppOptions[] = [];
  3463. const requestClient = vi.fn(async () => ({
  3464. headersApplied: true,
  3465. requestAuth: {
  3466. apiKey: "request-key",
  3467. apiKeyId: "real-key-id",
  3468. headers: { "X-Request": "request-header" },
  3469. },
  3470. }));
  3471. await createWorkspaceZCodeApp(
  3472. {
  3473. deps: {
  3474. createZCodeApp: (options) => {
  3475. createdAppOptions.push(options ?? {});
  3476. return createFakeApp(options);
  3477. },
  3478. },
  3479. notify: () => undefined,
  3480. requestClient,
  3481. sessions: new Map(),
  3482. },
  3483. workspace,
  3484. {
  3485. runtimeConfig: {
  3486. workingDirectory: workspace.workspacePath,
  3487. },
  3488. },
  3489. );
  3490. await expect(
  3491. createdAppOptions[0]?.providerRuntimeHeadersPort?.refreshBeforeModelRequest({
  3492. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  3493. modelId: "glm-5.1",
  3494. reason: "model-request",
  3495. sessionId: "sess_test" as never,
  3496. traceContext: {} as never,
  3497. }),
  3498. ).resolves.toMatchObject({
  3499. headersApplied: true,
  3500. requestAuth: {
  3501. apiKey: "request-key",
  3502. apiKeyId: "real-key-id",
  3503. headers: { "X-Request": "request-header" },
  3504. },
  3505. });
  3506. const clock = vi.spyOn(Date, "now").mockReturnValue(1234);
  3507. try {
  3508. const port = createdAppOptions[0]!.providerRuntimeHeadersPort!;
  3509. const input = {
  3510. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
  3511. modelId: "glm-5.1",
  3512. reason: "model-request" as const,
  3513. sessionId: "sess_test" as never,
  3514. traceContext: {} as never,
  3515. };
  3516. const results = await Promise.all([
  3517. port.refreshBeforeModelRequest(input),
  3518. port.refreshBeforeModelRequest(input),
  3519. ]);
  3520. expect(results.map((result) => result.requestAuth)).toEqual([
  3521. {
  3522. apiKey: "request-key",
  3523. apiKeyId: "real-key-id",
  3524. headers: { "X-Request": "request-header" },
  3525. },
  3526. {
  3527. apiKey: "request-key",
  3528. apiKeyId: "real-key-id",
  3529. headers: { "X-Request": "request-header" },
  3530. },
  3531. ]);
  3532. const requests = (
  3533. requestClient.mock.calls as unknown as Array<
  3534. [string, { requestId: string; reason: string }]
  3535. >
  3536. ).slice(-2);
  3537. expect(requests[0][1].requestId).not.toBe(requests[1][1].requestId);
  3538. expect(requests.map(([, request]) => request.reason)).toEqual([
  3539. "model-request",
  3540. "model-request",
  3541. ]);
  3542. } finally {
  3543. clock.mockRestore();
  3544. }
  3545. });
  3546. it("injects protocol MCP servers into session runtime config", async () => {
  3547. const createdAppOptions: ZCodeAppOptions[] = [];
  3548. const server = new ZCodeProtocolAgentServer({
  3549. createZCodeApp: (options) => {
  3550. createdAppOptions.push(options);
  3551. return createFakeApp(options);
  3552. },
  3553. cwd: workspace.workspacePath,
  3554. version: "test-version",
  3555. });
  3556. await requestResult(server, {
  3557. id: 1,
  3558. method: zcodeProtocolMethods.sessionCreate,
  3559. params: {
  3560. workspace,
  3561. mcpServers: [
  3562. {
  3563. name: "chrome-devtools",
  3564. command: "npx",
  3565. args: ["-y", "chrome-devtools-mcp@latest"],
  3566. env: [],
  3567. timeoutMs: 3,
  3568. },
  3569. {
  3570. name: "linear",
  3571. type: "http",
  3572. url: "https://mcp.example.test",
  3573. headers: [{ name: "X-Test", value: "1" }],
  3574. timeoutMs: 5000,
  3575. },
  3576. {
  3577. name: "events",
  3578. type: "sse",
  3579. url: "https://mcp.example.test/sse",
  3580. headers: [],
  3581. timeoutMs: 8000,
  3582. },
  3583. ],
  3584. },
  3585. });
  3586. expect(createdAppOptions[0]?.runtimeConfig?.mcp).toEqual({
  3587. enabled: true,
  3588. servers: {
  3589. "chrome-devtools": {
  3590. type: "stdio",
  3591. command: "npx",
  3592. args: ["-y", "chrome-devtools-mcp@latest"],
  3593. env: {},
  3594. timeoutMs: 3,
  3595. },
  3596. linear: {
  3597. type: "http",
  3598. url: "https://mcp.example.test",
  3599. headers: { "X-Test": "1" },
  3600. timeoutMs: 5000,
  3601. },
  3602. events: {
  3603. type: "sse",
  3604. url: "https://mcp.example.test/sse",
  3605. headers: {},
  3606. timeoutMs: 8000,
  3607. },
  3608. },
  3609. });
  3610. });
  3611. it("injects protocol tool allow and deny lists into session runtime config", async () => {
  3612. const createdAppOptions: ZCodeAppOptions[] = [];
  3613. const server = new ZCodeProtocolAgentServer({
  3614. createZCodeApp: (options) => {
  3615. createdAppOptions.push(options);
  3616. return createFakeApp(options);
  3617. },
  3618. cwd: workspace.workspacePath,
  3619. version: "test-version",
  3620. });
  3621. await requestResult(server, {
  3622. id: 1,
  3623. method: zcodeProtocolMethods.sessionCreate,
  3624. params: {
  3625. workspace,
  3626. toolAllowlist: ["mcp__zcode_cua__get_app_state"],
  3627. toolDenylist: ["Bash"],
  3628. },
  3629. });
  3630. expect(createdAppOptions[0]?.runtimeConfig?.toolAllowlist).toEqual([
  3631. "mcp__zcode_cua__get_app_state",
  3632. ]);
  3633. expect(createdAppOptions[0]?.runtimeConfig?.toolDisallowlist).toEqual(["Bash"]);
  3634. });
  3635. it("远程 SSH/WSL workspace 默认禁用全部 Cron 工具并保留调用方 denylist", async () => {
  3636. const createdAppOptions: ZCodeAppOptions[] = [];
  3637. const server = new ZCodeProtocolAgentServer({
  3638. createZCodeApp: (options) => {
  3639. createdAppOptions.push(options);
  3640. return createFakeApp(options);
  3641. },
  3642. cwd: workspace.workspacePath,
  3643. version: "test-version",
  3644. });
  3645. for (const [index, workspaceIdentity] of [
  3646. "remote:ssh:example.test:22:dev:/workspace/app",
  3647. "remote:wsl:Ubuntu-24.04:dev:/workspace/app",
  3648. ].entries()) {
  3649. await requestResult(server, {
  3650. id: index + 1,
  3651. method: zcodeProtocolMethods.sessionCreate,
  3652. params: {
  3653. workspace: {
  3654. ...workspace,
  3655. workspaceIdentity,
  3656. workspaceKey: workspaceIdentity,
  3657. },
  3658. toolDenylist: ["Bash"],
  3659. },
  3660. });
  3661. expect(createdAppOptions[index]?.runtimeConfig?.toolDisallowlist).toEqual([
  3662. "Bash",
  3663. "CronCreate",
  3664. "CronList",
  3665. "CronUpdate",
  3666. "CronDelete",
  3667. "CronPauseSelf",
  3668. ]);
  3669. }
  3670. });
  3671. it("reads materialization preferences once per root runtime and keeps active resumes stable", async () => {
  3672. const createdAppOptions: ZCodeAppOptions[] = [];
  3673. let nativeSearchEnabled = false;
  3674. let toolSearchMode: "off" | "local" = "off";
  3675. let totalTokensReminderEnabled = false;
  3676. let agentAlwaysBackgroundEnabled = false;
  3677. let memoryEnabled = false;
  3678. let modelContextBudgetStrategy: "legacy" | "preflight-v1" = "legacy";
  3679. const server = new ZCodeProtocolAgentServer({
  3680. createZCodeApp: (options) => {
  3681. createdAppOptions.push(options);
  3682. return createFakeApp(options);
  3683. },
  3684. cwd: workspace.workspacePath,
  3685. version: "test-version",
  3686. });
  3687. const preferenceRequests = attachSessionRuntimePreferencesResponder(server, () => ({
  3688. nativeSearchEnhancementsEnabled: nativeSearchEnabled,
  3689. toolSearchMode,
  3690. totalTokensReminderEnabled,
  3691. agentAlwaysBackgroundEnabled,
  3692. memoryEnabled,
  3693. modelContextBudgetStrategy,
  3694. }));
  3695. const disabled = zcodeSessionStateSnapshotSchema.parse(
  3696. await requestResult(server, {
  3697. id: 1,
  3698. method: zcodeProtocolMethods.sessionCreate,
  3699. params: { workspace },
  3700. }),
  3701. );
  3702. nativeSearchEnabled = true;
  3703. toolSearchMode = "local";
  3704. totalTokensReminderEnabled = true;
  3705. agentAlwaysBackgroundEnabled = true;
  3706. memoryEnabled = true;
  3707. modelContextBudgetStrategy = "preflight-v1";
  3708. await requestResult(server, {
  3709. id: 2,
  3710. method: zcodeProtocolMethods.sessionResume,
  3711. params: { sessionId: disabled.session.sessionId },
  3712. });
  3713. await requestResult(server, {
  3714. id: 3,
  3715. method: zcodeProtocolMethods.sessionCreate,
  3716. params: { workspace },
  3717. });
  3718. expect(
  3719. preferenceRequests.map((request) => (request.params as { scope: string }).scope),
  3720. ).toEqual(["runtime-materialization", "runtime-materialization"]);
  3721. expect(createdAppOptions).toHaveLength(2);
  3722. expect(createdAppOptions[0]?.runtimeConfig?.toolSearch).toEqual({ mode: "off" });
  3723. expect(createdAppOptions[1]?.runtimeConfig?.toolSearch).toEqual({ mode: "local" });
  3724. expect(createdAppOptions[0]?.runtimeConfig?.totalTokensReminder).toEqual({ enabled: false });
  3725. expect(createdAppOptions[1]?.runtimeConfig?.totalTokensReminder).toEqual({ enabled: true });
  3726. expect(createdAppOptions[0]?.runtimeConfig?.subagents?.alwaysBackground).toBe(false);
  3727. expect(createdAppOptions[1]?.runtimeConfig?.subagents?.alwaysBackground).toBe(true);
  3728. expect(createdAppOptions[0]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(false);
  3729. expect(createdAppOptions[0]?.runtimeConfig?.memory?.enabled).toBe(false);
  3730. expect(createdAppOptions[0]?.runtimeConfig?.modelContextBudgetStrategy).toBe("preflight-v1");
  3731. expect(createdAppOptions[1]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(true);
  3732. expect(createdAppOptions[1]?.runtimeConfig?.modelContextBudgetStrategy).toBe("preflight-v1");
  3733. // 开启 Settings 只解除总开关,不覆盖底层 features.memory/use 配置。
  3734. expect(createdAppOptions[1]?.runtimeConfig?.memory?.enabled).toBeUndefined();
  3735. });
  3736. it("reads the latest materialization preferences for a cold resume", async () => {
  3737. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  3738. const sessionId = "sess_native_search_cold_resume" as SessionId;
  3739. const createdAppOptions: ZCodeAppOptions[] = [];
  3740. try {
  3741. await store.createSession({
  3742. id: sessionId,
  3743. projectID: "project_native_search_cold_resume" as ProjectId,
  3744. slug: "native-search-cold-resume",
  3745. directory: workspace.workspacePath,
  3746. path: workspace.workspacePath,
  3747. title: "Native search cold resume",
  3748. version: "test-version",
  3749. time: { created: 1, updated: 1 },
  3750. });
  3751. const server = new ZCodeProtocolAgentServer({
  3752. createZCodeApp: (options) => {
  3753. createdAppOptions.push(options);
  3754. return createFakeApp(options);
  3755. },
  3756. cwd: workspace.workspacePath,
  3757. sessionStore: store,
  3758. version: "test-version",
  3759. });
  3760. const preferenceRequests = attachSessionRuntimePreferencesResponder(server, () => ({
  3761. nativeSearchEnhancementsEnabled: false,
  3762. toolSearchMode: "auto",
  3763. totalTokensReminderEnabled: true,
  3764. agentAlwaysBackgroundEnabled: false,
  3765. memoryEnabled: false,
  3766. modelContextBudgetStrategy: "preflight-v1",
  3767. }));
  3768. await requestResult(server, {
  3769. id: 1,
  3770. method: zcodeProtocolMethods.sessionResume,
  3771. params: { sessionId },
  3772. });
  3773. expect(preferenceRequests).toHaveLength(1);
  3774. expect(createdAppOptions[0]?.runtimeConfig?.toolSearch).toEqual({ mode: "auto" });
  3775. expect(createdAppOptions[0]?.runtimeConfig?.totalTokensReminder).toEqual({ enabled: true });
  3776. expect(createdAppOptions[0]?.runtimeConfig?.subagents?.alwaysBackground).toBe(false);
  3777. expect(createdAppOptions[0]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(false);
  3778. expect(createdAppOptions[0]?.runtimeConfig?.memory?.enabled).toBe(false);
  3779. expect(createdAppOptions[0]?.runtimeConfig?.modelContextBudgetStrategy).toBe("preflight-v1");
  3780. } finally {
  3781. await store.close();
  3782. }
  3783. });
  3784. // 远端 Host 同样持有子智能体快照:是否接入只看 Host 声明的能力,不按 workspace 身份排除远程。
  3785. it.each([
  3786. undefined,
  3787. "remote:ssh:example.test:22:dev:/workspace/app",
  3788. "remote:server:example-server:/workspace/app",
  3789. ])(
  3790. "injects pull access into advertised local and remote sessions (%s)",
  3791. async (workspaceIdentity) => {
  3792. const options: ZCodeAppOptions[] = [];
  3793. const reads: unknown[] = [];
  3794. let content = "old";
  3795. const server = new ZCodeProtocolAgentServer({
  3796. createZCodeApp: (input) => {
  3797. options.push(input);
  3798. return createFakeApp(input);
  3799. },
  3800. cwd: workspace.workspacePath,
  3801. version: "test-version",
  3802. });
  3803. server.setNotificationSink((message) => {
  3804. if (!("id" in message)) return;
  3805. if (message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences) {
  3806. void server.handleMessage({
  3807. id: message.id,
  3808. result: {
  3809. nativeSearchEnhancementsEnabled: true,
  3810. memoryEnabled: false,
  3811. subagentRuntimeConfigEnabled: true,
  3812. },
  3813. });
  3814. }
  3815. if (message.method === zcodeProtocolMethods.subagentsReadRuntimeConfig) {
  3816. reads.push(message.params);
  3817. void server.handleMessage({
  3818. id: message.id,
  3819. result: {
  3820. kind: "ready",
  3821. // Host 返回已解析快照;磁盘文档及启停状态不再跨这个协议边界。
  3822. profiles: [
  3823. {
  3824. name: "reviewer",
  3825. description: "review",
  3826. path: "/agents/reviewer.md",
  3827. source: "user",
  3828. systemPrompt: content,
  3829. },
  3830. ],
  3831. builtInModelSelectionOverrides: {},
  3832. pluginAgentModelSelectionOverrides: {},
  3833. },
  3834. });
  3835. }
  3836. });
  3837. await requestResult(server, {
  3838. id: 1,
  3839. method: zcodeProtocolMethods.sessionCreate,
  3840. params: {
  3841. workspace: {
  3842. ...workspace,
  3843. ...(workspaceIdentity ? { workspaceIdentity, workspaceKey: workspaceIdentity } : {}),
  3844. },
  3845. },
  3846. });
  3847. expect(reads).toEqual([]);
  3848. const reader = options[0]?.readSubagentRuntimeConfig;
  3849. expect(reader).toBeTypeOf("function");
  3850. const input = {
  3851. signal: new AbortController().signal,
  3852. traceContext: { traceId: createTraceId(), sessionId: options[0]!.sessionId! },
  3853. };
  3854. expect((await reader!(input)).profiles[0]?.systemPrompt).toBe("old");
  3855. content = "new";
  3856. expect((await reader!(input)).profiles[0]?.systemPrompt).toBe("new");
  3857. expect(reads).toEqual([
  3858. { sessionId: options[0]!.sessionId },
  3859. { sessionId: options[0]!.sessionId },
  3860. ]);
  3861. },
  3862. );
  3863. it("keeps native search on but defaults Memory off when no Host client is attached", async () => {
  3864. const createdAppOptions: ZCodeAppOptions[] = [];
  3865. const server = new ZCodeProtocolAgentServer({
  3866. createZCodeApp: (options) => {
  3867. createdAppOptions.push(options);
  3868. return createFakeApp(options);
  3869. },
  3870. cwd: workspace.workspacePath,
  3871. version: "test-version",
  3872. });
  3873. await requestResult(server, {
  3874. id: 1,
  3875. method: zcodeProtocolMethods.sessionCreate,
  3876. params: { workspace },
  3877. });
  3878. expect(createdAppOptions[0]?.readSubagentRuntimeConfig).toBeUndefined();
  3879. expect(createdAppOptions[0]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(true);
  3880. expect(createdAppOptions[0]?.runtimeConfig?.memory?.enabled).toBe(false);
  3881. expect(createdAppOptions[0]?.runtimeConfig?.modelContextBudgetStrategy).toBe("preflight-v1");
  3882. });
  3883. it("defaults Memory off for an old Host but rejects other preference failures", async () => {
  3884. const oldHostOptions: ZCodeAppOptions[] = [];
  3885. const oldHostServer = new ZCodeProtocolAgentServer({
  3886. createZCodeApp: (options) => {
  3887. oldHostOptions.push(options);
  3888. return createFakeApp(options);
  3889. },
  3890. cwd: workspace.workspacePath,
  3891. version: "test-version",
  3892. });
  3893. oldHostServer.setNotificationSink((message) => {
  3894. if (
  3895. "id" in message &&
  3896. message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences
  3897. ) {
  3898. void oldHostServer.handleMessage({
  3899. id: message.id,
  3900. error: { code: -32601, message: "Method not found" },
  3901. });
  3902. }
  3903. });
  3904. await requestResult(oldHostServer, {
  3905. id: 1,
  3906. method: zcodeProtocolMethods.sessionCreate,
  3907. params: { workspace },
  3908. });
  3909. expect(oldHostOptions[0]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(true);
  3910. expect(oldHostOptions[0]?.runtimeConfig?.totalTokensReminder).toEqual({ enabled: false });
  3911. // 旧 Host 不知道 Agent 后台开关,按产品缺省开启。
  3912. expect(oldHostOptions[0]?.runtimeConfig?.subagents?.alwaysBackground).toBe(true);
  3913. expect(oldHostOptions[0]?.runtimeConfig?.memory?.enabled).toBe(false);
  3914. expect(oldHostOptions[0]?.runtimeConfig?.modelContextBudgetStrategy).toBe("preflight-v1");
  3915. for (const response of [
  3916. { error: { code: -32603, message: "setting read failed" } },
  3917. { result: { nativeSearchEnhancementsEnabled: "invalid" } },
  3918. ]) {
  3919. const createdAppOptions: ZCodeAppOptions[] = [];
  3920. const server = new ZCodeProtocolAgentServer({
  3921. createZCodeApp: (options) => {
  3922. createdAppOptions.push(options);
  3923. return createFakeApp(options);
  3924. },
  3925. cwd: workspace.workspacePath,
  3926. version: "test-version",
  3927. });
  3928. server.setNotificationSink((message) => {
  3929. if (
  3930. "id" in message &&
  3931. message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences
  3932. ) {
  3933. void server.handleMessage({ id: message.id, ...response } as ZCodeProtocolMessage);
  3934. }
  3935. });
  3936. const result = await server.handleMessage({
  3937. id: 1,
  3938. method: zcodeProtocolMethods.sessionCreate,
  3939. params: { workspace },
  3940. });
  3941. expect(result).toMatchObject({ error: { code: -32603 } });
  3942. expect(createdAppOptions).toHaveLength(0);
  3943. }
  3944. });
  3945. it("times out runtime preference resolution while the Host remains connected", async () => {
  3946. vi.useFakeTimers();
  3947. const createdAppOptions: ZCodeAppOptions[] = [];
  3948. const logs: RecordedLog[] = [];
  3949. const server = new ZCodeProtocolAgentServer({
  3950. createZCodeApp: (options) => {
  3951. createdAppOptions.push(options);
  3952. return createFakeApp(options);
  3953. },
  3954. cwd: workspace.workspacePath,
  3955. loggerFactory: createProtocolTestLoggerFactory(logs),
  3956. version: "test-version",
  3957. });
  3958. server.setNotificationSink(() => {
  3959. // 保持 Host 连接但故意不响应,覆盖 transport 不断开时的生命周期收口。
  3960. });
  3961. try {
  3962. const resultPromise = server.handleMessage({
  3963. id: 1,
  3964. method: zcodeProtocolMethods.sessionCreate,
  3965. params: { workspace },
  3966. });
  3967. await vi.advanceTimersByTimeAsync(ZCODE_SESSION_RUNTIME_PREFERENCES_REQUEST_TIMEOUT_MS);
  3968. await expect(resultPromise).resolves.toMatchObject({
  3969. error: {
  3970. code: -32022,
  3971. data: {
  3972. timeoutMs: ZCODE_SESSION_RUNTIME_PREFERENCES_REQUEST_TIMEOUT_MS,
  3973. },
  3974. },
  3975. });
  3976. expect(createdAppOptions).toHaveLength(0);
  3977. expect(logs).toContainEqual(
  3978. expect.objectContaining({
  3979. level: "warn",
  3980. message: "ZCode Protocol runtime preferences request timed out",
  3981. context: expect.objectContaining({
  3982. errorCode: -32022,
  3983. scope: "runtime-materialization",
  3984. sessionId: expect.any(String),
  3985. }),
  3986. }),
  3987. );
  3988. } finally {
  3989. vi.useRealTimers();
  3990. }
  3991. });
  3992. it("defaults Memory off when an older responder omits the preference field", async () => {
  3993. const createdAppOptions: ZCodeAppOptions[] = [];
  3994. const server = new ZCodeProtocolAgentServer({
  3995. createZCodeApp: (options) => {
  3996. createdAppOptions.push(options);
  3997. return createFakeApp(options);
  3998. },
  3999. cwd: workspace.workspacePath,
  4000. version: "test-version",
  4001. });
  4002. attachSessionRuntimePreferencesResponder(server, () => ({
  4003. nativeSearchEnhancementsEnabled: true,
  4004. }));
  4005. await requestResult(server, {
  4006. id: 1,
  4007. method: zcodeProtocolMethods.sessionCreate,
  4008. params: { workspace },
  4009. });
  4010. expect(createdAppOptions[0]?.readSubagentRuntimeConfig).toBeUndefined();
  4011. expect(createdAppOptions[0]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(true);
  4012. expect(createdAppOptions[0]?.runtimeConfig?.memory?.enabled).toBe(false);
  4013. });
  4014. it("settles queued Session creation when the Host disconnects during preference resolution", async () => {
  4015. const createdAppOptions: ZCodeAppOptions[] = [];
  4016. const server = new ZCodeProtocolAgentServer({
  4017. createZCodeApp: (options) => {
  4018. createdAppOptions.push(options);
  4019. return createFakeApp(options);
  4020. },
  4021. cwd: workspace.workspacePath,
  4022. version: "test-version",
  4023. });
  4024. const input = new PassThrough();
  4025. const output = new PassThrough();
  4026. let written = "";
  4027. output.on("data", (chunk: Buffer) => {
  4028. written += chunk.toString("utf8");
  4029. });
  4030. const connection = new ZCodeProtocolNdjsonConnection({
  4031. clearPostResponseMessages: () => server.clearPostResponseMessages(),
  4032. handleMessage: (message) => server.handleMessage(message),
  4033. input,
  4034. onTransportClosed: (error) => server.disconnectClient(error),
  4035. output,
  4036. takePostResponseBatch: (requestId) => server.takePostResponseBatch(requestId),
  4037. });
  4038. server.setNotificationSink((message) => connection.send(message));
  4039. connection.start();
  4040. input.write(
  4041. [
  4042. {
  4043. id: "create-before-close",
  4044. method: zcodeProtocolMethods.sessionCreate,
  4045. params: { workspace },
  4046. },
  4047. {
  4048. id: "create-queued",
  4049. method: zcodeProtocolMethods.sessionCreate,
  4050. params: { workspace },
  4051. },
  4052. ]
  4053. .map((message) => JSON.stringify(message))
  4054. .join("\n") + "\n",
  4055. );
  4056. await vi.waitFor(() =>
  4057. expect(written).toContain(zcodeProtocolMethods.sessionRequestRuntimePreferences),
  4058. );
  4059. input.end();
  4060. await connection.waitForClose();
  4061. const messages = written
  4062. .trim()
  4063. .split("\n")
  4064. .map((line) => JSON.parse(line) as ZCodeProtocolMessage);
  4065. expect(
  4066. messages.filter(
  4067. (message) =>
  4068. "method" in message &&
  4069. message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences,
  4070. ),
  4071. ).toHaveLength(1);
  4072. expect(messages).toEqual(
  4073. expect.arrayContaining([
  4074. expect.objectContaining({
  4075. id: "create-before-close",
  4076. error: expect.objectContaining({ code: -32603 }),
  4077. }),
  4078. expect.objectContaining({
  4079. id: "create-queued",
  4080. error: expect.objectContaining({ code: -32603 }),
  4081. }),
  4082. ]),
  4083. );
  4084. expect(createdAppOptions).toHaveLength(0);
  4085. });
  4086. it("stops every active Session runtime when the owning protocol transport disconnects", () => {
  4087. const app = createFakeApp();
  4088. const stopActiveForegroundExecution = vi.fn(() => ({
  4089. foregroundExecutionId: "foreground-test",
  4090. kind: "stopped" as const,
  4091. }));
  4092. app.runtime.stopActiveForegroundExecution = stopActiveForegroundExecution;
  4093. const activeAbortController = new AbortController();
  4094. const server = new ZCodeProtocolAgentServer({
  4095. createZCodeApp: () => app,
  4096. cwd: workspace.workspacePath,
  4097. version: "test-version",
  4098. });
  4099. const context = (server as unknown as { context: ZCodeProtocolAgentServerContext }).context;
  4100. context.sessions.set("sess_active", {
  4101. activeAbortController,
  4102. app,
  4103. } as unknown as ZCodeProtocolSessionRecord);
  4104. const disconnectError = new Error("Core owner disconnected");
  4105. server.disconnectClient(disconnectError);
  4106. expect(stopActiveForegroundExecution).toHaveBeenCalledOnce();
  4107. expect(stopActiveForegroundExecution).toHaveBeenCalledWith({
  4108. reason: "ZCode Protocol owner disconnected",
  4109. });
  4110. expect(activeAbortController.signal.aborted).toBe(true);
  4111. expect(activeAbortController.signal.reason).toBe(disconnectError);
  4112. });
  4113. it("initializes the configured integrated terminal shell before the first prompt", async () => {
  4114. const createdAppOptions: ZCodeAppOptions[] = [];
  4115. const shellInitializations: unknown[] = [];
  4116. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-protocol-shell-"));
  4117. const fakeGitBash = join(tempRoot, "bash.exe");
  4118. await writeFile(fakeGitBash, "");
  4119. await chmod(fakeGitBash, 0o755);
  4120. try {
  4121. const server = new ZCodeProtocolAgentServer({
  4122. createZCodeApp: (options) =>
  4123. createShellRecordingFakeApp(options, shellInitializations, createdAppOptions),
  4124. cwd: workspace.workspacePath,
  4125. platform: "win32",
  4126. version: "test-version",
  4127. });
  4128. const preferenceRequests = attachSessionRuntimePreferencesResponder(server, (scope) => ({
  4129. nativeSearchEnhancementsEnabled: true,
  4130. ...(scope === "user-execution"
  4131. ? {
  4132. integratedTerminalShell: {
  4133. mode: "shell" as const,
  4134. dialect: "git-bash" as const,
  4135. id: `git-bash:${fakeGitBash}`,
  4136. label: "Git Bash",
  4137. path: fakeGitBash,
  4138. },
  4139. }
  4140. : {}),
  4141. }));
  4142. const created = zcodeSessionStateSnapshotSchema.parse(
  4143. await requestResult(server, {
  4144. id: 1,
  4145. method: zcodeProtocolMethods.sessionCreate,
  4146. params: {
  4147. workspace,
  4148. },
  4149. }),
  4150. );
  4151. await requestResult(server, {
  4152. id: 2,
  4153. method: zcodeProtocolMethods.sessionSend,
  4154. params: {
  4155. sessionId: created.session.sessionId,
  4156. inputId: "input_shell_init",
  4157. content: "first prompt",
  4158. },
  4159. });
  4160. expect(
  4161. preferenceRequests.map((request) => (request.params as { scope: string }).scope),
  4162. ).toEqual(["runtime-materialization", "user-execution"]);
  4163. } finally {
  4164. await rm(tempRoot, { force: true, recursive: true });
  4165. }
  4166. expect(createdAppOptions[0]?.runtimeConfig?.bashShellSelection).toBeUndefined();
  4167. expect(shellInitializations).toEqual([
  4168. {
  4169. display: {
  4170. name: "Git Bash",
  4171. },
  4172. dialect: "git-bash",
  4173. id: `git-bash:${fakeGitBash}`,
  4174. label: "Git Bash",
  4175. path: fakeGitBash,
  4176. source: "user-config",
  4177. },
  4178. ]);
  4179. });
  4180. it("keeps an existing session on its first prompt shell when later sends carry a newer shell setting", async () => {
  4181. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-protocol-shell-static-"));
  4182. const initialGitBash = join(tempRoot, "initial-bash.exe");
  4183. const laterGitBash = join(tempRoot, "later-bash.exe");
  4184. const shellInitializations: unknown[] = [];
  4185. await writeFile(initialGitBash, "");
  4186. await writeFile(laterGitBash, "");
  4187. await chmod(initialGitBash, 0o755);
  4188. await chmod(laterGitBash, 0o755);
  4189. try {
  4190. let selectedShell = initialGitBash;
  4191. const server = new ZCodeProtocolAgentServer({
  4192. createZCodeApp: (options) => createShellRecordingFakeApp(options, shellInitializations),
  4193. cwd: workspace.workspacePath,
  4194. platform: "win32",
  4195. version: "test-version",
  4196. });
  4197. const preferenceRequests = attachSessionRuntimePreferencesResponder(server, (scope) => ({
  4198. nativeSearchEnhancementsEnabled: true,
  4199. ...(scope === "user-execution"
  4200. ? {
  4201. integratedTerminalShell: {
  4202. mode: "shell" as const,
  4203. dialect: "git-bash" as const,
  4204. id: `git-bash:${selectedShell}`,
  4205. label: "Git Bash",
  4206. path: selectedShell,
  4207. },
  4208. }
  4209. : {}),
  4210. }));
  4211. const created = zcodeSessionStateSnapshotSchema.parse(
  4212. await requestResult(server, {
  4213. id: 1,
  4214. method: zcodeProtocolMethods.sessionCreate,
  4215. params: {
  4216. workspace,
  4217. },
  4218. }),
  4219. );
  4220. await requestResult(server, {
  4221. id: 2,
  4222. method: zcodeProtocolMethods.sessionSend,
  4223. params: {
  4224. sessionId: created.session.sessionId,
  4225. inputId: "input_shell_init",
  4226. content: "first prompt",
  4227. },
  4228. });
  4229. selectedShell = laterGitBash;
  4230. await requestResult(server, {
  4231. id: 3,
  4232. method: zcodeProtocolMethods.sessionResume,
  4233. params: {
  4234. sessionId: created.session.sessionId,
  4235. workspace,
  4236. },
  4237. });
  4238. await requestResult(server, {
  4239. id: 4,
  4240. method: zcodeProtocolMethods.sessionSend,
  4241. params: {
  4242. sessionId: created.session.sessionId,
  4243. inputId: "input_after_shell_change",
  4244. content: "continue",
  4245. },
  4246. });
  4247. expect(
  4248. preferenceRequests.map((request) => (request.params as { scope: string }).scope),
  4249. ).toEqual(["runtime-materialization", "user-execution"]);
  4250. } finally {
  4251. await rm(tempRoot, { force: true, recursive: true });
  4252. }
  4253. expect(shellInitializations).toEqual([
  4254. {
  4255. display: {
  4256. name: "Git Bash",
  4257. },
  4258. dialect: "git-bash",
  4259. id: `git-bash:${initialGitBash}`,
  4260. label: "Git Bash",
  4261. path: initialGitBash,
  4262. source: "user-config",
  4263. },
  4264. ]);
  4265. });
  4266. it("initializes a deferred draft shell before accepting its first prompt", async () => {
  4267. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-protocol-shell-deferred-"));
  4268. const laterGitBash = join(tempRoot, "later-bash.exe");
  4269. const createdAppOptions: ZCodeAppOptions[] = [];
  4270. const shellInitializations: unknown[] = [];
  4271. await writeFile(laterGitBash, "");
  4272. await chmod(laterGitBash, 0o755);
  4273. try {
  4274. const server = new ZCodeProtocolAgentServer({
  4275. createZCodeApp: (options) =>
  4276. createShellRecordingFakeApp(options, shellInitializations, createdAppOptions),
  4277. cwd: workspace.workspacePath,
  4278. platform: "win32",
  4279. version: "test-version",
  4280. });
  4281. attachSessionRuntimePreferencesResponder(server, (scope) => ({
  4282. nativeSearchEnhancementsEnabled: true,
  4283. ...(scope === "user-execution"
  4284. ? {
  4285. integratedTerminalShell: {
  4286. mode: "shell" as const,
  4287. dialect: "git-bash" as const,
  4288. id: `git-bash:${laterGitBash}`,
  4289. label: "Git Bash",
  4290. path: laterGitBash,
  4291. },
  4292. }
  4293. : {}),
  4294. }));
  4295. const draft = zcodeSessionStateSnapshotSchema.parse(
  4296. await requestResult(server, {
  4297. id: 1,
  4298. method: zcodeProtocolMethods.sessionCreate,
  4299. params: {
  4300. workspace,
  4301. persistence: "deferred",
  4302. },
  4303. }),
  4304. );
  4305. await requestResult(server, {
  4306. id: 2,
  4307. method: zcodeProtocolMethods.sessionSend,
  4308. params: {
  4309. sessionId: draft.session.sessionId,
  4310. inputId: "input_deferred_shell_change",
  4311. content: "first prompt",
  4312. },
  4313. });
  4314. } finally {
  4315. await rm(tempRoot, { force: true, recursive: true });
  4316. }
  4317. expect(createdAppOptions[0]?.runtimeConfig?.bashShellSelection).toBeUndefined();
  4318. expect(shellInitializations).toEqual([
  4319. {
  4320. display: { name: "Git Bash" },
  4321. dialect: "git-bash",
  4322. id: `git-bash:${laterGitBash}`,
  4323. label: "Git Bash",
  4324. path: laterGitBash,
  4325. source: "user-config",
  4326. },
  4327. ]);
  4328. });
  4329. it("rejects integrated terminal shell params on create, resume, and send", async () => {
  4330. const server = new ZCodeProtocolAgentServer({
  4331. createZCodeApp: (options) => createFakeApp(options),
  4332. cwd: workspace.workspacePath,
  4333. platform: "win32",
  4334. version: "test-version",
  4335. });
  4336. const integratedTerminalShell = {
  4337. mode: "shell",
  4338. dialect: "git-bash",
  4339. id: "git-bash:/tmp/bash.exe",
  4340. label: "Git Bash",
  4341. path: "/tmp/bash.exe",
  4342. };
  4343. await expect(
  4344. server.handleMessage({
  4345. id: 1,
  4346. method: zcodeProtocolMethods.sessionCreate,
  4347. params: {
  4348. workspace,
  4349. integratedTerminalShell,
  4350. } as never,
  4351. }),
  4352. ).resolves.toMatchObject({
  4353. error: {
  4354. code: -32602,
  4355. },
  4356. });
  4357. await expect(
  4358. server.handleMessage({
  4359. id: 2,
  4360. method: zcodeProtocolMethods.sessionResume,
  4361. params: {
  4362. sessionId: "sess_shell_resume_schema",
  4363. workspace,
  4364. integratedTerminalShell,
  4365. } as never,
  4366. }),
  4367. ).resolves.toMatchObject({
  4368. error: {
  4369. code: -32602,
  4370. },
  4371. });
  4372. await expect(
  4373. server.handleMessage({
  4374. id: 3,
  4375. method: zcodeProtocolMethods.sessionSend,
  4376. params: {
  4377. sessionId: "sess_shell_send_schema",
  4378. content: "hello",
  4379. integratedTerminalShell,
  4380. } as never,
  4381. }),
  4382. ).resolves.toMatchObject({
  4383. error: {
  4384. code: -32602,
  4385. },
  4386. });
  4387. });
  4388. it("keeps deferred draft sessions out of session/list until the first send", async () => {
  4389. const server = new ZCodeProtocolAgentServer({
  4390. createZCodeApp: (options) => createFakeApp(options),
  4391. cwd: workspace.workspacePath,
  4392. });
  4393. const draft = zcodeSessionStateSnapshotSchema.parse(
  4394. await requestResult(server, {
  4395. id: 1,
  4396. method: zcodeProtocolMethods.sessionCreate,
  4397. params: { workspace, persistence: "deferred" },
  4398. }),
  4399. );
  4400. const hiddenList = zcodeSessionListResultSchema.parse(
  4401. await requestResult(server, {
  4402. id: 2,
  4403. method: zcodeProtocolMethods.sessionList,
  4404. params: { workspace },
  4405. }),
  4406. );
  4407. expect(hiddenList.sessions.map((session) => session.sessionId)).not.toContain(
  4408. draft.session.sessionId,
  4409. );
  4410. await requestResult(server, {
  4411. id: 3,
  4412. method: zcodeProtocolMethods.sessionSend,
  4413. params: { sessionId: draft.session.sessionId, content: "hello" },
  4414. });
  4415. const visibleList = zcodeSessionListResultSchema.parse(
  4416. await requestResult(server, {
  4417. id: 4,
  4418. method: zcodeProtocolMethods.sessionList,
  4419. params: { workspace },
  4420. }),
  4421. );
  4422. expect(visibleList.sessions.map((session) => session.sessionId)).toContain(
  4423. draft.session.sessionId,
  4424. );
  4425. });
  4426. it("keeps server-owned model state and emits state update notifications", async () => {
  4427. const notifications: ZCodeProtocolNotification[] = [];
  4428. const server = new ZCodeProtocolAgentServer({
  4429. createZCodeApp: (options) => createFakeApp(options),
  4430. cwd: workspace.workspacePath,
  4431. });
  4432. setTestNotificationSink(server, (notification) => notifications.push(notification));
  4433. const created = zcodeSessionStateSnapshotSchema.parse(
  4434. await requestResult(server, {
  4435. id: 1,
  4436. method: zcodeProtocolMethods.sessionCreate,
  4437. params: { workspace },
  4438. }),
  4439. );
  4440. const updated = zcodeSessionStateSnapshotSchema.parse(
  4441. await requestResult(server, {
  4442. id: 2,
  4443. method: zcodeProtocolMethods.sessionSetModel,
  4444. params: {
  4445. sessionId: created.session.sessionId,
  4446. model: { providerId: "glm", modelId: "glm-4-air" },
  4447. expectedRevision: created.runtime.stateRevision,
  4448. },
  4449. }),
  4450. );
  4451. expect(updated.settings.model.current).toEqual({ providerId: "glm", modelId: "glm-4-air" });
  4452. expect(updated.runtime.stateRevision).toBe(created.runtime.stateRevision + 1);
  4453. // 新生命周期合同在 create 时发布 starting/ready;模型状态断言只读取自己的通知域。
  4454. expect(
  4455. notifications.filter((notification) => notification.method === "state.updated"),
  4456. ).toMatchObject([
  4457. {
  4458. method: "state.updated",
  4459. params: {
  4460. type: "state.updated",
  4461. scope: "session",
  4462. sessionId: created.session.sessionId,
  4463. reason: "model_changed",
  4464. },
  4465. },
  4466. ]);
  4467. });
  4468. it("maps a protocol session model to structured Runtime Selection", async () => {
  4469. const createdAppOptions: ZCodeAppOptions[] = [];
  4470. const server = new ZCodeProtocolAgentServer({
  4471. createZCodeApp: (options) => {
  4472. createdAppOptions.push(options);
  4473. return createFakeApp(options);
  4474. },
  4475. cwd: workspace.workspacePath,
  4476. });
  4477. await requestResult(server, {
  4478. id: 1,
  4479. method: zcodeProtocolMethods.sessionCreate,
  4480. params: {
  4481. workspace,
  4482. model: {
  4483. providerId: "glm",
  4484. modelId: "glm-4-air",
  4485. options: { reasoningLevel: "deep" },
  4486. },
  4487. },
  4488. });
  4489. expect(createdAppOptions[0]?.runtimeConfig?.modelSelection).toEqual({
  4490. providerId: "glm",
  4491. modelId: "glm-4-air",
  4492. options: { reasoningLevel: "deep" },
  4493. });
  4494. });
  4495. it("resumes persisted sessions with the latest historical model and mode", async () => {
  4496. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  4497. const sessionId = "sess_history" as SessionId;
  4498. const userMessageId = "msg_user_history" as MessageId;
  4499. const assistantMessageId = "msg_assistant_history" as MessageId;
  4500. try {
  4501. await store.createSession({
  4502. id: sessionId,
  4503. projectID: "project_history" as ProjectId,
  4504. slug: "history-session",
  4505. directory: workspace.workspacePath,
  4506. path: workspace.workspacePath,
  4507. title: "History session",
  4508. version: "test-version",
  4509. time: { created: 1, updated: 4 },
  4510. });
  4511. await store.saveMessage({
  4512. id: userMessageId,
  4513. sessionID: sessionId,
  4514. role: "user",
  4515. time: { created: 2 },
  4516. agent: "zcode-agent",
  4517. modelSelection: {
  4518. providerId: "glm" as ModelProviderId,
  4519. modelId: "glm-4-air" as ModelId,
  4520. },
  4521. tools: {},
  4522. });
  4523. await store.saveMessage({
  4524. id: assistantMessageId,
  4525. sessionID: sessionId,
  4526. role: "assistant",
  4527. time: { created: 3, completed: 4 },
  4528. parentID: userMessageId,
  4529. providerId: "glm" as ModelProviderId,
  4530. modelId: "glm-4-air" as ModelId,
  4531. mode: "plan",
  4532. agent: "zcode-agent",
  4533. path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
  4534. cost: 0,
  4535. tokens: { input: 12345, output: 67, reasoning: 0, cache: { read: 2345, write: 678 } },
  4536. });
  4537. const appOptions: ZCodeAppOptions[] = [];
  4538. const server = new ZCodeProtocolAgentServer({
  4539. createZCodeApp: (options) => {
  4540. appOptions.push(options ?? {});
  4541. return createFakeApp(options);
  4542. },
  4543. cwd: workspace.workspacePath,
  4544. sessionStore: store,
  4545. });
  4546. const resumed = zcodeSessionStateSnapshotSchema.parse(
  4547. await requestResult(server, {
  4548. id: 1,
  4549. method: zcodeProtocolMethods.sessionResume,
  4550. params: { sessionId, workspace },
  4551. }),
  4552. );
  4553. expect(appOptions[0]?.runtimeConfig).toMatchObject({ mode: "plan" });
  4554. // 当前结构只能来自 Session 当前选择 entry;Protocol 不再把历史消息伪装成当前选择。
  4555. expect(appOptions[0]?.runtimeConfig?.modelSelection).toBeUndefined();
  4556. // Process Registry 在协议入口启动时已经就绪,冷恢复不再创建旧 deferred adapter。
  4557. expect(appOptions[0]?.modelAdapter).toBeUndefined();
  4558. expect(resumed.settings).toMatchObject({
  4559. mode: { current: "plan" },
  4560. model: { current: { providerId: "glm", modelId: "glm-4.6" } },
  4561. });
  4562. expect(resumed.projection.lastError).toBeUndefined();
  4563. expect(resumed.runtime.contextUsage).toEqual({
  4564. used: 12412,
  4565. size: 128000,
  4566. cost: null,
  4567. cache: {
  4568. inputTokens: 12345,
  4569. cacheReadTokens: 2345,
  4570. cacheWriteTokens: 678,
  4571. latestHitRate: 2345 / 12345,
  4572. hitRate: 2345 / 12345,
  4573. hitRateRequestCount: 1,
  4574. totalInputTokens: 12345,
  4575. totalCacheReadTokens: 2345,
  4576. totalCacheWriteTokens: 678,
  4577. },
  4578. });
  4579. expect(resumed.messages.map((message) => message.info.model)).toEqual([
  4580. { providerId: "glm", modelId: "glm-4-air" },
  4581. { providerId: "glm", modelId: "glm-4-air" },
  4582. ]);
  4583. const sendResult = await server.handleMessage({
  4584. id: 2,
  4585. method: zcodeProtocolMethods.sessionSend,
  4586. params: { sessionId, content: "continue" },
  4587. });
  4588. expect(sendResult).toMatchObject({ id: 2, result: expect.any(Object) });
  4589. } finally {
  4590. store.close();
  4591. }
  4592. });
  4593. it("resume 回填持久化 taskType:workflow_child 绝不落回缺省 interactive", async () => {
  4594. // Bug 根因(2026-08-24 实测):resume 物化 record 时丢掉了持久化的 taskType(fork 路径
  4595. // 一直带着,resume 路径没带),createRecord 落回缺省 "interactive"。于是被 resume 的
  4596. // dwf actor 会话通过 isTaskListSessionType 的筛,经 getSessionWorkspaceId 漏进
  4597. // sessions-index,desktop 任务列表里长出 25 条「workflow actor actor#N@k」假任务。
  4598. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  4599. const sessionId = "sess_dwf_actor_tasktype" as SessionId;
  4600. try {
  4601. await store.createSession({
  4602. id: sessionId,
  4603. projectID: "project_tasktype" as ProjectId,
  4604. slug: "dwf-actor-tasktype",
  4605. directory: workspace.workspacePath,
  4606. path: workspace.workspacePath,
  4607. title: "workflow actor actor#1@1",
  4608. version: "test-version",
  4609. taskType: "workflow_child",
  4610. time: { created: 1, updated: 2 },
  4611. });
  4612. const server = new ZCodeProtocolAgentServer({
  4613. createZCodeApp: (options) => createFakeApp(options),
  4614. cwd: workspace.workspacePath,
  4615. sessionStore: store,
  4616. });
  4617. await requestResult(server, {
  4618. id: 1,
  4619. method: zcodeProtocolMethods.sessionResume,
  4620. params: { sessionId, workspace },
  4621. });
  4622. const record = (
  4623. server as unknown as { context: ZCodeProtocolAgentServerContext }
  4624. ).context.sessions.get(sessionId);
  4625. expect(record?.taskType).toBe("workflow_child");
  4626. } finally {
  4627. store.close();
  4628. }
  4629. });
  4630. it("workspace presentation omits model facts", async () => {
  4631. const server = new ZCodeProtocolAgentServer({
  4632. createZCodeApp: (options) => createFakeApp(options),
  4633. cwd: workspace.workspacePath,
  4634. });
  4635. const presentation = zcodeWorkspacePresentationSchema.parse(
  4636. await requestResult(server, {
  4637. id: 1,
  4638. method: zcodeProtocolMethods.workspaceReadPresentation,
  4639. params: { workspace },
  4640. }),
  4641. );
  4642. expect(presentation.mode).toBe("build");
  4643. expect("model" in presentation).toBe(false);
  4644. expect("settings" in presentation).toBe(false);
  4645. });
  4646. it("通过独立协议同步 Account Config,不再从 Workspace Snapshot 反向投影", async () => {
  4647. const syncAccountProviderConfig = vi.fn(async () => true);
  4648. const server = new ZCodeProtocolAgentServer({
  4649. createZCodeApp: () => createFakeApp(),
  4650. cwd: workspace.workspacePath,
  4651. syncAccountProviderConfig,
  4652. });
  4653. const result = await requestResult(server, {
  4654. id: 1,
  4655. method: zcodeProtocolMethods.providerUpdateAccountConfig,
  4656. params: {
  4657. revision: "account-1",
  4658. basedOnZCodeBuiltinRevision: "zcode-builtin:1",
  4659. states: {
  4660. "account:zai-individual-coding-plan": {
  4661. availability: "available",
  4662. entitled: true,
  4663. current: false,
  4664. },
  4665. },
  4666. providers: {
  4667. "account:zai-individual-coding-plan": {
  4668. access: { type: "zhipu-account", entitled: true },
  4669. builtinModelIds: ["GLM-5.2"],
  4670. },
  4671. },
  4672. },
  4673. });
  4674. expect(result).toEqual({
  4675. receivedRevision: "account-1",
  4676. providerCount: 1,
  4677. status: "received",
  4678. });
  4679. expect(syncAccountProviderConfig).toHaveBeenCalledTimes(1);
  4680. const snapshot = syncAccountProviderConfig.mock.calls[0]?.[0];
  4681. expect(snapshot?.revision).toBe("account-1");
  4682. expect(snapshot?.basedOnZCodeBuiltinRevision).toBe("zcode-builtin:1");
  4683. expect(snapshot?.states?.["account:zai-individual-coding-plan"].current).toBe(false);
  4684. expect(snapshot?.providers.get("account:zai-individual-coding-plan")?.toJSON()).toEqual({
  4685. access: { type: "zhipu-account", entitled: true },
  4686. builtinModelIds: ["GLM-5.2"],
  4687. });
  4688. });
  4689. it("在执行前刷新 Worker 自己的 Provider Registry,不接收 Desktop 快照", async () => {
  4690. const refreshProviderRegistry = vi.fn(async (reason: string) => {
  4691. expect(reason).toBe("before-turn");
  4692. });
  4693. const server = new ZCodeProtocolAgentServer({
  4694. createZCodeApp: () => createFakeApp(),
  4695. cwd: workspace.workspacePath,
  4696. refreshProviderRegistry,
  4697. });
  4698. const result = await requestResult(server, {
  4699. id: 1,
  4700. method: zcodeProtocolMethods.providerRefreshRegistry,
  4701. params: { reason: "before-turn" },
  4702. });
  4703. expect(zcodeProviderRefreshRegistryResultSchema.parse(result)).toEqual({
  4704. refreshed: true,
  4705. });
  4706. expect(refreshProviderRegistry).toHaveBeenCalledTimes(1);
  4707. });
  4708. it("workspace presentation rejects legacy runtimeModel", async () => {
  4709. const firstProviderRuntimeModel = {
  4710. generatedAt: 2,
  4711. model: {
  4712. modelId: "first-model",
  4713. providerId: "provider-first",
  4714. },
  4715. provider: {
  4716. baseURL: "https://first.example.com/v1",
  4717. kind: "openai-compatible" as const,
  4718. models: [
  4719. {
  4720. label: "First Model",
  4721. modelId: "first-model",
  4722. reasoning: {
  4723. defaultLevel: "max",
  4724. enabled: true,
  4725. levels: [
  4726. { label: "High", value: "high" },
  4727. { label: "Max", value: "max" },
  4728. ],
  4729. },
  4730. },
  4731. ],
  4732. providerId: "provider-first",
  4733. },
  4734. revision: "model-runtime:first-provider-default",
  4735. thoughtLevel: "max",
  4736. };
  4737. const server = new ZCodeProtocolAgentServer({
  4738. createZCodeApp: (options) => createFakeApp(options),
  4739. cwd: workspace.workspacePath,
  4740. });
  4741. const rejected = await server.handleMessage({
  4742. id: 2,
  4743. method: zcodeProtocolMethods.workspaceReadPresentation,
  4744. params: {
  4745. runtimeModel: firstProviderRuntimeModel,
  4746. workspace,
  4747. },
  4748. });
  4749. expect(rejected).toMatchObject({
  4750. error: { code: -32602 },
  4751. id: 2,
  4752. });
  4753. });
  4754. it("uses app-provided thought level when creating a session", async () => {
  4755. const server = new ZCodeProtocolAgentServer({
  4756. createZCodeApp: (options) => createFakeApp(options),
  4757. cwd: workspace.workspacePath,
  4758. });
  4759. const created = zcodeSessionStateSnapshotSchema.parse(
  4760. await requestResult(server, {
  4761. id: 1,
  4762. method: zcodeProtocolMethods.sessionCreate,
  4763. params: {
  4764. workspace,
  4765. model: { providerId: "glm", modelId: "glm-4-air" },
  4766. thoughtLevel: "deep",
  4767. },
  4768. }),
  4769. );
  4770. expect(created.settings).toMatchObject({
  4771. model: { current: { providerId: "glm", modelId: "glm-4-air" } },
  4772. thoughtLevel: { current: "deep" },
  4773. });
  4774. });
  4775. it("acks session/send before the prompt turn finishes", async () => {
  4776. let resolveSendInput!: () => void;
  4777. let sendInputSettled = false;
  4778. let receivedInputId: string | undefined;
  4779. let receivedBrowserAmbientContext: unknown;
  4780. let receivedOffPeakTaskId: string | undefined;
  4781. let receivedOffPeakRunType: string | undefined;
  4782. const sendInputCompletion = new Promise<void>((resolve) => {
  4783. resolveSendInput = resolve;
  4784. });
  4785. const server = new ZCodeProtocolAgentServer({
  4786. createZCodeApp: (options) =>
  4787. createFakeApp(options, {
  4788. sendInput: async (_input, options) => {
  4789. receivedInputId = options?.inputId;
  4790. receivedBrowserAmbientContext = options?.browserAmbientContext;
  4791. receivedOffPeakTaskId = options?.offPeakTaskId;
  4792. receivedOffPeakRunType = options?.offPeakRunType;
  4793. await sendInputCompletion;
  4794. sendInputSettled = true;
  4795. return { kind: "rejected", reason: "no_active_turn" };
  4796. },
  4797. }),
  4798. cwd: workspace.workspacePath,
  4799. });
  4800. const created = zcodeSessionStateSnapshotSchema.parse(
  4801. await requestResult(server, {
  4802. id: 1,
  4803. method: zcodeProtocolMethods.sessionCreate,
  4804. params: { workspace },
  4805. }),
  4806. );
  4807. const sendResponse = server.handleMessage({
  4808. id: 2,
  4809. method: zcodeProtocolMethods.sessionSend,
  4810. params: {
  4811. sessionId: created.session.sessionId,
  4812. content: "hello",
  4813. inputId: "t-sess_test-run",
  4814. offPeakTaskId: "off-peak-task-1",
  4815. offPeakRunType: "resume",
  4816. browserAmbientContext: {
  4817. tabCount: 1,
  4818. currentUrl: "https://example.com/current",
  4819. },
  4820. expectedRevision: created.runtime.stateRevision,
  4821. },
  4822. });
  4823. const raceResult = await Promise.race([
  4824. sendResponse.then((response) => ({ response, status: "resolved" as const })),
  4825. new Promise<{ status: "timeout" }>((resolve) =>
  4826. setTimeout(() => resolve({ status: "timeout" }), 20),
  4827. ),
  4828. ]);
  4829. expect(raceResult.status).toBe("resolved");
  4830. expect(receivedInputId).toBe("t-sess_test-run");
  4831. expect(receivedBrowserAmbientContext).toEqual({
  4832. tabCount: 1,
  4833. currentUrl: "https://example.com/current",
  4834. });
  4835. expect(receivedOffPeakTaskId).toBe("off-peak-task-1");
  4836. expect(receivedOffPeakRunType).toBe("resume");
  4837. expect(sendInputSettled).toBe(false);
  4838. resolveSendInput();
  4839. await sendInputCompletion;
  4840. });
  4841. it("Bot 私聊带附件走 legacy session/send 时,ambient 块不声明设计模式", async () => {
  4842. // Bot 私聊带附件时 Host 仍走旧版 session/send(zcodeTaskServiceAdapter 附件回退)。旧协议没有
  4843. // inputOrigin 字段,Core 拿不到「桌面输入」,所以不写「Design mode: available」——锁住这一现状。
  4844. let receivedOptions: SendInputOptions | undefined;
  4845. let resolveSendInput!: () => void;
  4846. const sendInputCalled = new Promise<void>((resolve) => {
  4847. resolveSendInput = resolve;
  4848. });
  4849. const server = new ZCodeProtocolAgentServer({
  4850. createZCodeApp: (options) =>
  4851. createFakeApp(options, {
  4852. sendInput: async (_input, sendOptions) => {
  4853. receivedOptions = sendOptions;
  4854. resolveSendInput();
  4855. return { kind: "rejected", reason: "no_active_turn" };
  4856. },
  4857. }),
  4858. cwd: workspace.workspacePath,
  4859. });
  4860. const created = zcodeSessionStateSnapshotSchema.parse(
  4861. await requestResult(server, {
  4862. id: 1,
  4863. method: zcodeProtocolMethods.sessionCreate,
  4864. params: { workspace },
  4865. }),
  4866. );
  4867. await requestResult(server, {
  4868. id: 2,
  4869. method: zcodeProtocolMethods.sessionSend,
  4870. params: {
  4871. sessionId: created.session.sessionId,
  4872. content: "E2E_BOT_ATTACHMENT 看图",
  4873. inputId: "bot-legacy-input",
  4874. browserAmbientContext: { tabCount: 1, currentUrl: "http://localhost:5173/" },
  4875. botDeliveryTarget: {
  4876. provider: "feishu",
  4877. botId: "bot-1",
  4878. providerUserId: "ou_user",
  4879. chatType: "private",
  4880. },
  4881. expectedRevision: created.runtime.stateRevision,
  4882. },
  4883. });
  4884. await sendInputCalled;
  4885. expect(receivedOptions?.browserAmbientContext).toEqual({
  4886. tabCount: 1,
  4887. currentUrl: "http://localhost:5173/",
  4888. });
  4889. expect(receivedOptions?.intent?.inputOrigin).toBeUndefined();
  4890. // 与 Core turn.ts 相同的取值:inputOrigin / clientId 都来自 intent。
  4891. const content = String(
  4892. buildRuntimeUserEntriesFromTurn("E2E_BOT_ATTACHMENT 看图", [], {
  4893. browserAmbientContext: receivedOptions?.browserAmbientContext,
  4894. ...(receivedOptions?.intent?.inputOrigin
  4895. ? { inputOrigin: receivedOptions.intent.inputOrigin }
  4896. : {}),
  4897. ...(receivedOptions?.intent?.clientId
  4898. ? { inputClientId: receivedOptions.intent.clientId }
  4899. : {}),
  4900. })[0]?.message.content,
  4901. );
  4902. expect(content).toContain("- The user has the in-app browser open with 1 tab.");
  4903. expect(content).not.toContain("Design mode");
  4904. });
  4905. it("legacy session/send 在 busy 入队时把显式 automation 身份交给 Core admission", async () => {
  4906. let receivedAutomationId: string | undefined;
  4907. let receivedToolDisallowlist: readonly string[] | undefined;
  4908. let resolveSendInputStarted!: () => void;
  4909. const sendInputStarted = new Promise<void>((resolve) => {
  4910. resolveSendInputStarted = resolve;
  4911. });
  4912. const server = new ZCodeProtocolAgentServer({
  4913. createZCodeApp: (options) =>
  4914. createFakeApp(options, {
  4915. sendInput: async (_input, sendOptions) => {
  4916. receivedAutomationId = sendOptions?.automationId;
  4917. receivedToolDisallowlist = sendOptions?.toolDisallowlist;
  4918. resolveSendInputStarted();
  4919. return {
  4920. kind: "queued",
  4921. pendingInputId: "pending-automation-queued",
  4922. queueLength: 1,
  4923. turnId: "turn-busy" as never,
  4924. };
  4925. },
  4926. }),
  4927. cwd: workspace.workspacePath,
  4928. });
  4929. const created = zcodeSessionStateSnapshotSchema.parse(
  4930. await requestResult(server, {
  4931. id: 1,
  4932. method: zcodeProtocolMethods.sessionCreate,
  4933. params: { workspace },
  4934. }),
  4935. );
  4936. await requestResult(server, {
  4937. id: 2,
  4938. method: zcodeProtocolMethods.sessionSend,
  4939. params: {
  4940. sessionId: created.session.sessionId,
  4941. content: "automation busy prompt",
  4942. automationId: "automation-queued",
  4943. inputId: "automation-queued:scheduled:run-1",
  4944. expectedRevision: created.runtime.stateRevision,
  4945. },
  4946. });
  4947. await sendInputStarted;
  4948. expect(receivedAutomationId).toBe("automation-queued");
  4949. expect(receivedToolDisallowlist).toEqual(["CronCreate"]);
  4950. });
  4951. it("does not restore automation identity from a caller-controlled inputId", async () => {
  4952. let receivedAutomationId: string | undefined;
  4953. let receivedToolDisallowlist: readonly string[] | undefined;
  4954. let resolveSendInputStarted!: () => void;
  4955. const sendInputStarted = new Promise<void>((resolve) => {
  4956. resolveSendInputStarted = resolve;
  4957. });
  4958. const server = new ZCodeProtocolAgentServer({
  4959. createZCodeApp: (options) =>
  4960. createFakeApp(options, {
  4961. sendInput: async (_input, options) => {
  4962. receivedAutomationId = options?.automationId;
  4963. receivedToolDisallowlist = options?.toolDisallowlist;
  4964. resolveSendInputStarted();
  4965. return { kind: "rejected", reason: "no_active_turn" };
  4966. },
  4967. }),
  4968. cwd: workspace.workspacePath,
  4969. });
  4970. const created = zcodeSessionStateSnapshotSchema.parse(
  4971. await requestResult(server, {
  4972. id: 1,
  4973. method: zcodeProtocolMethods.sessionCreate,
  4974. params: { workspace },
  4975. }),
  4976. );
  4977. await requestResult(server, {
  4978. id: 2,
  4979. method: zcodeProtocolMethods.sessionSend,
  4980. params: {
  4981. sessionId: created.session.sessionId,
  4982. content: "ordinary prompt",
  4983. inputId: "automation-other-task:manual:forged-run",
  4984. expectedRevision: created.runtime.stateRevision,
  4985. },
  4986. });
  4987. await sendInputStarted;
  4988. expect(receivedAutomationId).toBeUndefined();
  4989. expect(receivedToolDisallowlist).toBeUndefined();
  4990. });
  4991. it("emits prompt_completed after the active prompt lock is released", async () => {
  4992. let sessionId = "";
  4993. let secondSendDuringCompleted: Promise<unknown> | undefined;
  4994. let finalizationCountDuringCompleted: number | undefined;
  4995. let activeLockDuringCompleted: AbortController | undefined;
  4996. const server = new ZCodeProtocolAgentServer({
  4997. createZCodeApp: (options) =>
  4998. createFakeApp(options, {
  4999. sendInput: async () => ({
  5000. kind: "started_turn",
  5001. turnId: "completed-fixture" as never,
  5002. completion: Promise.resolve({} as never),
  5003. }),
  5004. }),
  5005. cwd: workspace.workspacePath,
  5006. });
  5007. setTestNotificationSink(server, (notification) => {
  5008. if (
  5009. notification.method === "state.updated" &&
  5010. (notification.params as { reason?: string }).reason === "prompt_completed" &&
  5011. !secondSendDuringCompleted
  5012. ) {
  5013. const record = (
  5014. server as unknown as { context: ZCodeProtocolAgentServerContext }
  5015. ).context.sessions.get(sessionId);
  5016. finalizationCountDuringCompleted = record?.residencyFinalizationCount;
  5017. activeLockDuringCompleted = record?.activeAbortController;
  5018. secondSendDuringCompleted = server.handleMessage({
  5019. id: 3,
  5020. method: zcodeProtocolMethods.sessionSend,
  5021. params: {
  5022. sessionId,
  5023. content: "second",
  5024. inputId: "input_second",
  5025. },
  5026. });
  5027. }
  5028. });
  5029. const created = zcodeSessionStateSnapshotSchema.parse(
  5030. await requestResult(server, {
  5031. id: 1,
  5032. method: zcodeProtocolMethods.sessionCreate,
  5033. params: { workspace },
  5034. }),
  5035. );
  5036. sessionId = created.session.sessionId;
  5037. await requestResult(server, {
  5038. id: 2,
  5039. method: zcodeProtocolMethods.sessionSend,
  5040. params: {
  5041. sessionId,
  5042. content: "first",
  5043. inputId: "input_first",
  5044. expectedRevision: created.runtime.stateRevision,
  5045. },
  5046. });
  5047. await vi.waitFor(() => {
  5048. expect(secondSendDuringCompleted).toBeDefined();
  5049. });
  5050. const secondResponse = await secondSendDuringCompleted;
  5051. expect(secondResponse).toMatchObject({
  5052. result: {
  5053. accepted: true,
  5054. sessionId,
  5055. },
  5056. });
  5057. expect(activeLockDuringCompleted).toBeUndefined();
  5058. expect(finalizationCountDuringCompleted).toBe(1);
  5059. await vi.waitFor(() => {
  5060. const record = (
  5061. server as unknown as { context: ZCodeProtocolAgentServerContext }
  5062. ).context.sessions.get(sessionId);
  5063. expect(record?.residencyFinalizationCount).toBe(0);
  5064. });
  5065. });
  5066. it("maps protocol localPath attachments before sending input to core", async () => {
  5067. let receivedInput: unknown;
  5068. let resolveReceived!: () => void;
  5069. const received = new Promise<void>((resolve) => {
  5070. resolveReceived = resolve;
  5071. });
  5072. const server = new ZCodeProtocolAgentServer({
  5073. createZCodeApp: (options) =>
  5074. createFakeApp(options, {
  5075. sendInput: async (input) => {
  5076. receivedInput = input;
  5077. resolveReceived();
  5078. return { kind: "rejected", reason: "no_active_turn" };
  5079. },
  5080. }),
  5081. cwd: workspace.workspacePath,
  5082. });
  5083. const created = zcodeSessionStateSnapshotSchema.parse(
  5084. await requestResult(server, {
  5085. id: 1,
  5086. method: zcodeProtocolMethods.sessionCreate,
  5087. params: { workspace },
  5088. }),
  5089. );
  5090. await requestResult(server, {
  5091. id: 2,
  5092. method: zcodeProtocolMethods.sessionSend,
  5093. params: {
  5094. sessionId: created.session.sessionId,
  5095. content: "inspect attachments",
  5096. expectedRevision: created.runtime.stateRevision,
  5097. attachments: [
  5098. {
  5099. kind: "file",
  5100. filename: "report.pdf",
  5101. mimeType: "application/pdf",
  5102. sizeBytes: 0,
  5103. localPath: "/tmp/report.pdf",
  5104. },
  5105. {
  5106. kind: "file",
  5107. filename: "pasted-text.txt",
  5108. mimeType: "text/plain",
  5109. sizeBytes: 8192,
  5110. localPath: "/tmp/.zcode/tmp/paste-attachments/2026-06-30/pasted-text.txt",
  5111. sourceKind: "clipboard-text",
  5112. },
  5113. {
  5114. kind: "image",
  5115. filename: "diagram.png",
  5116. mimeType: "image/png",
  5117. localPath: "/tmp/diagram.png",
  5118. },
  5119. ],
  5120. },
  5121. });
  5122. await received;
  5123. expect(receivedInput).toMatchObject({
  5124. text: "inspect attachments",
  5125. attachments: [
  5126. { path: "/tmp/report.pdf", type: "pdf" },
  5127. {
  5128. path: "/tmp/.zcode/tmp/paste-attachments/2026-06-30/pasted-text.txt",
  5129. sourceKind: "clipboard-text",
  5130. type: "file",
  5131. },
  5132. { path: "/tmp/diagram.png", type: "image" },
  5133. ],
  5134. });
  5135. });
  5136. it("bridges protocol permission requests through server-to-client JSON-RPC", async () => {
  5137. const outgoing: ZCodeProtocolMessage[] = [];
  5138. const origin = {
  5139. kind: "subagent",
  5140. agentId: "agent_perm",
  5141. agentType: "general",
  5142. childSessionId: "sess_child_perm",
  5143. childTurnId: "turn_child_perm",
  5144. parentSessionId: "sess_parent_perm",
  5145. parentToolCallId: "tool_parent_agent",
  5146. parentTurnId: "turn_parent_perm",
  5147. } as const;
  5148. let brokerResult:
  5149. | Awaited<ReturnType<NonNullable<ZCodeAppOptions["permissionBroker"]>["requestPermission"]>>
  5150. | undefined;
  5151. const server = new ZCodeProtocolAgentServer({
  5152. createZCodeApp: (options) =>
  5153. createFakeApp(options, {
  5154. sendInput: async () => {
  5155. brokerResult = await options?.permissionBroker?.requestPermission({
  5156. input: { command: "rm -rf tmp" },
  5157. mode: "build",
  5158. origin,
  5159. reason: "Bash requires approval",
  5160. requestId: "perm_1",
  5161. requestedAt: new Date(1),
  5162. riskLevel: "high",
  5163. ruleId: "rule_1",
  5164. sessionId: (options?.sessionId ?? "sess_test") as never,
  5165. toolCallId: "tool_1" as never,
  5166. toolName: "Bash",
  5167. traceId: "trace_test" as never,
  5168. });
  5169. return { kind: "rejected", reason: "no_active_turn" };
  5170. },
  5171. }),
  5172. cwd: workspace.workspacePath,
  5173. });
  5174. setTestNotificationSink(server, (message) => outgoing.push(message));
  5175. const created = zcodeSessionStateSnapshotSchema.parse(
  5176. await requestResult(server, {
  5177. id: 1,
  5178. method: zcodeProtocolMethods.sessionCreate,
  5179. params: { workspace },
  5180. }),
  5181. );
  5182. await requestResult(server, {
  5183. id: 2,
  5184. method: zcodeProtocolMethods.sessionSend,
  5185. params: { sessionId: created.session.sessionId, content: "run command" },
  5186. });
  5187. await vi.waitFor(() => {
  5188. expect(outgoing.some((message) => message.method === "interaction/requestPermission")).toBe(
  5189. true,
  5190. );
  5191. });
  5192. const permissionRequest = outgoing.find(
  5193. (message) => message.method === "interaction/requestPermission" && "id" in message,
  5194. );
  5195. expect(permissionRequest).toMatchObject({
  5196. method: "interaction/requestPermission",
  5197. params: {
  5198. options: [
  5199. {
  5200. optionId: "allow_once",
  5201. response: { decision: "allow" },
  5202. },
  5203. {
  5204. optionId: "allow_project",
  5205. response: {
  5206. decision: "allow",
  5207. permissionUpdates: [
  5208. {
  5209. behavior: "allow",
  5210. rules: [{ ruleContent: "rm -rf tmp", toolName: "Bash" }],
  5211. type: "addRules",
  5212. },
  5213. ],
  5214. },
  5215. },
  5216. {
  5217. optionId: "deny",
  5218. response: { decision: "deny" },
  5219. },
  5220. ],
  5221. origin,
  5222. requestId: "perm_1",
  5223. toolName: "Bash",
  5224. },
  5225. });
  5226. await server.handleMessage({ id: permissionRequest?.id ?? "", result: { decision: "allow" } });
  5227. await vi.waitFor(() => {
  5228. expect(brokerResult).toMatchObject({ decision: "allow" });
  5229. });
  5230. });
  5231. it("reannounces pending protocol permission requests so a later client request can be answered", async () => {
  5232. vi.useFakeTimers();
  5233. try {
  5234. const outgoing: ZCodeProtocolMessage[] = [];
  5235. let brokerResultPromise:
  5236. | ReturnType<NonNullable<ZCodeAppOptions["permissionBroker"]>["requestPermission"]>
  5237. | undefined;
  5238. const server = new ZCodeProtocolAgentServer({
  5239. createZCodeApp: (options) =>
  5240. createFakeApp(options, {
  5241. sendInput: async () => {
  5242. brokerResultPromise = options?.permissionBroker?.requestPermission({
  5243. input: { command: "rm -rf tmp" },
  5244. mode: "build",
  5245. reason: "Bash requires approval",
  5246. requestId: "perm_reannounce",
  5247. requestedAt: new Date(1),
  5248. riskLevel: "high",
  5249. ruleId: "rule_1",
  5250. sessionId: (options?.sessionId ?? "sess_test") as never,
  5251. toolCallId: "tool_1" as never,
  5252. toolName: "Bash",
  5253. traceId: "trace_test" as never,
  5254. });
  5255. await brokerResultPromise;
  5256. return { kind: "rejected", reason: "no_active_turn" };
  5257. },
  5258. }),
  5259. cwd: workspace.workspacePath,
  5260. });
  5261. setTestNotificationSink(server, (message) => outgoing.push(message));
  5262. const created = zcodeSessionStateSnapshotSchema.parse(
  5263. await requestResult(server, {
  5264. id: 1,
  5265. method: zcodeProtocolMethods.sessionCreate,
  5266. params: { workspace },
  5267. }),
  5268. );
  5269. await requestResult(server, {
  5270. id: 2,
  5271. method: zcodeProtocolMethods.sessionSend,
  5272. params: { sessionId: created.session.sessionId, content: "run command" },
  5273. });
  5274. await vi.waitFor(() => {
  5275. expect(brokerResultPromise).toBeDefined();
  5276. });
  5277. const firstRequest = outgoing.find(
  5278. (message) => message.method === "interaction/requestPermission" && "id" in message,
  5279. );
  5280. expect(firstRequest).toMatchObject({
  5281. method: "interaction/requestPermission",
  5282. params: {
  5283. requestId: "perm_reannounce",
  5284. toolName: "Bash",
  5285. },
  5286. });
  5287. await vi.advanceTimersByTimeAsync(1_000);
  5288. const permissionRequests = outgoing.filter(
  5289. (message) => message.method === "interaction/requestPermission" && "id" in message,
  5290. );
  5291. expect(permissionRequests).toHaveLength(2);
  5292. expect(permissionRequests[1]).toMatchObject({
  5293. method: "interaction/requestPermission",
  5294. params: {
  5295. requestId: "perm_reannounce",
  5296. toolName: "Bash",
  5297. },
  5298. });
  5299. const firstProtocolRequestId =
  5300. firstRequest && "id" in firstRequest ? firstRequest.id : undefined;
  5301. expect(permissionRequests[1]?.id).not.toBe(firstProtocolRequestId);
  5302. await server.handleMessage({
  5303. id: permissionRequests[1]?.id ?? "",
  5304. result: { decision: "allow" },
  5305. });
  5306. await expect(brokerResultPromise).resolves.toMatchObject({
  5307. decision: "allow",
  5308. });
  5309. } finally {
  5310. vi.useRealTimers();
  5311. }
  5312. });
  5313. it("bridges AskUserQuestion through protocol user input requests", async () => {
  5314. const outgoing: ZCodeProtocolMessage[] = [];
  5315. const origin = {
  5316. kind: "subagent",
  5317. agentId: "agent_ask",
  5318. agentType: "general",
  5319. childSessionId: "sess_child_ask",
  5320. childTurnId: "turn_child_ask",
  5321. parentSessionId: "sess_parent_ask",
  5322. parentToolCallId: "tool_parent_agent",
  5323. parentTurnId: "turn_parent_ask",
  5324. } as const;
  5325. let brokerResult:
  5326. | Awaited<ReturnType<NonNullable<ZCodeAppOptions["permissionBroker"]>["requestPermission"]>>
  5327. | undefined;
  5328. const askInput = {
  5329. questions: [
  5330. {
  5331. question: "Which branch should I test?",
  5332. header: "Branch",
  5333. options: [
  5334. { label: "main", description: "Use main branch" },
  5335. { label: "release", description: "Use release branch" },
  5336. ],
  5337. },
  5338. ],
  5339. };
  5340. const server = new ZCodeProtocolAgentServer({
  5341. createZCodeApp: (options) =>
  5342. createFakeApp(options, {
  5343. sendInput: async () => {
  5344. brokerResult = await options?.permissionBroker?.requestPermission({
  5345. input: askInput,
  5346. mode: "build",
  5347. origin,
  5348. reason: "AskUserQuestion pauses execution to collect answers from the user",
  5349. requestId: "ask_1",
  5350. requestedAt: new Date(1),
  5351. riskLevel: "low",
  5352. ruleId: "rule_ask",
  5353. sessionId: (options?.sessionId ?? "sess_test") as never,
  5354. toolCallId: "tool_ask" as never,
  5355. toolName: "AskUserQuestion",
  5356. traceId: "trace_test" as never,
  5357. });
  5358. return { kind: "rejected", reason: "no_active_turn" };
  5359. },
  5360. }),
  5361. cwd: workspace.workspacePath,
  5362. });
  5363. setTestNotificationSink(server, (message) => outgoing.push(message));
  5364. const created = zcodeSessionStateSnapshotSchema.parse(
  5365. await requestResult(server, {
  5366. id: 1,
  5367. method: zcodeProtocolMethods.sessionCreate,
  5368. params: { workspace },
  5369. }),
  5370. );
  5371. await requestResult(server, {
  5372. id: 2,
  5373. method: zcodeProtocolMethods.sessionSend,
  5374. params: { sessionId: created.session.sessionId, content: "ask" },
  5375. });
  5376. await vi.waitFor(() => {
  5377. expect(outgoing.some((message) => message.method === "interaction/requestUserInput")).toBe(
  5378. true,
  5379. );
  5380. });
  5381. const userInputRequest = outgoing.find(
  5382. (message) => message.method === "interaction/requestUserInput" && "id" in message,
  5383. );
  5384. expect(userInputRequest).toMatchObject({
  5385. method: "interaction/requestUserInput",
  5386. params: {
  5387. origin,
  5388. requestId: "ask_1",
  5389. questions: [{ question: "Which branch should I test?" }],
  5390. },
  5391. });
  5392. await server.handleMessage({
  5393. id: userInputRequest?.id ?? "",
  5394. result: {
  5395. action: "accept",
  5396. content: {
  5397. answers: { "Which branch should I test?": "release" },
  5398. answer_0: "release",
  5399. answer: "release",
  5400. },
  5401. },
  5402. });
  5403. await vi.waitFor(() => {
  5404. expect(brokerResult).toMatchObject({
  5405. decision: "modify",
  5406. modifiedInput: {
  5407. answers: { "Which branch should I test?": "release" },
  5408. questions: askInput.questions,
  5409. },
  5410. });
  5411. });
  5412. expect(
  5413. (brokerResult as { modifiedInput?: Record<string, unknown> }).modifiedInput,
  5414. ).not.toHaveProperty("answer_0");
  5415. expect(
  5416. (brokerResult as { modifiedInput?: Record<string, unknown> }).modifiedInput,
  5417. ).not.toHaveProperty("answer");
  5418. });
  5419. it("bridges ExitPlanMode approval through protocol user input requests", async () => {
  5420. const outgoing: ZCodeProtocolMessage[] = [];
  5421. const origin = {
  5422. kind: "subagent",
  5423. agentId: "agent_exit_plan",
  5424. agentType: "general",
  5425. childSessionId: "sess_child_exit_plan",
  5426. childTurnId: "turn_child_exit_plan",
  5427. parentSessionId: "sess_parent_exit_plan",
  5428. parentToolCallId: "tool_parent_agent",
  5429. parentTurnId: "turn_parent_exit_plan",
  5430. } as const;
  5431. let brokerResult:
  5432. | Awaited<ReturnType<NonNullable<ZCodeAppOptions["permissionBroker"]>["requestPermission"]>>
  5433. | undefined;
  5434. const exitPlanInput = {
  5435. plan: "1. Change the runtime\n2. Add tests",
  5436. };
  5437. const server = new ZCodeProtocolAgentServer({
  5438. createZCodeApp: (options) =>
  5439. createFakeApp(options, {
  5440. sendInput: async () => {
  5441. brokerResult = await options?.permissionBroker?.requestPermission({
  5442. input: exitPlanInput,
  5443. mode: "plan",
  5444. origin,
  5445. reason: "ExitPlanMode requires user approval before implementation",
  5446. requestId: "exit_plan_1",
  5447. requestedAt: new Date(1),
  5448. riskLevel: "high",
  5449. ruleId: "rule_exit_plan",
  5450. sessionId: (options?.sessionId ?? "sess_test") as never,
  5451. toolCallId: "tool_exit_plan" as never,
  5452. toolName: "ExitPlanMode",
  5453. traceId: "trace_test" as never,
  5454. });
  5455. return { kind: "rejected", reason: "no_active_turn" };
  5456. },
  5457. }),
  5458. cwd: workspace.workspacePath,
  5459. });
  5460. setTestNotificationSink(server, (message) => outgoing.push(message));
  5461. const created = zcodeSessionStateSnapshotSchema.parse(
  5462. await requestResult(server, {
  5463. id: 1,
  5464. method: zcodeProtocolMethods.sessionCreate,
  5465. params: { workspace },
  5466. }),
  5467. );
  5468. await requestResult(server, {
  5469. id: 2,
  5470. method: zcodeProtocolMethods.sessionSend,
  5471. params: { sessionId: created.session.sessionId, content: "plan" },
  5472. });
  5473. await vi.waitFor(() => {
  5474. expect(outgoing.some((message) => message.method === "interaction/requestUserInput")).toBe(
  5475. true,
  5476. );
  5477. });
  5478. expect(outgoing.some((message) => message.method === "interaction/requestPermission")).toBe(
  5479. false,
  5480. );
  5481. const userInputRequest = outgoing.find(
  5482. (message) => message.method === "interaction/requestUserInput" && "id" in message,
  5483. );
  5484. expect(userInputRequest).toMatchObject({
  5485. method: "interaction/requestUserInput",
  5486. params: {
  5487. origin,
  5488. requestId: "exit_plan_1",
  5489. schema: { interaction: "plan_approval", toolName: "ExitPlanMode" },
  5490. questions: [
  5491. {
  5492. header: "Plan",
  5493. options: [{ value: "approve", label: "Approve" }],
  5494. },
  5495. ],
  5496. },
  5497. });
  5498. await server.handleMessage({
  5499. id: userInputRequest?.id ?? "",
  5500. result: {
  5501. action: "accept",
  5502. content: {
  5503. answer_0: "Please add tests before implementation.",
  5504. answer: "Please add tests before implementation.",
  5505. },
  5506. },
  5507. });
  5508. await vi.waitFor(() => {
  5509. expect(brokerResult).toMatchObject({
  5510. decision: "deny",
  5511. reason: "Please add tests before implementation.",
  5512. reasonSource: "plan_approval_feedback",
  5513. });
  5514. });
  5515. });
  5516. it("reannounces pending ExitPlanMode approval so a later client request can be answered", async () => {
  5517. vi.useFakeTimers();
  5518. try {
  5519. const outgoing: ZCodeProtocolMessage[] = [];
  5520. let brokerResultPromise:
  5521. | ReturnType<NonNullable<ZCodeAppOptions["permissionBroker"]>["requestPermission"]>
  5522. | undefined;
  5523. const exitPlanInput = {
  5524. plan: "1. Change the runtime\n2. Add tests",
  5525. };
  5526. const server = new ZCodeProtocolAgentServer({
  5527. createZCodeApp: (options) =>
  5528. createFakeApp(options, {
  5529. sendInput: async () => {
  5530. brokerResultPromise = options?.permissionBroker?.requestPermission({
  5531. input: exitPlanInput,
  5532. mode: "plan",
  5533. reason: "ExitPlanMode requires user approval before implementation",
  5534. requestId: "exit_plan_reannounce",
  5535. requestedAt: new Date(1),
  5536. riskLevel: "high",
  5537. ruleId: "rule_exit_plan",
  5538. sessionId: (options?.sessionId ?? "sess_test") as never,
  5539. toolCallId: "tool_exit_plan" as never,
  5540. toolName: "ExitPlanMode",
  5541. traceId: "trace_test" as never,
  5542. });
  5543. await brokerResultPromise;
  5544. return { kind: "rejected", reason: "no_active_turn" };
  5545. },
  5546. }),
  5547. cwd: workspace.workspacePath,
  5548. });
  5549. setTestNotificationSink(server, (message) => outgoing.push(message));
  5550. const created = zcodeSessionStateSnapshotSchema.parse(
  5551. await requestResult(server, {
  5552. id: 1,
  5553. method: zcodeProtocolMethods.sessionCreate,
  5554. params: { workspace },
  5555. }),
  5556. );
  5557. await requestResult(server, {
  5558. id: 2,
  5559. method: zcodeProtocolMethods.sessionSend,
  5560. params: { sessionId: created.session.sessionId, content: "plan" },
  5561. });
  5562. await vi.waitFor(() => {
  5563. expect(brokerResultPromise).toBeDefined();
  5564. });
  5565. const firstRequest = outgoing.find(
  5566. (message) => message.method === "interaction/requestUserInput" && "id" in message,
  5567. );
  5568. expect(firstRequest).toMatchObject({
  5569. method: "interaction/requestUserInput",
  5570. params: {
  5571. requestId: "exit_plan_reannounce",
  5572. schema: { interaction: "plan_approval", toolName: "ExitPlanMode" },
  5573. },
  5574. });
  5575. await vi.advanceTimersByTimeAsync(1_000);
  5576. const userInputRequests = outgoing.filter(
  5577. (message) => message.method === "interaction/requestUserInput" && "id" in message,
  5578. );
  5579. expect(userInputRequests).toHaveLength(2);
  5580. expect(userInputRequests[1]).toMatchObject({
  5581. method: "interaction/requestUserInput",
  5582. params: {
  5583. requestId: "exit_plan_reannounce",
  5584. schema: { interaction: "plan_approval", toolName: "ExitPlanMode" },
  5585. },
  5586. });
  5587. const firstProtocolRequestId =
  5588. firstRequest && "id" in firstRequest ? firstRequest.id : undefined;
  5589. expect(userInputRequests[1]?.id).not.toBe(firstProtocolRequestId);
  5590. await server.handleMessage({
  5591. id: userInputRequests[1]?.id ?? "",
  5592. result: {
  5593. action: "accept",
  5594. content: {
  5595. answer_0: "approve",
  5596. answer: "approve",
  5597. },
  5598. },
  5599. });
  5600. await expect(brokerResultPromise).resolves.toMatchObject({
  5601. decision: "allow",
  5602. });
  5603. } finally {
  5604. vi.useRealTimers();
  5605. }
  5606. });
  5607. // M5 ③-4:session/rewind、session/rewindCascade 旧协议词已删除(v4 fork/edit/retry
  5608. // 经原生 handler 直发 `/rewind conversation <messageId>` slash command,见
  5609. // zcode-protocol-v4/commands/handlers/fork-edit-retry.ts);本用例收敛为 compact 单验证。
  5610. it("runs compact through the explicit session protocol method", async () => {
  5611. const submittedPrompts: string[] = [];
  5612. const server = new ZCodeProtocolAgentServer({
  5613. createZCodeApp: (options) =>
  5614. createFakeApp(options, {
  5615. submitPrompt: async (prompt) => {
  5616. submittedPrompts.push(typeof prompt === "string" ? prompt : prompt.text);
  5617. return { response: `ok:${submittedPrompts.at(-1)}` } as never;
  5618. },
  5619. }),
  5620. cwd: workspace.workspacePath,
  5621. });
  5622. const created = zcodeSessionStateSnapshotSchema.parse(
  5623. await requestResult(server, {
  5624. id: 1,
  5625. method: zcodeProtocolMethods.sessionCreate,
  5626. params: { workspace },
  5627. }),
  5628. );
  5629. const compacted = zcodeSessionCompactResultSchema.parse(
  5630. await requestResult(server, {
  5631. id: 2,
  5632. method: zcodeProtocolMethods.sessionCompact,
  5633. params: {
  5634. sessionId: created.session.sessionId,
  5635. instructions: "keep recent files",
  5636. },
  5637. }),
  5638. );
  5639. expect(submittedPrompts).toEqual(["/compact keep recent files"]);
  5640. expect(compacted.response).toBe("");
  5641. expect(compacted.compact?.state).toBe("accepted");
  5642. });
  5643. it("aborts in-flight compact requests when the session is stopped", async () => {
  5644. let resolveCompactStarted!: () => void;
  5645. let resolveCompactAborted!: () => void;
  5646. let compactSignal: AbortSignal | undefined;
  5647. const compactStarted = new Promise<void>((resolve) => {
  5648. resolveCompactStarted = resolve;
  5649. });
  5650. const compactAborted = new Promise<void>((resolve) => {
  5651. resolveCompactAborted = resolve;
  5652. });
  5653. const submitPrompt = vi.fn(async (_prompt, options) => {
  5654. compactSignal = options?.abortSignal;
  5655. resolveCompactStarted();
  5656. return await new Promise<never>((_resolve, reject) => {
  5657. const abort = () => {
  5658. resolveCompactAborted();
  5659. reject(options?.abortSignal?.reason ?? new Error("compact aborted"));
  5660. };
  5661. if (options?.abortSignal?.aborted) {
  5662. abort();
  5663. return;
  5664. }
  5665. options?.abortSignal?.addEventListener("abort", abort, { once: true });
  5666. });
  5667. });
  5668. const server = new ZCodeProtocolAgentServer({
  5669. createZCodeApp: (options) => createFakeApp(options, { submitPrompt }),
  5670. cwd: workspace.workspacePath,
  5671. });
  5672. const created = zcodeSessionStateSnapshotSchema.parse(
  5673. await requestResult(server, {
  5674. id: 1,
  5675. method: zcodeProtocolMethods.sessionCreate,
  5676. params: { workspace },
  5677. }),
  5678. );
  5679. const compactResponse = server.handleMessage({
  5680. id: 2,
  5681. method: zcodeProtocolMethods.sessionCompact,
  5682. params: {
  5683. sessionId: created.session.sessionId,
  5684. inputId: "input-compact",
  5685. instructions: "keep recent files",
  5686. },
  5687. });
  5688. await compactStarted;
  5689. expect(compactSignal?.aborted).toBe(false);
  5690. await requestResult(server, {
  5691. id: 3,
  5692. method: zcodeProtocolMethods.sessionStop,
  5693. params: { sessionId: created.session.sessionId },
  5694. });
  5695. await compactAborted;
  5696. expect(compactSignal?.aborted).toBe(true);
  5697. expect(submitPrompt).toHaveBeenCalledWith(
  5698. "/compact keep recent files",
  5699. expect.objectContaining({
  5700. abortSignal: compactSignal,
  5701. inputId: "input-compact",
  5702. }),
  5703. );
  5704. const response = await compactResponse;
  5705. const result = zcodeSessionCompactResultSchema.parse(
  5706. response && "result" in response ? response.result : undefined,
  5707. );
  5708. expect(result.compact?.state).toBe("accepted");
  5709. });
  5710. it("generates workspace text through an active app", async () => {
  5711. const generateWorkspaceText = vi.fn(async (input: { prompt: string; querySource: string }) => ({
  5712. text: `generated:${input.querySource}:${input.prompt}`,
  5713. selection: { providerId: "glm", modelId: "glm-4.6" },
  5714. finishReason: "length",
  5715. usage: { inputTokens: 3, outputTokens: 256, totalTokens: 259 },
  5716. }));
  5717. const server = new ZCodeProtocolAgentServer({
  5718. createZCodeApp: (options) => createFakeApp(options, { generateWorkspaceText }),
  5719. cwd: workspace.workspacePath,
  5720. });
  5721. await requestResult(server, {
  5722. id: 1,
  5723. method: zcodeProtocolMethods.sessionCreate,
  5724. params: { workspace },
  5725. });
  5726. const result = zcodeWorkspaceGenerateTextResultSchema.parse(
  5727. await requestResult(server, {
  5728. id: 2,
  5729. method: zcodeProtocolMethods.workspaceGenerateText,
  5730. params: {
  5731. workspace,
  5732. selection: { providerId: "glm", modelId: "glm-4.6" },
  5733. prompt: "write a commit message",
  5734. querySource: "git_commit_message",
  5735. maxOutputTokens: 256,
  5736. },
  5737. }),
  5738. );
  5739. expect(result).toEqual({
  5740. text: "generated:git_commit_message:write a commit message",
  5741. selection: { providerId: "glm", modelId: "glm-4.6" },
  5742. finishReason: "length",
  5743. usage: { inputTokens: 3, outputTokens: 256, totalTokens: 259 },
  5744. });
  5745. expect(generateWorkspaceText).toHaveBeenCalledWith(
  5746. expect.objectContaining({
  5747. selection: { providerId: "glm", modelId: "glm-4.6" },
  5748. prompt: "write a commit message",
  5749. querySource: "git_commit_message",
  5750. maxOutputTokens: 256,
  5751. }),
  5752. { abortSignal: undefined },
  5753. );
  5754. expect(generateWorkspaceText.mock.calls[0]?.[0]).not.toHaveProperty("modelSelection");
  5755. });
  5756. it("tests provider connectivity through the selected formal Model", async () => {
  5757. const calls: string[] = [];
  5758. const refreshProviderRegistry = vi.fn(async () => {
  5759. calls.push("refresh");
  5760. });
  5761. const testModelConnectivity = vi.fn(async () => {});
  5762. const server = new ZCodeProtocolAgentServer({
  5763. createZCodeApp: (options) =>
  5764. createFakeApp(options, {
  5765. testModelConnectivity: async (...args) => {
  5766. calls.push("connectivity");
  5767. await testModelConnectivity(...args);
  5768. },
  5769. }),
  5770. cwd: workspace.workspacePath,
  5771. refreshProviderRegistry,
  5772. });
  5773. await requestResult(server, {
  5774. id: 1,
  5775. method: zcodeProtocolMethods.sessionCreate,
  5776. params: { workspace },
  5777. });
  5778. const result = zcodeProviderTestModelConnectivityResultSchema.parse(
  5779. await requestResult(server, {
  5780. id: 2,
  5781. method: zcodeProtocolMethods.providerTestModelConnectivity,
  5782. params: {
  5783. workspace,
  5784. selection: {
  5785. providerId: "custom-openai",
  5786. modelId: "agent-model",
  5787. options: { reasoningLevel: "high" },
  5788. },
  5789. },
  5790. }),
  5791. );
  5792. expect(result).toEqual({ success: true });
  5793. expect(refreshProviderRegistry).toHaveBeenCalledWith("provider-connectivity");
  5794. expect(calls).toEqual(["refresh", "connectivity"]);
  5795. expect(testModelConnectivity).toHaveBeenCalledWith(
  5796. {
  5797. selection: {
  5798. providerId: "custom-openai",
  5799. modelId: "agent-model",
  5800. options: { reasoningLevel: "high" },
  5801. },
  5802. },
  5803. { abortSignal: undefined },
  5804. );
  5805. });
  5806. it("closes the temporary app after provider connectivity testing", async () => {
  5807. const close = vi.fn(async () => {});
  5808. const testModelConnectivity = vi.fn(async () => {});
  5809. const server = new ZCodeProtocolAgentServer({
  5810. createZCodeApp: (options) => createFakeApp(options, { close, testModelConnectivity }),
  5811. cwd: workspace.workspacePath,
  5812. });
  5813. await requestResult(server, {
  5814. id: 1,
  5815. method: zcodeProtocolMethods.providerTestModelConnectivity,
  5816. params: {
  5817. workspace,
  5818. selection: { providerId: "custom-openai", modelId: "agent-model" },
  5819. },
  5820. });
  5821. expect(testModelConnectivity).toHaveBeenCalledOnce();
  5822. expect(close).toHaveBeenCalledOnce();
  5823. });
  5824. it("cancels an active workspace text generation by operation id", async () => {
  5825. let generatedSignal: AbortSignal | undefined;
  5826. let resolveStarted: (() => void) | undefined;
  5827. const started = new Promise<void>((resolve) => {
  5828. resolveStarted = resolve;
  5829. });
  5830. const generateWorkspaceText = vi.fn(
  5831. async (...[, options]: Parameters<ZCodeApp["generateWorkspaceText"]>) => {
  5832. generatedSignal = options?.abortSignal;
  5833. resolveStarted?.();
  5834. await new Promise<never>((_resolve, reject) => {
  5835. generatedSignal?.addEventListener("abort", () => reject(generatedSignal?.reason), {
  5836. once: true,
  5837. });
  5838. });
  5839. },
  5840. );
  5841. const server = new ZCodeProtocolAgentServer({
  5842. createZCodeApp: (options) => createFakeApp(options, { generateWorkspaceText }),
  5843. cwd: workspace.workspacePath,
  5844. });
  5845. const generateResponse = server.handleMessage({
  5846. id: 1,
  5847. method: zcodeProtocolMethods.workspaceGenerateText,
  5848. params: {
  5849. workspace,
  5850. selection: { providerId: "glm", modelId: "glm-4.6" },
  5851. prompt: "generate text",
  5852. querySource: "test_sidecar",
  5853. operationId: "workspace_model_1",
  5854. },
  5855. });
  5856. await started;
  5857. const cancelResult = zcodeWorkspaceCancelGenerateTextResultSchema.parse(
  5858. await requestResult(server, {
  5859. id: 2,
  5860. method: zcodeProtocolMethods.workspaceCancelGenerateText,
  5861. params: { operationId: "workspace_model_1" },
  5862. }),
  5863. );
  5864. expect(cancelResult).toEqual({ operationId: "workspace_model_1", cancelled: true });
  5865. expect(generatedSignal?.aborted).toBe(true);
  5866. await expect(generateResponse).resolves.toMatchObject({
  5867. id: 1,
  5868. error: expect.objectContaining({ message: expect.any(String) }),
  5869. });
  5870. });
  5871. it("rejects a duplicate active workspace text operation id without replacing its controller", async () => {
  5872. let firstSignal: AbortSignal | undefined;
  5873. let resolveStarted: (() => void) | undefined;
  5874. const started = new Promise<void>((resolve) => {
  5875. resolveStarted = resolve;
  5876. });
  5877. let invocation = 0;
  5878. const generateWorkspaceText = vi.fn(
  5879. async (...[, options]: Parameters<ZCodeApp["generateWorkspaceText"]>) => {
  5880. invocation += 1;
  5881. if (invocation > 1) {
  5882. return {
  5883. text: "reused",
  5884. selection: { providerId: "glm", modelId: "glm-4.6" },
  5885. finishReason: "stop",
  5886. };
  5887. }
  5888. firstSignal = options?.abortSignal;
  5889. resolveStarted?.();
  5890. await new Promise<never>((_resolve, reject) => {
  5891. firstSignal?.addEventListener("abort", () => reject(firstSignal?.reason), { once: true });
  5892. });
  5893. },
  5894. );
  5895. const server = new ZCodeProtocolAgentServer({
  5896. createZCodeApp: (options) => createFakeApp(options, { generateWorkspaceText }),
  5897. cwd: workspace.workspacePath,
  5898. });
  5899. const params = {
  5900. workspace,
  5901. selection: { providerId: "glm", modelId: "glm-4.6" },
  5902. prompt: "generate text",
  5903. querySource: "test_sidecar",
  5904. operationId: "workspace_model_duplicate",
  5905. } as const;
  5906. const firstResponse = server.handleMessage({
  5907. id: 1,
  5908. method: zcodeProtocolMethods.workspaceGenerateText,
  5909. params,
  5910. });
  5911. await started;
  5912. await expect(
  5913. server.handleMessage({
  5914. id: 2,
  5915. method: zcodeProtocolMethods.workspaceGenerateText,
  5916. params,
  5917. }),
  5918. ).resolves.toMatchObject({
  5919. id: 2,
  5920. error: expect.objectContaining({
  5921. code: -32600,
  5922. message: expect.stringContaining("already active"),
  5923. }),
  5924. });
  5925. expect(generateWorkspaceText).toHaveBeenCalledOnce();
  5926. const cancelResult = zcodeWorkspaceCancelGenerateTextResultSchema.parse(
  5927. await requestResult(server, {
  5928. id: 3,
  5929. method: zcodeProtocolMethods.workspaceCancelGenerateText,
  5930. params: { operationId: params.operationId },
  5931. }),
  5932. );
  5933. expect(cancelResult.cancelled).toBe(true);
  5934. expect(firstSignal?.aborted).toBe(true);
  5935. await expect(firstResponse).resolves.toMatchObject({
  5936. id: 1,
  5937. error: expect.objectContaining({ message: expect.any(String) }),
  5938. });
  5939. const reused = await requestResult(server, {
  5940. id: 4,
  5941. method: zcodeProtocolMethods.workspaceGenerateText,
  5942. params: { ...params, operationId: params.operationId, prompt: "reuse id after completion" },
  5943. });
  5944. expect(reused).toMatchObject({ text: expect.any(String) });
  5945. });
  5946. it("closes the temporary app after draft workspace text generation", async () => {
  5947. const close = vi.fn(async () => {});
  5948. const appOptions: ZCodeAppOptions[] = [];
  5949. const generateWorkspaceText = vi.fn(async () => ({
  5950. text: "fix(git): generate message",
  5951. selection: { providerId: "custom-openai", modelId: "backup-model" },
  5952. finishReason: "stop",
  5953. }));
  5954. const providerRegistry = createProtocolTestProviderRegistry();
  5955. const server = new ZCodeProtocolAgentServer({
  5956. createZCodeApp: (options) => {
  5957. const effectiveOptions = { ...options, providerRegistry };
  5958. appOptions.push(effectiveOptions);
  5959. return createFakeApp(effectiveOptions, { close, generateWorkspaceText });
  5960. },
  5961. cwd: workspace.workspacePath,
  5962. });
  5963. const result = zcodeWorkspaceGenerateTextResultSchema.parse(
  5964. await requestResult(server, {
  5965. id: 2,
  5966. method: zcodeProtocolMethods.workspaceGenerateText,
  5967. params: {
  5968. workspace,
  5969. selection: { providerId: "custom-openai", modelId: "backup-model" },
  5970. prompt: "write a commit message",
  5971. querySource: "git_commit_message",
  5972. },
  5973. }),
  5974. );
  5975. expect(result.text).toBe("fix(git): generate message");
  5976. expect(generateWorkspaceText).toHaveBeenCalledOnce();
  5977. expect(close).toHaveBeenCalledOnce();
  5978. const temporaryAppOptions = appOptions.at(-1);
  5979. expect(temporaryAppOptions?.providerRegistry).toBe(providerRegistry);
  5980. expect(temporaryAppOptions?.modelAdapter).toBeUndefined();
  5981. });
  5982. it("drops duplicate compact requests while the same session is compacting", async () => {
  5983. const submitPrompt = vi.fn();
  5984. const server = new ZCodeProtocolAgentServer({
  5985. createZCodeApp: (options) => {
  5986. const app = createFakeApp(options);
  5987. return {
  5988. ...app,
  5989. runtime: {
  5990. ...app.runtime,
  5991. getActiveTurnInfo: () =>
  5992. ({
  5993. kind: "compact",
  5994. queueLength: 0,
  5995. steerable: false,
  5996. turnId: "turn_compact",
  5997. }) as never,
  5998. },
  5999. submitPrompt,
  6000. };
  6001. },
  6002. cwd: workspace.workspacePath,
  6003. });
  6004. const created = zcodeSessionStateSnapshotSchema.parse(
  6005. await requestResult(server, {
  6006. id: 1,
  6007. method: zcodeProtocolMethods.sessionCreate,
  6008. params: { workspace },
  6009. }),
  6010. );
  6011. const compacted = zcodeSessionCompactResultSchema.parse(
  6012. await requestResult(server, {
  6013. id: 2,
  6014. method: zcodeProtocolMethods.sessionCompact,
  6015. params: {
  6016. sessionId: created.session.sessionId,
  6017. instructions: "keep recent files",
  6018. },
  6019. }),
  6020. );
  6021. expect(submitPrompt).not.toHaveBeenCalled();
  6022. expect(compacted.response).toBe("");
  6023. expect(compacted.snapshot.runtime.activeTurnKind).toBe("compact");
  6024. });
  6025. it("runs goal through target APIs instead of submitPrompt", async () => {
  6026. let target: Awaited<ReturnType<NonNullable<ZCodeApp["readTarget"]>>> = null;
  6027. const submitPrompt = vi.fn();
  6028. const continueActiveTarget = vi.fn(async () => ({ response: "continued" }) as never);
  6029. const server = new ZCodeProtocolAgentServer({
  6030. createZCodeApp: (options) => {
  6031. const app = createFakeApp(options);
  6032. return {
  6033. ...app,
  6034. clearTarget: async () => {
  6035. const hadTarget = target !== null;
  6036. target = null;
  6037. return hadTarget;
  6038. },
  6039. continueActiveTarget,
  6040. readTarget: async () => target,
  6041. runtime: {
  6042. ...app.runtime,
  6043. getProjection: async () =>
  6044. ({
  6045. activeToolCalls: [],
  6046. backgroundTasks: [],
  6047. contextUsed: 0,
  6048. contextWindow: 128_000,
  6049. createdAt: new Date(1),
  6050. id: app.sessionId,
  6051. mode: "build",
  6052. pendingPermissions: [],
  6053. pendingSteerInputs: [],
  6054. status: "idle",
  6055. streamingToolLedger: [],
  6056. target,
  6057. totalTokenCount: 0,
  6058. turnCount: 0,
  6059. updatedAt: new Date(1),
  6060. }) as never,
  6061. } as never,
  6062. setTarget: async (input) => {
  6063. target = {
  6064. objective: input.objective,
  6065. sessionID: app.sessionId,
  6066. status: input.status ?? "active",
  6067. summaryTitle: null,
  6068. targetID: "goal_1" as never,
  6069. time: {
  6070. created: 1,
  6071. updated: 2,
  6072. },
  6073. tokenBudget: input.tokenBudget,
  6074. tokensUsed: 0,
  6075. };
  6076. return target;
  6077. },
  6078. submitPrompt,
  6079. updateTargetStatus: async (status) => {
  6080. if (!target) return null;
  6081. target = { ...target, status, time: { ...target.time, updated: 3 } };
  6082. return target;
  6083. },
  6084. } satisfies ZCodeApp;
  6085. },
  6086. cwd: workspace.workspacePath,
  6087. });
  6088. const created = zcodeSessionStateSnapshotSchema.parse(
  6089. await requestResult(server, {
  6090. id: 1,
  6091. method: zcodeProtocolMethods.sessionCreate,
  6092. params: { workspace },
  6093. }),
  6094. );
  6095. const setResult = zcodeSessionGoalResultSchema.parse(
  6096. await requestResult(server, {
  6097. id: 2,
  6098. method: zcodeProtocolMethods.sessionGoal,
  6099. params: {
  6100. sessionId: created.session.sessionId,
  6101. action: "set",
  6102. objective: "Ship slash command routing",
  6103. inputId: "input_goal_1",
  6104. },
  6105. }),
  6106. );
  6107. const replaceBySetResult = zcodeSessionGoalResultSchema.parse(
  6108. await requestResult(server, {
  6109. id: 3,
  6110. method: zcodeProtocolMethods.sessionGoal,
  6111. params: {
  6112. sessionId: created.session.sessionId,
  6113. action: "set",
  6114. objective: "Replace without explicit keyword",
  6115. inputId: "input_goal_2",
  6116. },
  6117. }),
  6118. );
  6119. const clearResult = zcodeSessionGoalResultSchema.parse(
  6120. await requestResult(server, {
  6121. id: 4,
  6122. method: zcodeProtocolMethods.sessionGoal,
  6123. params: {
  6124. sessionId: created.session.sessionId,
  6125. action: "clear",
  6126. },
  6127. }),
  6128. );
  6129. expect(submitPrompt).not.toHaveBeenCalled();
  6130. expect(continueActiveTarget).toHaveBeenCalledWith(
  6131. expect.objectContaining({ inputId: "input_goal_1" }),
  6132. );
  6133. expect(continueActiveTarget).toHaveBeenCalledWith(
  6134. expect.objectContaining({ inputId: "input_goal_2" }),
  6135. );
  6136. expect(setResult).toMatchObject({
  6137. response: expect.stringContaining("Goal active"),
  6138. startedTurn: true,
  6139. snapshot: {
  6140. projection: {
  6141. target: expect.objectContaining({ objective: "Ship slash command routing" }),
  6142. },
  6143. },
  6144. });
  6145. expect(replaceBySetResult).toMatchObject({
  6146. response: expect.stringContaining("Goal active"),
  6147. startedTurn: true,
  6148. snapshot: {
  6149. projection: {
  6150. target: expect.objectContaining({ objective: "Replace without explicit keyword" }),
  6151. },
  6152. },
  6153. });
  6154. expect(clearResult).toMatchObject({
  6155. response: "Goal cleared.",
  6156. startedTurn: false,
  6157. snapshot: { projection: { target: null } },
  6158. });
  6159. });
  6160. it("rejects session goal commands while a prompt is running", async () => {
  6161. const sendInput = vi.fn(async () => await new Promise<never>(() => {}));
  6162. const setTarget = vi.fn(async () => ({
  6163. objective: "Should wait",
  6164. sessionID: "sess_test" as SessionId,
  6165. status: "active" as const,
  6166. targetID: "goal_running",
  6167. time: { created: 1, updated: 1 },
  6168. }));
  6169. const server = new ZCodeProtocolAgentServer({
  6170. createZCodeApp: (options) => createFakeApp(options, { sendInput, setTarget }),
  6171. });
  6172. const created = zcodeSessionStateSnapshotSchema.parse(
  6173. await requestResult(server, {
  6174. id: 1,
  6175. method: zcodeProtocolMethods.sessionCreate,
  6176. params: { workspace },
  6177. }),
  6178. );
  6179. await requestResult(server, {
  6180. id: 2,
  6181. method: zcodeProtocolMethods.sessionSend,
  6182. params: {
  6183. sessionId: created.session.sessionId,
  6184. content: "keep running",
  6185. inputId: "input_running",
  6186. },
  6187. });
  6188. const response = await server.handleMessage({
  6189. id: 3,
  6190. method: zcodeProtocolMethods.sessionGoal,
  6191. params: {
  6192. sessionId: created.session.sessionId,
  6193. action: "set",
  6194. objective: "Should wait",
  6195. inputId: "input_goal_blocked",
  6196. },
  6197. });
  6198. expect(response).toMatchObject({
  6199. error: {
  6200. code: -32010,
  6201. message: "Cannot manage goals while a prompt is running",
  6202. },
  6203. id: 3,
  6204. });
  6205. expect(setTarget).not.toHaveBeenCalled();
  6206. });
  6207. it("allows session goal pause to stop a running prompt", async () => {
  6208. const abortReasons: string[] = [];
  6209. let target: Awaited<ReturnType<NonNullable<ZCodeApp["readTarget"]>>> = null;
  6210. const sendInput = vi.fn<ZCodeApp["sendInput"]>(
  6211. async (_input, options) =>
  6212. await new Promise<never>((_resolve, reject) => {
  6213. const signal = options.abortSignal;
  6214. const rejectFromAbort = () => {
  6215. const reason = signal.reason;
  6216. abortReasons.push(reason instanceof Error ? reason.message : String(reason));
  6217. reject(reason instanceof Error ? reason : new Error(String(reason)));
  6218. };
  6219. if (signal.aborted) {
  6220. rejectFromAbort();
  6221. return;
  6222. }
  6223. signal.addEventListener("abort", rejectFromAbort, { once: true });
  6224. }),
  6225. );
  6226. const server = new ZCodeProtocolAgentServer({
  6227. createZCodeApp: (options) => {
  6228. const app = createFakeApp(options, { sendInput });
  6229. target = {
  6230. objective: "Pause current goal immediately",
  6231. sessionID: app.sessionId,
  6232. status: "active",
  6233. targetID: "goal_pause_running",
  6234. time: { created: 1, updated: 1 },
  6235. };
  6236. return {
  6237. ...app,
  6238. readTarget: async () => target,
  6239. runtime: {
  6240. ...app.runtime,
  6241. getProjection: async () =>
  6242. ({
  6243. activeToolCalls: [],
  6244. backgroundTasks: [],
  6245. contextUsed: 0,
  6246. contextWindow: 128_000,
  6247. createdAt: new Date(1),
  6248. id: app.sessionId,
  6249. mode: "build",
  6250. pendingPermissions: [],
  6251. pendingSteerInputs: [],
  6252. status: "running",
  6253. streamingToolLedger: [],
  6254. target,
  6255. totalTokenCount: 0,
  6256. turnCount: 1,
  6257. updatedAt: new Date(2),
  6258. }) as never,
  6259. } as never,
  6260. updateTargetStatus: async (status) => {
  6261. if (!target) return null;
  6262. target = { ...target, status, time: { ...target.time, updated: 3 } };
  6263. return target;
  6264. },
  6265. } satisfies ZCodeApp;
  6266. },
  6267. });
  6268. const created = zcodeSessionStateSnapshotSchema.parse(
  6269. await requestResult(server, {
  6270. id: 1,
  6271. method: zcodeProtocolMethods.sessionCreate,
  6272. params: { workspace },
  6273. }),
  6274. );
  6275. await requestResult(server, {
  6276. id: 2,
  6277. method: zcodeProtocolMethods.sessionSend,
  6278. params: {
  6279. sessionId: created.session.sessionId,
  6280. content: "keep running",
  6281. inputId: "input_pause_running",
  6282. },
  6283. });
  6284. const pauseResult = zcodeSessionGoalResultSchema.parse(
  6285. await requestResult(server, {
  6286. id: 3,
  6287. method: zcodeProtocolMethods.sessionGoal,
  6288. params: {
  6289. sessionId: created.session.sessionId,
  6290. action: "pause",
  6291. inputId: "input_goal_pause_running",
  6292. },
  6293. }),
  6294. );
  6295. await vi.waitFor(() => {
  6296. expect(abortReasons).toContain("ZCode Protocol goal paused");
  6297. });
  6298. expect(target?.status).toBe("paused");
  6299. expect(pauseResult).toMatchObject({
  6300. response: "",
  6301. startedTurn: false,
  6302. snapshot: {
  6303. projection: {
  6304. target: expect.objectContaining({ status: "paused" }),
  6305. },
  6306. },
  6307. });
  6308. });
  6309. it("pauses an active goal when session stop cancels goal continuation", async () => {
  6310. const notifications: ZCodeProtocolNotification[] = [];
  6311. const abortReasons: string[] = [];
  6312. let resolveContinuationStarted!: () => void;
  6313. const continuationStarted = new Promise<void>((resolve) => {
  6314. resolveContinuationStarted = resolve;
  6315. });
  6316. let target: Awaited<ReturnType<NonNullable<ZCodeApp["readTarget"]>>> = null;
  6317. const continueActiveTarget = vi.fn<ZCodeApp["continueActiveTarget"]>(
  6318. async (options) =>
  6319. await new Promise<never>((_resolve, reject) => {
  6320. const signal = options?.abortSignal;
  6321. resolveContinuationStarted();
  6322. const rejectFromAbort = () => {
  6323. const reason = signal?.reason;
  6324. abortReasons.push(reason instanceof Error ? reason.message : String(reason));
  6325. reject(reason instanceof Error ? reason : new Error(String(reason)));
  6326. };
  6327. if (signal?.aborted) {
  6328. rejectFromAbort();
  6329. return;
  6330. }
  6331. signal?.addEventListener("abort", rejectFromAbort, { once: true });
  6332. }),
  6333. );
  6334. const server = new ZCodeProtocolAgentServer({
  6335. createZCodeApp: (options) => {
  6336. const app = createFakeApp(options, { continueActiveTarget });
  6337. return {
  6338. ...app,
  6339. readTarget: async () => target,
  6340. runtime: {
  6341. ...app.runtime,
  6342. getProjection: async () =>
  6343. ({
  6344. activeToolCalls: [],
  6345. backgroundTasks: [],
  6346. contextUsed: 0,
  6347. contextWindow: 128_000,
  6348. createdAt: new Date(1),
  6349. id: app.sessionId,
  6350. mode: "build",
  6351. pendingPermissions: [],
  6352. pendingSteerInputs: [],
  6353. status: continueActiveTarget.mock.calls.length > 0 ? "running" : "idle",
  6354. streamingToolLedger: [],
  6355. target,
  6356. totalTokenCount: 0,
  6357. turnCount: continueActiveTarget.mock.calls.length,
  6358. updatedAt: new Date(2),
  6359. }) as never,
  6360. } as never,
  6361. setTarget: async (input) => {
  6362. target = {
  6363. objective: input.objective,
  6364. sessionID: app.sessionId,
  6365. status: input.status ?? "active",
  6366. summaryTitle: null,
  6367. targetID: "goal_stop_running",
  6368. time: { created: 1, updated: 2 },
  6369. timeUsedSeconds: 0,
  6370. tokenBudget: input.tokenBudget ?? null,
  6371. tokensUsed: 0,
  6372. };
  6373. return target;
  6374. },
  6375. updateTargetStatus: async (status) => {
  6376. if (!target) return null;
  6377. target = { ...target, status, time: { ...target.time, updated: 3 } };
  6378. return target;
  6379. },
  6380. } satisfies ZCodeApp;
  6381. },
  6382. cwd: workspace.workspacePath,
  6383. });
  6384. setTestNotificationSink(server, (notification) => notifications.push(notification));
  6385. const created = zcodeSessionStateSnapshotSchema.parse(
  6386. await requestResult(server, {
  6387. id: 1,
  6388. method: zcodeProtocolMethods.sessionCreate,
  6389. params: { workspace },
  6390. }),
  6391. );
  6392. const goalResult = zcodeSessionGoalResultSchema.parse(
  6393. await requestResult(server, {
  6394. id: 2,
  6395. method: zcodeProtocolMethods.sessionGoal,
  6396. params: {
  6397. sessionId: created.session.sessionId,
  6398. action: "set",
  6399. objective: "Stop should pause this goal",
  6400. inputId: "input_goal_stop_running",
  6401. },
  6402. }),
  6403. );
  6404. await continuationStarted;
  6405. const notificationCountBeforeStop = notifications.length;
  6406. await requestResult(server, {
  6407. id: 3,
  6408. method: zcodeProtocolMethods.sessionStop,
  6409. params: { sessionId: created.session.sessionId },
  6410. });
  6411. await vi.waitFor(() => {
  6412. expect(abortReasons).toContain("ZCode Protocol session stopped");
  6413. });
  6414. expect(goalResult.startedTurn).toBe(true);
  6415. expect(target?.status).toBe("paused");
  6416. expect(
  6417. notifications
  6418. .slice(notificationCountBeforeStop)
  6419. .some((item) => item.method === "state.updated"),
  6420. ).toBe(true);
  6421. });
  6422. it("includes persisted goal and todos in protocol snapshots", async () => {
  6423. const server = new ZCodeProtocolAgentServer({
  6424. createZCodeApp: (options) => {
  6425. const app = createFakeApp(options);
  6426. const persistedTarget = {
  6427. objective: "Restore parser goal",
  6428. sessionID: app.sessionId,
  6429. status: "paused" as const,
  6430. summaryTitle: "Restore parser goal",
  6431. targetID: "goal_db",
  6432. time: { created: 10, updated: 20 },
  6433. timeUsedSeconds: 7,
  6434. tokenBudget: null,
  6435. tokensUsed: 123,
  6436. };
  6437. return {
  6438. ...app,
  6439. readTarget: async () => persistedTarget,
  6440. readTodos: async () => [
  6441. { content: "Implement lexer", priority: "high", status: "completed" },
  6442. { content: "Implement parser", priority: "high", status: "in_progress" },
  6443. ],
  6444. };
  6445. },
  6446. cwd: workspace.workspacePath,
  6447. });
  6448. const created = zcodeSessionStateSnapshotSchema.parse(
  6449. await requestResult(server, {
  6450. id: 1,
  6451. method: zcodeProtocolMethods.sessionCreate,
  6452. params: { workspace },
  6453. }),
  6454. );
  6455. expect(created.projection.target).toMatchObject({
  6456. objective: "Restore parser goal",
  6457. status: "paused",
  6458. summaryTitle: "Restore parser goal",
  6459. targetId: "goal_db",
  6460. });
  6461. expect(created.session.target).toMatchObject({
  6462. objective: "Restore parser goal",
  6463. summaryTitle: "Restore parser goal",
  6464. targetId: "goal_db",
  6465. });
  6466. expect(created.todos).toEqual([
  6467. { content: "Implement lexer", priority: "high", status: "completed" },
  6468. { content: "Implement parser", priority: "high", status: "in_progress" },
  6469. ]);
  6470. });
  6471. it("derives goal stats and todo groups from persisted verifier boundaries", async () => {
  6472. const app = createFakeApp();
  6473. const target = {
  6474. objective: "Ship grouped todo restore",
  6475. sessionID: app.sessionId,
  6476. status: "active" as const,
  6477. summaryTitle: null,
  6478. targetID: "goal_1" as never,
  6479. time: { created: 1_000, updated: 9_400 },
  6480. timeUsedSeconds: 0,
  6481. tokenBudget: 120_000,
  6482. tokensUsed: 0,
  6483. };
  6484. const messages = [
  6485. {
  6486. info: {
  6487. id: "msg_goal_1" as MessageId,
  6488. sessionID: app.sessionId,
  6489. role: "user",
  6490. time: { created: 1_000 },
  6491. agent: "zcode-agent",
  6492. modelSelection: {
  6493. providerId: "glm" as ModelProviderId,
  6494. modelId: "glm-4.6" as ModelId,
  6495. },
  6496. source: "goal-continuation",
  6497. synthetic: true,
  6498. visibility: "model-only",
  6499. metadata: { source: "goal-continuation", targetId: "goal_1" },
  6500. },
  6501. parts: [
  6502. {
  6503. id: "part_goal_1" as never,
  6504. sessionID: app.sessionId,
  6505. messageID: "msg_goal_1" as MessageId,
  6506. type: "text",
  6507. text: "continue the active goal",
  6508. },
  6509. ],
  6510. },
  6511. {
  6512. info: {
  6513. id: "msg_assistant_1" as MessageId,
  6514. sessionID: app.sessionId,
  6515. role: "assistant",
  6516. parentID: "msg_goal_1" as MessageId,
  6517. time: { created: 2_000, completed: 4_500 },
  6518. agent: "zcode-agent",
  6519. providerId: "glm" as ModelProviderId,
  6520. modelId: "glm-4.6" as ModelId,
  6521. mode: "build",
  6522. path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
  6523. cost: 0,
  6524. tokens: {
  6525. input: 100,
  6526. output: 10,
  6527. reasoning: 1,
  6528. total: 111,
  6529. cache: { read: 0, write: 0 },
  6530. },
  6531. },
  6532. parts: [
  6533. {
  6534. id: "part_todo_1" as never,
  6535. sessionID: app.sessionId,
  6536. messageID: "msg_assistant_1" as MessageId,
  6537. type: "tool",
  6538. callID: "tool_todo_1",
  6539. tool: "TodoWrite",
  6540. state: {
  6541. status: "completed",
  6542. input: {
  6543. todos: [
  6544. { content: "Read existing restore flow", priority: "high", status: "completed" },
  6545. { content: "Project grouped todos", priority: "high", status: "in_progress" },
  6546. ],
  6547. },
  6548. output: "ok",
  6549. title: "TodoWrite",
  6550. metadata: {},
  6551. time: { start: 2_100, end: 4_200 },
  6552. },
  6553. },
  6554. ],
  6555. },
  6556. {
  6557. info: {
  6558. id: "msg_goal_2" as MessageId,
  6559. sessionID: app.sessionId,
  6560. role: "user",
  6561. time: { created: 5_000 },
  6562. agent: "zcode-agent",
  6563. modelSelection: {
  6564. providerId: "glm" as ModelProviderId,
  6565. modelId: "glm-4.6" as ModelId,
  6566. },
  6567. metadata: { source: "goal-continuation", targetId: "goal_1" },
  6568. },
  6569. parts: [
  6570. {
  6571. id: "part_goal_2" as never,
  6572. sessionID: app.sessionId,
  6573. messageID: "msg_goal_2" as MessageId,
  6574. type: "text",
  6575. text: "continue again",
  6576. },
  6577. ],
  6578. },
  6579. {
  6580. info: {
  6581. id: "msg_assistant_2" as MessageId,
  6582. sessionID: app.sessionId,
  6583. role: "assistant",
  6584. parentID: "msg_goal_2" as MessageId,
  6585. time: { created: 5_500, completed: 8_000 },
  6586. agent: "zcode-agent",
  6587. providerId: "glm" as ModelProviderId,
  6588. modelId: "glm-4.6" as ModelId,
  6589. mode: "build",
  6590. path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
  6591. cost: 0,
  6592. tokens: {
  6593. input: 200,
  6594. output: 20,
  6595. reasoning: 2,
  6596. total: 222,
  6597. cache: { read: 0, write: 0 },
  6598. },
  6599. },
  6600. parts: [
  6601. {
  6602. id: "part_bash_2" as never,
  6603. sessionID: app.sessionId,
  6604. messageID: "msg_assistant_2" as MessageId,
  6605. type: "tool",
  6606. callID: "tool_bash_2",
  6607. tool: "Bash",
  6608. state: {
  6609. status: "completed",
  6610. input: { command: "pnpm typecheck" },
  6611. output: "passed",
  6612. title: "Bash",
  6613. metadata: {},
  6614. time: { start: 5_600, end: 6_000 },
  6615. },
  6616. },
  6617. {
  6618. id: "part_todo_2" as never,
  6619. sessionID: app.sessionId,
  6620. messageID: "msg_assistant_2" as MessageId,
  6621. type: "tool",
  6622. callID: "tool_todo_2",
  6623. tool: "todo_write",
  6624. state: {
  6625. status: "completed",
  6626. input: {
  6627. todos: [
  6628. { content: "Project grouped todos", priority: "high", status: "completed" },
  6629. { content: "Verify restored summary", priority: "medium", status: "in_progress" },
  6630. ],
  6631. },
  6632. output: "ok",
  6633. title: "TodoWrite",
  6634. metadata: {},
  6635. time: { start: 6_100, end: 7_800 },
  6636. },
  6637. },
  6638. ],
  6639. },
  6640. {
  6641. info: {
  6642. id: "msg_assistant_3" as MessageId,
  6643. sessionID: app.sessionId,
  6644. role: "assistant",
  6645. parentID: "msg_assistant_2" as MessageId,
  6646. time: { created: 8_200, completed: 9_400 },
  6647. agent: "zcode-agent",
  6648. providerId: "glm" as ModelProviderId,
  6649. modelId: "glm-4.6" as ModelId,
  6650. mode: "build",
  6651. path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
  6652. cost: 0,
  6653. tokens: {
  6654. input: 20,
  6655. output: 8,
  6656. reasoning: 2,
  6657. total: 30,
  6658. cache: { read: 0, write: 0 },
  6659. },
  6660. },
  6661. parts: [
  6662. {
  6663. id: "part_todo_3" as never,
  6664. sessionID: app.sessionId,
  6665. messageID: "msg_assistant_3" as MessageId,
  6666. type: "tool",
  6667. callID: "tool_todo_3",
  6668. tool: "TodoWrite",
  6669. state: {
  6670. status: "completed",
  6671. input: {
  6672. todos: [
  6673. { content: "Project grouped todos", priority: "high", status: "completed" },
  6674. { content: "Verify restored summary", priority: "medium", status: "completed" },
  6675. ],
  6676. },
  6677. output: "ok",
  6678. title: "TodoWrite",
  6679. metadata: {},
  6680. time: { start: 8_300, end: 9_300 },
  6681. },
  6682. },
  6683. ],
  6684. },
  6685. ] as unknown as MessageWithParts[];
  6686. const snapshot = zcodeSessionStateSnapshotSchema.parse(
  6687. await buildSessionSnapshot({
  6688. app,
  6689. eventSeq: 1,
  6690. messages,
  6691. persistedGoalVerificationEvents: [
  6692. {
  6693. id: "evt_verify_1" as SessionEvent["id"],
  6694. payload: {
  6695. goalIteration: 1,
  6696. status: "completed",
  6697. targetId: "goal_1",
  6698. verification: {
  6699. nextAction: "Verify restored summary",
  6700. passed: false,
  6701. reason: "The restored summary is not verified yet.",
  6702. },
  6703. verificationId: "verify_1",
  6704. },
  6705. sequenceNumber: 10,
  6706. sessionId: app.sessionId,
  6707. timestamp: new Date(4_800),
  6708. traceId: "trace_verify_1" as SessionEvent["traceId"],
  6709. type: SessionEventType.TargetCompletionVerification,
  6710. },
  6711. ],
  6712. stateRevision: 1,
  6713. target,
  6714. todos: [],
  6715. workspace,
  6716. }),
  6717. );
  6718. expect(snapshot.goalStats).toEqual({
  6719. contextUsed: 0,
  6720. contextWindow: 128_000,
  6721. iterationCount: 2,
  6722. timeUsedSeconds: 8,
  6723. tokenBudget: 120_000,
  6724. tokensUsed: 363,
  6725. toolCallCount: 4,
  6726. });
  6727. expect(snapshot.runtime.goalVerificationTimeline).toEqual([
  6728. {
  6729. display: "separator",
  6730. goalIteration: 1,
  6731. kind: "synthetic",
  6732. status: "completed",
  6733. targetId: "goal_1",
  6734. type: "goal_verification",
  6735. updatedAt: 4_800,
  6736. verification: {
  6737. nextAction: "Verify restored summary",
  6738. passed: false,
  6739. reason: "The restored summary is not verified yet.",
  6740. },
  6741. verificationId: "verify_1",
  6742. version: 1,
  6743. },
  6744. ]);
  6745. expect(snapshot.todoGroups).toEqual([
  6746. {
  6747. id: "goal-iteration-1",
  6748. source: "goal_iteration",
  6749. goalIteration: 1,
  6750. targetId: "goal_1",
  6751. startedAt: 1_000,
  6752. updatedAt: 9_300,
  6753. todos: [
  6754. { content: "Read existing restore flow", priority: "high", status: "completed" },
  6755. { content: "Project grouped todos", priority: "high", status: "completed" },
  6756. ],
  6757. },
  6758. {
  6759. id: "goal-iteration-2",
  6760. source: "goal_iteration",
  6761. goalIteration: 2,
  6762. targetId: "goal_1",
  6763. startedAt: 4_800,
  6764. updatedAt: 9_300,
  6765. todos: [{ content: "Verify restored summary", priority: "medium", status: "completed" }],
  6766. },
  6767. ]);
  6768. });
  6769. it("does not advance goal stats after paused verifier cancellation", async () => {
  6770. const app = createFakeApp();
  6771. const target = {
  6772. objective: "Stop goal verification",
  6773. sessionID: app.sessionId,
  6774. status: "paused" as const,
  6775. summaryTitle: null,
  6776. targetID: "goal_paused_cancelled" as never,
  6777. time: { created: 1_000, updated: 4_000 },
  6778. timeUsedSeconds: 2,
  6779. tokenBudget: null,
  6780. tokensUsed: 10,
  6781. };
  6782. const snapshot = zcodeSessionStateSnapshotSchema.parse(
  6783. await buildSessionSnapshot({
  6784. app,
  6785. eventSeq: 1,
  6786. messages: [],
  6787. persistedGoalVerificationEvents: [
  6788. {
  6789. id: "evt_verify_cancelled" as SessionEvent["id"],
  6790. payload: {
  6791. goalIteration: 1,
  6792. status: "cancelled",
  6793. targetId: "goal_paused_cancelled",
  6794. verificationId: "verify_cancelled",
  6795. },
  6796. sequenceNumber: 10,
  6797. sessionId: app.sessionId,
  6798. timestamp: new Date(3_500),
  6799. traceId: "trace_verify_cancelled" as SessionEvent["traceId"],
  6800. type: SessionEventType.TargetCompletionVerification,
  6801. },
  6802. ],
  6803. stateRevision: 1,
  6804. target,
  6805. todos: [],
  6806. workspace,
  6807. }),
  6808. );
  6809. expect(snapshot.goalStats).toMatchObject({
  6810. iterationCount: 1,
  6811. timeUsedSeconds: 2,
  6812. tokensUsed: 10,
  6813. });
  6814. expect(snapshot.runtime.goalVerificationTimeline).toEqual([
  6815. expect.objectContaining({
  6816. goalIteration: 1,
  6817. status: "cancelled",
  6818. targetId: "goal_paused_cancelled",
  6819. }),
  6820. ]);
  6821. });
  6822. it("keeps visible user continuation todo updates in the current verifier iteration", async () => {
  6823. const app = createFakeApp();
  6824. const target = {
  6825. objective: "Ship dynamic grouped todos",
  6826. sessionID: app.sessionId,
  6827. status: "active" as const,
  6828. summaryTitle: null,
  6829. targetID: "goal_visible_continue" as never,
  6830. time: { created: 1_000, updated: 7_000 },
  6831. timeUsedSeconds: 0,
  6832. tokenBudget: null,
  6833. tokensUsed: 0,
  6834. };
  6835. const messages = [
  6836. {
  6837. info: {
  6838. id: "msg_goal_1" as MessageId,
  6839. sessionID: app.sessionId,
  6840. role: "user",
  6841. time: { created: 1_000 },
  6842. agent: "zcode-agent",
  6843. modelSelection: {
  6844. providerId: "glm" as ModelProviderId,
  6845. modelId: "glm-4.6" as ModelId,
  6846. },
  6847. source: "goal-continuation",
  6848. synthetic: true,
  6849. visibility: "model-only",
  6850. metadata: { source: "goal-continuation", targetId: "goal_visible_continue" },
  6851. },
  6852. parts: [
  6853. {
  6854. id: "part_goal_1" as never,
  6855. sessionID: app.sessionId,
  6856. messageID: "msg_goal_1" as MessageId,
  6857. type: "text",
  6858. text: "continue the active goal",
  6859. },
  6860. ],
  6861. },
  6862. {
  6863. info: {
  6864. id: "msg_assistant_1" as MessageId,
  6865. sessionID: app.sessionId,
  6866. role: "assistant",
  6867. parentID: "msg_goal_1" as MessageId,
  6868. time: { created: 2_000, completed: 3_000 },
  6869. agent: "zcode-agent",
  6870. providerId: "glm" as ModelProviderId,
  6871. modelId: "glm-4.6" as ModelId,
  6872. mode: "build",
  6873. path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
  6874. cost: 0,
  6875. tokens: {
  6876. input: 10,
  6877. output: 5,
  6878. reasoning: 0,
  6879. total: 15,
  6880. cache: { read: 0, write: 0 },
  6881. },
  6882. },
  6883. parts: [
  6884. {
  6885. id: "part_todo_1" as never,
  6886. sessionID: app.sessionId,
  6887. messageID: "msg_assistant_1" as MessageId,
  6888. type: "tool",
  6889. callID: "tool_todo_1",
  6890. tool: "TodoWrite",
  6891. state: {
  6892. status: "completed",
  6893. input: {
  6894. todos: [
  6895. { content: "Wire UI components in App", priority: "high", status: "in_progress" },
  6896. { content: "Wire undo/history system", priority: "medium", status: "pending" },
  6897. ],
  6898. },
  6899. output: "ok",
  6900. title: "TodoWrite",
  6901. metadata: {},
  6902. time: { start: 2_100, end: 2_900 },
  6903. },
  6904. },
  6905. ],
  6906. },
  6907. {
  6908. info: {
  6909. id: "msg_visible_continue" as MessageId,
  6910. sessionID: app.sessionId,
  6911. role: "user",
  6912. time: { created: 4_000 },
  6913. agent: "zcode-agent",
  6914. modelSelection: {
  6915. providerId: "glm" as ModelProviderId,
  6916. modelId: "glm-4.6" as ModelId,
  6917. },
  6918. },
  6919. parts: [
  6920. {
  6921. id: "part_visible_continue" as never,
  6922. sessionID: app.sessionId,
  6923. messageID: "msg_visible_continue" as MessageId,
  6924. type: "text",
  6925. text: "继续",
  6926. },
  6927. ],
  6928. },
  6929. {
  6930. info: {
  6931. id: "msg_assistant_2" as MessageId,
  6932. sessionID: app.sessionId,
  6933. role: "assistant",
  6934. parentID: "msg_visible_continue" as MessageId,
  6935. time: { created: 4_500, completed: 5_500 },
  6936. agent: "zcode-agent",
  6937. providerId: "glm" as ModelProviderId,
  6938. modelId: "glm-4.6" as ModelId,
  6939. mode: "build",
  6940. path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
  6941. cost: 0,
  6942. tokens: {
  6943. input: 20,
  6944. output: 5,
  6945. reasoning: 0,
  6946. total: 25,
  6947. cache: { read: 0, write: 0 },
  6948. },
  6949. },
  6950. parts: [
  6951. {
  6952. id: "part_todo_2" as never,
  6953. sessionID: app.sessionId,
  6954. messageID: "msg_assistant_2" as MessageId,
  6955. type: "tool",
  6956. callID: "tool_todo_2",
  6957. tool: "todo_write",
  6958. state: {
  6959. status: "completed",
  6960. input: {
  6961. todos: [
  6962. { content: "Wire UI components in App", priority: "high", status: "completed" },
  6963. {
  6964. content: "Complete remaining blend modes in WebGL shaders and Rust engine",
  6965. priority: "high",
  6966. status: "in_progress",
  6967. },
  6968. {
  6969. content: "Wire PSD import through worker into App",
  6970. priority: "medium",
  6971. status: "pending",
  6972. },
  6973. ],
  6974. },
  6975. output: "ok",
  6976. title: "TodoWrite",
  6977. metadata: {},
  6978. time: { start: 4_600, end: 5_300 },
  6979. },
  6980. },
  6981. ],
  6982. },
  6983. {
  6984. info: {
  6985. id: "msg_assistant_3" as MessageId,
  6986. sessionID: app.sessionId,
  6987. role: "assistant",
  6988. parentID: "msg_assistant_2" as MessageId,
  6989. time: { created: 5_800, completed: 7_000 },
  6990. agent: "zcode-agent",
  6991. providerId: "glm" as ModelProviderId,
  6992. modelId: "glm-4.6" as ModelId,
  6993. mode: "build",
  6994. path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
  6995. cost: 0,
  6996. tokens: {
  6997. input: 30,
  6998. output: 5,
  6999. reasoning: 0,
  7000. total: 35,
  7001. cache: { read: 0, write: 0 },
  7002. },
  7003. },
  7004. parts: [
  7005. {
  7006. id: "part_todo_3" as never,
  7007. sessionID: app.sessionId,
  7008. messageID: "msg_assistant_3" as MessageId,
  7009. type: "tool",
  7010. callID: "tool_todo_3",
  7011. tool: "TodoWrite",
  7012. state: {
  7013. status: "completed",
  7014. input: {
  7015. todos: [
  7016. { content: "Wire UI components in App", priority: "high", status: "completed" },
  7017. {
  7018. content: "Complete remaining blend modes in WebGL shaders and Rust engine",
  7019. priority: "high",
  7020. status: "completed",
  7021. },
  7022. {
  7023. content: "Wire PSD import through worker into App",
  7024. priority: "medium",
  7025. status: "in_progress",
  7026. },
  7027. ],
  7028. },
  7029. output: "ok",
  7030. title: "TodoWrite",
  7031. metadata: {},
  7032. time: { start: 5_900, end: 6_900 },
  7033. },
  7034. },
  7035. ],
  7036. },
  7037. ] as unknown as MessageWithParts[];
  7038. const snapshot = zcodeSessionStateSnapshotSchema.parse(
  7039. await buildSessionSnapshot({
  7040. app,
  7041. eventSeq: 1,
  7042. messages,
  7043. stateRevision: 1,
  7044. target,
  7045. todos: [],
  7046. workspace,
  7047. }),
  7048. );
  7049. expect(snapshot.goalStats).toMatchObject({
  7050. iterationCount: 1,
  7051. toolCallCount: 3,
  7052. tokensUsed: 75,
  7053. });
  7054. expect(snapshot.todoGroups).toEqual([
  7055. {
  7056. id: "goal-iteration-1",
  7057. source: "goal_iteration",
  7058. goalIteration: 1,
  7059. targetId: "goal_visible_continue",
  7060. startedAt: 1_000,
  7061. updatedAt: 6_900,
  7062. todos: [
  7063. { content: "Wire UI components in App", priority: "high", status: "completed" },
  7064. { content: "Wire undo/history system", priority: "medium", status: "pending" },
  7065. {
  7066. content: "Complete remaining blend modes in WebGL shaders and Rust engine",
  7067. priority: "high",
  7068. status: "completed",
  7069. },
  7070. {
  7071. content: "Wire PSD import through worker into App",
  7072. priority: "medium",
  7073. status: "in_progress",
  7074. },
  7075. ],
  7076. },
  7077. ]);
  7078. });
  7079. it("keeps standalone non-goal todos grouped as session current todos", async () => {
  7080. const app = createFakeApp();
  7081. const snapshot = zcodeSessionStateSnapshotSchema.parse(
  7082. await buildSessionSnapshot({
  7083. app,
  7084. eventSeq: 1,
  7085. messages: [],
  7086. stateRevision: 1,
  7087. target: null,
  7088. todos: [
  7089. { content: "Read logs", priority: "high", status: "completed" },
  7090. { content: "Reproduce locally", priority: "high", status: "in_progress" },
  7091. { content: "Write fix", priority: "medium", status: "pending" },
  7092. ],
  7093. workspace,
  7094. }),
  7095. );
  7096. expect(snapshot.goalStats).toBeUndefined();
  7097. expect(snapshot.todoGroups).toEqual([
  7098. {
  7099. id: "session-current",
  7100. source: "session",
  7101. todos: [
  7102. { content: "Read logs", priority: "high", status: "completed" },
  7103. { content: "Reproduce locally", priority: "high", status: "in_progress" },
  7104. { content: "Write fix", priority: "medium", status: "pending" },
  7105. ],
  7106. },
  7107. ]);
  7108. });
  7109. it("ignores subagent TodoWrite parts when building main session todo groups", async () => {
  7110. const app = createFakeApp();
  7111. const messages = [
  7112. {
  7113. info: {
  7114. id: "msg_main_todo" as MessageId,
  7115. sessionID: app.sessionId,
  7116. role: "assistant",
  7117. time: { created: 1_000, completed: 1_200 },
  7118. agent: "zcode-agent",
  7119. providerId: "glm" as ModelProviderId,
  7120. modelId: "glm-4.6" as ModelId,
  7121. mode: "build",
  7122. path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
  7123. cost: 0,
  7124. tokens: { input: 1, output: 1, reasoning: 0, total: 2, cache: { read: 0, write: 0 } },
  7125. },
  7126. parts: [
  7127. {
  7128. id: "part_main_todo" as never,
  7129. sessionID: app.sessionId,
  7130. messageID: "msg_main_todo" as MessageId,
  7131. type: "tool",
  7132. callID: "call_main_todo",
  7133. tool: "TodoWrite",
  7134. state: {
  7135. status: "completed",
  7136. input: {
  7137. todos: [
  7138. { content: "Main inspect logs", priority: "high", status: "completed" },
  7139. { content: "Main patch projection", priority: "high", status: "in_progress" },
  7140. ],
  7141. },
  7142. output: "ok",
  7143. title: "TodoWrite",
  7144. metadata: {},
  7145. time: { start: 1_050, end: 1_100 },
  7146. },
  7147. },
  7148. ],
  7149. },
  7150. {
  7151. info: {
  7152. id: "msg_subagent_todo" as MessageId,
  7153. sessionID: app.sessionId,
  7154. role: "assistant",
  7155. time: { created: 2_000, completed: 2_200 },
  7156. agent: "zcode-agent",
  7157. providerId: "glm" as ModelProviderId,
  7158. modelId: "glm-4.6" as ModelId,
  7159. mode: "build",
  7160. path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
  7161. cost: 0,
  7162. tokens: { input: 1, output: 1, reasoning: 0, total: 2, cache: { read: 0, write: 0 } },
  7163. },
  7164. parts: [
  7165. {
  7166. id: "part_subagent_todo" as never,
  7167. sessionID: app.sessionId,
  7168. messageID: "msg_subagent_todo" as MessageId,
  7169. type: "tool",
  7170. callID: "tool_subagent_agent_1_call_todo",
  7171. tool: "TodoWrite",
  7172. metadata: { source: "subagent" },
  7173. state: {
  7174. status: "completed",
  7175. input: {
  7176. todos: [
  7177. { content: "Subagent search market", priority: "high", status: "completed" },
  7178. {
  7179. content: "Subagent summarize sources",
  7180. priority: "medium",
  7181. status: "completed",
  7182. },
  7183. ],
  7184. },
  7185. output: "ok",
  7186. title: "TodoWrite",
  7187. metadata: { source: "subagent", parentToolCallId: "call_agent" },
  7188. time: { start: 2_050, end: 2_100 },
  7189. },
  7190. },
  7191. ],
  7192. },
  7193. ] as unknown as MessageWithParts[];
  7194. const snapshot = zcodeSessionStateSnapshotSchema.parse(
  7195. await buildSessionSnapshot({
  7196. app,
  7197. eventSeq: 1,
  7198. messages,
  7199. stateRevision: 1,
  7200. target: null,
  7201. todos: [],
  7202. workspace,
  7203. }),
  7204. );
  7205. expect(snapshot.todoGroups).toEqual([
  7206. {
  7207. id: "session",
  7208. source: "session",
  7209. startedAt: 1_000,
  7210. updatedAt: 1_100,
  7211. todos: [
  7212. { content: "Main inspect logs", priority: "high", status: "completed" },
  7213. { content: "Main patch projection", priority: "high", status: "in_progress" },
  7214. ],
  7215. },
  7216. ]);
  7217. });
  7218. it("forks sessions and lets selection children inherit parent runtime preferences", async () => {
  7219. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  7220. const forkTargets: Array<{ targetCheckpointId?: string; targetMessageId?: string }> = [];
  7221. const createdAppOptions: ZCodeAppOptions[] = [];
  7222. const selectionChildId = "sess_selection_runtime_preferences" as SessionId;
  7223. try {
  7224. const server = new ZCodeProtocolAgentServer({
  7225. createZCodeApp: (options) => {
  7226. createdAppOptions.push(options);
  7227. const app = createFakeApp(options);
  7228. return {
  7229. ...app,
  7230. clearTarget: async () => await store.clearTarget({ sessionID: app.sessionId }),
  7231. forkFromCheckpoint: async (target) => {
  7232. forkTargets.push({
  7233. targetCheckpointId: target?.targetCheckpointId,
  7234. targetMessageId: target?.targetMessageId,
  7235. });
  7236. const forkedSessionId = "sess_forked" as SessionId;
  7237. if (!(await store.getSession(forkedSessionId))) {
  7238. await store.createSession({
  7239. id: forkedSessionId,
  7240. parentID: options?.sessionId,
  7241. projectID: "project_fork_runtime_settings" as ProjectId,
  7242. slug: "fork-runtime-settings",
  7243. directory: workspace.workspacePath,
  7244. path: workspace.workspacePath,
  7245. title: "Fork runtime settings",
  7246. version: "test-version",
  7247. time: { created: 10, updated: 10 },
  7248. });
  7249. }
  7250. return {
  7251. checkpoint: {} as never,
  7252. copiedMessageCount: 2,
  7253. forkedSessionId,
  7254. parentSessionId: (options?.sessionId ?? "sess_parent") as never,
  7255. targetMessageId: "msg_assistant_1" as never,
  7256. targetCheckpointId: "checkpoint_1",
  7257. restoredFiles: [],
  7258. response: "forked",
  7259. };
  7260. },
  7261. readTarget: async () => await store.readTarget({ sessionID: app.sessionId }),
  7262. runtime: {
  7263. ...app.runtime,
  7264. createSelectionSideConversation: async () => {
  7265. if (!(await store.getSession(selectionChildId))) {
  7266. await store.createSession({
  7267. id: selectionChildId,
  7268. parentID: app.sessionId,
  7269. projectID: "project_selection_runtime_preferences" as ProjectId,
  7270. slug: "selection-runtime-preferences",
  7271. directory: workspace.workspacePath,
  7272. path: workspace.workspacePath,
  7273. taskType: "selection_side_chat",
  7274. title: "Selection runtime preferences",
  7275. version: "test-version",
  7276. time: { created: 20, updated: 20 },
  7277. });
  7278. }
  7279. return {
  7280. forkedSessionId: selectionChildId,
  7281. parentSessionId: app.sessionId,
  7282. response: "selection child",
  7283. targetMessageId: "msg_assistant_1" as MessageId,
  7284. } as never;
  7285. },
  7286. } as never,
  7287. setTarget: async (input) =>
  7288. await store.setTarget({
  7289. objective: input.objective,
  7290. sessionID: app.sessionId,
  7291. status: input.status ?? "active",
  7292. tokenBudget: input.tokenBudget,
  7293. }),
  7294. updateTargetStatus: async (status) =>
  7295. await store.updateTargetStatus({ sessionID: app.sessionId, status }),
  7296. } satisfies ZCodeApp;
  7297. },
  7298. cwd: workspace.workspacePath,
  7299. sessionStore: store,
  7300. });
  7301. let toolSearchMode: "local" | "off" = "local";
  7302. let totalTokensReminderEnabled = true;
  7303. let agentAlwaysBackgroundEnabled = false;
  7304. const preferenceRequests = attachSessionRuntimePreferencesResponder(server, () => ({
  7305. nativeSearchEnhancementsEnabled: false,
  7306. toolSearchMode,
  7307. totalTokensReminderEnabled,
  7308. agentAlwaysBackgroundEnabled,
  7309. memoryEnabled: false,
  7310. subagentRuntimeConfigEnabled: true,
  7311. modelContextBudgetStrategy: "preflight-v1",
  7312. }));
  7313. const created = zcodeSessionStateSnapshotSchema.parse(
  7314. await requestResult(server, {
  7315. id: 1,
  7316. method: zcodeProtocolMethods.sessionCreate,
  7317. params: { workspace },
  7318. }),
  7319. );
  7320. if (!(await store.getSession(created.session.sessionId as SessionId))) {
  7321. await store.createSession({
  7322. id: created.session.sessionId as SessionId,
  7323. projectID: "project_fork_runtime_settings" as ProjectId,
  7324. slug: "fork-runtime-settings-parent",
  7325. directory: workspace.workspacePath,
  7326. path: workspace.workspacePath,
  7327. title: "Fork runtime settings parent",
  7328. version: "test-version",
  7329. time: { created: 1, updated: 1 },
  7330. });
  7331. }
  7332. await requestResult(server, {
  7333. id: 2,
  7334. method: zcodeProtocolMethods.sessionSetModel,
  7335. params: {
  7336. sessionId: created.session.sessionId,
  7337. model: { providerId: "glm", modelId: "glm-4-air" },
  7338. },
  7339. });
  7340. await requestResult(server, {
  7341. id: 3,
  7342. method: zcodeProtocolMethods.sessionSetMode,
  7343. params: {
  7344. sessionId: created.session.sessionId,
  7345. mode: "plan",
  7346. },
  7347. });
  7348. await requestResult(server, {
  7349. id: 4,
  7350. method: zcodeProtocolMethods.sessionSetThoughtLevel,
  7351. params: {
  7352. sessionId: created.session.sessionId,
  7353. thoughtLevel: "deep",
  7354. },
  7355. });
  7356. const goal = zcodeSessionGoalResultSchema.parse(
  7357. await requestResult(server, {
  7358. id: 5,
  7359. method: zcodeProtocolMethods.sessionGoal,
  7360. params: {
  7361. sessionId: created.session.sessionId,
  7362. action: "set",
  7363. objective: "Fork inherits parent goal target",
  7364. },
  7365. }),
  7366. );
  7367. expect(goal.snapshot.session.target).toMatchObject({
  7368. objective: "Fork inherits parent goal target",
  7369. sessionId: created.session.sessionId,
  7370. status: "active",
  7371. });
  7372. toolSearchMode = "off";
  7373. totalTokensReminderEnabled = false;
  7374. agentAlwaysBackgroundEnabled = true;
  7375. const result = zcodeSessionForkResultSchema.parse(
  7376. await requestResult(server, {
  7377. id: 6,
  7378. method: zcodeProtocolMethods.sessionFork,
  7379. params: {
  7380. sessionId: created.session.sessionId,
  7381. target: { kind: "message", messageId: "msg_assistant_1" },
  7382. },
  7383. }),
  7384. );
  7385. expect(forkTargets).toEqual([
  7386. expect.objectContaining({ targetMessageId: "msg_assistant_1" }),
  7387. ]);
  7388. expect(result).toMatchObject({
  7389. forkedSessionId: "sess_forked",
  7390. targetMessageId: "msg_assistant_1",
  7391. targetCheckpointId: "checkpoint_1",
  7392. });
  7393. expect(result.snapshot.session.sessionId).toBe("sess_forked");
  7394. expect(result.snapshot.settings).toMatchObject({
  7395. mode: { current: "plan" },
  7396. model: { current: { providerId: "glm", modelId: "glm-4-air" } },
  7397. thoughtLevel: { current: "deep" },
  7398. });
  7399. expect(createdAppOptions).toHaveLength(2);
  7400. expect(createdAppOptions[1]?.readSubagentRuntimeConfig).toBeTypeOf("function");
  7401. expect(preferenceRequests).toHaveLength(1);
  7402. expect(createdAppOptions[1]?.runtimeConfig?.toolSearch).toEqual({ mode: "local" });
  7403. expect(createdAppOptions[1]?.runtimeConfig?.totalTokensReminder).toEqual({ enabled: true });
  7404. expect(createdAppOptions[1]?.runtimeConfig?.subagents?.alwaysBackground).toBe(false);
  7405. expect(createdAppOptions[1]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(false);
  7406. expect(createdAppOptions[1]?.runtimeConfig?.memory?.enabled).toBe(false);
  7407. expect(createdAppOptions[1]?.runtimeConfig?.modelContextBudgetStrategy).toBe("preflight-v1");
  7408. expect(result.snapshot.session.target).toMatchObject({
  7409. objective: "Fork inherits parent goal target",
  7410. sessionId: "sess_forked",
  7411. status: "active",
  7412. });
  7413. expect(result.snapshot.projection.target).toMatchObject({
  7414. objective: "Fork inherits parent goal target",
  7415. sessionId: "sess_forked",
  7416. status: "active",
  7417. });
  7418. expect(result.snapshot.session.target?.targetId).toBe(goal.snapshot.session.target?.targetId);
  7419. expect(await store.readTarget({ sessionID: "sess_forked" as SessionId })).toMatchObject({
  7420. objective: "Fork inherits parent goal target",
  7421. });
  7422. const selection = await requestResult(server, {
  7423. id: 7,
  7424. method: V4_METHODS.command,
  7425. params: {
  7426. clientId: "client-selection-runtime-preferences",
  7427. commandId: "cmd-selection-runtime-preferences",
  7428. issuedAt: 20,
  7429. payload: {},
  7430. sessionId: created.session.sessionId,
  7431. type: "createSelectionSideSession",
  7432. },
  7433. });
  7434. expect(selection).toMatchObject({
  7435. status: "accepted",
  7436. result: {
  7437. sessionId: selectionChildId,
  7438. type: "createSelectionSideSession",
  7439. },
  7440. });
  7441. expect(createdAppOptions).toHaveLength(3);
  7442. expect(createdAppOptions[2]?.readSubagentRuntimeConfig).toBeTypeOf("function");
  7443. expect(preferenceRequests).toHaveLength(1);
  7444. expect(createdAppOptions[2]?.runtimeConfig?.toolSearch).toEqual({ mode: "local" });
  7445. expect(createdAppOptions[2]?.runtimeConfig?.totalTokensReminder).toEqual({ enabled: true });
  7446. expect(createdAppOptions[2]?.runtimeConfig?.subagents?.alwaysBackground).toBe(false);
  7447. expect(createdAppOptions[2]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(false);
  7448. expect(createdAppOptions[2]?.runtimeConfig?.memory?.enabled).toBe(false);
  7449. expect(createdAppOptions[2]?.runtimeConfig?.modelContextBudgetStrategy).toBe("preflight-v1");
  7450. expect((await store.getSession(selectionChildId))?.taskType).toBe("selection_side_chat");
  7451. } finally {
  7452. await store.close();
  7453. }
  7454. });
  7455. it("resolves turn fork targets before later user, fork, and compact synthetic messages", async () => {
  7456. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  7457. const sessionId = "sess_fork_turn_history" as SessionId;
  7458. const forkTargets: Array<{ targetCheckpointId?: string; targetMessageId?: string }> = [];
  7459. try {
  7460. await store.createSession({
  7461. id: sessionId,
  7462. projectID: "project_fork_turn_history" as ProjectId,
  7463. slug: "fork-turn-history",
  7464. directory: workspace.workspacePath,
  7465. path: workspace.workspacePath,
  7466. title: "Fork turn history",
  7467. version: "test-version",
  7468. time: { created: 1, updated: 12 },
  7469. });
  7470. await saveUserTextMessage(store, sessionId, "msg_user_0" as MessageId, "第一轮", 2);
  7471. await saveAssistantTextMessage(
  7472. store,
  7473. sessionId,
  7474. "msg_assistant_0" as MessageId,
  7475. "msg_user_0" as MessageId,
  7476. "第一轮回复",
  7477. 3,
  7478. );
  7479. await saveUserTextMessage(store, sessionId, "msg_user_1" as MessageId, "第二轮", 4);
  7480. await saveAssistantTextMessage(
  7481. store,
  7482. sessionId,
  7483. "msg_assistant_1" as MessageId,
  7484. "msg_user_1" as MessageId,
  7485. "第二轮回复",
  7486. 5,
  7487. );
  7488. await saveSyntheticForkNotice(store, sessionId, "msg_fork_notice" as MessageId, 6);
  7489. await saveCompactSummary(store, sessionId, "msg_compact_summary" as MessageId, 7);
  7490. const server = new ZCodeProtocolAgentServer({
  7491. createZCodeApp: (options) =>
  7492. createFakeApp(options, {
  7493. forkFromCheckpoint: async (target) => {
  7494. forkTargets.push({
  7495. targetCheckpointId: target?.targetCheckpointId,
  7496. targetMessageId: target?.targetMessageId,
  7497. });
  7498. // 两次 fork 必须像真实 core 一样生成不同身份,否则第二次会命中已初始化实例。
  7499. const forkedSessionId = `sess_forked_${forkTargets.length}` as SessionId;
  7500. // fake 必须遵守 core fork 契约:返回前 child 已落 store。旧夹具只返回 id,
  7501. // registerForkedSession 按生产语义回读时必然报 Persisted child not found。
  7502. if (!(await store.getSession(forkedSessionId))) {
  7503. await store.createSession({
  7504. id: forkedSessionId,
  7505. parentID: sessionId,
  7506. projectID: "project_fork_turn_history" as ProjectId,
  7507. slug: "fork-turn-history-child",
  7508. directory: workspace.workspacePath,
  7509. path: workspace.workspacePath,
  7510. title: "Fork turn history child",
  7511. version: "test-version",
  7512. time: { created: 10, updated: 10 },
  7513. });
  7514. }
  7515. return {
  7516. checkpoint: {} as never,
  7517. copiedMessageCount: 2,
  7518. forkedSessionId,
  7519. parentSessionId: sessionId,
  7520. targetMessageId: target?.targetMessageId as never,
  7521. restoredFiles: [],
  7522. response: "forked",
  7523. };
  7524. },
  7525. }),
  7526. cwd: workspace.workspacePath,
  7527. sessionStore: store,
  7528. });
  7529. await requestResult(server, {
  7530. id: 1,
  7531. method: zcodeProtocolMethods.sessionResume,
  7532. params: { sessionId, workspace },
  7533. });
  7534. await requestResult(server, {
  7535. id: 2,
  7536. method: zcodeProtocolMethods.sessionFork,
  7537. params: {
  7538. sessionId,
  7539. target: { kind: "turn", turnIndex: 0 },
  7540. },
  7541. });
  7542. await requestResult(server, {
  7543. id: 3,
  7544. method: zcodeProtocolMethods.sessionFork,
  7545. params: {
  7546. sessionId,
  7547. target: { kind: "turn", turnIndex: 1 },
  7548. },
  7549. });
  7550. expect(forkTargets).toEqual([
  7551. expect.objectContaining({ targetMessageId: "msg_assistant_0" }),
  7552. expect.objectContaining({ targetMessageId: "msg_assistant_1" }),
  7553. ]);
  7554. } finally {
  7555. await store.close();
  7556. }
  7557. });
  7558. it("maps core session title updates into explicit protocol events", () => {
  7559. const event = mapSessionEvent(
  7560. {
  7561. id: "evt_title" as never,
  7562. payload: {
  7563. previousTitle: "please fix the mobile login button",
  7564. source: "generated",
  7565. title: "Fix mobile login",
  7566. },
  7567. sequenceNumber: 3,
  7568. sessionId: "sess_test" as SessionId,
  7569. timestamp: new Date(4),
  7570. traceId: "trace_test" as never,
  7571. type: SessionEventType.SessionTitleUpdated,
  7572. } satisfies SessionEvent,
  7573. "desktop-continuous",
  7574. );
  7575. expect(event.type).toBe("session.titleUpdated");
  7576. expect(event.payload).toMatchObject({ title: "Fix mobile login" });
  7577. });
  7578. });
  7579. type TestSessionStore = Awaited<ReturnType<typeof createSqliteSessionStore>>;
  7580. async function saveUserTextMessage(
  7581. store: TestSessionStore,
  7582. sessionId: SessionId,
  7583. messageId: MessageId,
  7584. text: string,
  7585. created: number,
  7586. ) {
  7587. await store.saveMessage({
  7588. id: messageId,
  7589. sessionID: sessionId,
  7590. role: "user",
  7591. time: { created },
  7592. agent: "zcode-agent",
  7593. model: {
  7594. providerId: "glm" as ModelProviderId,
  7595. modelId: "glm-4-air" as ModelId,
  7596. },
  7597. tools: {},
  7598. });
  7599. await saveTextPart(store, sessionId, messageId, text, created);
  7600. }
  7601. async function saveSyntheticForkNotice(
  7602. store: TestSessionStore,
  7603. sessionId: SessionId,
  7604. messageId: MessageId,
  7605. created: number,
  7606. ) {
  7607. const metadata = {
  7608. forkContext: {
  7609. kind: "session_fork",
  7610. parentSessionId: "sess_parent",
  7611. targetMessageId: "msg_assistant_1",
  7612. },
  7613. source: "fork",
  7614. visibility: "user-visible",
  7615. };
  7616. await store.saveMessage({
  7617. id: messageId,
  7618. sessionID: sessionId,
  7619. role: "user",
  7620. time: { created },
  7621. agent: "zcode-agent",
  7622. metadata,
  7623. model: {
  7624. providerId: "glm" as ModelProviderId,
  7625. modelId: "glm-4-air" as ModelId,
  7626. },
  7627. source: "fork",
  7628. synthetic: true,
  7629. tools: {},
  7630. visibility: "user-visible",
  7631. });
  7632. await saveTextPart(
  7633. store,
  7634. sessionId,
  7635. messageId,
  7636. "<system-reminder>\nThis session was forked from a previous session message.\n</system-reminder>",
  7637. created,
  7638. {
  7639. metadata,
  7640. synthetic: true,
  7641. },
  7642. );
  7643. }
  7644. async function saveCompactSummary(
  7645. store: TestSessionStore,
  7646. sessionId: SessionId,
  7647. messageId: MessageId,
  7648. created: number,
  7649. ) {
  7650. await store.saveMessage({
  7651. id: messageId,
  7652. sessionID: sessionId,
  7653. role: "user",
  7654. time: { created },
  7655. agent: "zcode-agent",
  7656. model: {
  7657. providerId: "glm" as ModelProviderId,
  7658. modelId: "glm-4-air" as ModelId,
  7659. },
  7660. summary: {
  7661. body: "历史摘要",
  7662. diffs: [],
  7663. title: "Compact summary",
  7664. },
  7665. tools: {},
  7666. });
  7667. await saveTextPart(store, sessionId, messageId, "compact summary context", created, {
  7668. synthetic: true,
  7669. });
  7670. await store.savePart({
  7671. id: `${messageId}_compaction` as MessagePart["id"],
  7672. sessionID: sessionId,
  7673. messageID: messageId,
  7674. type: "compaction",
  7675. auto: false,
  7676. trigger: "manual",
  7677. phase: "standalone_turn",
  7678. compactReason: "user_requested",
  7679. operationId: "cmp_test",
  7680. } as MessagePart);
  7681. }
  7682. async function saveAssistantTextMessage(
  7683. store: TestSessionStore,
  7684. sessionId: SessionId,
  7685. messageId: MessageId,
  7686. parentMessageId: MessageId,
  7687. text: string,
  7688. created: number,
  7689. ) {
  7690. await store.saveMessage({
  7691. id: messageId,
  7692. sessionID: sessionId,
  7693. role: "assistant",
  7694. time: { created, completed: created },
  7695. parentID: parentMessageId,
  7696. providerId: "glm" as ModelProviderId,
  7697. modelId: "glm-4-air" as ModelId,
  7698. mode: "build",
  7699. agent: "zcode-agent",
  7700. path: { cwd: workspace.workspacePath, root: workspace.workspacePath },
  7701. cost: 0,
  7702. tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
  7703. });
  7704. await saveTextPart(store, sessionId, messageId, text, created);
  7705. }
  7706. async function saveTextPart(
  7707. store: TestSessionStore,
  7708. sessionId: SessionId,
  7709. messageId: MessageId,
  7710. text: string,
  7711. created: number,
  7712. options: Pick<MessagePart, "metadata" | "synthetic"> = {},
  7713. ) {
  7714. await store.savePart({
  7715. id: `${messageId}_text` as MessagePart["id"],
  7716. sessionID: sessionId,
  7717. messageID: messageId,
  7718. type: "text",
  7719. text,
  7720. time: { start: created, end: created },
  7721. ...options,
  7722. });
  7723. }
  7724. function messageTexts(
  7725. messages: ReadonlyArray<{ parts: ReadonlyArray<{ text?: string; type: string }> }>,
  7726. ) {
  7727. return messages.map((message) =>
  7728. message.parts
  7729. .filter((part) => part.type === "text")
  7730. .map((part) => part.text ?? "")
  7731. .join(""),
  7732. );
  7733. }
  7734. function setTestNotificationSink(
  7735. server: ZCodeProtocolAgentServer,
  7736. sink: Parameters<ZCodeProtocolAgentServer["setNotificationSink"]>[0],
  7737. ): void {
  7738. server.setNotificationSink((message) => {
  7739. if (answerReplyLanguageRequest(server, message)) return;
  7740. if (
  7741. "id" in message &&
  7742. message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences
  7743. ) {
  7744. void server.handleMessage({
  7745. id: message.id,
  7746. result: { nativeSearchEnhancementsEnabled: true, memoryEnabled: true },
  7747. });
  7748. return;
  7749. }
  7750. sink(message);
  7751. });
  7752. }
  7753. interface RecordedLog {
  7754. context: Record<string, unknown>;
  7755. level: "debug" | "error" | "info" | "warn";
  7756. message: string;
  7757. }
  7758. function createProtocolTestLoggerFactory(logs: RecordedLog[]): LoggerFactory {
  7759. const loggerFor = (baseContext: LogContext = {}): Logger => ({
  7760. child(childContext) {
  7761. return loggerFor({ ...baseContext, ...childContext });
  7762. },
  7763. debug(message, logContext) {
  7764. recordLog(logs, "debug", message, baseContext, logContext);
  7765. },
  7766. error(message, _error, logContext) {
  7767. recordLog(logs, "error", message, baseContext, logContext);
  7768. },
  7769. info(message, logContext) {
  7770. recordLog(logs, "info", message, baseContext, logContext);
  7771. },
  7772. warn(message, logContext) {
  7773. recordLog(logs, "warn", message, baseContext, logContext);
  7774. },
  7775. });
  7776. return {
  7777. createLogger: () => loggerFor(),
  7778. setLevel: () => {},
  7779. withContext: (context) => loggerFor(context),
  7780. };
  7781. }
  7782. function recordLog(
  7783. logs: RecordedLog[],
  7784. level: RecordedLog["level"],
  7785. message: string,
  7786. baseContext: LogContext,
  7787. logContext?: LogContext,
  7788. ): void {
  7789. logs.push({
  7790. level,
  7791. message,
  7792. context: { ...baseContext, ...logContext },
  7793. });
  7794. }
  7795. function createProtocolListMcpPort(connectedConfigs: Record<string, McpServerConfig>[]): McpPort {
  7796. const statuses: Awaited<ReturnType<McpPort["status"]>> = {};
  7797. return {
  7798. async callTool() {
  7799. return { content: [] };
  7800. },
  7801. async close() {},
  7802. async connectConfiguredServers(servers) {
  7803. connectedConfigs.push(servers);
  7804. for (const [name, config] of Object.entries(servers)) {
  7805. statuses[name] = {
  7806. status: config.enabled === false ? "disabled" : "connected",
  7807. transport: config.type,
  7808. toolCount: config.enabled === false ? 0 : 3,
  7809. updatedAt: new Date(1).toISOString(),
  7810. };
  7811. }
  7812. return {
  7813. statuses,
  7814. tools: [],
  7815. };
  7816. },
  7817. async connectServer(name, config) {
  7818. const status = {
  7819. status: "connected" as const,
  7820. transport: config.type,
  7821. toolCount: 3,
  7822. updatedAt: new Date(1).toISOString(),
  7823. };
  7824. statuses[name] = status;
  7825. return status;
  7826. },
  7827. async disconnectServer(name) {
  7828. const status = statuses[name];
  7829. delete statuses[name];
  7830. return status;
  7831. },
  7832. async listTools() {
  7833. return [];
  7834. },
  7835. async status() {
  7836. return statuses;
  7837. },
  7838. };
  7839. }
  7840. function createProtocolReplaceMcpPort(
  7841. connectedConfigs: Record<string, McpServerConfig>[],
  7842. disconnectedNames: string[],
  7843. initialStatuses: Awaited<ReturnType<McpPort["status"]>>,
  7844. ): McpPort {
  7845. const statuses: Awaited<ReturnType<McpPort["status"]>> = { ...initialStatuses };
  7846. return {
  7847. async callTool() {
  7848. return { content: [] };
  7849. },
  7850. async close() {},
  7851. async connectConfiguredServers(servers) {
  7852. connectedConfigs.push(servers);
  7853. for (const name of Object.keys(statuses)) {
  7854. if (!(name in servers)) {
  7855. disconnectedNames.push(name);
  7856. delete statuses[name];
  7857. }
  7858. }
  7859. for (const [name, config] of Object.entries(servers)) {
  7860. statuses[name] = {
  7861. status: config.enabled === false ? "disabled" : "connected",
  7862. transport: config.type,
  7863. toolCount: config.enabled === false ? 0 : 3,
  7864. updatedAt: new Date(2).toISOString(),
  7865. };
  7866. }
  7867. return {
  7868. statuses,
  7869. tools: [],
  7870. };
  7871. },
  7872. async connectServer(name, config) {
  7873. const status = {
  7874. status: "connected" as const,
  7875. transport: config.type,
  7876. toolCount: 3,
  7877. updatedAt: new Date(2).toISOString(),
  7878. };
  7879. statuses[name] = status;
  7880. return status;
  7881. },
  7882. async disconnectServer(name) {
  7883. disconnectedNames.push(name);
  7884. const status = statuses[name];
  7885. delete statuses[name];
  7886. return status;
  7887. },
  7888. async listTools() {
  7889. return [];
  7890. },
  7891. async status() {
  7892. return statuses;
  7893. },
  7894. };
  7895. }
  7896. function createProtocolPendingAuthorizationMcpPort(
  7897. connectedConfigs: Record<string, McpServerConfig>[],
  7898. onConnectWaiter: (resolve: () => void) => void,
  7899. ): McpPort {
  7900. const statuses: Awaited<ReturnType<McpPort["status"]>> = {};
  7901. return {
  7902. async callTool() {
  7903. return { content: [] };
  7904. },
  7905. async close() {},
  7906. async connectConfiguredServers(servers) {
  7907. connectedConfigs.push(servers);
  7908. statuses.notion = {
  7909. authorization: {
  7910. authorizationUrl: "https://auth.example.test/authorize?state=state_test",
  7911. startedAt: new Date(1).toISOString(),
  7912. type: "oauth_authorization_code",
  7913. },
  7914. status: "connecting",
  7915. transport: "http",
  7916. toolCount: 0,
  7917. updatedAt: new Date(1).toISOString(),
  7918. };
  7919. await new Promise<void>((resolve) => {
  7920. onConnectWaiter(resolve);
  7921. });
  7922. statuses.notion = {
  7923. status: "connected",
  7924. transport: "http",
  7925. toolCount: 3,
  7926. updatedAt: new Date(2).toISOString(),
  7927. };
  7928. return {
  7929. statuses,
  7930. tools: [],
  7931. };
  7932. },
  7933. async connectServer(name, config) {
  7934. const status = {
  7935. status: "connecting" as const,
  7936. transport: config.type,
  7937. toolCount: 0,
  7938. updatedAt: new Date(1).toISOString(),
  7939. };
  7940. statuses[name] = status;
  7941. return status;
  7942. },
  7943. async disconnectServer(name) {
  7944. const status = statuses[name];
  7945. delete statuses[name];
  7946. return status;
  7947. },
  7948. async listTools() {
  7949. return [];
  7950. },
  7951. async status() {
  7952. return statuses;
  7953. },
  7954. };
  7955. }