cli.unit.test.ts 232 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217
  1. import assert from "node:assert/strict";
  2. import { spawn } from "node:child_process";
  3. import { once } from "node:events";
  4. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  5. import { homedir, tmpdir } from "node:os";
  6. import { PassThrough } from "node:stream";
  7. import { join } from "node:path";
  8. import { setTimeout as delay } from "node:timers/promises";
  9. import test from "node:test";
  10. import { fileURLToPath } from "node:url";
  11. import { ZCODE_OFFICIAL_PLUGIN_MARKETPLACE, ZCODE_PLUGIN_HOST_COMMAND } from "@zcode/contracts";
  12. import {
  13. ZCODE_CUA_OFFICIAL_PLUGIN_ID,
  14. ZCODE_CUA_NODE_REPL_HOST_ENV_KEY,
  15. ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY,
  16. ZCODE_PLUGIN_ID_ENV_KEY,
  17. ZCODE_RUNTIME_ENV_KEY,
  18. readZCodeToolEnvPassthroughEnv,
  19. resetCapturedZCodeCuaBrokerCredentialsForTest,
  20. sanitizeZCodeRuntimeEnvInPlace,
  21. type ModelSelection,
  22. type ZCodeModelOption,
  23. } from "@zcode/shared";
  24. import type { RunContext } from "@zcode/shared-types";
  25. import type { TuiOptions } from "@zcode/tui";
  26. import type { ZCodeAppOptions } from "@zcode/bootstrap";
  27. import { run } from "../src/run.js";
  28. import { createTuiSubmitPrompt } from "../src/tui-prompt-handler.js";
  29. import {
  30. buildManualSkillPrompt,
  31. createCommandCenter,
  32. parseSlashCommand,
  33. } from "../src/command-center.js";
  34. import type { CommandCenterTarget } from "../src/command-center.js";
  35. import { expandCliCustomCommandPrompt } from "../src/custom-command-expand.js";
  36. import { findDotenv, loadCliDotenv, prepareCliRuntimeEnv } from "../src/env.js";
  37. import { runPluginsCommand } from "../src/plugins-command.js";
  38. import { runPluginHostCommand } from "../src/plugin-host-command.js";
  39. import { CLI_PROCESS_NAME, setCliProcessTitle } from "../src/process-name.js";
  40. import { loadCliPlaywrightChromium } from "../src/sea-playwright-runtime.js";
  41. import { interceptKnownRuntimeWarnings } from "../src/runtime-warnings.js";
  42. import { installStderrConsoleBoundary } from "../src/protocol-console.js";
  43. import { interceptTuiStderr, isTuiInvocation } from "../src/tui-stderr.js";
  44. import { resolveWorkspaceGitBranch } from "../src/tui-workspace-git.js";
  45. import { createWorkspacePathSuggestionProvider } from "../src/tui-workspace-paths.js";
  46. import type { RunDependencies } from "../src/run.js";
  47. import { scheduleCliExitWatchdog, type CliShutdownProcess } from "../src/shutdown.js";
  48. type CapturedWriteStream = NodeJS.WriteStream & {
  49. output: () => string;
  50. };
  51. const createWriteStream = (isTTY = false): CapturedWriteStream => {
  52. let output = "";
  53. return {
  54. isTTY,
  55. output: () => output,
  56. write: (
  57. chunk: string | Uint8Array,
  58. encodingOrCallback?: BufferEncoding | ((err?: Error | null) => void),
  59. callback?: (err?: Error | null) => void,
  60. ): boolean => {
  61. output += typeof chunk === "string" ? chunk : chunk.toString();
  62. const writeCallback =
  63. typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
  64. writeCallback?.();
  65. return true;
  66. },
  67. } as CapturedWriteStream;
  68. };
  69. const createContext = (
  70. argv: string[],
  71. ): RunContext & {
  72. stderr: CapturedWriteStream;
  73. stdout: CapturedWriteStream;
  74. } => ({
  75. argv,
  76. stderr: createWriteStream(),
  77. stdin: {
  78. isTTY: false,
  79. } as NodeJS.ReadStream,
  80. stdout: createWriteStream(),
  81. });
  82. const withTimeout = async <T>(promise: Promise<T>, timeoutMs: number, message: string) => {
  83. let timeout: NodeJS.Timeout | undefined;
  84. try {
  85. return await Promise.race([
  86. promise,
  87. new Promise<never>((_resolve, reject) => {
  88. timeout = setTimeout(() => reject(new Error(message)), timeoutMs);
  89. timeout.unref?.();
  90. }),
  91. ]);
  92. } finally {
  93. if (timeout) clearTimeout(timeout);
  94. }
  95. };
  96. const fakeProjection = {
  97. contextUsed: 0,
  98. contextWindow: 0,
  99. status: "idle",
  100. totalTokenCount: 0,
  101. turnCount: 1,
  102. };
  103. /** 协议 Model Option 测试夹具;TUI 登录态由 App 模型目录中是否存在可选模型推导。 */
  104. const createTestModelOption = (
  105. providerId: string,
  106. modelId: string,
  107. {
  108. defaultLevel = "medium",
  109. label = modelId,
  110. levels = ["low", "medium", "high"],
  111. }: { defaultLevel?: string; label?: string; levels?: readonly string[] } = {},
  112. ): ZCodeModelOption => ({
  113. ref: { providerId, modelId },
  114. label,
  115. providerLabel: providerId,
  116. reasoning: {
  117. levels: levels.map((value) => ({ value, label: value })),
  118. defaultLevel,
  119. },
  120. properties: {
  121. inputFormat: {
  122. supportsText: true,
  123. supportsImage: false,
  124. supportsVideo: false,
  125. supportsAudio: false,
  126. supportsPdf: false,
  127. },
  128. outputFormat: { supportsText: true },
  129. },
  130. });
  131. /** 至少一个未禁用的模型,表示 Provider/账号已可用,普通 prompt 不会被登录提示拦截。 */
  132. const selectableTestModels = (): ZCodeModelOption[] => [
  133. createTestModelOption("openai", "gpt-test"),
  134. ];
  135. /**
  136. * 真实 runTui 先绘制启动屏,再调用 loadStartupOptions 并把结果合并进 TUI 选项;
  137. * 测试替身按同一顺序模拟启动,断言 TUI 最终拿到的初始模型、主题、命令等数据。
  138. */
  139. const loadTuiStartup = async (options: TuiOptions): Promise<TuiOptions> => ({
  140. ...options,
  141. ...(await options.loadStartupOptions?.()),
  142. });
  143. const createPromptDeps = (): RunDependencies => ({
  144. createModelAdapter: () => ({}) as never,
  145. createZCodeApp: () =>
  146. ({
  147. getModel: () => "openai/gpt-test",
  148. getLocale: () => "en-US",
  149. getThoughtLevel: () => "medium",
  150. listModels: selectableTestModels,
  151. sessionId: "session-test",
  152. traceId: "trace-test",
  153. runtime: {} as never,
  154. submitPrompt: async (prompt: string) => ({
  155. events: [{} as never, {} as never],
  156. projection: fakeProjection as never,
  157. response: prompt,
  158. traceId: "trace-test" as never,
  159. turnId: "turn-test" as never,
  160. }),
  161. }) as never,
  162. loadDotenv: () => ({
  163. keys: [],
  164. loaded: false,
  165. }),
  166. startProcessProviderRegistryRuntime: async () =>
  167. ({
  168. dispose: () => {},
  169. runtime: { registryService: {} },
  170. }) as never,
  171. skipUserConfig: true,
  172. });
  173. test("prepares a sanitized CLI runtime env with ZCode-owned runtime keys", () => {
  174. const sourceEnv = {
  175. NODE_ENV: "development",
  176. HTTP_PROXY: "http://ambient-proxy:8080",
  177. NODE_EXTRA_CA_CERTS: "/tmp/ambient-ca.pem",
  178. ZCODE_HTTP_PROXY: "http://zcode-proxy:8080",
  179. no_proxy: ".example.test",
  180. npm_config_proxy: "http://npm-proxy:8080",
  181. };
  182. const env = prepareCliRuntimeEnv(sourceEnv, ["/usr/bin/node", "/workspace/bin/zcode.js"]);
  183. const toolEnv = readZCodeToolEnvPassthroughEnv(env);
  184. assert.equal(env.ZCODE_RUNTIME_ENV, "production");
  185. assert.equal(env.ZCODE_HTTP_PROXY, "http://zcode-proxy:8080");
  186. assert.deepEqual(toolEnv, {
  187. HTTP_PROXY: "http://ambient-proxy:8080",
  188. NODE_EXTRA_CA_CERTS: "/tmp/ambient-ca.pem",
  189. no_proxy: ".example.test",
  190. npm_config_proxy: "http://npm-proxy:8080",
  191. });
  192. assert.equal(env.NODE_ENV, undefined);
  193. assert.equal(env.HTTP_PROXY, undefined);
  194. assert.equal(env.NODE_EXTRA_CA_CERTS, undefined);
  195. assert.equal(env.no_proxy, undefined);
  196. assert.equal(env.npm_config_proxy, undefined);
  197. assert.equal(sourceEnv.NODE_ENV, "development");
  198. });
  199. test("prepares beta CLI runtime env with beta storage root", () => {
  200. const env = prepareCliRuntimeEnv(
  201. {
  202. ZCODE_BETA: "1",
  203. },
  204. ["/usr/bin/node", "/workspace/bin/zcode.js"],
  205. );
  206. assert.equal(env.ZCODE_STORAGE_DIR, join(homedir(), ".zcode-beta"));
  207. });
  208. test("preserves explicit storage root when beta mode is enabled", () => {
  209. const env = prepareCliRuntimeEnv(
  210. {
  211. ZCODE_BETA: "1",
  212. ZCODE_STORAGE_DIR: "/tmp/custom-zcode-home",
  213. },
  214. ["/usr/bin/node", "/workspace/bin/zcode.js"],
  215. );
  216. assert.equal(env.ZCODE_STORAGE_DIR, "/tmp/custom-zcode-home");
  217. });
  218. test("opens the TUI by default", async () => {
  219. const ctx = createContext([]);
  220. let opened = false;
  221. const exitCode = await run(ctx, {
  222. ...createPromptDeps(),
  223. runTui: async (options) => {
  224. opened = true;
  225. assert.equal(options.stdin, ctx.stdin);
  226. // 启动屏先于运行时绘制:模型、主题、命令等启动数据改由 loadStartupOptions 在首帧后提供。
  227. const startup = await loadTuiStartup(options);
  228. assert.equal(startup.initialModel, "openai/gpt-test");
  229. assert.equal(startup.initialThoughtLevel, "medium");
  230. assert.equal(startup.theme, "auto");
  231. assert.equal(typeof options.listMcpServers, "function");
  232. assert.equal(typeof options.listWorkspacePathSuggestions, "function");
  233. assert.equal(typeof options.submitPrompt, "function");
  234. assert.equal(typeof options.writeClipboardText, "function");
  235. assert.ok(startup.slashCommands?.some((command) => command.name === "model"));
  236. return 0;
  237. },
  238. });
  239. assert.equal(exitCode, 0);
  240. assert.equal(opened, true);
  241. assert.equal(ctx.stdout.output(), "");
  242. assert.equal(ctx.stderr.output(), "");
  243. });
  244. test("ignores ambient NODE_ENV when deciding TUI developer mode", async () => {
  245. const ctx = createContext([]);
  246. const exitCode = await run(ctx, {
  247. ...createPromptDeps(),
  248. env: {
  249. NODE_ENV: "development",
  250. },
  251. runTui: async (options) => {
  252. assert.equal(options.developerMode, false);
  253. return 0;
  254. },
  255. });
  256. assert.equal(exitCode, 0);
  257. });
  258. test("passes developer mode, version, and workspace git branch into the TUI", async () => {
  259. const ctx = createContext([]);
  260. const workspaceDirectory = "/workspace/dev";
  261. const exitCode = await run(ctx, {
  262. ...createPromptDeps(),
  263. cwd: () => workspaceDirectory,
  264. env: {
  265. ZCODE_RUNTIME_ENV: "development",
  266. },
  267. resolveWorkspaceGitBranch: async (options) => {
  268. assert.equal(options.workspaceDirectory, workspaceDirectory);
  269. return "feature/sidebar";
  270. },
  271. runTui: async (options) => {
  272. assert.equal(options.developerMode, true);
  273. assert.equal(options.version, "0.0.0");
  274. assert.equal(options.workspaceDirectory, workspaceDirectory);
  275. // Git 分支解析不阻塞首帧,随 loadStartupOptions 一起返回。
  276. const startup = await loadTuiStartup(options);
  277. assert.equal(startup.workspaceGitBranch, "feature/sidebar");
  278. return 0;
  279. },
  280. });
  281. assert.equal(exitCode, 0);
  282. });
  283. test("resolves workspace git branch from a non-shell git command", async () => {
  284. const branch = await resolveWorkspaceGitBranch({
  285. workspaceDirectory: "/workspace/project",
  286. runCommand: async (file, args) => {
  287. assert.equal(file, "git");
  288. assert.deepEqual(args, [
  289. "-C",
  290. "/workspace/project",
  291. "symbolic-ref",
  292. "--quiet",
  293. "--short",
  294. "HEAD",
  295. ]);
  296. return { exitCode: 0, stdout: "main\n" };
  297. },
  298. });
  299. assert.equal(branch, "main");
  300. });
  301. test("ignores missing workspace git branch", async () => {
  302. assert.equal(
  303. await resolveWorkspaceGitBranch({
  304. workspaceDirectory: "/workspace/project",
  305. runCommand: async () => ({ exitCode: 1, stdout: "" }),
  306. }),
  307. undefined,
  308. );
  309. assert.equal(
  310. await resolveWorkspaceGitBranch({
  311. workspaceDirectory: "/workspace/project",
  312. runCommand: async () => ({ exitCode: 0, stdout: "HEAD\n" }),
  313. }),
  314. undefined,
  315. );
  316. });
  317. test("passes configured TUI theme into the TUI", async () => {
  318. const ctx = createContext([]);
  319. const exitCode = await run(ctx, {
  320. ...createPromptDeps(),
  321. createZCodeApp: () =>
  322. ({
  323. getLocale: () => "en-US",
  324. getModel: () => "openai/gpt-test",
  325. getTheme: () => "light",
  326. getThoughtLevel: () => "medium",
  327. runtime: {} as never,
  328. sessionId: "session-test",
  329. submitPrompt: async () => {
  330. throw new Error("submitPrompt should not be called");
  331. },
  332. traceId: "trace-test",
  333. }) as never,
  334. runTui: async (options) => {
  335. const startup = await loadTuiStartup(options);
  336. assert.equal(startup.theme, "light");
  337. return 0;
  338. },
  339. });
  340. assert.equal(exitCode, 0);
  341. });
  342. test("suggests workspace paths for TUI file mentions", async () => {
  343. const dir = await mkdtemp(join(tmpdir(), "zcode-tui-paths-"));
  344. try {
  345. await mkdir(join(dir, "public"));
  346. await mkdir(join(dir, "node_modules"));
  347. await writeFile(join(dir, "public", "app.ts"), "export {}", "utf8");
  348. await writeFile(join(dir, "puzzle.md"), "# puzzle", "utf8");
  349. await writeFile(join(dir, ".hidden.md"), "# hidden", "utf8");
  350. const suggest = createWorkspacePathSuggestionProvider({ workspaceDirectory: dir });
  351. assert.deepEqual(await suggest({ token: "pu" }), {
  352. items: [
  353. { kind: "directory", path: "public/" },
  354. { kind: "file", path: "puzzle.md" },
  355. ],
  356. truncated: false,
  357. });
  358. assert.deepEqual(await suggest({ token: "public/" }), {
  359. items: [{ kind: "file", path: "public/app.ts" }],
  360. truncated: false,
  361. });
  362. assert.deepEqual(await suggest({ token: "../" }), {
  363. items: [],
  364. truncated: false,
  365. });
  366. assert.equal(
  367. (await suggest({ token: "" })).items.some((item) => item.path === ".hidden.md"),
  368. false,
  369. );
  370. } finally {
  371. await rm(dir, { force: true, recursive: true });
  372. }
  373. });
  374. test("enables session title generation for TUI sessions", async () => {
  375. const ctx = createContext(["tui"]);
  376. const exitCode = await run(ctx, {
  377. ...createPromptDeps(),
  378. createZCodeApp: (options) => {
  379. assert.deepEqual(options?.runtimeConfig?.titleGeneration, {});
  380. assert.equal(options?.runtimeConfig?.memory?.extractionEnabled, undefined);
  381. return {
  382. getLocale: () => "en-US",
  383. getModel: () => "openai/gpt-test",
  384. getThoughtLevel: () => "medium",
  385. sessionId: "session-test",
  386. traceId: "trace-test",
  387. runtime: {} as never,
  388. submitPrompt: async (prompt: string) => ({
  389. events: [],
  390. projection: fakeProjection as never,
  391. response: prompt,
  392. traceId: "trace-test" as never,
  393. turnId: "turn-test" as never,
  394. }),
  395. } as never;
  396. },
  397. runTui: async () => 0,
  398. });
  399. assert.equal(exitCode, 0);
  400. });
  401. test("TUI requests background MCP startup while --prompt keeps the blocking default", async () => {
  402. const policies: Record<string, unknown[]> = { prompt: [], tui: [] };
  403. const depsFor = (target: unknown[]): RunDependencies => ({
  404. ...createPromptDeps(),
  405. createZCodeApp: (options) => {
  406. target.push(options?.mcpStartupPolicy);
  407. return (createPromptDeps().createZCodeApp as (input: unknown) => unknown)(options) as never;
  408. },
  409. });
  410. assert.equal(
  411. await run(createContext(["tui"]), {
  412. ...depsFor(policies.tui!),
  413. runTui: async (options) => {
  414. await loadTuiStartup(options);
  415. return 0;
  416. },
  417. }),
  418. 0,
  419. );
  420. assert.equal(await run(createContext(["--prompt", "hello"]), depsFor(policies.prompt!)), 0);
  421. assert.ok(policies.tui!.length > 0, "the TUI creates its first app at startup");
  422. for (const policy of policies.tui!) assert.equal(policy, "background");
  423. assert.deepEqual(policies.prompt, [undefined]);
  424. });
  425. test("passes --disallowedTools into TUI runtime config", async () => {
  426. const ctx = createContext(["tui", "--disallowedTools", "Bash", "Edit,web_search"]);
  427. const exitCode = await run(ctx, {
  428. ...createPromptDeps(),
  429. createZCodeApp: (options) => {
  430. assert.deepEqual(options?.runtimeConfig?.toolDisallowlist, ["Bash", "Edit", "WebSearch"]);
  431. return {
  432. getLocale: () => "en-US",
  433. getModel: () => "openai/gpt-test",
  434. getThoughtLevel: () => "medium",
  435. sessionId: "session-test",
  436. traceId: "trace-test",
  437. runtime: {} as never,
  438. submitPrompt: async (prompt: string) => ({
  439. events: [],
  440. projection: fakeProjection as never,
  441. response: prompt,
  442. traceId: "trace-test" as never,
  443. turnId: "turn-test" as never,
  444. }),
  445. } as never;
  446. },
  447. runTui: async () => 0,
  448. });
  449. assert.equal(exitCode, 0);
  450. });
  451. test("passes force MCS into TUI runtime config", async () => {
  452. const ctx = createContext(["tui", "--force-mcs"]);
  453. const exitCode = await run(ctx, {
  454. ...createPromptDeps(),
  455. createZCodeApp: (options) => {
  456. assert.deepEqual((options?.runtimeConfig as any)?.midConversationSystem, {
  457. mode: "force",
  458. });
  459. return {
  460. getLocale: () => "en-US",
  461. getModel: () => "openai/gpt-test",
  462. getThoughtLevel: () => "medium",
  463. sessionId: "session-test",
  464. traceId: "trace-test",
  465. runtime: {} as never,
  466. submitPrompt: async (prompt: string) => ({
  467. events: [],
  468. projection: fakeProjection as never,
  469. response: prompt,
  470. traceId: "trace-test" as never,
  471. turnId: "turn-test" as never,
  472. }),
  473. } as never;
  474. },
  475. runTui: async () => 0,
  476. });
  477. assert.equal(exitCode, 0);
  478. });
  479. test("does not enable session title generation for headless prompts", async () => {
  480. const ctx = createContext(["--prompt", "hello"]);
  481. const exitCode = await run(ctx, {
  482. ...createPromptDeps(),
  483. createZCodeApp: (options) => {
  484. assert.equal(options?.runtimeConfig?.titleGeneration, undefined);
  485. assert.equal(options?.standaloneSessionControl, true);
  486. return {
  487. sessionId: "session-test",
  488. traceId: "trace-test",
  489. runtime: {} as never,
  490. close: async () => {},
  491. submitPrompt: async (prompt: string) => ({
  492. events: [],
  493. projection: fakeProjection as never,
  494. response: prompt,
  495. traceId: "trace-test" as never,
  496. turnId: "turn-test" as never,
  497. }),
  498. } as never;
  499. },
  500. });
  501. assert.equal(exitCode, 0);
  502. assert.equal(ctx.stdout.output(), "hello\n");
  503. });
  504. test("disables automatic Memory Extraction for headless prompts", async () => {
  505. const ctx = createContext(["-p", "hello Memory"]);
  506. const exitCode = await run(ctx, {
  507. ...createPromptDeps(),
  508. createZCodeApp: (options) => {
  509. assert.deepEqual(options?.runtimeConfig?.memory, {
  510. extractionEnabled: false,
  511. });
  512. return {
  513. sessionId: "session-test",
  514. traceId: "trace-test",
  515. runtime: {} as never,
  516. close: async () => {},
  517. submitPrompt: async (prompt: string) => ({
  518. events: [],
  519. projection: fakeProjection as never,
  520. response: prompt,
  521. traceId: "trace-test" as never,
  522. turnId: "turn-test" as never,
  523. }),
  524. } as never;
  525. },
  526. });
  527. assert.equal(exitCode, 0);
  528. assert.equal(ctx.stdout.output(), "hello Memory\n");
  529. });
  530. test("injects process provider endpoint routing into headless prompts", async () => {
  531. const ctx = createContext(["--prompt", "route me"]);
  532. const providerEndpointRoutingPort = {
  533. async resolve(url: string) {
  534. return { routed: false, url };
  535. },
  536. };
  537. let routingFactoryCalls = 0;
  538. const exitCode = await run(ctx, {
  539. ...createPromptDeps(),
  540. createProviderEndpointRoutingPort: (options) => {
  541. routingFactoryCalls += 1;
  542. assert.equal(options.workingDirectory, "/tmp/zcode-routing-headless");
  543. return providerEndpointRoutingPort;
  544. },
  545. createZCodeApp: (options) => {
  546. assert.equal(options?.providerEndpointRoutingPort, providerEndpointRoutingPort);
  547. return {
  548. close: async () => {},
  549. runtime: {} as never,
  550. sessionId: "session-routing-headless",
  551. submitPrompt: async (prompt: string) => ({
  552. events: [],
  553. projection: fakeProjection as never,
  554. response: prompt,
  555. traceId: "trace-routing-headless" as never,
  556. turnId: "turn-routing-headless" as never,
  557. }),
  558. traceId: "trace-routing-headless",
  559. } as never;
  560. },
  561. cwd: () => "/tmp/zcode-routing-headless",
  562. });
  563. assert.equal(exitCode, 0);
  564. assert.equal(routingFactoryCalls, 1);
  565. assert.equal(ctx.stdout.output(), "route me\n");
  566. });
  567. test("borrows one process provider registry for a headless prompt and disposes it", async () => {
  568. const ctx = createContext(["--prompt", "registry me"]);
  569. const providerRegistry = {} as never;
  570. const providerRuntimeHeadersPort = {} as never;
  571. let runtimeStarts = 0;
  572. let runtimeDisposals = 0;
  573. let selectionRepositoryDisposals = 0;
  574. const exitCode = await run(ctx, {
  575. ...createPromptDeps(),
  576. skipUserConfig: false,
  577. userConfigPath: "/tmp/zcode-legacy-cli.json",
  578. startProcessProviderRegistryRuntime: async (_env, options) => {
  579. runtimeStarts += 1;
  580. // 刷新回调是当前 CLI 装配的一部分,仍验证唯一 Runtime 和旧配置迁移路径。
  581. assert.equal(typeof options?.standalone?.onBuiltinRefreshError, "function");
  582. assert.equal(typeof options?.standalone?.onBuiltinRefreshResult, "function");
  583. assert.deepEqual(
  584. {
  585. standalone: {
  586. legacyCliUserConfigFilePath: options?.standalone?.legacyCliUserConfigFilePath,
  587. },
  588. },
  589. {
  590. standalone: {
  591. legacyCliUserConfigFilePath: "/tmp/zcode-legacy-cli.json",
  592. },
  593. },
  594. );
  595. return {
  596. accountSource: {} as never,
  597. dispose: () => {
  598. selectionRepositoryDisposals += 1;
  599. runtimeDisposals += 1;
  600. },
  601. configuredDefaultModelSelection: { providerId: "provider-a", modelId: "model-a" },
  602. modelSelectionConfigRepository: {
  603. dispose: () => {
  604. selectionRepositoryDisposals += 1;
  605. },
  606. read: async () => ({ providerId: "provider-a", modelId: "model-a" }),
  607. },
  608. providerRuntimeHeadersPort,
  609. snapshot: {} as never,
  610. runtime: {
  611. dispose: () => {
  612. runtimeDisposals += 1;
  613. },
  614. registryService: providerRegistry,
  615. },
  616. } as never;
  617. },
  618. createZCodeApp: (options) => {
  619. assert.equal(options?.providerRegistry, providerRegistry);
  620. assert.equal(options?.providerRuntimeHeadersPort, providerRuntimeHeadersPort);
  621. assert.deepEqual(options?.configuredDefaultModelSelection, {
  622. providerId: "provider-a",
  623. modelId: "model-a",
  624. });
  625. return {
  626. close: async () => {},
  627. runtime: {} as never,
  628. sessionId: "session-registry-headless",
  629. submitPrompt: async (prompt: string) => ({
  630. events: [],
  631. projection: fakeProjection as never,
  632. response: prompt,
  633. traceId: "trace-registry-headless" as never,
  634. turnId: "turn-registry-headless" as never,
  635. }),
  636. traceId: "trace-registry-headless",
  637. } as never;
  638. },
  639. });
  640. assert.equal(exitCode, 0);
  641. assert.equal(runtimeStarts, 1);
  642. assert.equal(runtimeDisposals, 1);
  643. assert.equal(selectionRepositoryDisposals, 1);
  644. });
  645. test("shows a non-blocking login notice when no coding plan key is configured", async () => {
  646. const ctx = createContext([]);
  647. const exitCode = await run(ctx, {
  648. ...createPromptDeps(),
  649. // 登录态改由 Registry 的可选模型推导:未配置 Coding Plan 时模型目录只有被禁用的选项。
  650. createZCodeApp: () =>
  651. ({
  652. getLocale: () => "en-US",
  653. getModel: () => undefined,
  654. listModels: () => [
  655. {
  656. ...createTestModelOption("zai", "glm-5.1"),
  657. disabledReason: "Sign in to Z.AI Coding Plan first.",
  658. },
  659. ],
  660. runtime: {} as never,
  661. sessionId: "session-test",
  662. submitPrompt: async () => {
  663. throw new Error("submitPrompt should not be called");
  664. },
  665. traceId: "trace-test",
  666. }) as never,
  667. runTui: async (options) => {
  668. const startup = await loadTuiStartup(options);
  669. assert.equal(startup.loginRequired, true);
  670. assert.equal(startup.initialResult, undefined);
  671. return 0;
  672. },
  673. });
  674. assert.equal(exitCode, 0);
  675. });
  676. test("honors configured locale before app creation when login is required", async () => {
  677. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-cli-prelogin-locale-"));
  678. const configPath = join(tempRoot, "config.json");
  679. await writeFile(configPath, JSON.stringify({ ui: { locale: "zh-CN" } }));
  680. try {
  681. const ctx = createContext([]);
  682. let appCreated = false;
  683. const exitCode = await run(ctx, {
  684. cwd: () => tempRoot,
  685. env: {},
  686. // 登录态改由 App 的可选模型推导;App 在启动屏首帧之后才创建,这里模拟没有可选模型。
  687. createZCodeApp: () => {
  688. appCreated = true;
  689. return {
  690. listModels: () => [],
  691. runtime: {} as never,
  692. sessionId: "session-prelogin",
  693. submitPrompt: async () => {
  694. throw new Error("submitPrompt should not be called");
  695. },
  696. traceId: "trace-prelogin",
  697. } as never;
  698. },
  699. listCustomCommands: async () =>
  700. ({
  701. commands: [],
  702. diagnostics: [],
  703. totalDiscovered: 0,
  704. }) as never,
  705. loadDotenv: () => ({
  706. keys: [],
  707. loaded: false,
  708. }),
  709. startProcessProviderRegistryRuntime: async () =>
  710. ({
  711. dispose: () => {},
  712. runtime: { registryService: {} },
  713. }) as never,
  714. runTui: async (options) => {
  715. // 启动屏在 App 创建前就按用户配置的语言渲染。
  716. assert.equal(options.locale, "zh-CN");
  717. assert.equal(appCreated, false);
  718. const startup = await loadTuiStartup(options);
  719. assert.equal(startup.loginRequired, true);
  720. assert.equal(startup.locale, "zh-CN");
  721. const pickerResult = await options.submitPrompt("/login", {
  722. abortSignal: new AbortController().signal,
  723. });
  724. assert.equal(pickerResult.response, "选择 Coding Plan 提供商的配置方式。");
  725. assert.equal(pickerResult.selection?.title, "配置 Coding Plan");
  726. assert.equal(pickerResult.selection?.prompt, "选择登录或 API key 配置方式。");
  727. return 0;
  728. },
  729. userConfigPath: configPath,
  730. });
  731. assert.equal(exitCode, 0);
  732. } finally {
  733. await rm(tempRoot, { force: true, recursive: true });
  734. }
  735. });
  736. test("passes detected auto locale into the app and TUI", async () => {
  737. const ctx = createContext(["--locale", "auto"]);
  738. const exitCode = await run(ctx, {
  739. ...createPromptDeps(),
  740. createZCodeApp: (options) => {
  741. assert.equal(options?.uiLocale, "auto");
  742. assert.equal(options?.uiDetectedLocale, "zh-CN");
  743. return {
  744. getLocale: () => "zh-CN",
  745. getModel: () => "openai/gpt-test",
  746. getThoughtLevel: () => "medium",
  747. runtime: {} as never,
  748. sessionId: "session-test",
  749. submitPrompt: async () => {
  750. throw new Error("submitPrompt should not be called");
  751. },
  752. traceId: "trace-test",
  753. } as never;
  754. },
  755. env: {
  756. LANG: "zh_CN.UTF-8",
  757. },
  758. runTui: async (options) => {
  759. assert.equal(options.locale, "zh-CN");
  760. return 0;
  761. },
  762. });
  763. assert.equal(exitCode, 0);
  764. });
  765. test("TUI locale command updates later app creation locale", async () => {
  766. const ctx = createContext(["--locale", "en-US"]);
  767. const createdLocales: Array<unknown> = [];
  768. let activeLocale: "en-US" | "zh-CN" = "en-US";
  769. const exitCode = await run(ctx, {
  770. ...createPromptDeps(),
  771. createZCodeApp: (options) => {
  772. createdLocales.push(options?.uiLocale);
  773. return {
  774. getLocale: () => activeLocale,
  775. getModel: () => "openai/gpt-test",
  776. getThoughtLevel: () => "medium",
  777. runtime: {} as never,
  778. sessionId: `session-${createdLocales.length}`,
  779. setLocale: async (locale: "auto" | "en-US" | "zh-CN") => {
  780. activeLocale = locale === "zh-CN" ? "zh-CN" : "en-US";
  781. return {
  782. configPath: "/tmp/zcode/config.json",
  783. locale: activeLocale,
  784. previousLocale: "en-US",
  785. requestedLocale: locale,
  786. traceId: "trace-test" as never,
  787. };
  788. },
  789. submitPrompt: async () => {
  790. throw new Error("submitPrompt should not be called");
  791. },
  792. traceId: `trace-${createdLocales.length}`,
  793. } as never;
  794. },
  795. runTui: async (options) => {
  796. // 真实 TUI 首帧后即创建初始 App;/locale 由该 App 持久化,不会落到默认用户配置文件。
  797. await loadTuiStartup(options);
  798. const switched = await options.submitPrompt("/locale zh-CN", {
  799. abortSignal: new AbortController().signal,
  800. });
  801. const created = await options.submitPrompt("/new", {
  802. abortSignal: new AbortController().signal,
  803. });
  804. assert.equal(switched.locale, "zh-CN");
  805. assert.equal(created.locale, "zh-CN");
  806. return 0;
  807. },
  808. });
  809. assert.equal(exitCode, 0);
  810. assert.deepEqual(createdLocales, ["en-US", "zh-CN"]);
  811. });
  812. test("prints localized CLI help with explicit locale", async () => {
  813. const ctx = createContext(["--help", "--locale", "zh-CN"]);
  814. const exitCode = await run(ctx, createPromptDeps());
  815. assert.equal(exitCode, 0);
  816. assert.match(ctx.stdout.output(), /用法:/);
  817. assert.match(ctx.stdout.output(), /--locale <locale>/);
  818. });
  819. test("prints localized CLI help with auto locale detection", async () => {
  820. const ctx = createContext(["--help", "--locale", "auto"]);
  821. const exitCode = await run(ctx, {
  822. ...createPromptDeps(),
  823. env: {
  824. LC_ALL: "zh_CN.UTF-8",
  825. },
  826. });
  827. assert.equal(exitCode, 0);
  828. assert.match(ctx.stdout.output(), /用法:/);
  829. });
  830. test("passes custom command suggestions into the TUI", async () => {
  831. const ctx = createContext([]);
  832. const exitCode = await run(ctx, {
  833. ...createPromptDeps(),
  834. listCustomCommands: async () =>
  835. ({
  836. commands: [
  837. {
  838. allowedTools: [],
  839. argumentHint: "[scope]",
  840. description: "Review custom changes",
  841. disableNonInteractive: false,
  842. frontmatterKeys: [],
  843. name: "review",
  844. path: "/workspace/.zcode/commands/review.md",
  845. rootPath: "/workspace/.zcode/commands",
  846. scope: "project",
  847. source: "zcode",
  848. },
  849. ],
  850. diagnostics: [],
  851. totalDiscovered: 1,
  852. }) as never,
  853. runTui: async (options) => {
  854. // 自定义命令扫描与首帧并行,随 loadStartupOptions 返回。
  855. const startup = await loadTuiStartup(options);
  856. assert.ok(startup.slashCommands?.some((command) => command.name === "review"));
  857. assert.ok(startup.slashCommands?.some((command) => command.usage === "/review [scope]"));
  858. return 0;
  859. },
  860. });
  861. assert.equal(exitCode, 0);
  862. });
  863. test("command center expands custom commands before submitting to runtime", async () => {
  864. let submittedPrompt = "";
  865. const commandCenter = createCommandCenter({
  866. getApp: async () =>
  867. ({
  868. getModel: () => "openai/gpt-test",
  869. getThoughtLevel: () => "medium",
  870. sessionId: "session-custom",
  871. traceId: "trace-custom",
  872. submitPrompt: async (prompt: string) => {
  873. submittedPrompt = prompt;
  874. return {
  875. projection: fakeProjection as never,
  876. response: prompt,
  877. traceId: "trace-custom" as never,
  878. turnId: "turn-custom" as never,
  879. };
  880. },
  881. }) as never,
  882. getMode: () => "build",
  883. loadCustomCommand: async () =>
  884. ({
  885. content: "Review $1 and $ARGUMENTS.",
  886. metadata: {
  887. description: "Review custom changes",
  888. name: "review",
  889. path: "/workspace/.zcode/commands/review.md",
  890. scope: "project",
  891. source: "zcode",
  892. },
  893. }) as never,
  894. resumeApp: async () => {
  895. throw new Error("resume should not be called");
  896. },
  897. });
  898. const result = await commandCenter("/review auth high", {});
  899. assert.match(result.response, /Run custom command \/review/);
  900. assert.match(submittedPrompt, /Review auth and auth high/);
  901. });
  902. test("zcode commands list prints custom commands", async () => {
  903. const ctx = createContext(["commands"]);
  904. const logger = {} as NonNullable<RunDependencies["logger"]>;
  905. const exitCode = await run(ctx, {
  906. ...createPromptDeps(),
  907. cwd: () => "/workspace/project",
  908. logger,
  909. listCustomCommands: async (options) => {
  910. assert.equal(options.logger, logger);
  911. assert.equal(options.workingDirectory, "/workspace/project");
  912. return {
  913. commands: [
  914. {
  915. allowedTools: [],
  916. argumentHint: "[scope]",
  917. description: "Review custom changes",
  918. disableNonInteractive: false,
  919. frontmatterKeys: [],
  920. name: "review",
  921. path: "/workspace/project/.zcode/commands/review.md",
  922. rootPath: "/workspace/project/.zcode/commands",
  923. scope: "project",
  924. source: "zcode",
  925. },
  926. ],
  927. diagnostics: [],
  928. totalDiscovered: 1,
  929. } as never;
  930. },
  931. });
  932. assert.equal(exitCode, 0);
  933. assert.match(ctx.stdout.output(), /Custom commands \(1\)/);
  934. assert.match(ctx.stdout.output(), /\/review \[scope\]/);
  935. });
  936. test("zcode login runs OAuth flow and prints the authorization URL", async () => {
  937. const ctx = createContext(["login", "--no-browser"]);
  938. let sawNoBrowser = false;
  939. const exitCode = await run(ctx, {
  940. ...createPromptDeps(),
  941. loginZCodeCli: async (options) => {
  942. sawNoBrowser = options?.noBrowser === true;
  943. await options?.onAuthorizeUrl?.({
  944. authorize_url: "https://chat.z.ai/oauth/authorize?state=state",
  945. expires_at: 1735000000,
  946. flow_id: "flow-1",
  947. poll_interval_sec: 2,
  948. poll_token: "poll-token",
  949. });
  950. return {
  951. configPath: "/home/test/.zcode/v2/model-selection.json",
  952. credentialsPath: "/home/test/.zcode/v2/credentials.json",
  953. model: "zai/glm-5.1",
  954. providerId: "zai",
  955. user: {
  956. user_id: "u_1",
  957. email: "alice@example.com",
  958. name: "Alice",
  959. },
  960. };
  961. },
  962. });
  963. assert.equal(exitCode, 0);
  964. assert.equal(sawNoBrowser, true);
  965. assert.match(ctx.stdout.output(), /Open this URL to sign in/);
  966. assert.match(ctx.stdout.output(), /https:\/\/chat\.z\.ai\/oauth\/authorize/);
  967. assert.match(ctx.stdout.output(), /Login successful as Alice/);
  968. assert.match(
  969. ctx.stdout.output(),
  970. /Model selection: \/home\/test\/\.zcode\/v2\/model-selection\.json/,
  971. );
  972. });
  973. test("zcode logout clears shared OAuth credentials", async () => {
  974. const ctx = createContext(["logout"]);
  975. let logoutCalled = false;
  976. const exitCode = await run(ctx, {
  977. ...createPromptDeps(),
  978. logoutZCodeCli: async () => {
  979. logoutCalled = true;
  980. return {
  981. credentialsPath: "/home/test/.zcode/v2/credentials.json",
  982. };
  983. },
  984. });
  985. assert.equal(exitCode, 0);
  986. assert.equal(logoutCalled, true);
  987. assert.match(ctx.stdout.output(), /Logged out from Coding Plan accounts/);
  988. });
  989. test("parses login and logout slash commands", () => {
  990. assert.deepEqual(parseSlashCommand("/login"), {
  991. args: "",
  992. name: "login",
  993. rawName: "login",
  994. type: "known",
  995. });
  996. assert.deepEqual(parseSlashCommand("/login zai-coding-plan"), {
  997. args: "zai-coding-plan",
  998. name: "login",
  999. rawName: "login",
  1000. type: "known",
  1001. });
  1002. assert.deepEqual(parseSlashCommand("/logout"), {
  1003. args: "",
  1004. name: "logout",
  1005. rawName: "logout",
  1006. type: "known",
  1007. });
  1008. });
  1009. test("command center handles login and logout locally", async () => {
  1010. let loginCalled = false;
  1011. let loginAbortSignal: AbortSignal | undefined;
  1012. let apiKeyCalled = false;
  1013. let logoutCalled = false;
  1014. const emittedEvents: Array<{
  1015. payload?: unknown;
  1016. sessionId?: unknown;
  1017. traceId?: unknown;
  1018. type?: string;
  1019. }> = [];
  1020. const commandCenter = createCommandCenter({
  1021. // 授权链接消息归属当前活动会话(TUI 首帧后已创建 App),但登录流程本身不向模型提交 prompt。
  1022. getApp: async () =>
  1023. ({
  1024. sessionId: "session-login",
  1025. traceId: "trace-login",
  1026. submitPrompt: async () => {
  1027. throw new Error("login must not submit a model prompt");
  1028. },
  1029. }) as never,
  1030. login: async (options) => {
  1031. loginCalled = true;
  1032. loginAbortSignal = options?.abortSignal;
  1033. await options?.onAuthorizeUrl?.({
  1034. authorize_url: "https://chat.z.ai/oauth/authorize?state=state",
  1035. expires_at: 1735000000,
  1036. flow_id: "flow-1",
  1037. poll_interval_sec: 2,
  1038. });
  1039. return {
  1040. configPath: "/home/test/.zcode/v2/model-selection.json",
  1041. credentialsPath: "/home/test/.zcode/v2/credentials.json",
  1042. model: "zai/glm-5.1",
  1043. providerId: "zai",
  1044. user: {
  1045. user_id: "u_1",
  1046. email: "alice@example.com",
  1047. name: "Alice",
  1048. },
  1049. };
  1050. },
  1051. configureApiKey: async (options) => {
  1052. apiKeyCalled = options.providerId === "bigmodel" && options.apiKey === "manual-key";
  1053. return {
  1054. configPath: "/home/test/.zcode/v2/model-selection.json",
  1055. model: "bigmodel/glm-5.1",
  1056. providerId: "bigmodel",
  1057. };
  1058. },
  1059. logout: async () => {
  1060. logoutCalled = true;
  1061. return {
  1062. credentialsPath: "/home/test/.zcode/v2/credentials.json",
  1063. };
  1064. },
  1065. resumeApp: async () => {
  1066. throw new Error("resume should not be called");
  1067. },
  1068. });
  1069. const pickerResult = await commandCenter("/login", {});
  1070. const loginAbort = new AbortController();
  1071. const loginResult = await commandCenter("/login zai-coding-plan", {
  1072. abortSignal: loginAbort.signal,
  1073. onEvent: async (event) => {
  1074. emittedEvents.push(event);
  1075. },
  1076. } as never);
  1077. const apiKeyResult = await commandCenter("/login bigmodel-coding-plan-api-key manual-key", {});
  1078. const logoutResult = await commandCenter("/logout", {});
  1079. assert.equal(pickerResult.selection?.items.length, 4);
  1080. assert.equal(pickerResult.selection?.filterable, false);
  1081. assert.equal(
  1082. pickerResult.selection?.items[0]?.pending?.primary,
  1083. "Waiting for Z.AI authorization",
  1084. );
  1085. assert.equal(pickerResult.selection?.items[2]?.input?.primary, "Enter Z.AI Coding Plan API Key");
  1086. assert.equal(pickerResult.selection?.items[2]?.input?.mask, true);
  1087. assert.equal(loginAbortSignal, loginAbort.signal);
  1088. assert.equal(loginCalled, true);
  1089. assert.equal(apiKeyCalled, true);
  1090. assert.equal(logoutCalled, true);
  1091. assert.equal(emittedEvents[0]?.type, "assistant_message");
  1092. assert.equal(emittedEvents[0]?.sessionId, "session-login");
  1093. assert.equal(emittedEvents[0]?.traceId, "trace-login");
  1094. assert.match(
  1095. String((emittedEvents[0]?.payload as { content?: string } | undefined)?.content),
  1096. /https:\/\/chat\.z\.ai\/oauth\/authorize/,
  1097. );
  1098. assert.match(loginResult.response, /Configured Z\.AI Coding Plan as Alice/);
  1099. assert.match(
  1100. loginResult.response,
  1101. /Model selection: \/home\/test\/\.zcode\/v2\/model-selection\.json/,
  1102. );
  1103. assert.match(apiKeyResult.response, /Configured BigModel Coding Plan/);
  1104. assert.match(logoutResult.response, /Logged out from Coding Plan accounts/);
  1105. });
  1106. test("command center localizes the Coding Plan setup picker", async () => {
  1107. const commandCenter = createCommandCenter({
  1108. getApp: async () => {
  1109. throw new Error("app should not be created");
  1110. },
  1111. getLocale: () => "zh-CN",
  1112. resumeApp: async () => {
  1113. throw new Error("resume should not be called");
  1114. },
  1115. });
  1116. const result = await commandCenter("/login", {});
  1117. assert.equal(result.response, "选择 Coding Plan 提供商的配置方式。");
  1118. assert.equal(result.selection?.title, "配置 Coding Plan");
  1119. assert.equal(result.selection?.prompt, "选择登录或 API key 配置方式。");
  1120. assert.equal(result.selection?.filterable, false);
  1121. assert.match(result.selection?.items[0]?.secondary ?? "", /打开浏览器登录/);
  1122. assert.equal(result.selection?.items[2]?.input?.primary, "输入 Z.AI Coding Plan API Key");
  1123. assert.equal(result.selection?.items[2]?.input?.placeholder, "粘贴 API key");
  1124. });
  1125. test("command center keeps local commands usable before login", async () => {
  1126. let appCreated = false;
  1127. const commandCenter = createCommandCenter({
  1128. getApp: async () => {
  1129. appCreated = true;
  1130. throw new Error("app should not be created before login");
  1131. },
  1132. getLocale: () => "en-US",
  1133. // 登录判定改为“是否存在可选模型”,由注入的检查器回答,命令中心自身不创建 App。
  1134. hasSelectableModels: async () => false,
  1135. resumeApp: async () => {
  1136. throw new Error("resume should not be called");
  1137. },
  1138. setLocale: async (locale) => ({
  1139. locale: locale === "zh-CN" ? "zh-CN" : "en-US",
  1140. requestedLocale: locale,
  1141. }),
  1142. });
  1143. const promptResult = await commandCenter("hello model", {});
  1144. const localeResult = await commandCenter("/locale zh-CN", {});
  1145. assert.equal(promptResult.loginRequired, true);
  1146. assert.match(promptResult.response, /No available models/);
  1147. assert.equal(localeResult.locale, "zh-CN");
  1148. assert.match(localeResult.response, /Locale switched to zh-CN/);
  1149. assert.equal(appCreated, false);
  1150. const zhCommandCenter = createCommandCenter({
  1151. getApp: async () => {
  1152. throw new Error("app should not be created before login");
  1153. },
  1154. getLocale: () => "zh-CN",
  1155. hasSelectableModels: async () => false,
  1156. });
  1157. const zhPromptResult = await zhCommandCenter("hello model", {});
  1158. assert.equal(zhPromptResult.loginRequired, true);
  1159. assert.match(zhPromptResult.response, /没有可用模型/);
  1160. });
  1161. const reviewCustomCommand = {
  1162. content: "Review $ARGUMENTS.",
  1163. metadata: {
  1164. description: "Review custom changes",
  1165. name: "review",
  1166. path: "/workspace/.zcode/commands/review.md",
  1167. scope: "project",
  1168. source: "zcode",
  1169. },
  1170. } as never;
  1171. test("headless prompt submits a resolvable custom command as raw text", async () => {
  1172. // Bug 回归钉:这条过去早退进 command-center(响应 "Run custom command /review …"),
  1173. // 于是只挂在普通 prompt 路径上的 headless dwf 结算等待被整体跳过。现在它必须落到普通
  1174. // prompt 路径,并把**原文**交给 app——展开是 facade 的 customCommandPromptResolver 干的。
  1175. const ctx = createContext(["--prompt", "/review auth"]);
  1176. const base = createPromptDeps();
  1177. const loadedNames: string[] = [];
  1178. let submitted: unknown;
  1179. const exitCode = await run(ctx, {
  1180. ...base,
  1181. createZCodeApp: (options) => {
  1182. const app = base.createZCodeApp?.(options) as {
  1183. submitPrompt: (prompt: unknown, submitOptions?: unknown) => Promise<unknown>;
  1184. };
  1185. return {
  1186. ...app,
  1187. submitPrompt: async (prompt: unknown, submitOptions?: unknown) => {
  1188. submitted = prompt;
  1189. return await app.submitPrompt(prompt, submitOptions);
  1190. },
  1191. } as never;
  1192. },
  1193. loadCustomCommand: async (options) => {
  1194. loadedNames.push(options.name);
  1195. return reviewCustomCommand;
  1196. },
  1197. isReservedSlashCommandName: () => false,
  1198. });
  1199. assert.equal(exitCode, 0);
  1200. // 原文,未展开:CLI 不再本地展开自定义命令。
  1201. assert.equal(submitted, "/review auth");
  1202. assert.deepEqual(loadedNames, ["review"]);
  1203. // command-center 的包装文案彻底不在这条路径上了。
  1204. assert.equal(ctx.stdout.output().includes("Run custom command"), false);
  1205. });
  1206. test("headless prompt keeps a facade-reserved custom command name on the command-center path", async () => {
  1207. // `compress` 是唯一一个 CLI 解析成 unknown、而 facade 的 resolver 又因保留名拒绝展开的
  1208. // 名字。若探测把它判成"可解析",它就会以字面文本 `/compress …` 被当普通 prompt 提交给
  1209. // 模型——静默走错路。这条刻意**不注入**保留名判据,用真实 bootstrap 的那份清单,这样
  1210. // 两侧是否真的同源就是可证的(清单长出新成员时这条会跟着变)。
  1211. const ctx = createContext(["--prompt", "/compress tighten it"]);
  1212. const base = createPromptDeps();
  1213. let submitted: unknown;
  1214. const exitCode = await run(ctx, {
  1215. ...base,
  1216. createZCodeApp: (options) => {
  1217. const app = base.createZCodeApp?.(options) as {
  1218. submitPrompt: (prompt: unknown, submitOptions?: unknown) => Promise<unknown>;
  1219. };
  1220. return {
  1221. ...app,
  1222. submitPrompt: async (prompt: unknown, submitOptions?: unknown) => {
  1223. submitted = prompt;
  1224. return await app.submitPrompt(prompt, submitOptions);
  1225. },
  1226. } as never;
  1227. },
  1228. loadCustomCommand: async () =>
  1229. ({
  1230. content: "Compress $ARGUMENTS.",
  1231. metadata: {
  1232. description: "Compress things",
  1233. name: "compress",
  1234. path: "/workspace/.zcode/commands/compress.md",
  1235. scope: "project",
  1236. source: "zcode",
  1237. },
  1238. }) as never,
  1239. });
  1240. assert.equal(exitCode, 0);
  1241. // command-center 在本地展开了它(今天的行为,逐字保留)。
  1242. assert.match(ctx.stdout.output(), /Run custom command \/compress\./);
  1243. assert.match(ctx.stdout.output(), /Compress tighten it/);
  1244. // 关键:绝不能把原文丢给模型当普通 prompt。
  1245. assert.notEqual(submitted, "/compress tighten it");
  1246. });
  1247. test("TUI custom command expansion hands shell blocks to the model like the app path", () => {
  1248. const { prompt } = expandCliCustomCommandPrompt({
  1249. args: "go !`touch arg-marker`",
  1250. command: {
  1251. content: [
  1252. "Run !`git status`, then report.",
  1253. "```!",
  1254. '"${CLAUDE_PLUGIN_ROOT}/s.sh" "$CLAUDE_PROJECT_DIR" $ARGUMENTS',
  1255. "```",
  1256. ].join("\n"),
  1257. metadata: {
  1258. name: "probe",
  1259. plugin: { dataPath: "/data/p", id: "p@market", name: "p", rootPath: "/plugins/p" },
  1260. scope: "user",
  1261. source: "plugin",
  1262. },
  1263. },
  1264. });
  1265. assert.match(prompt, /the \/probe command file \(user\/plugin\), not from ZCode\./);
  1266. // 代码块结束后原文另起一行;插件变量换成真实路径,工作区变量留给 Bash 环境;参数原样进入。
  1267. assert.ok(prompt.includes("```bash\ngit status\n```\n, then report."));
  1268. assert.ok(
  1269. prompt.includes('```bash\n"/plugins/p/s.sh" "$CLAUDE_PROJECT_DIR" go !`touch arg-marker`\n```'),
  1270. );
  1271. });
  1272. test("headless prompt keeps the Unknown command response for an unresolvable slash name", async () => {
  1273. const ctx = createContext(["--prompt", "/nope please"]);
  1274. const exitCode = await run(ctx, {
  1275. ...createPromptDeps(),
  1276. listCustomCommands: async () =>
  1277. ({
  1278. commands: [reviewCustomCommand.metadata],
  1279. diagnostics: [],
  1280. totalDiscovered: 1,
  1281. }) as never,
  1282. loadCustomCommand: async () => {
  1283. throw new Error("Custom command not found: nope");
  1284. },
  1285. isReservedSlashCommandName: () => false,
  1286. });
  1287. assert.equal(exitCode, 0);
  1288. assert.match(ctx.stdout.output(), /Unknown command: \/nope\./);
  1289. assert.match(ctx.stdout.output(), /Available commands: .*\/review/);
  1290. });
  1291. test("headless prompt propagates a custom command load failure that is not a miss", async () => {
  1292. // 只有 /not found/i 算"不可解析"。读盘失败必须冒泡成进程错误,不能被一句
  1293. // "Unknown command" 盖掉真正的原因。
  1294. const ctx = createContext(["--prompt", "/review auth"]);
  1295. const exitCode = await run(ctx, {
  1296. ...createPromptDeps(),
  1297. loadCustomCommand: async () => {
  1298. throw new Error("EACCES: permission denied, open '/workspace/.zcode/commands/review.md'");
  1299. },
  1300. isReservedSlashCommandName: () => false,
  1301. });
  1302. assert.equal(exitCode, 1);
  1303. assert.match(ctx.stderr.output(), /EACCES: permission denied/);
  1304. assert.equal(ctx.stdout.output().includes("Unknown command"), false);
  1305. });
  1306. test("wires TUI input recall skip into the active app", async () => {
  1307. const ctx = createContext(["tui"]);
  1308. const recalledSkips: Array<number | undefined> = [];
  1309. const exitCode = await run(ctx, {
  1310. ...createPromptDeps(),
  1311. createZCodeApp: () =>
  1312. ({
  1313. sessionId: "session-test",
  1314. traceId: "trace-test",
  1315. runtime: {} as never,
  1316. recallPreviousInputHistory: async (skip?: number) => {
  1317. recalledSkips.push(skip);
  1318. return { text: skip === 1 ? "older project prompt" : "previous project prompt" };
  1319. },
  1320. submitPrompt: async (prompt: string) => ({
  1321. events: [],
  1322. projection: fakeProjection as never,
  1323. response: prompt,
  1324. traceId: "trace-test" as never,
  1325. turnId: "turn-test" as never,
  1326. }),
  1327. }) as never,
  1328. runTui: async (options) => {
  1329. const previous = await options.recallPreviousInput?.();
  1330. const older = await options.recallPreviousInput?.(1);
  1331. assert.equal(previous?.text, "previous project prompt");
  1332. assert.equal(older?.text, "older project prompt");
  1333. return 0;
  1334. },
  1335. });
  1336. assert.equal(exitCode, 0);
  1337. assert.deepEqual(recalledSkips, [undefined, 1]);
  1338. });
  1339. test("wires TUI slash command history recording into the active app", async () => {
  1340. const ctx = createContext(["tui"]);
  1341. const recorded: Array<{ input: unknown; kind: unknown }> = [];
  1342. const exitCode = await run(ctx, {
  1343. ...createPromptDeps(),
  1344. createZCodeApp: () =>
  1345. ({
  1346. getModel: () => "openai/gpt-main",
  1347. listModels: () => [],
  1348. recordInputHistory: async (input: unknown, kind?: unknown) => {
  1349. recorded.push({ input, kind });
  1350. return null;
  1351. },
  1352. sessionId: "session-test",
  1353. traceId: "trace-test",
  1354. runtime: {} as never,
  1355. recallPreviousInputHistory: async () => null,
  1356. submitPrompt: async (prompt: string) => ({
  1357. events: [],
  1358. projection: fakeProjection as never,
  1359. response: prompt,
  1360. traceId: "trace-test" as never,
  1361. turnId: "turn-test" as never,
  1362. }),
  1363. }) as never,
  1364. runTui: async (options) => {
  1365. // 活动 App 在启动屏首帧后创建;此后的 slash 命令写入该 App 的输入历史。
  1366. await loadTuiStartup(options);
  1367. await options.submitPrompt("/help", {
  1368. abortSignal: new AbortController().signal,
  1369. });
  1370. return 0;
  1371. },
  1372. });
  1373. assert.equal(exitCode, 0);
  1374. assert.deepEqual(recorded, [{ input: "/help", kind: "slash_command" }]);
  1375. });
  1376. test("TUI bare skill command lists skills when startup metadata is unavailable", async () => {
  1377. const ctx = createContext([]);
  1378. let appCreationAttempts = 0;
  1379. let listed = false;
  1380. const exitCode = await run(ctx, {
  1381. ...createPromptDeps(),
  1382. createZCodeApp: () => {
  1383. appCreationAttempts += 1;
  1384. throw new Error("app is unavailable");
  1385. },
  1386. cwd: () => "/workspace/project",
  1387. listSkills: async (options) => {
  1388. listed = true;
  1389. assert.equal(options.workingDirectory, "/workspace/project");
  1390. return {
  1391. diagnostics: [],
  1392. skills: [
  1393. {
  1394. description: "Use for demo tasks.",
  1395. directory: "/workspace/project/.zcode/skills/demo",
  1396. frontmatterKeys: ["name", "description"],
  1397. name: "demo-skill",
  1398. path: "/workspace/project/.zcode/skills/demo/SKILL.md",
  1399. rootPath: "/workspace/project/.zcode/skills",
  1400. safeToAutoLoad: true,
  1401. scope: "project",
  1402. source: "zcode",
  1403. },
  1404. ],
  1405. totalDiscovered: 1,
  1406. } as never;
  1407. },
  1408. runTui: async (options) => {
  1409. // 启动元数据在首帧后加载;App 创建失败时降级为空元数据,TUI 仍可进入。
  1410. const startup = await loadTuiStartup(options);
  1411. assert.equal(startup.initialModel, undefined);
  1412. const result = await options.submitPrompt("/skill", {
  1413. abortSignal: new AbortController().signal,
  1414. });
  1415. assert.match(result.response, /Available skills \(1\)/);
  1416. assert.match(result.response, /demo-skill \(project\/zcode\)/);
  1417. return 0;
  1418. },
  1419. });
  1420. assert.equal(exitCode, 0);
  1421. assert.equal(appCreationAttempts, 1);
  1422. assert.equal(listed, true);
  1423. assert.equal(ctx.stderr.output(), "");
  1424. });
  1425. test("command center handles goal commands locally", async () => {
  1426. let submittedPrompt: string | undefined;
  1427. let target: CommandCenterTarget | null = null;
  1428. const commandCenter = createCommandCenter({
  1429. getApp: async () =>
  1430. ({
  1431. sessionId: "session-target",
  1432. traceId: "trace-target",
  1433. readTarget: async () => target,
  1434. setTarget: async ({ objective, status = "active" }) => {
  1435. target = {
  1436. objective,
  1437. sessionID: "session-target",
  1438. status,
  1439. targetID: "target-1",
  1440. time: { created: 1, updated: 1 },
  1441. };
  1442. return target;
  1443. },
  1444. updateTargetStatus: async (status) => {
  1445. if (!target) return null;
  1446. target = { ...target, status, time: { ...target.time, updated: 2 } };
  1447. return target;
  1448. },
  1449. clearTarget: async () => {
  1450. const hadTarget = target !== null;
  1451. target = null;
  1452. return hadTarget;
  1453. },
  1454. submitPrompt: async (prompt: string) => {
  1455. submittedPrompt = prompt;
  1456. return {
  1457. projection: fakeProjection as never,
  1458. response: prompt,
  1459. traceId: "trace-target" as never,
  1460. turnId: "turn-target" as never,
  1461. };
  1462. },
  1463. resume: async () => ({
  1464. appliedMessageCount: 0,
  1465. directory: "/tmp",
  1466. interruptedToolCount: 0,
  1467. messageCount: 0,
  1468. partCount: 0,
  1469. }),
  1470. }) as never,
  1471. getMode: () => "build",
  1472. resumeApp: async () => {
  1473. throw new Error("resume should not be called");
  1474. },
  1475. });
  1476. const set = await commandCenter("/goal Ship target MVP", {});
  1477. const paused = await commandCenter("/goal pause", {});
  1478. const summary = await commandCenter("/goal", {});
  1479. const cleared = await commandCenter("/goal clear", {});
  1480. assert.match(set.response, /Goal active/);
  1481. assert.match(set.response, /Ship target MVP/);
  1482. assert.match(paused.response, /Goal paused/);
  1483. assert.match(summary.response, /Goal paused/);
  1484. assert.match(cleared.response, /Goal cleared/);
  1485. assert.equal(submittedPrompt, undefined);
  1486. });
  1487. test("command center starts target continuation after setting a target", async () => {
  1488. let continued = false;
  1489. const commandCenter = createCommandCenter({
  1490. getApp: async () =>
  1491. ({
  1492. sessionId: "session-target-continue",
  1493. traceId: "trace-target-continue",
  1494. readTarget: async () => null,
  1495. setTarget: async ({ objective, status = "active" }) => ({
  1496. objective,
  1497. sessionID: "session-target-continue",
  1498. status,
  1499. targetID: "target-continue",
  1500. time: { created: 1, updated: 1 },
  1501. }),
  1502. updateTargetStatus: async () => null,
  1503. clearTarget: async () => false,
  1504. continueActiveTarget: async () => {
  1505. continued = true;
  1506. return {
  1507. projection: fakeProjection as never,
  1508. response: "continued target",
  1509. traceId: "trace-target-continue" as never,
  1510. turnId: "turn-target-continue" as never,
  1511. };
  1512. },
  1513. resume: async () => ({
  1514. appliedMessageCount: 0,
  1515. directory: "/tmp",
  1516. interruptedToolCount: 0,
  1517. messageCount: 0,
  1518. partCount: 0,
  1519. }),
  1520. submitPrompt: async () => {
  1521. throw new Error("prompt should not run");
  1522. },
  1523. }) as never,
  1524. getMode: () => "build",
  1525. resumeApp: async () => {
  1526. throw new Error("resume should not be called");
  1527. },
  1528. });
  1529. const result = await commandCenter("/goal Ship target MVP", {
  1530. abortSignal: new AbortController().signal,
  1531. });
  1532. assert.equal(continued, true);
  1533. assert.equal(result.response, "continued target");
  1534. assert.equal(result.traceId, "trace-target-continue");
  1535. });
  1536. test("command center explains skipped goal continuation in plan mode", async () => {
  1537. let continued = false;
  1538. const commandCenter = createCommandCenter({
  1539. getApp: async () =>
  1540. ({
  1541. sessionId: "session-target-plan",
  1542. traceId: "trace-target-plan",
  1543. readTarget: async () => null,
  1544. setTarget: async ({ objective, status = "active" }) => ({
  1545. objective,
  1546. sessionID: "session-target-plan",
  1547. status,
  1548. targetID: "target-plan",
  1549. time: { created: 1, updated: 1 },
  1550. }),
  1551. updateTargetStatus: async () => null,
  1552. clearTarget: async () => false,
  1553. continueActiveTarget: async () => {
  1554. continued = true;
  1555. return null;
  1556. },
  1557. resume: async () => ({
  1558. appliedMessageCount: 0,
  1559. directory: "/tmp",
  1560. interruptedToolCount: 0,
  1561. messageCount: 0,
  1562. partCount: 0,
  1563. }),
  1564. submitPrompt: async () => {
  1565. throw new Error("prompt should not run");
  1566. },
  1567. }) as never,
  1568. getMode: () => "plan",
  1569. resumeApp: async () => {
  1570. throw new Error("resume should not be called");
  1571. },
  1572. });
  1573. const result = await commandCenter("/goal Optimize performance", {
  1574. abortSignal: new AbortController().signal,
  1575. });
  1576. assert.equal(continued, true);
  1577. assert.match(result.response, /Goal active/);
  1578. assert.match(result.response, /Optimize performance/);
  1579. assert.match(result.response, /Plan mode 下已记录 goal,但不会自动继续。/);
  1580. });
  1581. test("command center asks before replacing an existing goal", async () => {
  1582. let setCalled = false;
  1583. const existing: CommandCenterTarget = {
  1584. objective: "Existing target",
  1585. sessionID: "session-target-replace",
  1586. status: "active",
  1587. targetID: "target-existing",
  1588. time: { created: 1, updated: 1 },
  1589. };
  1590. const commandCenter = createCommandCenter({
  1591. getApp: async () =>
  1592. ({
  1593. sessionId: "session-target-replace",
  1594. traceId: "trace-target-replace",
  1595. readTarget: async () => existing,
  1596. setTarget: async () => {
  1597. setCalled = true;
  1598. return existing;
  1599. },
  1600. updateTargetStatus: async () => existing,
  1601. clearTarget: async () => true,
  1602. resume: async () => ({
  1603. appliedMessageCount: 0,
  1604. directory: "/tmp",
  1605. interruptedToolCount: 0,
  1606. messageCount: 0,
  1607. partCount: 0,
  1608. }),
  1609. submitPrompt: async () => {
  1610. throw new Error("prompt should not run");
  1611. },
  1612. }) as never,
  1613. getMode: () => "build",
  1614. resumeApp: async () => {
  1615. throw new Error("resume should not be called");
  1616. },
  1617. });
  1618. const result = await commandCenter("/goal New target", {
  1619. abortSignal: new AbortController().signal,
  1620. });
  1621. assert.equal(setCalled, false);
  1622. assert.equal(result.selection?.title, "Replace Goal");
  1623. assert.equal(result.selection?.items[0]?.command, "/goal replace New target");
  1624. });
  1625. test("TUI startup migration failures return before entering fullscreen UI", async () => {
  1626. const ctx = createContext(["tui"]);
  1627. let mainUiMounted = false;
  1628. const migrationError = new Error(
  1629. "SQLite migration checksum mismatch for 0001_base_session_store",
  1630. );
  1631. migrationError.name = "SqliteSessionMigrationError";
  1632. const exitCode = await run(ctx, {
  1633. ...createPromptDeps(),
  1634. createZCodeApp: () => {
  1635. throw migrationError;
  1636. },
  1637. // 新启动流程先绘制启动屏,再在 loadStartupOptions 中创建运行时;真实 runTui 在启动数据
  1638. // 加载失败时销毁 renderer 并把错误抛回 CLI,因此主界面不会挂载,错误在终端恢复后输出。
  1639. runTui: async (options) => {
  1640. await options.loadStartupOptions?.();
  1641. mainUiMounted = true;
  1642. return 0;
  1643. },
  1644. });
  1645. assert.equal(exitCode, 1);
  1646. assert.equal(mainUiMounted, false);
  1647. assert.match(ctx.stderr.output(), /SQLite migration checksum mismatch/);
  1648. assert.equal(ctx.stdout.output(), "");
  1649. });
  1650. test("detects TUI invocations before loading the runtime", () => {
  1651. assert.equal(isTuiInvocation([]), true);
  1652. assert.equal(isTuiInvocation(["tui"]), true);
  1653. assert.equal(isTuiInvocation(["--mode", "build"]), true);
  1654. assert.equal(isTuiInvocation(["--resume", "session-test", "tui"]), true);
  1655. assert.equal(isTuiInvocation(["acp"]), false);
  1656. assert.equal(isTuiInvocation(["--help"]), false);
  1657. assert.equal(isTuiInvocation(["tui", "--help"]), false);
  1658. assert.equal(isTuiInvocation(["--prompt", "hello"]), false);
  1659. assert.equal(isTuiInvocation(["missing"]), false);
  1660. assert.equal(isTuiInvocation(["--wat"]), false);
  1661. });
  1662. test("buffers TUI stderr and drops it on clean restore", () => {
  1663. const stderr = createWriteStream();
  1664. const interceptor = interceptTuiStderr(stderr);
  1665. stderr.write("runtime warning\n");
  1666. assert.equal(stderr.output(), "");
  1667. assert.equal(interceptor.bufferedOutput, "runtime warning\n");
  1668. interceptor.restore();
  1669. assert.equal(stderr.output(), "");
  1670. });
  1671. test("flushes buffered TUI stderr when startup fails", async () => {
  1672. const stderr = createWriteStream();
  1673. const interceptor = interceptTuiStderr(stderr);
  1674. let callbackCalled = false;
  1675. await new Promise<void>((resolve) => {
  1676. stderr.write(Buffer.from("startup failed\n"), () => {
  1677. callbackCalled = true;
  1678. resolve();
  1679. });
  1680. });
  1681. assert.equal(callbackCalled, true);
  1682. assert.equal(stderr.output(), "");
  1683. interceptor.restore({ flush: true });
  1684. assert.equal(stderr.output(), "startup failed\n");
  1685. });
  1686. test("lets controlled TUI errors bypass raw stderr interception", () => {
  1687. const stderr = createWriteStream();
  1688. const interceptor = interceptTuiStderr(stderr);
  1689. interceptor.passthrough.write("TUI requires an interactive terminal.\n");
  1690. stderr.write("runtime warning\n");
  1691. assert.equal(stderr.output(), "TUI requires an interactive terminal.\n");
  1692. assert.equal(interceptor.bufferedOutput, "runtime warning\n");
  1693. interceptor.restore();
  1694. });
  1695. test("filters the known SQLite experimental warning from stderr", () => {
  1696. const stderr = createWriteStream();
  1697. const interceptor = interceptKnownRuntimeWarnings(stderr);
  1698. stderr.write(
  1699. "(node:59658) ExperimentalWarning: SQLite is an experimental feature and might change at any time\n",
  1700. );
  1701. stderr.write(
  1702. "(Use `zcode-darwin-arm64 --trace-warnings ...` to show where the warning was created)\n",
  1703. );
  1704. stderr.write("real error\n");
  1705. assert.equal(stderr.output(), "real error\n");
  1706. assert.equal(interceptor.suppressedCount, 2);
  1707. interceptor.restore();
  1708. });
  1709. test("filters the known module.register deprecation warning from stderr", () => {
  1710. const stderr = createWriteStream();
  1711. const interceptor = interceptKnownRuntimeWarnings(stderr);
  1712. stderr.write(
  1713. "(node:69362) [DEP0205] DeprecationWarning: `module.register()` is deprecated. Use `module.registerHooks()` instead.\n",
  1714. );
  1715. stderr.write("(Use `node --trace-deprecation ...` to show where the warning was created)\n");
  1716. stderr.write("help text stderr\n");
  1717. assert.equal(stderr.output(), "help text stderr\n");
  1718. assert.equal(interceptor.suppressedCount, 2);
  1719. interceptor.restore();
  1720. });
  1721. test("filters the known insecure Node TLS environment warning from stderr", () => {
  1722. const stderr = createWriteStream();
  1723. const interceptor = interceptKnownRuntimeWarnings(stderr);
  1724. stderr.write(
  1725. "(node:65726) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.\n",
  1726. );
  1727. stderr.write("provider error remains visible\n");
  1728. assert.equal(stderr.output(), "provider error remains visible\n");
  1729. assert.equal(interceptor.suppressedCount, 1);
  1730. interceptor.restore();
  1731. });
  1732. test("filters the known AI SDK Anthropic thinking budget warnings from stderr", () => {
  1733. const stderr = createWriteStream();
  1734. const interceptor = interceptKnownRuntimeWarnings(stderr);
  1735. stderr.write(
  1736. "AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.\n",
  1737. );
  1738. stderr.write(
  1739. 'AI SDK Warning (anthropic.messages / glm-5.1): The feature "extended thinking" is used in a compatibility mode. thinking budget is required when thinking is enabled. using default budget of 1024 tokens.\n',
  1740. );
  1741. stderr.write("AI SDK Warning (openai.responses / gpt-test): unrelated warning\n");
  1742. stderr.write("runtime error remains visible\n");
  1743. assert.equal(
  1744. stderr.output(),
  1745. "AI SDK Warning (openai.responses / gpt-test): unrelated warning\nruntime error remains visible\n",
  1746. );
  1747. assert.equal(interceptor.suppressedCount, 2);
  1748. interceptor.restore();
  1749. });
  1750. test("keeps unrelated stderr while filtering runtime warnings", () => {
  1751. const stderr = createWriteStream();
  1752. const interceptor = interceptKnownRuntimeWarnings(stderr);
  1753. stderr.write("(node:59658) ExperimentalWarning: Something else happened\n");
  1754. stderr.write(
  1755. "(node:59658) ExperimentalWarning: SQLite is an experimental feature and might change at any time\n",
  1756. );
  1757. stderr.write("still important\n");
  1758. assert.equal(
  1759. stderr.output(),
  1760. "(node:59658) ExperimentalWarning: Something else happened\nstill important\n",
  1761. );
  1762. assert.equal(interceptor.suppressedCount, 1);
  1763. interceptor.restore();
  1764. });
  1765. test("wires TUI approval requests into the runtime permission broker", async () => {
  1766. const ctx = createContext(["tui"]);
  1767. let approvalSeen = false;
  1768. const exitCode = await run(ctx, {
  1769. ...createPromptDeps(),
  1770. createZCodeApp: (options) => {
  1771. return {
  1772. listModels: selectableTestModels,
  1773. sessionId: "session-test",
  1774. traceId: "trace-test",
  1775. runtime: {} as never,
  1776. submitPrompt: async () => {
  1777. const permission = await options?.permissionBroker?.requestPermission(
  1778. createPermissionRequest(),
  1779. {
  1780. signal: new AbortController().signal,
  1781. },
  1782. );
  1783. return {
  1784. events: [],
  1785. projection: fakeProjection as never,
  1786. response: `permission ${permission?.decision}`,
  1787. traceId: "trace-test" as never,
  1788. turnId: "turn-test" as never,
  1789. };
  1790. },
  1791. } as never;
  1792. },
  1793. runTui: async (options) => {
  1794. // TUI 挂载时登记一次审批入口;提交不再携带单次回调。
  1795. const unregister = options.registerPermissionRequester!(async (request) => {
  1796. approvalSeen = true;
  1797. assert.equal(request.toolName, "Bash");
  1798. return {
  1799. decision: "allow",
  1800. reason: "approved by tui test",
  1801. };
  1802. });
  1803. const result = await options.submitPrompt("needs approval", {
  1804. abortSignal: new AbortController().signal,
  1805. });
  1806. assert.equal(result.response, "permission allow");
  1807. unregister();
  1808. return 0;
  1809. },
  1810. });
  1811. assert.equal(exitCode, 0);
  1812. assert.equal(approvalSeen, true);
  1813. });
  1814. test("wires TUI sendInput approval requests into the runtime permission broker", async () => {
  1815. const ctx = createContext(["tui"]);
  1816. let approvalSeen = false;
  1817. const exitCode = await run(ctx, {
  1818. ...createPromptDeps(),
  1819. createZCodeApp: (options) => {
  1820. return {
  1821. sessionId: "session-test",
  1822. traceId: "trace-test",
  1823. runtime: {} as never,
  1824. sendInput: async () => {
  1825. const permission = await options?.permissionBroker?.requestPermission(
  1826. createPermissionRequest(),
  1827. {
  1828. signal: new AbortController().signal,
  1829. },
  1830. );
  1831. return {
  1832. kind: "started_turn",
  1833. result: {
  1834. events: [],
  1835. projection: fakeProjection as never,
  1836. response: `permission ${permission?.decision}`,
  1837. traceId: "trace-test" as never,
  1838. turnId: "turn-test" as never,
  1839. },
  1840. };
  1841. },
  1842. submitPrompt: async () => {
  1843. throw new Error("sendInput should handle this prompt");
  1844. },
  1845. } as never;
  1846. },
  1847. runTui: async (options) => {
  1848. const unregister = options.registerPermissionRequester!(async (request) => {
  1849. approvalSeen = true;
  1850. assert.equal(request.toolName, "Bash");
  1851. return {
  1852. decision: "allow",
  1853. reason: "approved by tui sendInput test",
  1854. };
  1855. });
  1856. const result = await options.sendInput!("needs approval while busy", {
  1857. abortSignal: new AbortController().signal,
  1858. });
  1859. assert.equal(result.kind, "started_turn");
  1860. assert.equal(result.result.response, "permission allow");
  1861. unregister();
  1862. return 0;
  1863. },
  1864. });
  1865. assert.equal(exitCode, 0);
  1866. assert.equal(approvalSeen, true);
  1867. });
  1868. // 回归:审批入口原先只在单次提交内有效,回合之外的询问(后台会话、通知驱动的回合)被直接拒绝。
  1869. test("routes approvals raised outside any submit to the mounted TUI and fails closed after unmount", async () => {
  1870. const ctx = createContext(["tui"]);
  1871. let broker: NonNullable<ZCodeAppOptions["permissionBroker"]> | undefined;
  1872. const seen: string[] = [];
  1873. const exitCode = await run(ctx, {
  1874. ...createPromptDeps(),
  1875. createZCodeApp: (options) => {
  1876. broker = options?.permissionBroker;
  1877. return {
  1878. listModels: selectableTestModels,
  1879. sessionId: "session-test",
  1880. traceId: "trace-test",
  1881. runtime: {} as never,
  1882. submitPrompt: async () => ({
  1883. events: [],
  1884. projection: fakeProjection as never,
  1885. response: "created",
  1886. traceId: "trace-test" as never,
  1887. turnId: "turn-test" as never,
  1888. }),
  1889. } as never;
  1890. },
  1891. runTui: async (options) => {
  1892. const background = { ...(createPermissionRequest() as object), sessionId: "sess_background" };
  1893. const first = options.registerPermissionRequester!(async (request) => {
  1894. seen.push(`first:${request.sessionId}`);
  1895. return { decision: "deny", reason: "first" };
  1896. });
  1897. // 首次提交建出 App;提交结束后再询问,模拟后台会话在发起者回合之外请求审批。
  1898. await options.submitPrompt("create background work", {
  1899. abortSignal: new AbortController().signal,
  1900. });
  1901. const outside = await broker!.requestPermission(background as never);
  1902. assert.equal(outside.decision, "deny");
  1903. assert.equal(outside.reason, "first");
  1904. // 重新挂载:新入口先登记,旧入口的迟到注销不能把它清掉。
  1905. const second = options.registerPermissionRequester!(async (request) => {
  1906. seen.push(`second:${request.sessionId}`);
  1907. return { decision: "allow", reason: "second" };
  1908. });
  1909. first();
  1910. assert.equal((await broker!.requestPermission(background as never)).decision, "allow");
  1911. second();
  1912. const closed = await broker!.requestPermission(background as never);
  1913. assert.equal(closed.decision, "deny");
  1914. assert.match(closed.reason ?? "", /No interactive approval handler/);
  1915. return 0;
  1916. },
  1917. });
  1918. assert.equal(exitCode, 0);
  1919. assert.deepEqual(seen, ["first:sess_background", "second:sess_background"]);
  1920. });
  1921. test("wires TUI mode display and switching into runtime config", async () => {
  1922. const ctx = createContext(["--mode", "plan", "tui"]);
  1923. let appMode: "plan" | "build" | "edit" | "yolo" | "auto" = "build";
  1924. const runtimeModeUpdates: string[] = [];
  1925. const exitCode = await run(ctx, {
  1926. ...createPromptDeps(),
  1927. createZCodeApp: (options) => {
  1928. // 启动屏首帧后按 CLI --mode 创建 App;此后的模式切换都作用于活动 App。
  1929. assert.equal(options?.runtimeConfig?.mode, "plan");
  1930. appMode = options?.runtimeConfig?.mode ?? "build";
  1931. return {
  1932. getMode: () => appMode,
  1933. listModels: selectableTestModels,
  1934. sessionId: "session-test",
  1935. setMode: async (mode: typeof appMode) => {
  1936. runtimeModeUpdates.push(mode);
  1937. const previousMode = appMode;
  1938. appMode = mode;
  1939. return {
  1940. mode: appMode,
  1941. previousMode,
  1942. traceId: "trace-test",
  1943. };
  1944. },
  1945. traceId: "trace-test",
  1946. runtime: {
  1947. updateConfig: (patch: { mode?: typeof appMode }) => {
  1948. if (patch.mode) {
  1949. runtimeModeUpdates.push(patch.mode);
  1950. appMode = patch.mode;
  1951. }
  1952. },
  1953. } as never,
  1954. submitPrompt: async (prompt: string) => ({
  1955. events: [],
  1956. projection: fakeProjection as never,
  1957. response: prompt,
  1958. traceId: "trace-test" as never,
  1959. turnId: "turn-test" as never,
  1960. }),
  1961. } as never;
  1962. },
  1963. runTui: async (options) => {
  1964. const startup = await loadTuiStartup(options);
  1965. assert.equal(startup.initialMode, "plan");
  1966. const firstSwitch = await options.submitPrompt("/mode yolo", {
  1967. abortSignal: new AbortController().signal,
  1968. });
  1969. assert.equal(firstSwitch.mode, "yolo");
  1970. const promptResult = await options.submitPrompt("hello mode", {
  1971. abortSignal: new AbortController().signal,
  1972. });
  1973. assert.equal(promptResult.mode, "yolo");
  1974. const liveSwitch = await options.submitPrompt("/mode build", {
  1975. abortSignal: new AbortController().signal,
  1976. });
  1977. assert.equal(liveSwitch.mode, "build");
  1978. const shortcutSwitch = await options.setMode!("plan");
  1979. assert.equal(shortcutSwitch.mode, "plan");
  1980. return 0;
  1981. },
  1982. });
  1983. assert.equal(exitCode, 0);
  1984. assert.deepEqual(runtimeModeUpdates, ["yolo", "build", "plan"]);
  1985. });
  1986. test("wires TUI edit mode switching into runtime config", async () => {
  1987. const ctx = createContext(["--mode", "build", "tui"]);
  1988. let appMode: "plan" | "build" | "edit" | "yolo" | "auto" = "build";
  1989. const runtimeModeUpdates: string[] = [];
  1990. const exitCode = await run(ctx, {
  1991. ...createPromptDeps(),
  1992. createZCodeApp: (options) => {
  1993. // 启动屏首帧后按 CLI --mode 创建 App;edit 切换经活动 App 的 runtime config 生效。
  1994. assert.equal(options?.runtimeConfig?.mode, "build");
  1995. appMode = options?.runtimeConfig?.mode ?? "build";
  1996. return {
  1997. getMode: () => appMode,
  1998. listModels: selectableTestModels,
  1999. sessionId: "session-edit-test",
  2000. traceId: "trace-edit-test",
  2001. runtime: {
  2002. updateConfig: (patch: { mode?: typeof appMode }) => {
  2003. if (patch.mode) {
  2004. runtimeModeUpdates.push(patch.mode);
  2005. appMode = patch.mode;
  2006. }
  2007. },
  2008. } as never,
  2009. submitPrompt: async (prompt: string) => ({
  2010. events: [],
  2011. projection: fakeProjection as never,
  2012. response: prompt,
  2013. traceId: "trace-edit-test" as never,
  2014. turnId: "turn-edit-test" as never,
  2015. }),
  2016. } as never;
  2017. },
  2018. runTui: async (options) => {
  2019. const startup = await loadTuiStartup(options);
  2020. assert.equal(startup.initialMode, "build");
  2021. const liveSwitch = await options.submitPrompt("/mode edit", {
  2022. abortSignal: new AbortController().signal,
  2023. });
  2024. assert.equal(liveSwitch.mode, "edit");
  2025. const promptResult = await options.submitPrompt("hello edit mode", {
  2026. abortSignal: new AbortController().signal,
  2027. });
  2028. assert.equal(promptResult.mode, "edit");
  2029. return 0;
  2030. },
  2031. });
  2032. assert.equal(exitCode, 0);
  2033. assert.deepEqual(runtimeModeUpdates, ["edit"]);
  2034. });
  2035. test("wires TUI model command into app server state", async () => {
  2036. const ctx = createContext(["tui"]);
  2037. // 模型目录改为协议 Model Option(ref + 推理档位),/model 切换提交完整的结构化选择。
  2038. const modelOptions = [
  2039. createTestModelOption("openai", "gpt-main", {
  2040. defaultLevel: "high",
  2041. label: "Main",
  2042. levels: ["low", "high"],
  2043. }),
  2044. createTestModelOption("openai", "gpt-lite", {
  2045. defaultLevel: "low",
  2046. label: "Lite",
  2047. levels: ["low", "high"],
  2048. }),
  2049. ];
  2050. let current: ModelSelection = {
  2051. providerId: "openai",
  2052. modelId: "gpt-main",
  2053. options: { reasoningLevel: "high" },
  2054. };
  2055. const currentModelId = () => `${current.providerId}/${current.modelId}`;
  2056. const requestedSelections: unknown[] = [];
  2057. const savedDefaults: ModelSelection[] = [];
  2058. const exitCode = await run(ctx, {
  2059. ...createPromptDeps(),
  2060. startProcessProviderRegistryRuntime: async () =>
  2061. ({
  2062. dispose: () => {},
  2063. modelSelectionConfigRepository: {
  2064. dispose: () => {},
  2065. read: async () => undefined,
  2066. saveConfiguredDefault: async (selection: ModelSelection) => {
  2067. savedDefaults.push(selection);
  2068. },
  2069. },
  2070. runtime: { registryService: {} },
  2071. }) as never,
  2072. createZCodeApp: () => {
  2073. return {
  2074. getCurrentModelOption: () =>
  2075. modelOptions.find(
  2076. ({ ref }) => ref.providerId === current.providerId && ref.modelId === current.modelId,
  2077. ),
  2078. getModel: currentModelId,
  2079. getThoughtLevel: () => current.options?.reasoningLevel,
  2080. listModels: () => modelOptions,
  2081. sessionId: "session-test",
  2082. setModel: async (selection: ModelSelection) => {
  2083. requestedSelections.push(selection);
  2084. const previousModel = currentModelId();
  2085. current = selection;
  2086. return {
  2087. model: currentModelId(),
  2088. previousModel,
  2089. thoughtLevel: selection.options?.reasoningLevel,
  2090. traceId: "trace-test",
  2091. };
  2092. },
  2093. traceId: "trace-test",
  2094. runtime: {} as never,
  2095. submitPrompt: async () => ({
  2096. events: [],
  2097. projection: fakeProjection as never,
  2098. response: `using ${currentModelId()}`,
  2099. traceId: "trace-test" as never,
  2100. turnId: "turn-test" as never,
  2101. }),
  2102. } as never;
  2103. },
  2104. runTui: async (options) => {
  2105. const startup = await loadTuiStartup(options);
  2106. assert.equal(startup.initialModel, "openai/gpt-main");
  2107. assert.equal(startup.initialThoughtLevel, "high");
  2108. assert.deepEqual(startup.modelOptions, modelOptions);
  2109. const listed = await options.submitPrompt("/model", {
  2110. abortSignal: new AbortController().signal,
  2111. });
  2112. assert.match(listed.response, /Current model: openai\/gpt-main/);
  2113. assert.equal(listed.model, "openai/gpt-main");
  2114. assert.equal(listed.thoughtLevel, "high");
  2115. const switched = await options.submitPrompt("/model openai/gpt-lite", {
  2116. abortSignal: new AbortController().signal,
  2117. });
  2118. assert.equal(switched.response, "Model switched to openai/gpt-lite (low).");
  2119. assert.equal(switched.model, "openai/gpt-lite");
  2120. assert.equal(switched.thoughtLevel, "low");
  2121. const promptResult = await options.submitPrompt("hello model", {
  2122. abortSignal: new AbortController().signal,
  2123. });
  2124. assert.equal(promptResult.response, "using openai/gpt-lite");
  2125. assert.equal(promptResult.model, "openai/gpt-lite");
  2126. assert.equal(promptResult.thoughtLevel, "low");
  2127. return 0;
  2128. },
  2129. });
  2130. const expectedSelection = {
  2131. providerId: "openai",
  2132. modelId: "gpt-lite",
  2133. options: { reasoningLevel: "low" },
  2134. };
  2135. assert.equal(exitCode, 0);
  2136. assert.deepEqual(requestedSelections, [expectedSelection]);
  2137. // 用户主动切换成功后,完整选择同步保存为新会话默认值。
  2138. assert.deepEqual(savedDefaults, [expectedSelection]);
  2139. });
  2140. test("wires TUI effort command into app server state", async () => {
  2141. const ctx = createContext(["tui"]);
  2142. let thoughtLevel = "medium";
  2143. const requestedLevels: string[] = [];
  2144. const exitCode = await run(ctx, {
  2145. ...createPromptDeps(),
  2146. createZCodeApp: () => {
  2147. return {
  2148. getModel: () => "openai/gpt-main",
  2149. getThoughtLevel: () => thoughtLevel,
  2150. listModels: () => [createTestModelOption("openai", "gpt-main", { label: "Main" })],
  2151. listThoughtLevels: () => ["low", "medium", "high"],
  2152. sessionId: "session-test",
  2153. setThoughtLevel: async (level: string) => {
  2154. requestedLevels.push(level);
  2155. const previousThoughtLevel = thoughtLevel;
  2156. thoughtLevel = level;
  2157. return {
  2158. previousThoughtLevel,
  2159. thoughtLevel,
  2160. traceId: "trace-test",
  2161. };
  2162. },
  2163. traceId: "trace-test",
  2164. runtime: {} as never,
  2165. submitPrompt: async () => ({
  2166. events: [],
  2167. projection: fakeProjection as never,
  2168. response: `effort ${thoughtLevel}`,
  2169. traceId: "trace-test" as never,
  2170. turnId: "turn-test" as never,
  2171. }),
  2172. } as never;
  2173. },
  2174. runTui: async (options) => {
  2175. const startup = await loadTuiStartup(options);
  2176. assert.equal(startup.initialThoughtLevel, "medium");
  2177. assert.deepEqual(startup.effortOptions, [
  2178. { id: "low", label: "low" },
  2179. { id: "medium", label: "medium" },
  2180. { id: "high", label: "high" },
  2181. ]);
  2182. const listed = await options.submitPrompt("/effort", {
  2183. abortSignal: new AbortController().signal,
  2184. });
  2185. assert.equal(listed.selection, undefined);
  2186. assert.match(listed.response, /Current reasoning effort: medium/);
  2187. assert.match(listed.response, /- high/);
  2188. assert.equal(listed.thoughtLevel, "medium");
  2189. const switched = await options.submitPrompt("/variant high", {
  2190. abortSignal: new AbortController().signal,
  2191. });
  2192. assert.match(switched.response, /Reasoning effort switched to high/);
  2193. assert.deepEqual(switched.effortOptions, startup.effortOptions);
  2194. assert.equal(switched.thoughtLevel, "high");
  2195. const promptResult = await options.submitPrompt("hello effort", {
  2196. abortSignal: new AbortController().signal,
  2197. });
  2198. assert.equal(promptResult.response, "effort high");
  2199. assert.equal(promptResult.thoughtLevel, "high");
  2200. return 0;
  2201. },
  2202. });
  2203. assert.equal(exitCode, 0);
  2204. assert.deepEqual(requestedLevels, ["high"]);
  2205. });
  2206. test("wires TUI fork command into a new active app", async () => {
  2207. const ctx = createContext(["tui"]);
  2208. const createdSessionIds: Array<string | undefined> = [];
  2209. let forkTarget: string | undefined;
  2210. const exitCode = await run(ctx, {
  2211. ...createPromptDeps(),
  2212. createZCodeApp: (options) => {
  2213. const appSessionId = options?.sessionId ?? "sess_parent";
  2214. createdSessionIds.push(options?.sessionId);
  2215. return {
  2216. forkFromCheckpoint: async (forkOptions?: { targetCheckpointId?: string }) => {
  2217. forkTarget = forkOptions?.targetCheckpointId;
  2218. return {
  2219. checkpoint: {} as never,
  2220. copiedMessageCount: 1,
  2221. forkedSessionId: "sess_child",
  2222. restoredFiles: [],
  2223. response: "Forked session sess_child",
  2224. };
  2225. },
  2226. listModels: selectableTestModels,
  2227. sessionId: appSessionId,
  2228. traceId: "trace-test",
  2229. runtime: {} as never,
  2230. submitPrompt: async (prompt: string) => ({
  2231. events: [],
  2232. projection: fakeProjection as never,
  2233. response: `${appSessionId}:${prompt}`,
  2234. traceId: "trace-test" as never,
  2235. turnId: "turn-test" as never,
  2236. }),
  2237. } as never;
  2238. },
  2239. runTui: async (options) => {
  2240. const forked = await options.submitPrompt("/fork checkpoint_1", {
  2241. abortSignal: new AbortController().signal,
  2242. });
  2243. assert.match(forked.response, /Switched to forked session sess_child/);
  2244. const promptResult = await options.submitPrompt("hello fork", {
  2245. abortSignal: new AbortController().signal,
  2246. });
  2247. assert.equal(promptResult.response, "sess_child:hello fork");
  2248. return 0;
  2249. },
  2250. });
  2251. assert.equal(exitCode, 0);
  2252. assert.equal(forkTarget, "checkpoint_1");
  2253. assert.deepEqual(createdSessionIds, [undefined, "sess_child"]);
  2254. });
  2255. test("wires TUI new command into a fresh active app", async () => {
  2256. const ctx = createContext(["tui"]);
  2257. const createdSessionIds: Array<string | undefined> = [];
  2258. const closedSessionIds: string[] = [];
  2259. const exitCode = await run(ctx, {
  2260. ...createPromptDeps(),
  2261. createZCodeApp: (options) => {
  2262. assert.equal(options?.standaloneSessionControl, true);
  2263. const appSessionId = options?.sessionId ?? `sess_new_${createdSessionIds.length}`;
  2264. createdSessionIds.push(options?.sessionId);
  2265. return {
  2266. listModels: selectableTestModels,
  2267. sessionId: appSessionId,
  2268. traceId: `trace_${appSessionId}`,
  2269. runtime: {} as never,
  2270. close: async () => {
  2271. closedSessionIds.push(appSessionId);
  2272. },
  2273. submitPrompt: async (prompt: string) => ({
  2274. events: [],
  2275. projection: fakeProjection as never,
  2276. response: `${appSessionId}:${prompt}`,
  2277. traceId: `trace_${appSessionId}` as never,
  2278. turnId: "turn-test" as never,
  2279. }),
  2280. } as never;
  2281. },
  2282. runTui: async (options) => {
  2283. const initial = await options.submitPrompt("hello first", {
  2284. abortSignal: new AbortController().signal,
  2285. });
  2286. assert.equal(initial.response, "sess_new_0:hello first");
  2287. const created = await options.submitPrompt("/new", {
  2288. abortSignal: new AbortController().signal,
  2289. });
  2290. assert.match(created.response, /Started new session sess_new_1/);
  2291. assert.equal(created.sessionId, "sess_new_1");
  2292. assert.equal(created.resetSessionProjection, true);
  2293. const promptResult = await options.submitPrompt("hello new", {
  2294. abortSignal: new AbortController().signal,
  2295. });
  2296. assert.equal(promptResult.response, "sess_new_1:hello new");
  2297. return 0;
  2298. },
  2299. });
  2300. assert.equal(exitCode, 0);
  2301. assert.deepEqual(createdSessionIds, [undefined, undefined]);
  2302. assert.deepEqual(closedSessionIds, ["sess_new_0", "sess_new_1"]);
  2303. });
  2304. test("keeps shared telemetry alive across TUI session replacement and shuts it down once", async () => {
  2305. const ctx = createContext(["tui"]);
  2306. let telemetryPrepareCount = 0;
  2307. let telemetryShutdownCount = 0;
  2308. const exitCode = await run(ctx, {
  2309. ...createPromptDeps(),
  2310. prepareZCodeTelemetryEnv: async (env) => {
  2311. telemetryPrepareCount += 1;
  2312. return env;
  2313. },
  2314. shutdownZCodeTelemetry: async () => {
  2315. telemetryShutdownCount += 1;
  2316. },
  2317. runTui: async (options) => {
  2318. await options.submitPrompt("hello first", {
  2319. abortSignal: new AbortController().signal,
  2320. });
  2321. await options.submitPrompt("/new", {
  2322. abortSignal: new AbortController().signal,
  2323. });
  2324. assert.equal(telemetryShutdownCount, 0);
  2325. return 0;
  2326. },
  2327. });
  2328. assert.equal(exitCode, 0);
  2329. assert.equal(telemetryPrepareCount, 2);
  2330. assert.equal(telemetryShutdownCount, 1);
  2331. });
  2332. test("reuses provider endpoint routing when TUI replaces its active session", async () => {
  2333. const ctx = createContext(["tui"]);
  2334. const providerEndpointRoutingPort = {
  2335. async resolve(url: string) {
  2336. return { routed: false, url };
  2337. },
  2338. };
  2339. let routingFactoryCalls = 0;
  2340. let createdApps = 0;
  2341. const exitCode = await run(ctx, {
  2342. ...createPromptDeps(),
  2343. createProviderEndpointRoutingPort: () => {
  2344. routingFactoryCalls += 1;
  2345. return providerEndpointRoutingPort;
  2346. },
  2347. createZCodeApp: (options) => {
  2348. assert.equal(options?.providerEndpointRoutingPort, providerEndpointRoutingPort);
  2349. createdApps += 1;
  2350. return {
  2351. close: async () => {},
  2352. runtime: {} as never,
  2353. sessionId: `session-routing-tui-${createdApps}`,
  2354. submitPrompt: async (prompt: string) => ({
  2355. events: [],
  2356. projection: fakeProjection as never,
  2357. response: prompt,
  2358. traceId: `trace-routing-tui-${createdApps}` as never,
  2359. turnId: "turn-routing-tui" as never,
  2360. }),
  2361. traceId: `trace-routing-tui-${createdApps}`,
  2362. } as never;
  2363. },
  2364. runTui: async (options) => {
  2365. await options.submitPrompt("first", {
  2366. abortSignal: new AbortController().signal,
  2367. });
  2368. await options.submitPrompt("/new", {
  2369. abortSignal: new AbortController().signal,
  2370. });
  2371. return 0;
  2372. },
  2373. });
  2374. assert.equal(exitCode, 0);
  2375. assert.equal(createdApps, 2);
  2376. assert.equal(routingFactoryCalls, 1);
  2377. });
  2378. test("closes the active TUI app on process shutdown signals", async () => {
  2379. const ctx = createContext(["tui"]);
  2380. const shutdownProcess = createTestShutdownProcess("darwin");
  2381. const exitDeferred = createDeferred<number>();
  2382. let closeCount = 0;
  2383. let telemetryShutdownCount = 0;
  2384. const exitCode = await run(ctx, {
  2385. ...createPromptDeps(),
  2386. prepareZCodeTelemetryEnv: async (env) => env,
  2387. shutdownZCodeTelemetry: async () => {
  2388. telemetryShutdownCount += 1;
  2389. },
  2390. createZCodeApp: () =>
  2391. ({
  2392. close: async () => {
  2393. closeCount += 1;
  2394. },
  2395. getModel: () => "openai/gpt-test",
  2396. getThoughtLevel: () => "medium",
  2397. runtime: {} as never,
  2398. sessionId: "session-test",
  2399. submitPrompt: async (prompt: string) => ({
  2400. events: [],
  2401. projection: fakeProjection as never,
  2402. response: prompt,
  2403. traceId: "trace-test" as never,
  2404. turnId: "turn-test" as never,
  2405. }),
  2406. traceId: "trace-test",
  2407. }) as never,
  2408. exitProcess: (code) => {
  2409. exitDeferred.resolve(code);
  2410. },
  2411. runTui: async (options) => {
  2412. await options.submitPrompt("hello", {
  2413. abortSignal: new AbortController().signal,
  2414. });
  2415. shutdownProcess.emitSignal("SIGHUP");
  2416. assert.equal(await exitDeferred.promise, 129);
  2417. return 0;
  2418. },
  2419. shutdownProcess,
  2420. });
  2421. assert.equal(exitCode, 0);
  2422. assert.equal(closeCount, 1);
  2423. assert.equal(telemetryShutdownCount, 1);
  2424. });
  2425. test("parses built-in slash commands outside the TUI", () => {
  2426. assert.deepEqual(parseSlashCommand("hello"), null);
  2427. assert.deepEqual(parseSlashCommand("/compact keep files"), {
  2428. args: "keep files",
  2429. name: "compact",
  2430. rawName: "compact",
  2431. type: "known",
  2432. });
  2433. assert.deepEqual(parseSlashCommand("/expert migrate auth"), {
  2434. args: "migrate auth",
  2435. name: "expert",
  2436. rawName: "expert",
  2437. type: "known",
  2438. });
  2439. assert.deepEqual(parseSlashCommand("/fork latest"), {
  2440. args: "latest",
  2441. name: "fork",
  2442. rawName: "fork",
  2443. type: "known",
  2444. });
  2445. assert.deepEqual(parseSlashCommand("/help model"), {
  2446. args: "model",
  2447. name: "help",
  2448. rawName: "help",
  2449. type: "known",
  2450. });
  2451. assert.deepEqual(parseSlashCommand("/init include scripts"), {
  2452. args: "include scripts",
  2453. name: "init",
  2454. rawName: "init",
  2455. type: "known",
  2456. });
  2457. assert.deepEqual(parseSlashCommand("/workflow review the auth module"), {
  2458. args: "review the auth module",
  2459. name: "workflow",
  2460. rawName: "workflow",
  2461. type: "known",
  2462. });
  2463. assert.deepEqual(parseSlashCommand("/continue"), {
  2464. args: "",
  2465. name: "resume",
  2466. rawName: "continue",
  2467. type: "known",
  2468. });
  2469. assert.deepEqual(parseSlashCommand("/clear"), {
  2470. args: "",
  2471. name: "new",
  2472. rawName: "clear",
  2473. type: "known",
  2474. });
  2475. assert.deepEqual(parseSlashCommand("/mode yolo"), {
  2476. args: "yolo",
  2477. name: "mode",
  2478. rawName: "mode",
  2479. type: "known",
  2480. });
  2481. assert.deepEqual(parseSlashCommand("/locale zh-CN"), {
  2482. args: "zh-CN",
  2483. name: "locale",
  2484. rawName: "locale",
  2485. type: "known",
  2486. });
  2487. assert.deepEqual(parseSlashCommand("/language auto"), {
  2488. args: "auto",
  2489. name: "locale",
  2490. rawName: "language",
  2491. type: "known",
  2492. });
  2493. assert.deepEqual(parseSlashCommand("/mcp list"), {
  2494. args: "list",
  2495. name: "mcp",
  2496. rawName: "mcp",
  2497. type: "known",
  2498. });
  2499. assert.deepEqual(parseSlashCommand("/plugins enable ios-simulator"), {
  2500. args: "enable ios-simulator",
  2501. name: "plugins",
  2502. rawName: "plugins",
  2503. type: "known",
  2504. });
  2505. assert.deepEqual(parseSlashCommand("/plugin"), {
  2506. args: "",
  2507. name: "plugins",
  2508. rawName: "plugin",
  2509. type: "known",
  2510. });
  2511. assert.deepEqual(parseSlashCommand("/model lite"), {
  2512. args: "lite",
  2513. name: "model",
  2514. rawName: "model",
  2515. type: "known",
  2516. });
  2517. assert.deepEqual(parseSlashCommand("/effort high"), {
  2518. args: "high",
  2519. name: "effort",
  2520. rawName: "effort",
  2521. type: "known",
  2522. });
  2523. assert.deepEqual(parseSlashCommand("/variant max"), {
  2524. args: "max",
  2525. name: "effort",
  2526. rawName: "variant",
  2527. type: "known",
  2528. });
  2529. assert.deepEqual(parseSlashCommand("/new"), {
  2530. args: "",
  2531. name: "new",
  2532. rawName: "new",
  2533. type: "known",
  2534. });
  2535. assert.deepEqual(parseSlashCommand("/rewind latest"), {
  2536. args: "latest",
  2537. name: "rewind",
  2538. rawName: "rewind",
  2539. type: "known",
  2540. });
  2541. assert.deepEqual(parseSlashCommand("/skill"), {
  2542. args: "",
  2543. name: "skill",
  2544. rawName: "skill",
  2545. skillName: "",
  2546. task: "",
  2547. type: "known",
  2548. });
  2549. assert.deepEqual(parseSlashCommand("/skill demo-skill update docs"), {
  2550. args: "demo-skill update docs",
  2551. name: "skill",
  2552. rawName: "skill",
  2553. skillName: "demo-skill",
  2554. task: "update docs",
  2555. type: "known",
  2556. });
  2557. assert.deepEqual(parseSlashCommand("/goal Ship target MVP"), {
  2558. args: "Ship target MVP",
  2559. name: "goal",
  2560. rawName: "goal",
  2561. type: "known",
  2562. });
  2563. assert.deepEqual(parseSlashCommand("/target Ship target MVP"), {
  2564. args: "Ship target MVP",
  2565. name: "goal",
  2566. rawName: "target",
  2567. type: "known",
  2568. });
  2569. assert.deepEqual(parseSlashCommand("/wat"), {
  2570. args: "",
  2571. rawName: "wat",
  2572. type: "unknown",
  2573. });
  2574. });
  2575. test("command center returns slash help without creating an app", async () => {
  2576. const submitPrompt = createCommandCenter({
  2577. getApp: async () => {
  2578. throw new Error("app should not be created");
  2579. },
  2580. getMode: () => "build",
  2581. resumeApp: async () => {
  2582. throw new Error("resume should not run");
  2583. },
  2584. });
  2585. const allCommands = await submitPrompt("/help", {
  2586. abortSignal: new AbortController().signal,
  2587. });
  2588. const clearCommand = await submitPrompt("/help /clear", {
  2589. abortSignal: new AbortController().signal,
  2590. });
  2591. const effortCommand = await submitPrompt("/help /variant", {
  2592. abortSignal: new AbortController().signal,
  2593. });
  2594. const modelCommand = await submitPrompt("/help /model", {
  2595. abortSignal: new AbortController().signal,
  2596. });
  2597. assert.equal(allCommands.mode, "build");
  2598. assert.match(allCommands.response, /Slash commands:/);
  2599. assert.match(allCommands.response, /\/help \[command\]/);
  2600. assert.match(allCommands.response, /\/compact \[instructions\]/);
  2601. assert.match(allCommands.response, /\/init \[notes\]/);
  2602. assert.match(allCommands.response, /\/workflow \[what the workflow should accomplish\]/);
  2603. assert.match(allCommands.response, /\/expert \[status\|resume\|stop\|<task>\]/);
  2604. assert.match(clearCommand.response, /^\/new$/m);
  2605. assert.match(clearCommand.response, /Aliases: \/clear/);
  2606. assert.match(clearCommand.response, /Start a fresh session in the TUI\./);
  2607. assert.match(effortCommand.response, /^\/effort \[list\|<level>\]/);
  2608. assert.match(effortCommand.response, /Aliases: \/variant/);
  2609. assert.match(effortCommand.response, /reasoning effort/);
  2610. // /model main|lite 别名已随结构化模型选择移除,只接受 provider/model。
  2611. assert.match(modelCommand.response, /^\/model \[list\|provider\/model\]/);
  2612. assert.match(modelCommand.response, /Show or switch the current session model\./);
  2613. });
  2614. test("command center records accepted slash commands through the history port", async () => {
  2615. const recorded: Array<{ input: unknown; kind: unknown }> = [];
  2616. const submitPrompt = createCommandCenter({
  2617. getApp: async () => {
  2618. throw new Error("app should not be created");
  2619. },
  2620. recordInputHistory: async (input, kind) => {
  2621. recorded.push({ input, kind });
  2622. },
  2623. resumeApp: async () => {
  2624. throw new Error("resume should not run");
  2625. },
  2626. });
  2627. await submitPrompt("/help /model", {
  2628. abortSignal: new AbortController().signal,
  2629. });
  2630. await submitPrompt("/login zai-coding-plan-api-key secret-token", {
  2631. abortSignal: new AbortController().signal,
  2632. });
  2633. assert.deepEqual(recorded, [{ input: "/help /model", kind: "slash_command" }]);
  2634. });
  2635. test("command center passes attachments through for normal prompts", async () => {
  2636. let submitted: unknown;
  2637. const promptInput = {
  2638. text: "describe [image #1]",
  2639. attachments: [
  2640. {
  2641. content: "data:image/png;base64,aW1hZ2U=",
  2642. path: "[image #1]",
  2643. type: "image" as const,
  2644. },
  2645. ],
  2646. };
  2647. const submitPrompt = createCommandCenter({
  2648. getApp: async () =>
  2649. ({
  2650. sessionId: "sess_active",
  2651. traceId: "trace-active",
  2652. resume: async () => {
  2653. throw new Error("resume should not run");
  2654. },
  2655. submitPrompt: async (prompt: unknown) => {
  2656. submitted = prompt;
  2657. return {
  2658. response: "done",
  2659. };
  2660. },
  2661. }) as never,
  2662. getMode: () => "build",
  2663. resumeApp: async () => {
  2664. throw new Error("resume should not run");
  2665. },
  2666. });
  2667. const result = await submitPrompt(promptInput, {
  2668. abortSignal: new AbortController().signal,
  2669. });
  2670. assert.equal(result.response, "done");
  2671. assert.deepEqual(submitted, promptInput);
  2672. });
  2673. test("command center rejects attachments on slash commands", async () => {
  2674. const submitPrompt = createCommandCenter({
  2675. getApp: async () => {
  2676. throw new Error("app should not be created");
  2677. },
  2678. getMode: () => "build",
  2679. resumeApp: async () => {
  2680. throw new Error("resume should not run");
  2681. },
  2682. });
  2683. const result = await submitPrompt(
  2684. {
  2685. text: "/help [image #1]",
  2686. attachments: [
  2687. {
  2688. content: "data:image/png;base64,aW1hZ2U=",
  2689. path: "[image #1]",
  2690. type: "image",
  2691. },
  2692. ],
  2693. },
  2694. {
  2695. abortSignal: new AbortController().signal,
  2696. },
  2697. );
  2698. assert.equal(result.mode, "build");
  2699. assert.equal(result.response, "Image attachments are only supported for normal prompts.");
  2700. });
  2701. test("command center starts expert workflow in yolo mode", async () => {
  2702. let requestedMode = "";
  2703. let workflowTask = "";
  2704. let promptSubmitted = false;
  2705. const submitPrompt = createCommandCenter({
  2706. getApp: async () =>
  2707. ({
  2708. runExpertWorkflow: async (input: { task: string }) => {
  2709. workflowTask = input.task;
  2710. return {
  2711. response: "Expert workflow wf_1 completed.",
  2712. runId: "wf_1",
  2713. status: "completed",
  2714. traceId: "trace-workflow",
  2715. };
  2716. },
  2717. sessionId: "sess_active",
  2718. traceId: "trace-active",
  2719. resume: async () => {
  2720. throw new Error("resume should not run");
  2721. },
  2722. submitPrompt: async () => {
  2723. promptSubmitted = true;
  2724. return {
  2725. response: "prompt",
  2726. };
  2727. },
  2728. }) as never,
  2729. getMode: () => (requestedMode || "build") as never,
  2730. resumeApp: async () => {
  2731. throw new Error("resume should not run");
  2732. },
  2733. setMode: async (mode) => {
  2734. requestedMode = mode;
  2735. return mode;
  2736. },
  2737. });
  2738. const result = await submitPrompt("/expert migrate auth", {
  2739. abortSignal: new AbortController().signal,
  2740. });
  2741. assert.equal(promptSubmitted, false);
  2742. assert.equal(requestedMode, "yolo");
  2743. assert.equal(workflowTask, "migrate auth");
  2744. assert.equal(result.traceId, "trace-workflow");
  2745. assert.match(result.response, /wf_1 completed/);
  2746. });
  2747. test("command center shows expert workflow status without starting a prompt", async () => {
  2748. let statusRunId: string | undefined;
  2749. let workflowStarted = false;
  2750. const submitPrompt = createCommandCenter({
  2751. getApp: async () =>
  2752. ({
  2753. expertWorkflowStatus: async (options?: { runId?: string }) => {
  2754. statusRunId = options?.runId;
  2755. return {
  2756. response: "Expert workflow wf_1\nStatus: running",
  2757. runId: "wf_1",
  2758. status: "running",
  2759. };
  2760. },
  2761. runExpertWorkflow: async () => {
  2762. workflowStarted = true;
  2763. return {
  2764. response: "started",
  2765. };
  2766. },
  2767. sessionId: "sess_active",
  2768. traceId: "trace-active",
  2769. resume: async () => {
  2770. throw new Error("resume should not run");
  2771. },
  2772. submitPrompt: async () => {
  2773. throw new Error("prompt should not run");
  2774. },
  2775. }) as never,
  2776. getMode: () => "build",
  2777. resumeApp: async () => {
  2778. throw new Error("resume should not run");
  2779. },
  2780. });
  2781. const result = await submitPrompt("/expert status wf_1", {
  2782. abortSignal: new AbortController().signal,
  2783. });
  2784. assert.equal(workflowStarted, false);
  2785. assert.equal(statusRunId, "wf_1");
  2786. assert.match(result.response, /Status: running/);
  2787. });
  2788. test("command center reports MCP status without sending a model prompt", async () => {
  2789. let promptSubmitted = false;
  2790. const submitPrompt = createCommandCenter({
  2791. getApp: async () =>
  2792. ({
  2793. listMcpServers: async () => ({
  2794. local: {
  2795. status: "connected",
  2796. toolCount: 2,
  2797. transport: "stdio",
  2798. updatedAt: "now",
  2799. },
  2800. remote: {
  2801. error: "Connection timed out\n\nline two of stderr\nline three",
  2802. status: "failed",
  2803. toolCount: 0,
  2804. transport: "http",
  2805. updatedAt: "now",
  2806. },
  2807. }),
  2808. sessionId: "sess_active",
  2809. traceId: "trace-active",
  2810. resume: async () => {
  2811. throw new Error("resume should not run");
  2812. },
  2813. submitPrompt: async () => {
  2814. promptSubmitted = true;
  2815. return {
  2816. response: "prompt",
  2817. };
  2818. },
  2819. }) as never,
  2820. getMode: () => "build",
  2821. resumeApp: async () => {
  2822. throw new Error("resume should not run");
  2823. },
  2824. });
  2825. const result = await submitPrompt("/mcp list", {
  2826. abortSignal: new AbortController().signal,
  2827. });
  2828. assert.equal(promptSubmitted, false);
  2829. assert.match(result.response, /MCP servers:/);
  2830. assert.match(result.response, /local: connected via stdio; 2 tools/);
  2831. assert.match(result.response, /remote: failed via http; 0 tools \(Connection timed out\)/);
  2832. assert.doesNotMatch(result.response, /line two/);
  2833. });
  2834. test("command center opens a plugin toggle picker", async () => {
  2835. let promptSubmitted = false;
  2836. const submitPrompt = createCommandCenter({
  2837. getApp: async () =>
  2838. ({
  2839. listPlugins: async () => ({
  2840. commandRoots: [],
  2841. diagnostics: [],
  2842. mcpServers: {},
  2843. plugins: [
  2844. {
  2845. commandRootCount: 1,
  2846. dataPath: "/tmp/zcode/plugins/data/ios-simulator@zcode-plugins-official",
  2847. enabled: false,
  2848. id: "ios-simulator@zcode-plugins-official",
  2849. manifestPath: "/plugins/ios/.zcode-plugin/plugin.json",
  2850. marketplace: "zcode-plugins-official",
  2851. mcpServerNames: ["ios-simulator"],
  2852. name: "ios-simulator",
  2853. rootPath: "/plugins/ios",
  2854. skillCount: 1,
  2855. skillRootCount: 1,
  2856. source: "official",
  2857. version: "0.1.0",
  2858. },
  2859. ],
  2860. skillRoots: [],
  2861. }),
  2862. sessionId: "sess_active",
  2863. traceId: "trace-active",
  2864. submitPrompt: async () => {
  2865. promptSubmitted = true;
  2866. return {
  2867. response: "prompt",
  2868. };
  2869. },
  2870. }) as never,
  2871. getMode: () => "build",
  2872. resumeApp: async () => {
  2873. throw new Error("resume should not run");
  2874. },
  2875. });
  2876. const result = await submitPrompt("/plugins", {
  2877. abortSignal: new AbortController().signal,
  2878. });
  2879. assert.equal(promptSubmitted, false);
  2880. assert.equal(result.selection?.title, "Plugins");
  2881. assert.equal(result.selection?.placement, "composer");
  2882. assert.equal(result.selection?.items[0]?.primary, "○ Ios Simulator");
  2883. assert.equal(
  2884. result.selection?.items[0]?.command,
  2885. "/plugins enable ios-simulator@zcode-plugins-official",
  2886. );
  2887. });
  2888. test("command center resolves plugin labels from listings by stable plugin id", async () => {
  2889. const submitPrompt = createCommandCenter({
  2890. getApp: async () =>
  2891. ({
  2892. listPlugins: async () => ({
  2893. commandRoots: [],
  2894. diagnostics: [],
  2895. mcpServers: {},
  2896. pluginListingsById: {
  2897. "computer-use@zcode-plugins-official": {
  2898. displayName: "Computer Use",
  2899. displayNameI18n: { "zh-CN": "电脑控制" },
  2900. },
  2901. "zcode-cua@custom-marketplace": {
  2902. displayName: "Custom Computer Use",
  2903. displayNameI18n: { "zh-CN": "自定义电脑控制" },
  2904. },
  2905. },
  2906. plugins: [
  2907. {
  2908. commandRootCount: 0,
  2909. dataPath: "/tmp/zcode/plugins/data/computer-use@zcode-plugins-official",
  2910. enabled: true,
  2911. id: "computer-use@zcode-plugins-official",
  2912. manifestPath: "/plugins/cua/.zcode-plugin/plugin.json",
  2913. marketplace: "zcode-plugins-official",
  2914. mcpServerNames: [],
  2915. name: "computer-use",
  2916. rootPath: "/plugins/cua",
  2917. skillCount: 0,
  2918. skillRootCount: 0,
  2919. source: "official",
  2920. },
  2921. {
  2922. commandRootCount: 0,
  2923. dataPath: "/tmp/zcode/plugins/data/zcode-cua@custom-marketplace",
  2924. enabled: false,
  2925. id: "zcode-cua@custom-marketplace",
  2926. manifestPath: "/plugins/custom-cua/.zcode-plugin/plugin.json",
  2927. marketplace: "custom-marketplace",
  2928. mcpServerNames: [],
  2929. name: "zcode-cua",
  2930. rootPath: "/plugins/custom-cua",
  2931. skillCount: 0,
  2932. skillRootCount: 0,
  2933. source: "cache",
  2934. },
  2935. {
  2936. commandRootCount: 0,
  2937. dataPath: "/tmp/zcode/plugins/data/zcode-cua@unlisted-marketplace",
  2938. enabled: false,
  2939. id: "zcode-cua@unlisted-marketplace",
  2940. manifestPath: "/plugins/unlisted-cua/.zcode-plugin/plugin.json",
  2941. marketplace: "unlisted-marketplace",
  2942. mcpServerNames: [],
  2943. name: "zcode-cua",
  2944. rootPath: "/plugins/unlisted-cua",
  2945. skillCount: 0,
  2946. skillRootCount: 0,
  2947. source: "cache",
  2948. },
  2949. ],
  2950. skillRoots: [],
  2951. }),
  2952. sessionId: "sess_active",
  2953. traceId: "trace-active",
  2954. submitPrompt: async () => ({ response: "prompt" }),
  2955. }) as never,
  2956. getLocale: () => "zh-CN",
  2957. getMode: () => "build",
  2958. resumeApp: async () => {
  2959. throw new Error("resume should not run");
  2960. },
  2961. });
  2962. const result = await submitPrompt("/plugins", {
  2963. abortSignal: new AbortController().signal,
  2964. });
  2965. const items = result.selection?.items ?? [];
  2966. assert.equal(
  2967. items.find((item) => item.id === "computer-use@zcode-plugins-official")?.primary,
  2968. "✓ 电脑控制",
  2969. );
  2970. assert.equal(
  2971. items.find((item) => item.id === "zcode-cua@custom-marketplace")?.primary,
  2972. "○ 自定义电脑控制",
  2973. );
  2974. assert.equal(
  2975. items.find((item) => item.id === "zcode-cua@unlisted-marketplace")?.primary,
  2976. "○ ZCode Cua",
  2977. );
  2978. });
  2979. test("command center toggles plugins and refreshes the picker", async () => {
  2980. let enabled = false;
  2981. const submitPrompt = createCommandCenter({
  2982. getApp: async () =>
  2983. ({
  2984. listPlugins: async () => ({
  2985. commandRoots: [],
  2986. diagnostics: [],
  2987. mcpServers: {},
  2988. plugins: [
  2989. {
  2990. commandRootCount: 1,
  2991. dataPath: "/tmp/zcode/plugins/data/ios-simulator@zcode-plugins-official",
  2992. enabled,
  2993. id: "ios-simulator@zcode-plugins-official",
  2994. manifestPath: "/plugins/ios/.zcode-plugin/plugin.json",
  2995. marketplace: "zcode-plugins-official",
  2996. mcpServerNames: ["ios-simulator"],
  2997. name: "ios-simulator",
  2998. rootPath: "/plugins/ios",
  2999. skillCount: 1,
  3000. skillRootCount: 1,
  3001. source: "official",
  3002. version: "0.1.0",
  3003. },
  3004. ],
  3005. skillRoots: [],
  3006. }),
  3007. sessionId: "sess_active",
  3008. setPluginEnabled: async (plugin, nextEnabled) => {
  3009. assert.equal(plugin, "ios-simulator@zcode-plugins-official");
  3010. enabled = nextEnabled;
  3011. return {
  3012. enabled,
  3013. path: "/home/test/.zcode/cli/config.json",
  3014. plugin: {
  3015. commandRootCount: 1,
  3016. dataPath: "/tmp/zcode/plugins/data/ios-simulator@zcode-plugins-official",
  3017. enabled,
  3018. id: "ios-simulator@zcode-plugins-official",
  3019. manifestPath: "/plugins/ios/.zcode-plugin/plugin.json",
  3020. marketplace: "zcode-plugins-official",
  3021. mcpServerNames: ["ios-simulator"],
  3022. name: "ios-simulator",
  3023. rootPath: "/plugins/ios",
  3024. skillCount: 1,
  3025. skillRootCount: 1,
  3026. source: "official",
  3027. version: "0.1.0",
  3028. },
  3029. };
  3030. },
  3031. traceId: "trace-active",
  3032. }) as never,
  3033. getMode: () => "build",
  3034. resumeApp: async () => {
  3035. throw new Error("resume should not run");
  3036. },
  3037. });
  3038. const result = await submitPrompt("/plugins enable ios-simulator@zcode-plugins-official", {
  3039. abortSignal: new AbortController().signal,
  3040. });
  3041. assert.equal(enabled, true);
  3042. assert.match(result.response, /Enabled plugin ios-simulator@zcode-plugins-official/);
  3043. assert.equal(result.selection?.items[0]?.primary, "✓ Ios Simulator");
  3044. assert.equal(
  3045. result.selection?.items[0]?.command,
  3046. "/plugins disable ios-simulator@zcode-plugins-official",
  3047. );
  3048. });
  3049. test("command center requires --force before uninstalling a plugin", async () => {
  3050. let uninstalled = false;
  3051. const submitPrompt = createCommandCenter({
  3052. getApp: async () =>
  3053. ({
  3054. listPlugins: async () => ({
  3055. commandRoots: [],
  3056. diagnostics: [],
  3057. mcpServers: {},
  3058. plugins: [],
  3059. skillRoots: [],
  3060. }),
  3061. sessionId: "sess_active",
  3062. traceId: "trace-active",
  3063. uninstallPlugin: async () => {
  3064. uninstalled = true;
  3065. return { removed: { id: "hello@market", name: "hello" } };
  3066. },
  3067. }) as never,
  3068. getMode: () => "build",
  3069. resumeApp: async () => {
  3070. throw new Error("resume should not run");
  3071. },
  3072. });
  3073. const result = await submitPrompt("/plugins uninstall hello@market", {
  3074. abortSignal: new AbortController().signal,
  3075. });
  3076. assert.equal(uninstalled, false);
  3077. assert.match(result.response, /Re-run with: \/plugins uninstall hello@market --force/);
  3078. });
  3079. test("command center uninstalls a plugin when --force is provided", async () => {
  3080. let uninstalledPlugin = "";
  3081. const submitPrompt = createCommandCenter({
  3082. getApp: async () =>
  3083. ({
  3084. listPlugins: async () => ({
  3085. commandRoots: [],
  3086. diagnostics: [],
  3087. mcpServers: {},
  3088. plugins: [],
  3089. skillRoots: [],
  3090. }),
  3091. sessionId: "sess_active",
  3092. traceId: "trace-active",
  3093. uninstallPlugin: async (plugin: string) => {
  3094. uninstalledPlugin = plugin;
  3095. return { removed: { id: plugin, name: "hello" } };
  3096. },
  3097. }) as never,
  3098. getMode: () => "build",
  3099. resumeApp: async () => {
  3100. throw new Error("resume should not run");
  3101. },
  3102. });
  3103. const result = await submitPrompt("/plugins uninstall hello@market --force", {
  3104. abortSignal: new AbortController().signal,
  3105. });
  3106. assert.equal(uninstalledPlugin, "hello@market");
  3107. assert.match(result.response, /Uninstalled plugin hello@market/);
  3108. });
  3109. test("command center dispatches compact through the active app", async () => {
  3110. let submitted = "";
  3111. const submitPrompt = createCommandCenter({
  3112. getApp: async () =>
  3113. ({
  3114. sessionId: "sess_active",
  3115. traceId: "trace-active",
  3116. resume: async () => {
  3117. throw new Error("resume should not run");
  3118. },
  3119. submitPrompt: async (prompt: string) => {
  3120. submitted = prompt;
  3121. return {
  3122. response: "Compacted",
  3123. traceId: "trace-compact",
  3124. };
  3125. },
  3126. }) as never,
  3127. resumeApp: async () => {
  3128. throw new Error("resume should not run");
  3129. },
  3130. });
  3131. const result = await submitPrompt("/compact keep recent edits", {
  3132. abortSignal: new AbortController().signal,
  3133. });
  3134. assert.equal(submitted, "/compact keep recent edits");
  3135. assert.equal(result.response, "Compacted");
  3136. assert.equal(result.traceId, "trace-compact");
  3137. });
  3138. test("command center dispatches init through the active app", async () => {
  3139. let submitted = "";
  3140. const submitPrompt = createCommandCenter({
  3141. getApp: async () =>
  3142. ({
  3143. sessionId: "sess_active",
  3144. traceId: "trace-active",
  3145. resume: async () => {
  3146. throw new Error("resume should not run");
  3147. },
  3148. submitPrompt: async (prompt: string) => {
  3149. submitted = prompt;
  3150. return {
  3151. response: "Initialized",
  3152. traceId: "trace-init",
  3153. };
  3154. },
  3155. }) as never,
  3156. resumeApp: async () => {
  3157. throw new Error("resume should not run");
  3158. },
  3159. });
  3160. const result = await submitPrompt("/init include repo scripts", {
  3161. abortSignal: new AbortController().signal,
  3162. });
  3163. assert.equal(submitted, "/init include repo scripts");
  3164. assert.equal(result.response, "Initialized");
  3165. assert.equal(result.traceId, "trace-init");
  3166. });
  3167. test("command center dispatches workflow through the active app as a prompt", async () => {
  3168. // 与 /init 同款:TUI 只识别名字,原文交给 app.submitPrompt,由 bootstrap 的 builtin resolver
  3169. // 展开;没有显式分支会落到 resume 兜底,/workflow 就再也到不了模型。
  3170. let submitted = "";
  3171. const submitPrompt = createCommandCenter({
  3172. getApp: async () =>
  3173. ({
  3174. sessionId: "sess_active",
  3175. traceId: "trace-active",
  3176. resume: async () => {
  3177. throw new Error("resume should not run");
  3178. },
  3179. submitPrompt: async (prompt: string) => {
  3180. submitted = prompt;
  3181. return {
  3182. response: "Workflow drafted",
  3183. traceId: "trace-workflow",
  3184. };
  3185. },
  3186. }) as never,
  3187. resumeApp: async () => {
  3188. throw new Error("resume should not run");
  3189. },
  3190. });
  3191. const result = await submitPrompt("/workflow review the auth module", {
  3192. abortSignal: new AbortController().signal,
  3193. });
  3194. assert.equal(submitted, "/workflow review the auth module");
  3195. assert.equal(result.response, "Workflow drafted");
  3196. assert.equal(result.traceId, "trace-workflow");
  3197. });
  3198. test("command center dispatches rewind through the active app", async () => {
  3199. let submitted = "";
  3200. const submitPrompt = createCommandCenter({
  3201. getApp: async () =>
  3202. ({
  3203. sessionId: "sess_active",
  3204. traceId: "trace-active",
  3205. resume: async () => {
  3206. throw new Error("resume should not run");
  3207. },
  3208. submitPrompt: async (prompt: string) => {
  3209. submitted = prompt;
  3210. return {
  3211. response: "Rewound",
  3212. traceId: "trace-rewind",
  3213. };
  3214. },
  3215. }) as never,
  3216. resumeApp: async () => {
  3217. throw new Error("resume should not run");
  3218. },
  3219. });
  3220. const result = await submitPrompt("/rewind latest", {
  3221. abortSignal: new AbortController().signal,
  3222. });
  3223. assert.equal(submitted, "/rewind latest");
  3224. assert.equal(result.response, "Rewound");
  3225. assert.equal(result.traceId, "trace-rewind");
  3226. });
  3227. test("command center opens a checkpoint picker for bare rewind", async () => {
  3228. let promptSubmitted = false;
  3229. const submitPrompt = createCommandCenter({
  3230. getApp: async () =>
  3231. ({
  3232. listCheckpoints: async () => [
  3233. {
  3234. checkpointId: "checkpoint_2",
  3235. createdAt: new Date("2026-05-05T10:00:00Z"),
  3236. fileCount: 2,
  3237. messageId: "msg_2",
  3238. preview: "update tests",
  3239. scope: "workspace",
  3240. },
  3241. ],
  3242. sessionId: "sess_active",
  3243. traceId: "trace-active",
  3244. resume: async () => {
  3245. throw new Error("resume should not run");
  3246. },
  3247. submitPrompt: async () => {
  3248. promptSubmitted = true;
  3249. return {
  3250. response: "prompt",
  3251. };
  3252. },
  3253. }) as never,
  3254. getMode: () => "build",
  3255. resumeApp: async () => {
  3256. throw new Error("resume should not run");
  3257. },
  3258. });
  3259. const result = await submitPrompt("/rewind", {
  3260. abortSignal: new AbortController().signal,
  3261. });
  3262. assert.equal(promptSubmitted, false);
  3263. assert.equal(result.selection?.title, "Rewind To Checkpoint");
  3264. assert.equal(result.selection?.placement, "composer");
  3265. assert.equal(result.selection?.items[0]?.command, "/rewind checkpoint_2");
  3266. assert.match(result.selection?.items[0]?.primary ?? "", /update tests/);
  3267. });
  3268. test("command center forks and switches the active app", async () => {
  3269. let forkTarget: string | undefined;
  3270. const submitPrompt = createCommandCenter({
  3271. forkApp: async (targetCheckpointId) => {
  3272. forkTarget = targetCheckpointId;
  3273. return {
  3274. forkedSessionId: "sess_child",
  3275. response: "Forked session sess_child",
  3276. };
  3277. },
  3278. getApp: async () =>
  3279. ({
  3280. sessionId: "sess_active",
  3281. traceId: "trace-active",
  3282. resume: async () => {
  3283. throw new Error("resume should not run");
  3284. },
  3285. submitPrompt: async () => {
  3286. throw new Error("prompt should not run");
  3287. },
  3288. }) as never,
  3289. resumeApp: async () => {
  3290. throw new Error("resume should not run");
  3291. },
  3292. });
  3293. const result = await submitPrompt("/fork checkpoint_1", {
  3294. abortSignal: new AbortController().signal,
  3295. });
  3296. assert.equal(forkTarget, "checkpoint_1");
  3297. assert.equal(result.response, "Forked session sess_child");
  3298. });
  3299. test("command center opens a checkpoint picker for bare fork", async () => {
  3300. let forkCalled = false;
  3301. const submitPrompt = createCommandCenter({
  3302. forkApp: async () => {
  3303. forkCalled = true;
  3304. throw new Error("fork should not run");
  3305. },
  3306. getApp: async () =>
  3307. ({
  3308. listCheckpoints: async () => [
  3309. {
  3310. checkpointId: "checkpoint_1",
  3311. createdAt: 1777975200000,
  3312. fileCount: 1,
  3313. messageId: "msg_1",
  3314. preview: "write file",
  3315. scope: "workspace",
  3316. },
  3317. ],
  3318. sessionId: "sess_active",
  3319. traceId: "trace-active",
  3320. resume: async () => {
  3321. throw new Error("resume should not run");
  3322. },
  3323. submitPrompt: async () => {
  3324. throw new Error("prompt should not run");
  3325. },
  3326. }) as never,
  3327. resumeApp: async () => {
  3328. throw new Error("resume should not run");
  3329. },
  3330. });
  3331. const result = await submitPrompt("/fork", {
  3332. abortSignal: new AbortController().signal,
  3333. });
  3334. assert.equal(forkCalled, false);
  3335. assert.equal(result.selection?.title, "Fork From Checkpoint");
  3336. assert.equal(result.selection?.placement, undefined);
  3337. assert.equal(result.selection?.items[0]?.command, "/fork checkpoint_1");
  3338. });
  3339. test("command center starts a new session without sending a model prompt", async () => {
  3340. let promptSubmitted = false;
  3341. let newAppCreated = false;
  3342. const submitPrompt = createCommandCenter({
  3343. getApp: async () =>
  3344. ({
  3345. sessionId: "sess_active",
  3346. traceId: "trace-active",
  3347. resume: async () => {
  3348. throw new Error("resume should not run");
  3349. },
  3350. submitPrompt: async () => {
  3351. promptSubmitted = true;
  3352. return {
  3353. response: "prompt",
  3354. };
  3355. },
  3356. }) as never,
  3357. getMode: () => "build",
  3358. newApp: async () => {
  3359. newAppCreated = true;
  3360. return {
  3361. sessionId: "sess_new",
  3362. traceId: "trace-new",
  3363. resume: async () => {
  3364. throw new Error("resume should not run");
  3365. },
  3366. submitPrompt: async () => {
  3367. throw new Error("prompt should not run");
  3368. },
  3369. } as never;
  3370. },
  3371. resumeApp: async () => {
  3372. throw new Error("resume should not run");
  3373. },
  3374. });
  3375. const result = await submitPrompt("/new", {
  3376. abortSignal: new AbortController().signal,
  3377. });
  3378. assert.equal(promptSubmitted, false);
  3379. assert.equal(newAppCreated, true);
  3380. assert.equal(result.sessionId, "sess_new");
  3381. assert.equal(result.traceId, "trace-new");
  3382. assert.equal(result.resetSessionProjection, true);
  3383. assert.match(result.response, /Started new session sess_new/);
  3384. });
  3385. test("command center treats clear as a new-session alias", async () => {
  3386. let promptSubmitted = false;
  3387. let newAppCreated = false;
  3388. const submitPrompt = createCommandCenter({
  3389. getApp: async () =>
  3390. ({
  3391. sessionId: "sess_active",
  3392. traceId: "trace-active",
  3393. resume: async () => {
  3394. throw new Error("resume should not run");
  3395. },
  3396. submitPrompt: async () => {
  3397. promptSubmitted = true;
  3398. return {
  3399. response: "prompt",
  3400. };
  3401. },
  3402. }) as never,
  3403. getMode: () => "build",
  3404. newApp: async () => {
  3405. newAppCreated = true;
  3406. return {
  3407. sessionId: "sess_clear",
  3408. traceId: "trace-clear",
  3409. resume: async () => {
  3410. throw new Error("resume should not run");
  3411. },
  3412. submitPrompt: async () => {
  3413. throw new Error("prompt should not run");
  3414. },
  3415. } as never;
  3416. },
  3417. resumeApp: async () => {
  3418. throw new Error("resume should not run");
  3419. },
  3420. });
  3421. const result = await submitPrompt("/clear", {
  3422. abortSignal: new AbortController().signal,
  3423. });
  3424. assert.equal(promptSubmitted, false);
  3425. assert.equal(newAppCreated, true);
  3426. assert.equal(result.sessionId, "sess_clear");
  3427. assert.equal(result.traceId, "trace-clear");
  3428. assert.equal(result.resetSessionProjection, true);
  3429. assert.match(result.response, /Started new session sess_clear/);
  3430. });
  3431. test("command center dispatches skill through the active app", async () => {
  3432. let submitted = "";
  3433. const submitPrompt = createCommandCenter({
  3434. getApp: async () =>
  3435. ({
  3436. sessionId: "sess_active",
  3437. traceId: "trace-active",
  3438. resume: async () => {
  3439. throw new Error("resume should not run");
  3440. },
  3441. submitPrompt: async (prompt: string) => {
  3442. submitted = prompt;
  3443. return {
  3444. response: "Skill task done",
  3445. traceId: "trace-skill",
  3446. };
  3447. },
  3448. }) as never,
  3449. resumeApp: async () => {
  3450. throw new Error("resume should not run");
  3451. },
  3452. });
  3453. const result = await submitPrompt("/skill demo-skill update docs", {
  3454. abortSignal: new AbortController().signal,
  3455. });
  3456. assert.equal(submitted, buildManualSkillPrompt("demo-skill", "update docs"));
  3457. assert.equal(result.response, "Skill task done");
  3458. assert.equal(result.traceId, "trace-skill");
  3459. });
  3460. test("command center reports and switches mode without sending a model prompt", async () => {
  3461. let mode: "plan" | "build" | "edit" | "yolo" | "auto" = "build";
  3462. let promptSubmitted = false;
  3463. const submitPrompt = createCommandCenter({
  3464. getApp: async () =>
  3465. ({
  3466. sessionId: "sess_active",
  3467. traceId: "trace-active",
  3468. resume: async () => {
  3469. throw new Error("resume should not run");
  3470. },
  3471. submitPrompt: async () => {
  3472. promptSubmitted = true;
  3473. return {
  3474. response: "prompt",
  3475. };
  3476. },
  3477. }) as never,
  3478. getMode: () => mode,
  3479. resumeApp: async () => {
  3480. throw new Error("resume should not run");
  3481. },
  3482. setMode: async (nextMode) => {
  3483. mode = nextMode;
  3484. return mode;
  3485. },
  3486. });
  3487. const current = await submitPrompt("/mode", {
  3488. abortSignal: new AbortController().signal,
  3489. });
  3490. const switched = await submitPrompt("/mode plan", {
  3491. abortSignal: new AbortController().signal,
  3492. });
  3493. const editSwitched = await submitPrompt("/mode edit", {
  3494. abortSignal: new AbortController().signal,
  3495. });
  3496. const rejected = await submitPrompt("/mode auto", {
  3497. abortSignal: new AbortController().signal,
  3498. });
  3499. assert.equal(promptSubmitted, false);
  3500. assert.equal(current.mode, "build");
  3501. assert.match(current.response, /Current mode: build/);
  3502. assert.equal(current.selection, undefined);
  3503. assert.equal(switched.mode, "plan");
  3504. assert.match(switched.response, /Mode switched to plan/);
  3505. assert.equal(editSwitched.mode, "edit");
  3506. assert.match(editSwitched.response, /Mode switched to edit/);
  3507. assert.equal(rejected.mode, "edit");
  3508. assert.match(rejected.response, /Unsupported mode: auto/);
  3509. });
  3510. test("command center reports and switches model without sending a model prompt", async () => {
  3511. let model = "openai/gpt-main";
  3512. let promptSubmitted = false;
  3513. const submitPrompt = createCommandCenter({
  3514. getApp: async () =>
  3515. ({
  3516. getModel: () => model,
  3517. listModels: () => [
  3518. createTestModelOption("openai", "gpt-main", { label: "Main" }),
  3519. createTestModelOption("openai", "gpt-lite", { label: "Lite" }),
  3520. ],
  3521. sessionId: "sess_active",
  3522. setModel: async (selection: ModelSelection) => {
  3523. const previousModel = model;
  3524. model = `${selection.providerId}/${selection.modelId}`;
  3525. return {
  3526. model,
  3527. previousModel,
  3528. };
  3529. },
  3530. traceId: "trace-active",
  3531. resume: async () => {
  3532. throw new Error("resume should not run");
  3533. },
  3534. submitPrompt: async () => {
  3535. promptSubmitted = true;
  3536. return {
  3537. response: "prompt",
  3538. };
  3539. },
  3540. }) as never,
  3541. getMode: () => "build",
  3542. resumeApp: async () => {
  3543. throw new Error("resume should not run");
  3544. },
  3545. });
  3546. const current = await submitPrompt("/model", {
  3547. abortSignal: new AbortController().signal,
  3548. });
  3549. // /model lite 这类别名已移除,切换使用目录中的 provider/model。
  3550. const switched = await submitPrompt("/model openai/gpt-lite", {
  3551. abortSignal: new AbortController().signal,
  3552. });
  3553. assert.equal(promptSubmitted, false);
  3554. assert.match(current.response, /Current model: openai\/gpt-main/);
  3555. assert.match(current.response, /- openai\/gpt-lite \(Lite; openai\)/);
  3556. assert.match(switched.response, /Model switched to openai\/gpt-lite \(medium\)/);
  3557. });
  3558. test("command center reports and switches effort without sending a model prompt", async () => {
  3559. let thoughtLevel = "medium";
  3560. let promptSubmitted = false;
  3561. const requestedLevels: string[] = [];
  3562. const submitPrompt = createCommandCenter({
  3563. getApp: async () =>
  3564. ({
  3565. getThoughtLevel: () => thoughtLevel,
  3566. listThoughtLevels: () => ["low", "medium", "high"],
  3567. sessionId: "sess_active",
  3568. setThoughtLevel: async (level: string) => {
  3569. requestedLevels.push(level);
  3570. const previousThoughtLevel = thoughtLevel;
  3571. thoughtLevel = level;
  3572. return {
  3573. previousThoughtLevel,
  3574. thoughtLevel,
  3575. };
  3576. },
  3577. traceId: "trace-active",
  3578. resume: async () => {
  3579. throw new Error("resume should not run");
  3580. },
  3581. submitPrompt: async () => {
  3582. promptSubmitted = true;
  3583. return {
  3584. response: "prompt",
  3585. };
  3586. },
  3587. }) as never,
  3588. getMode: () => "build",
  3589. resumeApp: async () => {
  3590. throw new Error("resume should not run");
  3591. },
  3592. });
  3593. const current = await submitPrompt("/effort", {
  3594. abortSignal: new AbortController().signal,
  3595. });
  3596. const listed = await submitPrompt("/effort list", {
  3597. abortSignal: new AbortController().signal,
  3598. });
  3599. const switched = await submitPrompt("/variant HIGH", {
  3600. abortSignal: new AbortController().signal,
  3601. });
  3602. assert.equal(promptSubmitted, false);
  3603. assert.equal(current.selection, undefined);
  3604. assert.match(current.response, /Current reasoning effort: medium/);
  3605. assert.match(current.response, /- medium \(current\)/);
  3606. assert.deepEqual(current.effortOptions, [
  3607. { id: "low", label: "low" },
  3608. { id: "medium", label: "medium" },
  3609. { id: "high", label: "high" },
  3610. ]);
  3611. assert.match(listed.response, /Current reasoning effort: medium/);
  3612. assert.match(listed.response, /- high/);
  3613. assert.match(switched.response, /Reasoning effort switched to high/);
  3614. assert.equal(switched.thoughtLevel, "high");
  3615. assert.deepEqual(requestedLevels, ["high"]);
  3616. });
  3617. test("command center reports and switches locale without sending a model prompt", async () => {
  3618. let locale = "en-US" as const | "zh-CN";
  3619. let promptSubmitted = false;
  3620. const submitPrompt = createCommandCenter({
  3621. getApp: async () =>
  3622. ({
  3623. getLocale: () => locale,
  3624. sessionId: "sess_active",
  3625. setLocale: async (requestedLocale: "auto" | "en-US" | "zh-CN") => {
  3626. const previousLocale = locale;
  3627. locale = requestedLocale === "zh-CN" ? "zh-CN" : "en-US";
  3628. return {
  3629. configPath: "/tmp/zcode/config.json",
  3630. locale,
  3631. previousLocale,
  3632. requestedLocale,
  3633. };
  3634. },
  3635. traceId: "trace-active",
  3636. resume: async () => {
  3637. throw new Error("resume should not run");
  3638. },
  3639. submitPrompt: async () => {
  3640. promptSubmitted = true;
  3641. return {
  3642. response: "prompt",
  3643. };
  3644. },
  3645. }) as never,
  3646. getMode: () => "build",
  3647. resumeApp: async () => {
  3648. throw new Error("resume should not run");
  3649. },
  3650. });
  3651. const current = await submitPrompt("/locale", {
  3652. abortSignal: new AbortController().signal,
  3653. });
  3654. const switched = await submitPrompt("/locale zh-CN", {
  3655. abortSignal: new AbortController().signal,
  3656. });
  3657. const rejected = await submitPrompt("/locale fr-FR", {
  3658. abortSignal: new AbortController().signal,
  3659. });
  3660. assert.equal(promptSubmitted, false);
  3661. assert.equal(current.locale, "en-US");
  3662. assert.match(current.response, /Current locale: en-US/);
  3663. assert.equal(switched.locale, "zh-CN");
  3664. assert.match(switched.response, /Locale switched to zh-CN/);
  3665. assert.match(switched.response, /Config: \/tmp\/zcode\/config\.json/);
  3666. assert.equal(rejected.locale, "zh-CN");
  3667. assert.match(rejected.response, /Unsupported locale: fr-FR/);
  3668. });
  3669. test("command center lists skills without sending a model prompt", async () => {
  3670. let listed = false;
  3671. const submitPrompt = createCommandCenter({
  3672. getApp: async () => {
  3673. throw new Error("app should not be created");
  3674. },
  3675. getMode: () => "build",
  3676. listSkills: async () => {
  3677. listed = true;
  3678. return {
  3679. skills: [
  3680. {
  3681. description: "Use for demo tasks.",
  3682. name: "demo-skill",
  3683. path: "/workspace/project/.zcode/skills/demo/SKILL.md",
  3684. scope: "project",
  3685. source: "zcode",
  3686. whenToUse: "When demo files change.",
  3687. },
  3688. ],
  3689. totalDiscovered: 1,
  3690. };
  3691. },
  3692. resumeApp: async () => {
  3693. throw new Error("resume should not run");
  3694. },
  3695. });
  3696. const result = await submitPrompt("/skill", {
  3697. abortSignal: new AbortController().signal,
  3698. });
  3699. assert.equal(listed, true);
  3700. assert.equal(result.mode, "build");
  3701. assert.match(result.response, /Available skills \(1\)/);
  3702. assert.match(result.response, /demo-skill \(project\/zcode\)/);
  3703. assert.match(result.response, /Use for demo tasks\. When demo files change\./);
  3704. assert.match(result.response, /\/workspace\/project\/\.zcode\/skills\/demo\/SKILL\.md/);
  3705. assert.match(result.response, /Use \/skill <name> \[task\] to load one\./);
  3706. });
  3707. test("command center resumes the latest session", async () => {
  3708. let requestedSessionId: string | undefined = "unset";
  3709. const events: string[] = [];
  3710. const submitPrompt = createCommandCenter({
  3711. getApp: async () => {
  3712. throw new Error("default app should not run");
  3713. },
  3714. resumeApp: async (sessionId) => {
  3715. requestedSessionId = sessionId;
  3716. return {
  3717. sessionId: "sess_latest",
  3718. traceId: "trace-app",
  3719. loadSessionTranscript: async () => [
  3720. {
  3721. content: "previous user prompt",
  3722. role: "user",
  3723. },
  3724. {
  3725. content: "previous agent answer",
  3726. role: "agent",
  3727. },
  3728. ],
  3729. resume: async (options) => {
  3730. await options?.onEvent?.(
  3731. createRuntimeEvent("session_resumed", {
  3732. directory: "/tmp/project",
  3733. interruptedToolCount: 0,
  3734. messageCount: 3,
  3735. partCount: 5,
  3736. }),
  3737. );
  3738. return {
  3739. appliedMessageCount: 3,
  3740. directory: "/tmp/project",
  3741. interruptedToolCount: 0,
  3742. messageCount: 3,
  3743. partCount: 5,
  3744. traceId: "trace-resume",
  3745. };
  3746. },
  3747. submitPrompt: async () => {
  3748. throw new Error("prompt should not run");
  3749. },
  3750. };
  3751. },
  3752. });
  3753. const result = await submitPrompt("/resume", {
  3754. abortSignal: new AbortController().signal,
  3755. onEvent: (event) => {
  3756. events.push(event.type);
  3757. },
  3758. });
  3759. assert.equal(requestedSessionId, undefined);
  3760. assert.match(result.response, /Resumed session sess_latest/);
  3761. assert.match(result.response, /Messages: 3\/3/);
  3762. assert.equal(result.resetSessionProjection, true);
  3763. assert.deepEqual(result.restoredMessages, [
  3764. {
  3765. content: "previous user prompt",
  3766. role: "user",
  3767. },
  3768. {
  3769. content: "previous agent answer",
  3770. role: "agent",
  3771. },
  3772. ]);
  3773. assert.equal(result.traceId, "trace-resume");
  3774. assert.deepEqual(events, ["session_resumed"]);
  3775. });
  3776. test("command center opens a session picker for bare resume when sessions are available", async () => {
  3777. let resumeCalled = false;
  3778. const submitPrompt = createCommandCenter({
  3779. getApp: async () => {
  3780. throw new Error("default app should not run");
  3781. },
  3782. getMode: () => "build",
  3783. listSessions: async () => [
  3784. {
  3785. directory: "/workspace/project",
  3786. id: "sess_two",
  3787. title: "Second session",
  3788. updatedAt: new Date("2026-05-05T12:00:00Z"),
  3789. },
  3790. {
  3791. directory: "/workspace/project",
  3792. id: "sess_one",
  3793. parentId: "sess_parent",
  3794. title: "Forked session",
  3795. updatedAt: 1777971600000,
  3796. },
  3797. ],
  3798. resumeApp: async () => {
  3799. resumeCalled = true;
  3800. throw new Error("resume should not run");
  3801. },
  3802. });
  3803. const result = await submitPrompt("/resume", {
  3804. abortSignal: new AbortController().signal,
  3805. });
  3806. assert.equal(resumeCalled, false);
  3807. assert.equal(result.mode, "build");
  3808. assert.equal(result.selection?.title, "Resume Session");
  3809. assert.equal(result.selection?.placement, "composer");
  3810. assert.equal(result.selection?.items[0]?.command, "/resume sess_two");
  3811. assert.match(result.selection?.items[1]?.meta ?? "", /fork of sess_parent/);
  3812. });
  3813. test("prints help with help flag", async () => {
  3814. const ctx = createContext(["--help"]);
  3815. const exitCode = await run(ctx);
  3816. assert.equal(exitCode, 0);
  3817. assert.match(ctx.stdout.output(), /With no command, zcode opens the full-screen TUI\./);
  3818. assert.match(ctx.stdout.output(), /Commands:/);
  3819. assert.match(ctx.stdout.output(), /--force-mcs/);
  3820. assert.match(ctx.stdout.output(), /--total-tokens-reminder <on\|off>/);
  3821. assert.match(ctx.stdout.output(), /--agent-always-background <on\|off>/);
  3822. assert.match(ctx.stdout.output(), /--surface <surface>/);
  3823. assert.match(ctx.stdout.output(), /--resume <sessionId>/);
  3824. assert.match(ctx.stdout.output(), /sessionId \(sess_\.\.\.\)/);
  3825. assert.equal(ctx.stderr.output(), "");
  3826. });
  3827. test("prints version with version flag", async () => {
  3828. const ctx = createContext(["--version"]);
  3829. const exitCode = await run(ctx);
  3830. assert.equal(exitCode, 0);
  3831. assert.match(ctx.stdout.output().trim(), /^\d+\.\d+\.\d+|0\.0\.0$/);
  3832. assert.equal(ctx.stderr.output(), "");
  3833. });
  3834. test("prints version with version command", async () => {
  3835. const ctx = createContext(["version"]);
  3836. const exitCode = await run(ctx);
  3837. assert.equal(exitCode, 0);
  3838. assert.match(ctx.stdout.output().trim(), /^\d+\.\d+\.\d+|0\.0\.0$/);
  3839. assert.equal(ctx.stderr.output(), "");
  3840. });
  3841. test("rejects removed hello command", async () => {
  3842. const ctx = createContext(["hello"]);
  3843. const exitCode = await run(ctx);
  3844. assert.equal(exitCode, 1);
  3845. assert.match(ctx.stderr.output(), /Unknown command: hello/);
  3846. assert.equal(ctx.stdout.output(), "");
  3847. });
  3848. test("zcode plugins list prints installed plugins", async () => {
  3849. const ctx = createContext(["plugins", "list", "--verbose"]);
  3850. const logger = {} as NonNullable<RunDependencies["logger"]>;
  3851. const exitCode = await run(ctx, {
  3852. cwd: () => "/workspace/project",
  3853. logger,
  3854. listPlugins: (options) => {
  3855. assert.equal(options.logger, logger);
  3856. assert.equal(options.workingDirectory, "/workspace/project");
  3857. return {
  3858. commandRoots: [],
  3859. diagnostics: [
  3860. {
  3861. code: "plugin_unsupported_component",
  3862. message: "Plugin component is ignored in P0: hooks",
  3863. pluginId: "ios-dev@inline",
  3864. severity: "warning",
  3865. },
  3866. ],
  3867. mcpServers: {},
  3868. plugins: [
  3869. {
  3870. commandRootCount: 1,
  3871. dataPath: "/tmp/zcode/plugins/data/ios-dev@inline",
  3872. enabled: true,
  3873. id: "ios-dev@inline",
  3874. manifestPath: "/plugins/ios/.zcode-plugin/plugin.json",
  3875. marketplace: "inline",
  3876. mcpServerNames: ["ios-simulator"],
  3877. name: "ios-dev",
  3878. rootPath: "/plugins/ios",
  3879. skillCount: 1,
  3880. skillRootCount: 1,
  3881. source: "inline",
  3882. },
  3883. ],
  3884. skillRoots: [],
  3885. } as never;
  3886. },
  3887. });
  3888. const output = ctx.stdout.output();
  3889. assert.equal(exitCode, 0);
  3890. assert.match(output, /Plugins \(1\)/);
  3891. assert.match(output, /ios-dev@inline \[enabled\]/);
  3892. assert.match(output, /mcp: ios-simulator/);
  3893. assert.match(output, /Diagnostics \(1\)/);
  3894. });
  3895. test("official plugin host runs a seeded official plugin server main", async () => {
  3896. const root = await mkdtemp(join(tmpdir(), "zcode-cli-plugin-host-"));
  3897. const pluginRoot = join(
  3898. root,
  3899. "cache",
  3900. ZCODE_OFFICIAL_PLUGIN_MARKETPLACE,
  3901. "ios-simulator",
  3902. "0.1.0",
  3903. );
  3904. const serverPath = join(pluginRoot, "dist", "mcp", "server.js");
  3905. const outputPath = join(root, "host-output.json");
  3906. const originalOutputEnv = process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT;
  3907. try {
  3908. await mkdir(join(pluginRoot, "dist", "mcp"), { recursive: true });
  3909. await writeFile(
  3910. join(pluginRoot, ".zcode-plugin-seed.json"),
  3911. JSON.stringify({
  3912. marketplace: ZCODE_OFFICIAL_PLUGIN_MARKETPLACE,
  3913. plugin: "ios-simulator",
  3914. pluginVersion: "0.1.0",
  3915. version: 1,
  3916. }),
  3917. );
  3918. await writeFile(join(pluginRoot, "package.json"), JSON.stringify({ type: "module" }));
  3919. await writeFile(
  3920. serverPath,
  3921. `import { writeFile } from "node:fs/promises";
  3922. export async function main() {
  3923. await writeFile(process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT, JSON.stringify({ argv: process.argv }));
  3924. }
  3925. `,
  3926. );
  3927. process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT = outputPath;
  3928. const ctx = createContext([ZCODE_PLUGIN_HOST_COMMAND, serverPath]);
  3929. const exitCode = await run(ctx);
  3930. assert.equal(exitCode, 0);
  3931. assert.equal(ctx.stdout.output(), "");
  3932. assert.equal(ctx.stderr.output(), "");
  3933. const payload = JSON.parse(await readFile(outputPath, "utf8"));
  3934. assert.equal(payload.argv[0], process.execPath);
  3935. assert.equal(payload.argv[1], serverPath);
  3936. } finally {
  3937. if (originalOutputEnv === undefined) {
  3938. delete process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT;
  3939. } else {
  3940. process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT = originalOutputEnv;
  3941. }
  3942. await rm(root, { force: true, recursive: true });
  3943. }
  3944. });
  3945. test("retired argv-based CUA host fails closed without the shared node_repl marker", async () => {
  3946. const root = await mkdtemp(join(tmpdir(), "zcode-cli-cua-plugin-host-mismatch-"));
  3947. const serverPath = join(root, "server.js");
  3948. const outputPath = join(root, "host-output.json");
  3949. const keys = [
  3950. "ZCODE_CUA_PERMISSION_BROKER_SOCKET",
  3951. "ZCODE_CUA_PERMISSION_BROKER_TOKEN",
  3952. "ZCODE_PLUGIN_HOST_TEST_OUTPUT",
  3953. ZCODE_PLUGIN_ID_ENV_KEY,
  3954. ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY,
  3955. ZCODE_CUA_NODE_REPL_HOST_ENV_KEY,
  3956. ] as const;
  3957. const originalEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
  3958. try {
  3959. await writeFile(join(root, "package.json"), JSON.stringify({ type: "module" }));
  3960. await writeFile(
  3961. serverPath,
  3962. `import { writeFile } from "node:fs/promises";
  3963. export async function main() {
  3964. await writeFile(process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT, JSON.stringify({
  3965. token: process.env.ZCODE_CUA_PERMISSION_BROKER_TOKEN,
  3966. }));
  3967. }
  3968. `,
  3969. );
  3970. process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT = outputPath;
  3971. process.env[ZCODE_PLUGIN_ID_ENV_KEY] = ZCODE_CUA_OFFICIAL_PLUGIN_ID;
  3972. process.env.ZCODE_CUA_PERMISSION_BROKER_SOCKET = "/tmp/cua-broker.sock";
  3973. process.env.ZCODE_CUA_PERMISSION_BROKER_TOKEN = "scoped-secret-token";
  3974. process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY] = "official-authority";
  3975. resetCapturedZCodeCuaBrokerCredentialsForTest();
  3976. sanitizeZCodeRuntimeEnvInPlace(process.env);
  3977. assert.equal(process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY], undefined);
  3978. const ctx = createContext([ZCODE_PLUGIN_HOST_COMMAND, serverPath]);
  3979. const exitCode = await runPluginHostCommand(ctx, [
  3980. serverPath,
  3981. "--permission-broker-socket",
  3982. "/tmp/attacker.sock",
  3983. ]);
  3984. assert.equal(exitCode, 1);
  3985. assert.match(
  3986. ctx.stderr.output(),
  3987. /Captured ZCode CUA broker credentials may only launch the trusted shared node_repl host/,
  3988. );
  3989. await assert.rejects(readFile(outputPath, "utf8"), { code: "ENOENT" });
  3990. } finally {
  3991. resetCapturedZCodeCuaBrokerCredentialsForTest();
  3992. for (const key of keys) {
  3993. const value = originalEnv[key];
  3994. if (value === undefined) delete process.env[key];
  3995. else process.env[key] = value;
  3996. }
  3997. await rm(root, { force: true, recursive: true });
  3998. }
  3999. });
  4000. test("shared node_repl host restores the captured CUA broker credentials", async () => {
  4001. const root = await mkdtemp(join(tmpdir(), "zcode-cli-cua-node-repl-host-"));
  4002. const serverPath = join(root, "server.js");
  4003. const outputPath = join(root, "host-output.json");
  4004. const keys = [
  4005. "ZCODE_CUA_PERMISSION_BROKER_SOCKET",
  4006. "ZCODE_CUA_PERMISSION_BROKER_TOKEN",
  4007. "ZCODE_PLUGIN_HOST_TEST_OUTPUT",
  4008. ZCODE_PLUGIN_ID_ENV_KEY,
  4009. ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY,
  4010. ZCODE_CUA_NODE_REPL_HOST_ENV_KEY,
  4011. ] as const;
  4012. const originalEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
  4013. try {
  4014. await writeFile(join(root, "package.json"), JSON.stringify({ type: "module" }));
  4015. await writeFile(
  4016. serverPath,
  4017. `import { writeFile } from "node:fs/promises";
  4018. export async function main() {
  4019. await writeFile(process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT, JSON.stringify({
  4020. socket: process.env.ZCODE_CUA_PERMISSION_BROKER_SOCKET,
  4021. token: process.env.ZCODE_CUA_PERMISSION_BROKER_TOKEN,
  4022. }));
  4023. }
  4024. `,
  4025. );
  4026. process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT = outputPath;
  4027. process.env[ZCODE_PLUGIN_ID_ENV_KEY] = ZCODE_CUA_OFFICIAL_PLUGIN_ID;
  4028. process.env[ZCODE_CUA_NODE_REPL_HOST_ENV_KEY] = "1";
  4029. process.env.ZCODE_CUA_PERMISSION_BROKER_SOCKET = "/tmp/cua-broker.sock";
  4030. process.env.ZCODE_CUA_PERMISSION_BROKER_TOKEN = "scoped-secret-token";
  4031. process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY] = "official-authority";
  4032. resetCapturedZCodeCuaBrokerCredentialsForTest();
  4033. sanitizeZCodeRuntimeEnvInPlace(process.env);
  4034. const ctx = createContext([ZCODE_PLUGIN_HOST_COMMAND, serverPath]);
  4035. assert.equal(await runPluginHostCommand(ctx, [serverPath]), 0);
  4036. // identity 模式:恢复给宿主的只有 socket(配 authority),没有口令。环境里那个遗留
  4037. // token 是历史键,sanitize 会连它一起剔除,因此宿主根本看不到它 —— 否则旧版 Helper
  4038. // (认 bearer token 的那些)就能被同 agent 内的其它子进程直接驱动。
  4039. // 逐字段断言:JSON.stringify 会把值为 undefined 的键整个省掉,深比较对不上。
  4040. const hostEnv = JSON.parse(await readFile(outputPath, "utf8")) as {
  4041. socket?: string;
  4042. token?: string;
  4043. };
  4044. assert.equal(hostEnv.socket, "/tmp/cua-broker.sock");
  4045. assert.equal(hostEnv.token, undefined);
  4046. // 宿主只在运行期间短暂恢复,跑完父进程 env 必须回到已剔除状态。
  4047. assert.equal(process.env.ZCODE_CUA_PERMISSION_BROKER_SOCKET, undefined);
  4048. assert.equal(process.env.ZCODE_CUA_PERMISSION_BROKER_TOKEN, undefined);
  4049. } finally {
  4050. resetCapturedZCodeCuaBrokerCredentialsForTest();
  4051. for (const key of keys) {
  4052. const value = originalEnv[key];
  4053. if (value === undefined) delete process.env[key];
  4054. else process.env[key] = value;
  4055. }
  4056. await rm(root, { force: true, recursive: true });
  4057. }
  4058. });
  4059. test("shared node_repl host launches with identity-mode credentials (socket + authority, no token)", async () => {
  4060. // M1 身份模式(darwin):Helper 不签发 token;M7 懒启动:authority 由 spawn 铸造。
  4061. // 2026-09-10 回归:守卫曾要求 token,导致 node_repl 宿主启动即退出、工具面为空。
  4062. const root = await mkdtemp(join(tmpdir(), "zcode-cli-cua-node-repl-identity-"));
  4063. const serverPath = join(root, "server.js");
  4064. const outputPath = join(root, "host-output.json");
  4065. const keys = [
  4066. "ZCODE_CUA_PERMISSION_BROKER_SOCKET",
  4067. "ZCODE_CUA_PERMISSION_BROKER_TOKEN",
  4068. "ZCODE_PLUGIN_HOST_TEST_OUTPUT",
  4069. ZCODE_PLUGIN_ID_ENV_KEY,
  4070. ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY,
  4071. ZCODE_CUA_NODE_REPL_HOST_ENV_KEY,
  4072. ] as const;
  4073. const originalEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
  4074. try {
  4075. await writeFile(join(root, "package.json"), JSON.stringify({ type: "module" }));
  4076. await writeFile(
  4077. serverPath,
  4078. `import { writeFile } from "node:fs/promises";
  4079. export async function main() {
  4080. await writeFile(process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT, JSON.stringify({
  4081. socket: process.env.ZCODE_CUA_PERMISSION_BROKER_SOCKET,
  4082. token: process.env.ZCODE_CUA_PERMISSION_BROKER_TOKEN ?? null,
  4083. }));
  4084. }
  4085. `,
  4086. );
  4087. process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT = outputPath;
  4088. process.env[ZCODE_PLUGIN_ID_ENV_KEY] = ZCODE_CUA_OFFICIAL_PLUGIN_ID;
  4089. process.env[ZCODE_CUA_NODE_REPL_HOST_ENV_KEY] = "1";
  4090. process.env.ZCODE_CUA_PERMISSION_BROKER_SOCKET = "/tmp/cua-broker.sock";
  4091. delete process.env.ZCODE_CUA_PERMISSION_BROKER_TOKEN;
  4092. process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY] = "official-authority";
  4093. resetCapturedZCodeCuaBrokerCredentialsForTest();
  4094. sanitizeZCodeRuntimeEnvInPlace(process.env);
  4095. const ctx = createContext([ZCODE_PLUGIN_HOST_COMMAND, serverPath]);
  4096. assert.equal(await runPluginHostCommand(ctx, [serverPath]), 0);
  4097. assert.deepEqual(JSON.parse(await readFile(outputPath, "utf8")), {
  4098. socket: "/tmp/cua-broker.sock",
  4099. token: null,
  4100. });
  4101. } finally {
  4102. resetCapturedZCodeCuaBrokerCredentialsForTest();
  4103. for (const key of keys) {
  4104. const value = originalEnv[key];
  4105. if (value === undefined) delete process.env[key];
  4106. else process.env[key] = value;
  4107. }
  4108. await rm(root, { force: true, recursive: true });
  4109. }
  4110. });
  4111. test("plugin host refuses non-official code while product broker credentials are captured", async () => {
  4112. const root = await mkdtemp(join(tmpdir(), "zcode-cli-non-cua-plugin-host-"));
  4113. const serverPath = join(root, "server.js");
  4114. const outputPath = join(root, "host-output.json");
  4115. const keys = [
  4116. "ZCODE_CUA_PERMISSION_BROKER_SOCKET",
  4117. "ZCODE_CUA_PERMISSION_BROKER_TOKEN",
  4118. "ZCODE_PLUGIN_HOST_TEST_OUTPUT",
  4119. ZCODE_PLUGIN_ID_ENV_KEY,
  4120. ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY,
  4121. ZCODE_CUA_NODE_REPL_HOST_ENV_KEY,
  4122. ] as const;
  4123. const originalEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
  4124. try {
  4125. await writeFile(join(root, "package.json"), JSON.stringify({ type: "module" }));
  4126. await writeFile(
  4127. serverPath,
  4128. `import { writeFile } from "node:fs/promises";
  4129. export async function main() {
  4130. await writeFile(process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT, String(Boolean(process.env.ZCODE_CUA_PERMISSION_BROKER_TOKEN)));
  4131. }
  4132. `,
  4133. );
  4134. process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT = outputPath;
  4135. process.env[ZCODE_PLUGIN_ID_ENV_KEY] = "zcode-cua@third-party";
  4136. process.env.ZCODE_CUA_PERMISSION_BROKER_SOCKET = "/tmp/cua-broker.sock";
  4137. process.env.ZCODE_CUA_PERMISSION_BROKER_TOKEN = "must-not-leak";
  4138. process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY] = "captured-authority";
  4139. resetCapturedZCodeCuaBrokerCredentialsForTest();
  4140. sanitizeZCodeRuntimeEnvInPlace(process.env);
  4141. assert.equal(process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY], undefined);
  4142. const ctx = createContext([
  4143. ZCODE_PLUGIN_HOST_COMMAND,
  4144. serverPath,
  4145. "--permission-broker-socket",
  4146. "/tmp/cua-broker.sock",
  4147. ]);
  4148. assert.equal(await run(ctx), 1);
  4149. assert.match(
  4150. ctx.stderr.output(),
  4151. /Captured ZCode CUA broker credentials may only launch the trusted shared node_repl host/,
  4152. );
  4153. await assert.rejects(readFile(outputPath, "utf8"), { code: "ENOENT" });
  4154. } finally {
  4155. resetCapturedZCodeCuaBrokerCredentialsForTest();
  4156. for (const key of keys) {
  4157. const value = originalEnv[key];
  4158. if (value === undefined) delete process.env[key];
  4159. else process.env[key] = value;
  4160. }
  4161. await rm(root, { force: true, recursive: true });
  4162. }
  4163. });
  4164. test("plugin host can run an explicitly configured third-party module", async () => {
  4165. const root = await mkdtemp(join(tmpdir(), "zcode-cli-plugin-host-third-party-"));
  4166. const serverPath = join(root, "third-party", "server.js");
  4167. const outputPath = join(root, "third-party-output.json");
  4168. const originalOutputEnv = process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT;
  4169. try {
  4170. await mkdir(join(root, "third-party"), { recursive: true });
  4171. await writeFile(join(root, "third-party", "package.json"), JSON.stringify({ type: "module" }));
  4172. await writeFile(
  4173. serverPath,
  4174. `import { writeFile } from "node:fs/promises";
  4175. export async function main() {
  4176. await writeFile(process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT, JSON.stringify({ argv: process.argv }));
  4177. }
  4178. `,
  4179. );
  4180. process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT = outputPath;
  4181. const ctx = createContext([ZCODE_PLUGIN_HOST_COMMAND, serverPath, "--", "hello"]);
  4182. const exitCode = await run(ctx);
  4183. assert.equal(exitCode, 0);
  4184. assert.equal(ctx.stdout.output(), "");
  4185. assert.equal(ctx.stderr.output(), "");
  4186. const payload = JSON.parse(await readFile(outputPath, "utf8"));
  4187. assert.deepEqual(payload.argv, [process.execPath, serverPath, "--", "hello"]);
  4188. } finally {
  4189. if (originalOutputEnv === undefined) {
  4190. delete process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT;
  4191. } else {
  4192. process.env.ZCODE_PLUGIN_HOST_TEST_OUTPUT = originalOutputEnv;
  4193. }
  4194. await rm(root, { force: true, recursive: true });
  4195. }
  4196. });
  4197. test("plugin host stays alive past the one-shot CLI watchdog deadline", async () => {
  4198. const root = await mkdtemp(join(tmpdir(), "zcode-cli-plugin-host-lifetime-"));
  4199. const serverPath = join(root, "server.mjs");
  4200. const cliEntryPath = fileURLToPath(new URL("../src/main.ts", import.meta.url));
  4201. const tsxLoaderPath = fileURLToPath(import.meta.resolve("tsx"));
  4202. let child: ReturnType<typeof spawn> | undefined;
  4203. try {
  4204. await writeFile(
  4205. serverPath,
  4206. `export async function main() {
  4207. process.stdin.resume();
  4208. process.stdout.write("plugin-host-ready\\n");
  4209. }
  4210. `,
  4211. );
  4212. child = spawn(
  4213. process.execPath,
  4214. ["--import", tsxLoaderPath, cliEntryPath, ZCODE_PLUGIN_HOST_COMMAND, serverPath],
  4215. {
  4216. env: process.env,
  4217. stdio: ["pipe", "pipe", "pipe"],
  4218. },
  4219. );
  4220. child.stdout?.setEncoding("utf8");
  4221. await withTimeout(
  4222. new Promise<void>((resolve, reject) => {
  4223. let stdout = "";
  4224. const cleanup = () => {
  4225. child?.stdout?.off("data", onData);
  4226. child?.off("exit", onExit);
  4227. };
  4228. const onData = (chunk: string) => {
  4229. stdout += chunk;
  4230. if (!stdout.includes("plugin-host-ready")) return;
  4231. cleanup();
  4232. resolve();
  4233. };
  4234. const onExit = (code: number | null, signal: NodeJS.Signals | null) => {
  4235. cleanup();
  4236. reject(new Error(`plugin host exited before ready: code=${code}, signal=${signal}`));
  4237. };
  4238. child?.stdout?.on("data", onData);
  4239. child?.once("exit", onExit);
  4240. }),
  4241. 5_000,
  4242. "plugin host did not become ready",
  4243. );
  4244. await delay(1_250);
  4245. assert.equal(child.exitCode, null);
  4246. child.stdin?.end();
  4247. const [exitCode, signal] = (await withTimeout(
  4248. once(child, "exit"),
  4249. 5_000,
  4250. "plugin host did not exit after stdin closed",
  4251. )) as [number | null, NodeJS.Signals | null];
  4252. assert.equal(exitCode, 0);
  4253. assert.equal(signal, null);
  4254. } finally {
  4255. if (child && child.exitCode === null && child.signalCode === null) {
  4256. child.kill("SIGKILL");
  4257. await once(child, "exit");
  4258. }
  4259. await rm(root, { force: true, recursive: true });
  4260. }
  4261. });
  4262. test("failed plugin host still exits when initialization leaves stdin active", async () => {
  4263. const root = await mkdtemp(join(tmpdir(), "zcode-cli-plugin-host-failure-"));
  4264. const serverPath = join(root, "server.mjs");
  4265. const cliEntryPath = fileURLToPath(new URL("../src/main.ts", import.meta.url));
  4266. const tsxLoaderPath = fileURLToPath(import.meta.resolve("tsx"));
  4267. let child: ReturnType<typeof spawn> | undefined;
  4268. let stderr = "";
  4269. try {
  4270. await writeFile(
  4271. serverPath,
  4272. `export async function main() {
  4273. process.stdin.resume();
  4274. throw new Error("expected initialization failure");
  4275. }
  4276. `,
  4277. );
  4278. child = spawn(
  4279. process.execPath,
  4280. ["--import", tsxLoaderPath, cliEntryPath, ZCODE_PLUGIN_HOST_COMMAND, serverPath],
  4281. {
  4282. env: process.env,
  4283. stdio: ["pipe", "pipe", "pipe"],
  4284. },
  4285. );
  4286. child.stderr?.setEncoding("utf8");
  4287. child.stderr?.on("data", (chunk: string) => {
  4288. stderr += chunk;
  4289. });
  4290. const [exitCode, signal] = (await withTimeout(
  4291. once(child, "exit"),
  4292. 5_000,
  4293. "failed plugin host did not exit",
  4294. )) as [number | null, NodeJS.Signals | null];
  4295. assert.equal(exitCode, 1);
  4296. assert.equal(signal, null);
  4297. assert.match(stderr, /Plugin host failed: expected initialization failure/u);
  4298. } finally {
  4299. if (child && child.exitCode === null && child.signalCode === null) {
  4300. child.kill("SIGKILL");
  4301. await once(child, "exit");
  4302. }
  4303. await rm(root, { force: true, recursive: true });
  4304. }
  4305. });
  4306. test("zcode plugins enable persists the selected plugin", async () => {
  4307. const ctx = createContext(["plugins", "enable", "ios-dev"]);
  4308. const exitCode = await run(ctx, {
  4309. cwd: () => "/workspace/project",
  4310. setPluginEnabled: async (options) => {
  4311. assert.equal(options.enabled, true);
  4312. assert.equal(options.plugin, "ios-dev");
  4313. assert.equal(options.workingDirectory, "/workspace/project");
  4314. return {
  4315. enabled: true,
  4316. path: "/home/test/.zcode/cli/config.json",
  4317. plugin: {
  4318. commandRootCount: 1,
  4319. dataPath: "/tmp/zcode/plugins/data/ios-dev@zcode-plugins-official",
  4320. enabled: true,
  4321. id: "ios-dev@zcode-plugins-official",
  4322. manifestPath: "/plugins/ios/.zcode-plugin/plugin.json",
  4323. marketplace: "zcode-plugins-official",
  4324. mcpServerNames: ["ios-simulator"],
  4325. name: "ios-dev",
  4326. rootPath: "/plugins/ios",
  4327. skillCount: 1,
  4328. skillRootCount: 1,
  4329. source: "official",
  4330. },
  4331. } as never;
  4332. },
  4333. });
  4334. assert.equal(exitCode, 0);
  4335. assert.match(
  4336. ctx.stdout.output(),
  4337. /Enabled plugin ios-dev@zcode-plugins-official in \/home\/test\/.zcode\/cli\/config\.json/,
  4338. );
  4339. });
  4340. test("prints slash help for prompt help command without creating an app", async () => {
  4341. const ctx = createContext(["--prompt", "/help"]);
  4342. let appCreated = false;
  4343. const exitCode = await run(ctx, {
  4344. createZCodeApp: () => {
  4345. appCreated = true;
  4346. throw new Error("app should not be created");
  4347. },
  4348. });
  4349. assert.equal(exitCode, 0);
  4350. assert.equal(appCreated, false);
  4351. assert.match(ctx.stdout.output(), /Slash commands:/);
  4352. assert.match(ctx.stdout.output(), /\/help \[command\]/);
  4353. assert.match(ctx.stdout.output(), /Use \/help <command> for details\./);
  4354. assert.equal(ctx.stderr.output(), "");
  4355. });
  4356. test("lists skills in human format", async () => {
  4357. const ctx = createContext(["skills", "list", "--verbose"]);
  4358. const logger = {} as NonNullable<RunDependencies["logger"]>;
  4359. const exitCode = await run(ctx, {
  4360. cwd: () => "/workspace/project",
  4361. logger,
  4362. listSkills: async (options) => {
  4363. assert.equal(options.logger, logger);
  4364. assert.equal(options.workingDirectory, "/workspace/project");
  4365. return {
  4366. diagnostics: [
  4367. {
  4368. code: "skill_scan_failed",
  4369. message: "Failed to scan skill directory: demo",
  4370. path: "/workspace/project/.zcode/skills/demo/SKILL.md",
  4371. severity: "warning",
  4372. skillName: "demo",
  4373. },
  4374. ],
  4375. skills: [
  4376. {
  4377. description: "Use for demo tasks.",
  4378. directory: "/workspace/project/.zcode/skills/demo",
  4379. frontmatterKeys: ["name", "description", "version"],
  4380. name: "demo",
  4381. path: "/workspace/project/.zcode/skills/demo/SKILL.md",
  4382. rootPath: "/workspace/project/.zcode/skills",
  4383. safeToAutoLoad: true,
  4384. scope: "project",
  4385. source: "zcode",
  4386. },
  4387. ],
  4388. totalDiscovered: 1,
  4389. } as never;
  4390. },
  4391. });
  4392. const output = ctx.stdout.output();
  4393. assert.equal(exitCode, 0);
  4394. assert.match(output, /Available skills \(1\)/);
  4395. assert.match(output, /demo \(project\/zcode\)/);
  4396. assert.match(output, /Use for demo tasks\./);
  4397. assert.match(output, /Diagnostics \(1\)/);
  4398. assert.equal(ctx.stderr.output(), "");
  4399. });
  4400. test("lists skills for bare prompt skill command", async () => {
  4401. const ctx = createContext(["--prompt", "/skill"]);
  4402. let listed = false;
  4403. let appCreated = false;
  4404. const exitCode = await run(ctx, {
  4405. createZCodeApp: () => {
  4406. appCreated = true;
  4407. throw new Error("app should not be created");
  4408. },
  4409. cwd: () => "/workspace/project",
  4410. listSkills: async (options) => {
  4411. listed = true;
  4412. assert.equal(options.workingDirectory, "/workspace/project");
  4413. return {
  4414. diagnostics: [],
  4415. skills: [
  4416. {
  4417. description: "Review React code.",
  4418. directory: "/workspace/project/.zcode/skills/react",
  4419. frontmatterKeys: ["name", "description"],
  4420. name: "react-review",
  4421. path: "/workspace/project/.zcode/skills/react/SKILL.md",
  4422. rootPath: "/workspace/project/.zcode/skills",
  4423. safeToAutoLoad: true,
  4424. scope: "project",
  4425. source: "zcode",
  4426. },
  4427. ],
  4428. totalDiscovered: 1,
  4429. } as never;
  4430. },
  4431. });
  4432. assert.equal(exitCode, 0);
  4433. assert.equal(listed, true);
  4434. assert.equal(appCreated, false);
  4435. assert.match(ctx.stdout.output(), /Available skills \(1\)/);
  4436. assert.match(ctx.stdout.output(), /react-review \(project\/zcode\)/);
  4437. assert.equal(ctx.stderr.output(), "");
  4438. });
  4439. test("lists skills in JSON format", async () => {
  4440. const ctx = createContext(["skills", "--json"]);
  4441. const exitCode = await run(ctx, {
  4442. cwd: () => "/workspace/project",
  4443. listSkills: async () =>
  4444. ({
  4445. diagnostics: [],
  4446. skills: [
  4447. {
  4448. description: "Review React code.",
  4449. directory: "/workspace/project/.zcode/skills/react",
  4450. frontmatterKeys: ["name", "description", "when_to_use"],
  4451. name: "react-review",
  4452. path: "/workspace/project/.zcode/skills/react/SKILL.md",
  4453. rootPath: "/workspace/project/.zcode/skills",
  4454. safeToAutoLoad: true,
  4455. scope: "project",
  4456. source: "zcode",
  4457. whenToUse: "When React files change.",
  4458. },
  4459. ],
  4460. totalDiscovered: 1,
  4461. }) as never,
  4462. });
  4463. const payload = JSON.parse(ctx.stdout.output()) as {
  4464. cwd: string;
  4465. skills: Array<{ name: string; source: string; whenToUse?: string }>;
  4466. totalDiscovered: number;
  4467. };
  4468. assert.equal(exitCode, 0);
  4469. assert.equal(payload.cwd, "/workspace/project");
  4470. assert.equal(payload.skills[0]?.name, "react-review");
  4471. assert.equal(payload.skills[0]?.source, "zcode");
  4472. assert.equal(payload.skills[0]?.whenToUse, "When React files change.");
  4473. assert.equal(payload.totalDiscovered, 1);
  4474. assert.equal(ctx.stderr.output(), "");
  4475. });
  4476. test("rejects unknown skills subcommands", async () => {
  4477. const ctx = createContext(["skills", "missing"]);
  4478. const exitCode = await run(ctx, {
  4479. listSkills: async () => {
  4480. throw new Error("should not list");
  4481. },
  4482. });
  4483. assert.equal(exitCode, 1);
  4484. assert.match(ctx.stderr.output(), /Unknown skills command: missing/);
  4485. assert.match(ctx.stderr.output(), /Usage: zcode skills \[list\|inspect <name>\]/);
  4486. assert.equal(ctx.stdout.output(), "");
  4487. });
  4488. test("loads nearest dotenv without overriding shell env", async () => {
  4489. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dotenv-"));
  4490. const nested = join(tempRoot, "project", "nested");
  4491. try {
  4492. await mkdir(nested, { recursive: true });
  4493. await writeFile(
  4494. join(tempRoot, ".env"),
  4495. ["ZCODE_API_KEY=from-file", "ZCODE_BASE_URL=https://example.test"].join("\n"),
  4496. );
  4497. const env: NodeJS.ProcessEnv = {
  4498. ZCODE_API_KEY: "from-shell",
  4499. };
  4500. const result = loadCliDotenv({ cwd: nested, env });
  4501. assert.equal(findDotenv(nested), join(tempRoot, ".env"));
  4502. assert.equal(result.loaded, true);
  4503. assert.deepEqual(result.keys.sort(), ["ZCODE_API_KEY", "ZCODE_BASE_URL"].sort());
  4504. assert.equal(env.ZCODE_API_KEY, "from-shell");
  4505. assert.equal(env.ZCODE_BASE_URL, "https://example.test");
  4506. } finally {
  4507. await rm(tempRoot, { recursive: true, force: true });
  4508. }
  4509. });
  4510. test("loads dotenv before creating the prompt app", async () => {
  4511. const env: NodeJS.ProcessEnv = {};
  4512. const ctx = createContext(["--prompt", "hello env"]);
  4513. let appEnv: NodeJS.ProcessEnv | undefined;
  4514. const exitCode = await run(ctx, {
  4515. ...createPromptDeps(),
  4516. createZCodeApp: (options) => {
  4517. appEnv = options?.env;
  4518. return {
  4519. sessionId: "session-test",
  4520. traceId: "trace-test",
  4521. runtime: {} as never,
  4522. submitPrompt: async (prompt: string) => ({
  4523. events: [],
  4524. projection: fakeProjection as never,
  4525. response: prompt,
  4526. traceId: "trace-test" as never,
  4527. turnId: "turn-test" as never,
  4528. }),
  4529. } as never;
  4530. },
  4531. env,
  4532. loadDotenv: (options) => {
  4533. if (options?.env) {
  4534. options.env.ZCODE_API_KEY = "loaded-at-runtime";
  4535. }
  4536. return {
  4537. keys: ["ZCODE_API_KEY"],
  4538. loaded: true,
  4539. path: "/tmp/project/.env",
  4540. };
  4541. },
  4542. });
  4543. assert.equal(exitCode, 0);
  4544. assert.equal(appEnv?.ZCODE_API_KEY, "loaded-at-runtime");
  4545. assert.equal(ctx.stdout.output(), "hello env\n");
  4546. assert.equal(ctx.stderr.output(), "");
  4547. });
  4548. test("runs a single prompt without opening the TUI", async () => {
  4549. const ctx = createContext(["--prompt", "hello runtime"]);
  4550. const exitCode = await run(ctx, createPromptDeps());
  4551. assert.equal(exitCode, 0);
  4552. assert.equal(ctx.stdout.output(), "hello runtime\n");
  4553. assert.equal(ctx.stderr.output(), "");
  4554. });
  4555. test("passes the CLI version into app creation for prompt runs", async () => {
  4556. const ctx = createContext(["--prompt", "hello version"]);
  4557. let appVersion: string | undefined;
  4558. const exitCode = await run(ctx, {
  4559. ...createPromptDeps(),
  4560. createZCodeApp: (options) => {
  4561. appVersion = options?.version;
  4562. return {
  4563. getModel: () => "openai/gpt-test",
  4564. getThoughtLevel: () => "medium",
  4565. sessionId: "session-test",
  4566. traceId: "trace-test",
  4567. runtime: {} as never,
  4568. submitPrompt: async (prompt: string) => ({
  4569. events: [],
  4570. projection: fakeProjection as never,
  4571. response: prompt,
  4572. traceId: "trace-test" as never,
  4573. turnId: "turn-test" as never,
  4574. }),
  4575. } as never;
  4576. },
  4577. });
  4578. assert.equal(exitCode, 0);
  4579. assert.equal(appVersion, "0.0.0");
  4580. });
  4581. test("passes prompt attachments into the app API", async () => {
  4582. const ctx = createContext([
  4583. "--prompt",
  4584. "describe",
  4585. "--attach",
  4586. "screen.png",
  4587. "--attach",
  4588. "notes.txt",
  4589. "--attach",
  4590. "demo.MP4",
  4591. ]);
  4592. let submitted: unknown;
  4593. const exitCode = await run(ctx, {
  4594. ...createPromptDeps(),
  4595. createZCodeApp: () =>
  4596. ({
  4597. sessionId: "session-test",
  4598. traceId: "trace-test",
  4599. runtime: {} as never,
  4600. submitPrompt: async (prompt: unknown) => {
  4601. submitted = prompt;
  4602. return {
  4603. events: [],
  4604. projection: fakeProjection as never,
  4605. response: "done",
  4606. traceId: "trace-test" as never,
  4607. turnId: "turn-test" as never,
  4608. };
  4609. },
  4610. }) as never,
  4611. });
  4612. assert.equal(exitCode, 0);
  4613. assert.deepEqual(submitted, {
  4614. text: "describe",
  4615. attachments: [
  4616. { type: "image", path: "screen.png" },
  4617. { type: "file", path: "notes.txt" },
  4618. { type: "video", path: "demo.MP4" },
  4619. ],
  4620. });
  4621. assert.equal(ctx.stdout.output(), "done\n");
  4622. });
  4623. test("rewrites skill slash commands for single prompts", async () => {
  4624. const ctx = createContext(["--prompt", "/skill demo-skill update docs"]);
  4625. let submitted = "";
  4626. const exitCode = await run(ctx, {
  4627. ...createPromptDeps(),
  4628. createZCodeApp: () =>
  4629. ({
  4630. sessionId: "session-test",
  4631. traceId: "trace-test",
  4632. runtime: {} as never,
  4633. submitPrompt: async (prompt: string) => {
  4634. submitted = prompt;
  4635. return {
  4636. events: [],
  4637. projection: fakeProjection as never,
  4638. response: "done",
  4639. traceId: "trace-test" as never,
  4640. turnId: "turn-test" as never,
  4641. };
  4642. },
  4643. }) as never,
  4644. });
  4645. assert.equal(exitCode, 0);
  4646. assert.equal(submitted, buildManualSkillPrompt("demo-skill", "update docs"));
  4647. assert.equal(ctx.stdout.output(), "done\n");
  4648. assert.equal(ctx.stderr.output(), "");
  4649. });
  4650. test("rejects goal replacement flag without target", async () => {
  4651. const ctx = createContext(["--target-replace"]);
  4652. const exitCode = await run(ctx, createPromptDeps());
  4653. assert.equal(exitCode, 1);
  4654. assert.match(ctx.stderr.output(), /--target-replace requires --target/);
  4655. assert.equal(ctx.stdout.output(), "");
  4656. });
  4657. test("runs goal command without prompt", async () => {
  4658. const ctx = createContext(["--target", "Ship target MVP"]);
  4659. let continued = false;
  4660. const exitCode = await run(ctx, {
  4661. ...createPromptDeps(),
  4662. createZCodeApp: (options) => {
  4663. assert.deepEqual(options?.runtimeConfig?.memory, {
  4664. extractionEnabled: false,
  4665. });
  4666. return {
  4667. clearTarget: async () => false,
  4668. continueActiveTarget: async () => {
  4669. continued = true;
  4670. return {
  4671. projection: fakeProjection as never,
  4672. response: "continued target",
  4673. traceId: "trace-target-continue" as never,
  4674. turnId: "turn-target-continue" as never,
  4675. };
  4676. },
  4677. readTarget: async () => null,
  4678. sessionId: "session-target-continue",
  4679. setTarget: async ({ objective, status = "active" }) => ({
  4680. objective,
  4681. sessionID: "session-target-continue",
  4682. status,
  4683. targetID: "target-continue",
  4684. time: { created: 1, updated: 1 },
  4685. }),
  4686. traceId: "trace-target-continue",
  4687. runtime: {} as never,
  4688. submitPrompt: async () => {
  4689. throw new Error("prompt should not run");
  4690. },
  4691. updateTargetStatus: async () => null,
  4692. } as never;
  4693. },
  4694. });
  4695. assert.equal(exitCode, 0);
  4696. assert.equal(continued, true);
  4697. assert.equal(ctx.stdout.output(), "continued target\n");
  4698. assert.equal(ctx.stderr.output(), "");
  4699. });
  4700. // 修复回归:--target 走 command center,原来命令返回就输出并退出。目标续跑遇到后台子代理时先推迟,
  4701. // 进程随即退出,子代理被杀,通知回合里的续跑也没有发生。
  4702. test("a target run waits for background work before it writes the result", async () => {
  4703. const ctx = createContext(["--target", "Ship target MVP"]);
  4704. let busyPolls = 2;
  4705. let polls = 0;
  4706. const exitCode = await run(ctx, {
  4707. ...createPromptDeps(),
  4708. createZCodeApp: () =>
  4709. ({
  4710. clearTarget: async () => false,
  4711. continueActiveTarget: async () => ({
  4712. projection: fakeProjection as never,
  4713. response: "continued target",
  4714. traceId: "trace-target-wait" as never,
  4715. turnId: "turn-target-wait" as never,
  4716. }),
  4717. readTarget: async () => null,
  4718. sessionId: "session-target-wait",
  4719. setTarget: async ({
  4720. objective,
  4721. status = "active",
  4722. }: {
  4723. objective: string;
  4724. status?: string;
  4725. }) => ({
  4726. objective,
  4727. sessionID: "session-target-wait",
  4728. status,
  4729. targetID: "target-wait",
  4730. time: { created: 1, updated: 1 },
  4731. }),
  4732. traceId: "trace-target-wait",
  4733. runtime: {
  4734. hasActiveOrQueuedTurnWork: () => false,
  4735. hasRunningBackgroundTasks: () => {
  4736. polls += 1;
  4737. // 后台工作结束前不能写出结果。
  4738. assert.equal(ctx.stdout.output(), "");
  4739. return busyPolls-- > 0;
  4740. },
  4741. },
  4742. submitPrompt: async () => {
  4743. throw new Error("prompt should not run");
  4744. },
  4745. updateTargetStatus: async () => null,
  4746. }) as never,
  4747. });
  4748. assert.equal(exitCode, 0);
  4749. assert.equal(polls, 3);
  4750. assert.equal(ctx.stdout.output(), "continued target\n");
  4751. assert.equal(ctx.stderr.output(), "");
  4752. });
  4753. test("passes force MCS into target runtime config", async () => {
  4754. const ctx = createContext(["--force-mcs", "--target", "Ship target MVP"]);
  4755. let continued = false;
  4756. const exitCode = await run(ctx, {
  4757. ...createPromptDeps(),
  4758. createZCodeApp: (options) => {
  4759. assert.deepEqual((options?.runtimeConfig as any)?.midConversationSystem, {
  4760. mode: "force",
  4761. });
  4762. return {
  4763. clearTarget: async () => false,
  4764. continueActiveTarget: async () => {
  4765. continued = true;
  4766. return {
  4767. projection: fakeProjection as never,
  4768. response: "continued target",
  4769. traceId: "trace-target-force-mcs" as never,
  4770. turnId: "turn-target-force-mcs" as never,
  4771. };
  4772. },
  4773. readTarget: async () => null,
  4774. sessionId: "session-target-force-mcs",
  4775. setTarget: async ({ objective, status = "active" }) => ({
  4776. objective,
  4777. sessionID: "session-target-force-mcs",
  4778. status,
  4779. targetID: "target-force-mcs",
  4780. time: { created: 1, updated: 1 },
  4781. }),
  4782. traceId: "trace-target-force-mcs",
  4783. runtime: {} as never,
  4784. submitPrompt: async () => {
  4785. throw new Error("prompt should not run");
  4786. },
  4787. updateTargetStatus: async () => null,
  4788. } as never;
  4789. },
  4790. });
  4791. assert.equal(exitCode, 0);
  4792. assert.equal(continued, true);
  4793. assert.equal(ctx.stdout.output(), "continued target\n");
  4794. assert.equal(ctx.stderr.output(), "");
  4795. });
  4796. test("rejects empty target text", async () => {
  4797. const ctx = createContext(["--target", " "]);
  4798. const exitCode = await run(ctx, createPromptDeps());
  4799. assert.equal(exitCode, 1);
  4800. assert.match(ctx.stderr.output(), /--target requires non-empty text/);
  4801. assert.equal(ctx.stdout.output(), "");
  4802. });
  4803. test("rejects combining target with prompt", async () => {
  4804. const ctx = createContext(["--prompt", "hello target", "--target", "Ship target MVP"]);
  4805. const exitCode = await run(ctx, {
  4806. ...createPromptDeps(),
  4807. createZCodeApp: () =>
  4808. ({
  4809. sessionId: "session-test",
  4810. traceId: "trace-test",
  4811. runtime: {} as never,
  4812. submitPrompt: async () => {
  4813. throw new Error("prompt should not run");
  4814. },
  4815. }) as never,
  4816. });
  4817. assert.equal(exitCode, 1);
  4818. assert.match(ctx.stderr.output(), /--target cannot be used with --prompt/);
  4819. assert.equal(ctx.stdout.output(), "");
  4820. });
  4821. test("closes the app after a headless prompt", async () => {
  4822. const ctx = createContext(["--prompt", "hello"]);
  4823. let closeCount = 0;
  4824. const exitCode = await run(ctx, {
  4825. ...createPromptDeps(),
  4826. createZCodeApp: () =>
  4827. ({
  4828. sessionId: "session-test",
  4829. traceId: "trace-test",
  4830. runtime: {} as never,
  4831. close: async () => {
  4832. closeCount += 1;
  4833. },
  4834. submitPrompt: async (prompt: string) => ({
  4835. events: [],
  4836. projection: fakeProjection as never,
  4837. response: prompt,
  4838. traceId: "trace-test" as never,
  4839. turnId: "turn-test" as never,
  4840. }),
  4841. }) as never,
  4842. });
  4843. assert.equal(exitCode, 0);
  4844. assert.equal(closeCount, 1);
  4845. assert.equal(ctx.stdout.output(), "hello\n");
  4846. });
  4847. test("shuts down prepared telemetry after a headless prompt", async () => {
  4848. const ctx = createContext(["--prompt", "hello telemetry"]);
  4849. let telemetryShutdownCount = 0;
  4850. const exitCode = await run(ctx, {
  4851. ...createPromptDeps(),
  4852. prepareZCodeTelemetryEnv: async (env) => env,
  4853. shutdownZCodeTelemetry: async () => {
  4854. telemetryShutdownCount += 1;
  4855. },
  4856. });
  4857. assert.equal(exitCode, 0);
  4858. assert.equal(telemetryShutdownCount, 1);
  4859. });
  4860. test("shuts down prepared telemetry when headless app creation fails", async () => {
  4861. const ctx = createContext(["--prompt", "failing telemetry"]);
  4862. let telemetryShutdownCount = 0;
  4863. const exitCode = await run(ctx, {
  4864. ...createPromptDeps(),
  4865. createZCodeApp: () => {
  4866. throw new Error("app creation failed");
  4867. },
  4868. prepareZCodeTelemetryEnv: async (env) => env,
  4869. shutdownZCodeTelemetry: async () => {
  4870. telemetryShutdownCount += 1;
  4871. },
  4872. });
  4873. assert.equal(exitCode, 1);
  4874. assert.equal(telemetryShutdownCount, 1);
  4875. });
  4876. test("aborts and closes the headless app on process shutdown signals", async () => {
  4877. const ctx = createContext(["--prompt", "hello"]);
  4878. const shutdownProcess = createTestShutdownProcess("linux");
  4879. const exitDeferred = createDeferred<number>();
  4880. const promptStarted = createDeferred<void>();
  4881. let closeCount = 0;
  4882. let abortSeen = false;
  4883. const runPromise = run(ctx, {
  4884. ...createPromptDeps(),
  4885. createZCodeApp: () =>
  4886. ({
  4887. close: async () => {
  4888. closeCount += 1;
  4889. },
  4890. runtime: {} as never,
  4891. sessionId: "session-test",
  4892. submitPrompt: async (_prompt: string, options?: { abortSignal?: AbortSignal }) => {
  4893. promptStarted.resolve();
  4894. return await new Promise<never>((_resolve, reject) => {
  4895. options?.abortSignal?.addEventListener(
  4896. "abort",
  4897. () => {
  4898. abortSeen = true;
  4899. reject(new Error("aborted by signal"));
  4900. },
  4901. { once: true },
  4902. );
  4903. });
  4904. },
  4905. traceId: "trace-test",
  4906. }) as never,
  4907. exitProcess: (code) => {
  4908. exitDeferred.resolve(code);
  4909. },
  4910. shutdownProcess,
  4911. });
  4912. await promptStarted.promise;
  4913. shutdownProcess.emitSignal("SIGTERM");
  4914. assert.equal(await exitDeferred.promise, 143);
  4915. assert.equal(await runPromise, 1);
  4916. assert.equal(abortSeen, true);
  4917. assert.equal(closeCount, 1);
  4918. });
  4919. // 修复回归:等待期间收到信号时,等待立即返回,原来仍把结果写到 stdout,评测读到一行像正常结束的结果。
  4920. for (const args of [
  4921. ["--prompt", "hello"],
  4922. ["--target", "Ship target MVP"],
  4923. ] as const) {
  4924. test(`a signal during the background wait writes no result (${args[0]})`, async () => {
  4925. const ctx = createContext([...args]);
  4926. const shutdownProcess = createTestShutdownProcess("linux");
  4927. const exitDeferred = createDeferred<number>();
  4928. let signalled = false;
  4929. const turn = {
  4930. events: [],
  4931. projection: fakeProjection as never,
  4932. response: "first turn",
  4933. traceId: "trace-signal-wait" as never,
  4934. turnId: "turn-signal-wait" as never,
  4935. };
  4936. const exitCode = await run(ctx, {
  4937. ...createPromptDeps(),
  4938. createZCodeApp: () =>
  4939. ({
  4940. clearTarget: async () => false,
  4941. continueActiveTarget: async () => turn,
  4942. readTarget: async () => null,
  4943. sessionId: "session-signal-wait",
  4944. setTarget: async ({
  4945. objective,
  4946. status = "active",
  4947. }: {
  4948. objective: string;
  4949. status?: string;
  4950. }) => ({
  4951. objective,
  4952. sessionID: "session-signal-wait",
  4953. status,
  4954. targetID: "target-signal-wait",
  4955. time: { created: 1, updated: 1 },
  4956. }),
  4957. traceId: "trace-signal-wait",
  4958. runtime: {
  4959. hasActiveOrQueuedTurnWork: () => false,
  4960. // 后台工作一直在跑;第一次检查时调用方发出 SIGTERM。
  4961. hasRunningBackgroundTasks: () => {
  4962. if (!signalled) {
  4963. signalled = true;
  4964. shutdownProcess.emitSignal("SIGTERM");
  4965. }
  4966. return true;
  4967. },
  4968. },
  4969. submitPrompt: async () => turn,
  4970. updateTargetStatus: async () => null,
  4971. }) as never,
  4972. exitProcess: (code) => {
  4973. exitDeferred.resolve(code);
  4974. },
  4975. shutdownProcess,
  4976. });
  4977. assert.equal(await exitDeferred.promise, 143);
  4978. assert.equal(exitCode, 1);
  4979. assert.equal(ctx.stdout.output(), "");
  4980. assert.match(ctx.stderr.output(), /CLI received SIGTERM/);
  4981. });
  4982. }
  4983. test("closes a late async app without submitting after shutdown during initialization", async () => {
  4984. const ctx = createContext(["--prompt", "hello"]);
  4985. const shutdownProcess = createTestShutdownProcess("linux");
  4986. const started = createDeferred<void>();
  4987. const release = createDeferred<void>();
  4988. const exited = createDeferred<number>();
  4989. let closed = 0;
  4990. let submitted = 0;
  4991. const running = run(ctx, {
  4992. ...createPromptDeps(),
  4993. shutdownProcess,
  4994. exitProcess: (code) => exited.resolve(code),
  4995. createZCodeApp: async () => {
  4996. started.resolve();
  4997. await release.promise;
  4998. return {
  4999. close: async () => {
  5000. closed += 1;
  5001. },
  5002. submitPrompt: async () => {
  5003. submitted += 1;
  5004. throw new Error("must not submit");
  5005. },
  5006. runtime: {},
  5007. sessionId: "late-app",
  5008. traceId: "late-trace",
  5009. } as never;
  5010. },
  5011. });
  5012. await started.promise;
  5013. shutdownProcess.emitSignal("SIGTERM");
  5014. assert.equal(await exited.promise, 143);
  5015. release.resolve();
  5016. assert.equal(await running, 1);
  5017. assert.equal(submitted, 0);
  5018. assert.equal(closed, 1);
  5019. });
  5020. test("TUI closes an app that finishes initialization after handler shutdown", async () => {
  5021. const started = createDeferred<void>();
  5022. const release = createDeferred<void>();
  5023. let closed = 0;
  5024. const handler = createTuiSubmitPrompt(
  5025. {
  5026. ...createPromptDeps(),
  5027. createZCodeApp: async () => {
  5028. started.resolve();
  5029. await release.promise;
  5030. return {
  5031. close: async () => {
  5032. closed += 1;
  5033. },
  5034. getModel: () => "model",
  5035. } as never;
  5036. },
  5037. },
  5038. {},
  5039. "test",
  5040. );
  5041. const pending = handler.getSessionMetadata!();
  5042. // 立即注册 rejection observer,避免关闭与迟到返回之间产生未处理拒绝。
  5043. const rejected = assert.rejects(pending, /closed/);
  5044. await started.promise;
  5045. await handler.close?.();
  5046. release.resolve();
  5047. await rejected;
  5048. assert.equal(closed, 1);
  5049. });
  5050. test("rejects headless goal replacement without explicit target-replace", async () => {
  5051. const ctx = createContext(["--target", "New target"]);
  5052. const exitCode = await run(ctx, {
  5053. ...createPromptDeps(),
  5054. createZCodeApp: () =>
  5055. ({
  5056. clearTarget: async () => true,
  5057. continueActiveTarget: async () => null,
  5058. readTarget: async () => ({
  5059. objective: "Existing target",
  5060. sessionID: "session-test",
  5061. status: "active",
  5062. targetID: "target-existing",
  5063. time: { created: 1, updated: 1 },
  5064. }),
  5065. sessionId: "session-test",
  5066. setTarget: async () => {
  5067. throw new Error("target should not be replaced");
  5068. },
  5069. traceId: "trace-test",
  5070. runtime: {} as never,
  5071. submitPrompt: async () => {
  5072. throw new Error("prompt should not run");
  5073. },
  5074. updateTargetStatus: async () => null,
  5075. }) as never,
  5076. });
  5077. assert.equal(exitCode, 1);
  5078. assert.match(ctx.stderr.output(), /A goal already exists/);
  5079. assert.match(
  5080. ctx.stderr.output(),
  5081. /Headless goal commands cannot open an interactive replacement picker/,
  5082. );
  5083. assert.equal(ctx.stdout.output(), "");
  5084. });
  5085. test("replaces an existing goal for headless goal commands when target-replace is set", async () => {
  5086. const ctx = createContext(["--target", "New target", "--target-replace"]);
  5087. let replacedObjective = "";
  5088. let continued = false;
  5089. const exitCode = await run(ctx, {
  5090. ...createPromptDeps(),
  5091. createZCodeApp: () =>
  5092. ({
  5093. clearTarget: async () => true,
  5094. continueActiveTarget: async () => {
  5095. continued = true;
  5096. return {
  5097. projection: fakeProjection as never,
  5098. response: "continued target",
  5099. traceId: "trace-target-continue" as never,
  5100. turnId: "turn-target-continue" as never,
  5101. };
  5102. },
  5103. readTarget: async () => ({
  5104. objective: "Existing target",
  5105. sessionID: "session-test",
  5106. status: "active",
  5107. targetID: "target-existing",
  5108. time: { created: 1, updated: 1 },
  5109. }),
  5110. sessionId: "session-test",
  5111. setTarget: async (input: { objective: string; status?: string }) => {
  5112. replacedObjective = `${input.objective}:${input.status ?? "missing"}`;
  5113. return {
  5114. objective: input.objective,
  5115. sessionID: "session-test",
  5116. status: input.status ?? "active",
  5117. targetID: "target-replaced",
  5118. time: { created: 1, updated: 1 },
  5119. };
  5120. },
  5121. traceId: "trace-test",
  5122. runtime: {} as never,
  5123. submitPrompt: async () => {
  5124. throw new Error("prompt should not run");
  5125. },
  5126. updateTargetStatus: async () => null,
  5127. }) as never,
  5128. });
  5129. assert.equal(exitCode, 0);
  5130. assert.equal(replacedObjective, "New target:active");
  5131. assert.equal(continued, true);
  5132. assert.equal(ctx.stdout.output(), "continued target\n");
  5133. assert.equal(ctx.stderr.output(), "");
  5134. });
  5135. test("runs slash goal commands directly in headless prompt mode", async () => {
  5136. const ctx = createContext(["--prompt", "/goal Ship target MVP"]);
  5137. let continued = false;
  5138. const exitCode = await run(ctx, {
  5139. ...createPromptDeps(),
  5140. createZCodeApp: () =>
  5141. ({
  5142. clearTarget: async () => false,
  5143. continueActiveTarget: async () => {
  5144. continued = true;
  5145. return {
  5146. projection: fakeProjection as never,
  5147. response: "continued target",
  5148. traceId: "trace-target-continue" as never,
  5149. turnId: "turn-target-continue" as never,
  5150. };
  5151. },
  5152. readTarget: async () => null,
  5153. sessionId: "session-target-continue",
  5154. setTarget: async ({ objective, status = "active" }) => ({
  5155. objective,
  5156. sessionID: "session-target-continue",
  5157. status,
  5158. targetID: "target-continue",
  5159. time: { created: 1, updated: 1 },
  5160. }),
  5161. traceId: "trace-target-continue",
  5162. runtime: {} as never,
  5163. submitPrompt: async () => {
  5164. throw new Error("prompt should not run");
  5165. },
  5166. updateTargetStatus: async () => null,
  5167. }) as never,
  5168. });
  5169. assert.equal(exitCode, 0);
  5170. assert.equal(continued, true);
  5171. assert.equal(ctx.stdout.output(), "continued target\n");
  5172. assert.equal(ctx.stderr.output(), "");
  5173. });
  5174. test("rejects interactive goal replacement prompts in headless mode", async () => {
  5175. const ctx = createContext(["--prompt", "/goal New target"]);
  5176. const exitCode = await run(ctx, {
  5177. ...createPromptDeps(),
  5178. createZCodeApp: () =>
  5179. ({
  5180. clearTarget: async () => true,
  5181. continueActiveTarget: async () => null,
  5182. readTarget: async () => ({
  5183. objective: "Existing target",
  5184. sessionID: "session-target-existing",
  5185. status: "active",
  5186. targetID: "target-existing",
  5187. time: { created: 1, updated: 1 },
  5188. }),
  5189. sessionId: "session-target-existing",
  5190. setTarget: async () => {
  5191. throw new Error("replace should not happen without explicit confirmation");
  5192. },
  5193. traceId: "trace-target-existing",
  5194. runtime: {} as never,
  5195. submitPrompt: async () => {
  5196. throw new Error("prompt should not run");
  5197. },
  5198. updateTargetStatus: async () => null,
  5199. }) as never,
  5200. });
  5201. assert.equal(exitCode, 1);
  5202. assert.match(ctx.stderr.output(), /A goal already exists/);
  5203. assert.match(
  5204. ctx.stderr.output(),
  5205. /Headless goal commands cannot open an interactive replacement picker/,
  5206. );
  5207. assert.equal(ctx.stdout.output(), "");
  5208. });
  5209. test("defaults headless prompts to yolo mode", async () => {
  5210. const ctx = createContext(["--prompt", "hello default mode"]);
  5211. const exitCode = await run(ctx, {
  5212. ...createPromptDeps(),
  5213. createZCodeApp: (options) => {
  5214. assert.equal(options?.runtimeConfig?.mode, "yolo");
  5215. assert.equal(options?.runtimeConfig?.presentationSurface, "terminal");
  5216. return {
  5217. sessionId: "session-test",
  5218. traceId: "trace-test",
  5219. runtime: {} as never,
  5220. submitPrompt: async (prompt: string) => ({
  5221. events: [],
  5222. projection: fakeProjection as never,
  5223. response: prompt,
  5224. traceId: "trace-test" as never,
  5225. turnId: "turn-test" as never,
  5226. }),
  5227. } as never;
  5228. },
  5229. });
  5230. assert.equal(exitCode, 0);
  5231. assert.equal(ctx.stdout.output(), "hello default mode\n");
  5232. });
  5233. test("passes the Desktop presentation surface into headless runtime config", async () => {
  5234. const ctx = createContext(["--surface", "desktop", "--prompt", "hello desktop"]);
  5235. const exitCode = await run(ctx, {
  5236. ...createPromptDeps(),
  5237. createZCodeApp: (options) => {
  5238. assert.equal(options?.runtimeConfig?.presentationSurface, "zcode_desktop");
  5239. assert.equal(options?.sourceTitle, undefined);
  5240. return {
  5241. sessionId: "session-test",
  5242. traceId: "trace-test",
  5243. runtime: {} as never,
  5244. submitPrompt: async (prompt: string) => ({
  5245. events: [],
  5246. projection: fakeProjection as never,
  5247. response: prompt,
  5248. traceId: "trace-test" as never,
  5249. turnId: "turn-test" as never,
  5250. }),
  5251. } as never;
  5252. },
  5253. });
  5254. assert.equal(exitCode, 0);
  5255. assert.equal(ctx.stdout.output(), "hello desktop\n");
  5256. });
  5257. test("rejects unsupported presentation surfaces", async () => {
  5258. const ctx = createContext(["--surface", "web", "--prompt", "hello"]);
  5259. const exitCode = await run(ctx, createPromptDeps());
  5260. assert.equal(exitCode, 1);
  5261. assert.match(ctx.stderr.output(), /Unsupported --surface value: web/);
  5262. assert.equal(ctx.stdout.output(), "");
  5263. });
  5264. test("rejects the presentation surface option outside supported commands", async () => {
  5265. const ctx = createContext(["doctor", "--surface", "desktop"]);
  5266. const exitCode = await run(ctx);
  5267. assert.equal(exitCode, 1);
  5268. assert.match(
  5269. ctx.stderr.output(),
  5270. /--surface can only be used with --prompt, --target, app-server, or agent-server/,
  5271. );
  5272. assert.equal(ctx.stdout.output(), "");
  5273. });
  5274. test("passes prompt mode override into runtime config", async () => {
  5275. const ctx = createContext(["--prompt", "hello mode", "--mode", "plan"]);
  5276. const exitCode = await run(ctx, {
  5277. ...createPromptDeps(),
  5278. createZCodeApp: (options) => {
  5279. assert.equal(options?.runtimeConfig?.mode, "plan");
  5280. return {
  5281. sessionId: "session-test",
  5282. traceId: "trace-test",
  5283. runtime: {} as never,
  5284. submitPrompt: async (prompt: string) => ({
  5285. events: [],
  5286. projection: fakeProjection as never,
  5287. response: prompt,
  5288. traceId: "trace-test" as never,
  5289. turnId: "turn-test" as never,
  5290. }),
  5291. } as never;
  5292. },
  5293. });
  5294. assert.equal(exitCode, 0);
  5295. assert.equal(ctx.stdout.output(), "hello mode\n");
  5296. });
  5297. test("passes force MCS into headless runtime config", async () => {
  5298. const ctx = createContext(["--force-mcs", "--prompt", "hello force mcs"]);
  5299. const exitCode = await run(ctx, {
  5300. ...createPromptDeps(),
  5301. createZCodeApp: (options) => {
  5302. assert.deepEqual((options?.runtimeConfig as any)?.midConversationSystem, {
  5303. mode: "force",
  5304. });
  5305. return {
  5306. sessionId: "session-test",
  5307. traceId: "trace-test",
  5308. runtime: {} as never,
  5309. submitPrompt: async (prompt: string) => ({
  5310. events: [],
  5311. projection: fakeProjection as never,
  5312. response: prompt,
  5313. traceId: "trace-test" as never,
  5314. turnId: "turn-test" as never,
  5315. }),
  5316. } as never;
  5317. },
  5318. });
  5319. assert.equal(exitCode, 0);
  5320. assert.equal(ctx.stdout.output(), "hello force mcs\n");
  5321. });
  5322. test("passes --disallowedTools into headless runtime config", async () => {
  5323. const ctx = createContext([
  5324. "--prompt",
  5325. "hello disallowed tools",
  5326. "--disallowedTools",
  5327. "Bash(git *) Edit,web_search",
  5328. ]);
  5329. const exitCode = await run(ctx, {
  5330. ...createPromptDeps(),
  5331. createZCodeApp: (options) => {
  5332. assert.deepEqual(options?.runtimeConfig?.toolDisallowlist, [
  5333. "Bash(git *)",
  5334. "Edit",
  5335. "WebSearch",
  5336. ]);
  5337. return {
  5338. sessionId: "session-test",
  5339. traceId: "trace-test",
  5340. runtime: {} as never,
  5341. submitPrompt: async (prompt: string) => ({
  5342. events: [],
  5343. projection: fakeProjection as never,
  5344. response: prompt,
  5345. traceId: "trace-test" as never,
  5346. turnId: "turn-test" as never,
  5347. }),
  5348. } as never;
  5349. },
  5350. });
  5351. assert.equal(exitCode, 0);
  5352. assert.equal(ctx.stdout.output(), "hello disallowed tools\n");
  5353. });
  5354. test("supports the prompt short alias with --disallowedTools", async () => {
  5355. const ctx = createContext(["-p", "hello short prompt", "--disallowedTools", "Bash"]);
  5356. const exitCode = await run(ctx, {
  5357. ...createPromptDeps(),
  5358. createZCodeApp: (options) => {
  5359. assert.deepEqual(options?.runtimeConfig?.toolDisallowlist, ["Bash"]);
  5360. return {
  5361. sessionId: "session-test",
  5362. traceId: "trace-test",
  5363. runtime: {} as never,
  5364. submitPrompt: async (prompt: string) => ({
  5365. events: [],
  5366. projection: fakeProjection as never,
  5367. response: prompt,
  5368. traceId: "trace-test" as never,
  5369. turnId: "turn-test" as never,
  5370. }),
  5371. } as never;
  5372. },
  5373. });
  5374. assert.equal(exitCode, 0);
  5375. assert.equal(ctx.stdout.output(), "hello short prompt\n");
  5376. });
  5377. test("supports dashed disallowed tools alias before the prompt option", async () => {
  5378. const ctx = createContext([
  5379. "--disallowed-tools",
  5380. "Bash",
  5381. "Edit",
  5382. "--prompt",
  5383. "hello dashed disallowed tools",
  5384. ]);
  5385. const exitCode = await run(ctx, {
  5386. ...createPromptDeps(),
  5387. createZCodeApp: (options) => {
  5388. assert.deepEqual(options?.runtimeConfig?.toolDisallowlist, ["Bash", "Edit"]);
  5389. return {
  5390. sessionId: "session-test",
  5391. traceId: "trace-test",
  5392. runtime: {} as never,
  5393. submitPrompt: async (prompt: string) => ({
  5394. events: [],
  5395. projection: fakeProjection as never,
  5396. response: prompt,
  5397. traceId: "trace-test" as never,
  5398. turnId: "turn-test" as never,
  5399. }),
  5400. } as never;
  5401. },
  5402. });
  5403. assert.equal(exitCode, 0);
  5404. assert.equal(ctx.stdout.output(), "hello dashed disallowed tools\n");
  5405. });
  5406. test("passes edit prompt mode override into runtime config", async () => {
  5407. const ctx = createContext(["--prompt", "hello edit mode", "--mode", "edit"]);
  5408. const exitCode = await run(ctx, {
  5409. ...createPromptDeps(),
  5410. createZCodeApp: (options) => {
  5411. assert.equal(options?.runtimeConfig?.mode, "edit");
  5412. return {
  5413. sessionId: "session-test",
  5414. traceId: "trace-test",
  5415. runtime: {} as never,
  5416. submitPrompt: async (prompt: string) => ({
  5417. events: [],
  5418. projection: fakeProjection as never,
  5419. response: prompt,
  5420. traceId: "trace-test" as never,
  5421. turnId: "turn-test" as never,
  5422. }),
  5423. } as never;
  5424. },
  5425. });
  5426. assert.equal(exitCode, 0);
  5427. assert.equal(ctx.stdout.output(), "hello edit mode\n");
  5428. });
  5429. test("passes the CLI cwd into prompt runtime config", async () => {
  5430. const ctx = createContext(["--prompt", "hello cwd"]);
  5431. const cwd = join(tmpdir(), "zcode-cli-cwd-test");
  5432. const exitCode = await run(ctx, {
  5433. ...createPromptDeps(),
  5434. cwd: () => cwd,
  5435. createZCodeApp: (options) => {
  5436. assert.equal(options?.runtimeConfig?.workingDirectory, cwd);
  5437. return {
  5438. sessionId: "session-test",
  5439. traceId: "trace-test",
  5440. runtime: {} as never,
  5441. submitPrompt: async (prompt: string) => ({
  5442. events: [],
  5443. projection: fakeProjection as never,
  5444. response: prompt,
  5445. traceId: "trace-test" as never,
  5446. turnId: "turn-test" as never,
  5447. }),
  5448. } as never;
  5449. },
  5450. loadDotenv: (options) => {
  5451. assert.equal(options.cwd, cwd);
  5452. return {
  5453. keys: [],
  5454. loaded: false,
  5455. };
  5456. },
  5457. });
  5458. assert.equal(exitCode, 0);
  5459. assert.equal(ctx.stdout.output(), "hello cwd\n");
  5460. });
  5461. test("passes explicit resume session into prompt app creation", async () => {
  5462. const ctx = createContext(["--resume", "sess_existing", "--prompt", "hello resume"]);
  5463. const exitCode = await run(ctx, {
  5464. ...createPromptDeps(),
  5465. createZCodeApp: (options) => {
  5466. assert.equal(options?.resume, true);
  5467. assert.equal(options?.sessionId, "sess_existing");
  5468. return {
  5469. sessionId: "sess_existing",
  5470. traceId: "trace-test",
  5471. runtime: {} as never,
  5472. submitPrompt: async (prompt: string) => ({
  5473. events: [],
  5474. projection: fakeProjection as never,
  5475. response: prompt,
  5476. traceId: "trace-test" as never,
  5477. turnId: "turn-test" as never,
  5478. }),
  5479. } as never;
  5480. },
  5481. });
  5482. assert.equal(exitCode, 0);
  5483. assert.equal(ctx.stdout.output(), "hello resume\n");
  5484. });
  5485. test("resolves latest session for continue prompts", async () => {
  5486. const ctx = createContext(["--continue", "--prompt", "hello continue"]);
  5487. const cwd = join(tmpdir(), "zcode-cli-continue-test");
  5488. let resolved = false;
  5489. const exitCode = await run(ctx, {
  5490. ...createPromptDeps(),
  5491. cwd: () => cwd,
  5492. resolveLatestSession: async (options) => {
  5493. resolved = true;
  5494. assert.equal(options.directory, cwd);
  5495. return { id: "sess_latest" } as never;
  5496. },
  5497. createZCodeApp: (options) => {
  5498. assert.equal(options?.resume, true);
  5499. assert.equal(options?.sessionId, "sess_latest");
  5500. return {
  5501. sessionId: "sess_latest",
  5502. traceId: "trace-test",
  5503. runtime: {} as never,
  5504. submitPrompt: async (prompt: string) => ({
  5505. events: [],
  5506. projection: fakeProjection as never,
  5507. response: prompt,
  5508. traceId: "trace-test" as never,
  5509. turnId: "turn-test" as never,
  5510. }),
  5511. } as never;
  5512. },
  5513. });
  5514. assert.equal(exitCode, 0);
  5515. assert.equal(resolved, true);
  5516. assert.equal(ctx.stdout.output(), "hello continue\n");
  5517. });
  5518. test("rejects resume and continue together", async () => {
  5519. const ctx = createContext(["--resume", "sess_existing", "--continue", "--prompt", "hello"]);
  5520. const exitCode = await run(ctx, createPromptDeps());
  5521. assert.equal(exitCode, 1);
  5522. assert.match(ctx.stderr.output(), /--resume and --continue cannot be used together/);
  5523. assert.equal(ctx.stdout.output(), "");
  5524. });
  5525. test("rejects unsupported prompt mode", async () => {
  5526. const ctx = createContext(["--prompt", "hello mode", "--mode", "auto"]);
  5527. const exitCode = await run(ctx, createPromptDeps());
  5528. assert.equal(exitCode, 1);
  5529. assert.match(ctx.stderr.output(), /Unsupported --mode value/);
  5530. assert.equal(ctx.stdout.output(), "");
  5531. });
  5532. test("prints JSON for prompt command", async () => {
  5533. const ctx = createContext(["--prompt", "hello json", "--json"]);
  5534. const exitCode = await run(ctx, createPromptDeps());
  5535. const payload = JSON.parse(ctx.stdout.output()) as {
  5536. response: string;
  5537. traceId: string;
  5538. eventCount: number;
  5539. projection: { turnCount: number };
  5540. };
  5541. assert.equal(exitCode, 0);
  5542. assert.equal(payload.response, "hello json");
  5543. assert.equal(payload.traceId, "trace-test");
  5544. assert.equal(payload.eventCount, 2);
  5545. assert.equal(payload.projection.turnCount, 1);
  5546. });
  5547. test("prints provider token usage in prompt JSON", async () => {
  5548. const ctx = createContext(["--prompt", "hello usage", "--json"]);
  5549. const exitCode = await run(ctx, {
  5550. ...createPromptDeps(),
  5551. createZCodeApp: () =>
  5552. ({
  5553. sessionId: "session-test",
  5554. traceId: "trace-test",
  5555. runtime: {} as never,
  5556. submitPrompt: async () => ({
  5557. events: [],
  5558. projection: fakeProjection as never,
  5559. response: "done",
  5560. traceId: "trace-test" as never,
  5561. turnId: "turn-test" as never,
  5562. usage: {
  5563. source: "provider",
  5564. modelRequestCount: 1,
  5565. inputTokens: 11,
  5566. outputTokens: 3,
  5567. totalTokens: 14,
  5568. cacheReadTokens: 5,
  5569. cacheWriteTokens: 0,
  5570. reasoningTokens: 1,
  5571. },
  5572. }),
  5573. }) as never,
  5574. });
  5575. const payload = JSON.parse(ctx.stdout.output()) as {
  5576. usage: { source: string; totalTokens: number; cacheReadTokens: number };
  5577. };
  5578. assert.equal(exitCode, 0);
  5579. assert.equal(payload.usage.source, "provider");
  5580. assert.equal(payload.usage.totalTokens, 14);
  5581. assert.equal(payload.usage.cacheReadTokens, 5);
  5582. });
  5583. test("rejects empty prompt text", async () => {
  5584. const ctx = createContext(["--prompt", " "]);
  5585. const exitCode = await run(ctx);
  5586. assert.equal(exitCode, 1);
  5587. assert.match(ctx.stderr.output(), /--prompt requires non-empty text/);
  5588. assert.equal(ctx.stdout.output(), "");
  5589. });
  5590. test("prints JSON for doctor command", async () => {
  5591. const ctx = createContext(["doctor", "--json"]);
  5592. const originalTitle = process.title;
  5593. try {
  5594. setCliProcessTitle();
  5595. const exitCode = await run(ctx);
  5596. const payload = JSON.parse(ctx.stdout.output()) as {
  5597. cli: { name: string; processName: string };
  5598. packaging: { default: string; sea: string };
  5599. runtime: { node: string; processTitle: string };
  5600. };
  5601. assert.equal(exitCode, 0);
  5602. assert.equal(payload.cli.name, "zcode");
  5603. assert.equal(payload.cli.processName, CLI_PROCESS_NAME);
  5604. assert.equal(payload.runtime.node, process.version);
  5605. assert.equal(payload.runtime.processTitle, CLI_PROCESS_NAME);
  5606. assert.equal(payload.packaging.default, "node-bundle");
  5607. assert.equal(payload.packaging.sea, "optional");
  5608. } finally {
  5609. process.title = originalTitle;
  5610. }
  5611. });
  5612. test("prints human doctor details with verbose diagnostics", async () => {
  5613. const ctx = createContext(["doctor", "--verbose", "--no-color"]);
  5614. const originalTitle = process.title;
  5615. try {
  5616. setCliProcessTitle();
  5617. const exitCode = await run(ctx);
  5618. const output = ctx.stdout.output();
  5619. assert.equal(exitCode, 0);
  5620. assert.match(output, /zcode doctor/);
  5621. assert.match(output, /process: zcode-cli/);
  5622. assert.match(output, /execPath:/);
  5623. assert.match(output, /cwd:/);
  5624. assert.equal(output.includes("["), false);
  5625. } finally {
  5626. process.title = originalTitle;
  5627. }
  5628. });
  5629. test("rejects force MCS outside prompt, target, or TUI commands", async () => {
  5630. const ctx = createContext(["doctor", "--force-mcs"]);
  5631. const exitCode = await run(ctx);
  5632. assert.equal(exitCode, 1);
  5633. assert.match(ctx.stderr.output(), /--force-mcs can only be used with --prompt, --target, or tui/);
  5634. assert.equal(ctx.stdout.output(), "");
  5635. });
  5636. test("dispatches app-server stdio command to the ZCode Protocol runner without production dotenv", async () => {
  5637. const ctx = createContext(["app-server", "--stdio"]);
  5638. let called = false;
  5639. let dotenvCalls = 0;
  5640. const exitCode = await run(ctx, {
  5641. cwd: () => "/workspace",
  5642. loadDotenv: () => {
  5643. dotenvCalls += 1;
  5644. return {
  5645. keys: [],
  5646. loaded: false,
  5647. };
  5648. },
  5649. runZCodeProtocolAgent: async (options) => {
  5650. called = true;
  5651. assert.equal(options?.cwd, "/workspace");
  5652. assert.equal(options?.input, ctx.stdin);
  5653. assert.equal(options?.output, ctx.stdout);
  5654. assert.equal(options?.version, "0.0.0");
  5655. assert.equal(options?.presentationSurface, "terminal");
  5656. assert.equal(options?.env?.[ZCODE_RUNTIME_ENV_KEY], "production");
  5657. },
  5658. });
  5659. assert.equal(exitCode, 0);
  5660. assert.equal(called, true);
  5661. assert.equal(dotenvCalls, 0);
  5662. assert.equal(ctx.stderr.output(), "");
  5663. });
  5664. test("redirects every protocol console level to stderr and restores the global console", () => {
  5665. const originalConsole = globalThis.console;
  5666. const stderr = new PassThrough();
  5667. let stderrOutput = "";
  5668. stderr.setEncoding("utf8");
  5669. stderr.on("data", (chunk: string) => {
  5670. stderrOutput += chunk;
  5671. });
  5672. const restore = installStderrConsoleBoundary(stderr);
  5673. try {
  5674. console.debug("protocol debug must not reach stdout");
  5675. console.log("protocol log must not reach stdout");
  5676. console.info("protocol info must not reach stdout");
  5677. console.warn("protocol warning must not reach stdout");
  5678. console.error("protocol error must not reach stdout");
  5679. assert.match(stderrOutput, /protocol debug must not reach stdout/u);
  5680. assert.match(stderrOutput, /protocol log must not reach stdout/u);
  5681. assert.match(stderrOutput, /protocol info must not reach stdout/u);
  5682. assert.match(stderrOutput, /protocol warning must not reach stdout/u);
  5683. assert.match(stderrOutput, /protocol error must not reach stdout/u);
  5684. } finally {
  5685. restore();
  5686. stderr.destroy();
  5687. }
  5688. assert.equal(globalThis.console, originalConsole);
  5689. });
  5690. test("passes the Desktop presentation surface to the protocol app server", async () => {
  5691. const ctx = createContext(["app-server", "--stdio", "--surface", "desktop"]);
  5692. let called = false;
  5693. const exitCode = await run(ctx, {
  5694. runZCodeProtocolAgent: async (options) => {
  5695. called = true;
  5696. assert.equal(options?.presentationSurface, "zcode_desktop");
  5697. },
  5698. });
  5699. assert.equal(exitCode, 0);
  5700. assert.equal(called, true);
  5701. assert.equal(ctx.stderr.output(), "");
  5702. });
  5703. test("rejects force MCS before starting the protocol app server", async () => {
  5704. const ctx = createContext(["app-server", "--stdio", "--force-mcs"]);
  5705. let called = false;
  5706. const exitCode = await run(ctx, {
  5707. runZCodeProtocolAgent: async () => {
  5708. called = true;
  5709. },
  5710. });
  5711. assert.equal(exitCode, 1);
  5712. assert.equal(called, false);
  5713. assert.match(ctx.stderr.output(), /--force-mcs can only be used with --prompt, --target, or tui/);
  5714. assert.equal(ctx.stdout.output(), "");
  5715. });
  5716. test("loads dotenv for app-server only in development runtime", async () => {
  5717. const ctx = createContext(["app-server", "--stdio"]);
  5718. let called = false;
  5719. let dotenvCalls = 0;
  5720. const exitCode = await run(ctx, {
  5721. cwd: () => "/workspace",
  5722. env: {
  5723. [ZCODE_RUNTIME_ENV_KEY]: "development",
  5724. },
  5725. loadDotenv: (options) => {
  5726. dotenvCalls += 1;
  5727. assert.equal(options?.cwd, "/workspace");
  5728. if (options?.env) {
  5729. options.env.ZCODE_API_KEY = "loaded-for-dev-protocol";
  5730. }
  5731. return {
  5732. keys: ["ZCODE_API_KEY"],
  5733. loaded: true,
  5734. path: "/workspace/.env",
  5735. };
  5736. },
  5737. runZCodeProtocolAgent: async (options) => {
  5738. called = true;
  5739. assert.equal(options?.cwd, "/workspace");
  5740. assert.equal(options?.env?.[ZCODE_RUNTIME_ENV_KEY], "development");
  5741. assert.equal(options?.env?.ZCODE_API_KEY, "loaded-for-dev-protocol");
  5742. },
  5743. });
  5744. assert.equal(exitCode, 0);
  5745. assert.equal(called, true);
  5746. assert.equal(dotenvCalls, 1);
  5747. assert.equal(ctx.stderr.output(), "");
  5748. });
  5749. test("rejects the removed acp command", async () => {
  5750. const ctx = createContext(["acp"]);
  5751. const exitCode = await run(ctx);
  5752. assert.equal(exitCode, 1);
  5753. assert.match(ctx.stderr.output(), /Unknown command: acp/);
  5754. assert.equal(ctx.stdout.output(), "");
  5755. });
  5756. test("returns an error for unknown commands", async () => {
  5757. const ctx = createContext(["missing"]);
  5758. const exitCode = await run(ctx);
  5759. assert.equal(exitCode, 1);
  5760. assert.match(ctx.stderr.output(), /Unknown command: missing/);
  5761. assert.match(ctx.stderr.output(), /Usage:/);
  5762. assert.equal(ctx.stdout.output(), "");
  5763. });
  5764. const PLUGINS_TEST_OPTIONS = {
  5765. force: false,
  5766. json: false,
  5767. noColor: false,
  5768. verbose: false,
  5769. } as const;
  5770. test("plugins uninstall refuses on a non-TTY without --force", async () => {
  5771. const ctx = createContext(["plugins", "uninstall", "hello@market"]);
  5772. let called = false;
  5773. const exitCode = await runPluginsCommand(
  5774. ctx,
  5775. { ...PLUGINS_TEST_OPTIONS },
  5776. {
  5777. cwd: () => process.cwd(),
  5778. uninstallPlugin: async () => {
  5779. called = true;
  5780. return null;
  5781. },
  5782. },
  5783. ["uninstall", "hello@market"],
  5784. );
  5785. assert.equal(called, false);
  5786. assert.equal(exitCode, 1);
  5787. assert.match(ctx.stderr.output(), /Refusing to uninstall hello@market without confirmation/);
  5788. });
  5789. test("plugins uninstall proceeds with --force and reports the removed plugin", async () => {
  5790. const ctx = createContext(["plugins", "uninstall", "hello@market", "--force"]);
  5791. let uninstalledId = "";
  5792. const exitCode = await runPluginsCommand(
  5793. ctx,
  5794. { ...PLUGINS_TEST_OPTIONS, force: true },
  5795. {
  5796. cwd: () => process.cwd(),
  5797. uninstallPlugin: async (options) => {
  5798. uninstalledId = options.pluginId ?? "";
  5799. return {
  5800. id: options.pluginId ?? "",
  5801. name: "hello",
  5802. marketplace: "market",
  5803. enabled: false,
  5804. scope: "user",
  5805. };
  5806. },
  5807. },
  5808. ["uninstall", "hello@market"],
  5809. );
  5810. assert.equal(uninstalledId, "hello@market");
  5811. assert.equal(exitCode, 0);
  5812. assert.match(ctx.stdout.output(), /Uninstalled plugin hello@market/);
  5813. });
  5814. test("plugins uninstall reports a not-installed plugin as a non-zero no-op", async () => {
  5815. const ctx = createContext(["plugins", "uninstall", "missing@market", "--force"]);
  5816. const exitCode = await runPluginsCommand(
  5817. ctx,
  5818. { ...PLUGINS_TEST_OPTIONS, force: true },
  5819. {
  5820. cwd: () => process.cwd(),
  5821. uninstallPlugin: async () => null,
  5822. },
  5823. ["uninstall", "missing@market"],
  5824. );
  5825. assert.equal(exitCode, 1);
  5826. assert.match(ctx.stdout.output(), /Plugin not installed: missing@market/);
  5827. });
  5828. test("returns an error for unknown options", async () => {
  5829. const ctx = createContext(["--wat"]);
  5830. const exitCode = await run(ctx);
  5831. assert.equal(exitCode, 1);
  5832. assert.match(ctx.stderr.output(), /Unknown option/);
  5833. assert.match(ctx.stderr.output(), /Usage:/);
  5834. });
  5835. test("rejects unsupported Browser Use modes and invalid CLI surfaces", async () => {
  5836. const unsupported = createContext(["--browser-use=extension", "--prompt", "test"]);
  5837. assert.equal(await run(unsupported, createPromptDeps()), 1);
  5838. assert.match(unsupported.stderr.output(), /Unsupported --browser-use value/u);
  5839. const executableOnly = createContext([
  5840. "--browser-executable",
  5841. process.execPath,
  5842. "--prompt",
  5843. "test",
  5844. ]);
  5845. assert.equal(await run(executableOnly, createPromptDeps()), 1);
  5846. assert.match(executableOnly.stderr.output(), /requires --browser-use=headless/u);
  5847. const appServer = createContext(["--browser-use=headless", "app-server", "--stdio"]);
  5848. assert.equal(await run(appServer, createPromptDeps()), 1);
  5849. assert.match(appServer.stderr.output(), /can only be used with --prompt, --target, or tui/u);
  5850. });
  5851. test("loads the pinned Playwright runtime from a standard Node CLI install", async () => {
  5852. const playwright = await loadCliPlaywrightChromium();
  5853. assert.equal(typeof playwright.chromium.launch, "function");
  5854. assert.match(playwright.chromium.executablePath(), /chromium|chrome/u);
  5855. });
  5856. test("injects and closes the managed CDP port for headless prompt", async () => {
  5857. const ctx = createContext(["--browser-use=headless", "--prompt", "browser smoke"]);
  5858. const browserControlPort = {} as never;
  5859. let runtimeClosed = 0;
  5860. let appClosed = 0;
  5861. const exitCode = await run(ctx, {
  5862. ...createPromptDeps(),
  5863. createManagedCdpBrowserRuntime: (options) => {
  5864. assert.equal(options?.executablePath, undefined);
  5865. return {
  5866. browserControlPort,
  5867. close: async () => {
  5868. runtimeClosed += 1;
  5869. },
  5870. };
  5871. },
  5872. createZCodeApp: (options) => {
  5873. assert.equal(options?.browserControlPort, browserControlPort);
  5874. return {
  5875. close: async () => {
  5876. appClosed += 1;
  5877. },
  5878. sessionId: "session-browser-headless",
  5879. traceId: "trace-browser-headless",
  5880. runtime: {} as never,
  5881. submitPrompt: async (prompt: string) => ({
  5882. events: [],
  5883. projection: fakeProjection as never,
  5884. response: prompt,
  5885. traceId: "trace-browser-headless" as never,
  5886. turnId: "turn-browser-headless" as never,
  5887. }),
  5888. } as never;
  5889. },
  5890. });
  5891. assert.equal(exitCode, 0);
  5892. assert.equal(appClosed, 1);
  5893. assert.equal(runtimeClosed, 1);
  5894. assert.equal(ctx.stdout.output(), "browser smoke\n");
  5895. });
  5896. test("continues managed browser cleanup when app close never settles", async () => {
  5897. const ctx = createContext(["--browser-use=headless", "--prompt", "browser shutdown"]);
  5898. let appCloseCount = 0;
  5899. let browserCloseCount = 0;
  5900. const startedAt = Date.now();
  5901. const exitCode = await run(ctx, {
  5902. ...createPromptDeps(),
  5903. createManagedCdpBrowserRuntime: () => ({
  5904. browserControlPort: {} as never,
  5905. close: async () => {
  5906. browserCloseCount += 1;
  5907. },
  5908. }),
  5909. createZCodeApp: () =>
  5910. ({
  5911. close: async () => {
  5912. appCloseCount += 1;
  5913. await new Promise<void>(() => undefined);
  5914. },
  5915. runtime: {} as never,
  5916. sessionId: "session-browser-close-timeout",
  5917. submitPrompt: async (prompt: string) => ({
  5918. events: [],
  5919. projection: fakeProjection as never,
  5920. response: prompt,
  5921. traceId: "trace-browser-close-timeout" as never,
  5922. turnId: "turn-browser-close-timeout" as never,
  5923. }),
  5924. traceId: "trace-browser-close-timeout",
  5925. }) as never,
  5926. shutdownCleanupTimeoutMs: 20,
  5927. });
  5928. assert.equal(exitCode, 0);
  5929. assert.equal(appCloseCount, 1);
  5930. assert.equal(browserCloseCount, 1);
  5931. assert.ok(Date.now() - startedAt < 200);
  5932. });
  5933. test("returns from a headless prompt when managed browser close never settles", async () => {
  5934. const ctx = createContext(["--browser-use=headless", "--prompt", "browser shutdown"]);
  5935. let appCloseCount = 0;
  5936. let browserCloseCount = 0;
  5937. const startedAt = Date.now();
  5938. const exitCode = await run(ctx, {
  5939. ...createPromptDeps(),
  5940. createManagedCdpBrowserRuntime: () => ({
  5941. browserControlPort: {} as never,
  5942. close: async () => {
  5943. browserCloseCount += 1;
  5944. await new Promise<void>(() => undefined);
  5945. },
  5946. }),
  5947. createZCodeApp: () =>
  5948. ({
  5949. close: async () => {
  5950. appCloseCount += 1;
  5951. },
  5952. runtime: {} as never,
  5953. sessionId: "session-browser-runtime-close-timeout",
  5954. submitPrompt: async (prompt: string) => ({
  5955. events: [],
  5956. projection: fakeProjection as never,
  5957. response: prompt,
  5958. traceId: "trace-browser-runtime-close-timeout" as never,
  5959. turnId: "turn-browser-runtime-close-timeout" as never,
  5960. }),
  5961. traceId: "trace-browser-runtime-close-timeout",
  5962. }) as never,
  5963. shutdownCleanupTimeoutMs: 20,
  5964. });
  5965. assert.equal(exitCode, 0);
  5966. assert.equal(appCloseCount, 1);
  5967. assert.equal(browserCloseCount, 1);
  5968. assert.ok(Date.now() - startedAt < 200);
  5969. });
  5970. test("forces the existing exit code when the CLI watchdog deadline is reached", async () => {
  5971. const exitDeferred = createDeferred<number>();
  5972. scheduleCliExitWatchdog({
  5973. exitCode: 7,
  5974. exitProcess: (code) => exitDeferred.resolve(code),
  5975. timeoutMs: 20,
  5976. });
  5977. assert.equal(await exitDeferred.promise, 7);
  5978. });
  5979. test("injects one managed CDP runtime into TUI app lifecycle and closes it", async () => {
  5980. const ctx = createContext(["--browser-use=headless", "tui"]);
  5981. const browserControlPort = {} as never;
  5982. let runtimeClosed = 0;
  5983. let appClosed = 0;
  5984. const exitCode = await run(ctx, {
  5985. ...createPromptDeps(),
  5986. createManagedCdpBrowserRuntime: () => ({
  5987. browserControlPort,
  5988. close: async () => {
  5989. runtimeClosed += 1;
  5990. },
  5991. }),
  5992. createZCodeApp: (options) => {
  5993. assert.equal(options?.browserControlPort, browserControlPort);
  5994. return {
  5995. close: async () => {
  5996. appClosed += 1;
  5997. },
  5998. getLocale: () => "en-US",
  5999. getModel: () => "openai/gpt-test",
  6000. getThoughtLevel: () => "medium",
  6001. runtime: {} as never,
  6002. sessionId: "session-browser-tui",
  6003. submitPrompt: async (prompt: string) => ({
  6004. events: [],
  6005. projection: fakeProjection as never,
  6006. response: prompt,
  6007. traceId: "trace-browser-tui" as never,
  6008. turnId: "turn-browser-tui" as never,
  6009. }),
  6010. traceId: "trace-browser-tui",
  6011. } as never;
  6012. },
  6013. // 真实 TUI 在首帧后通过 loadStartupOptions 创建 App;浏览器运行时随该 App 注入和关闭。
  6014. runTui: async (options) => {
  6015. await loadTuiStartup(options);
  6016. return 0;
  6017. },
  6018. });
  6019. assert.equal(exitCode, 0);
  6020. assert.equal(appClosed, 1);
  6021. assert.equal(runtimeClosed, 1);
  6022. });
  6023. test("reuses one process provider registry across TUI app replacements", async () => {
  6024. const ctx = createContext(["tui"]);
  6025. const providerRegistry = {} as never;
  6026. const providerRuntimeHeadersPort = {} as never;
  6027. let runtimeStarts = 0;
  6028. let runtimeDisposals = 0;
  6029. let selectionRepositoryDisposals = 0;
  6030. let appCreations = 0;
  6031. const exitCode = await run(ctx, {
  6032. ...createPromptDeps(),
  6033. skipUserConfig: false,
  6034. userConfigPath: "/tmp/zcode-legacy-tui.json",
  6035. startProcessProviderRegistryRuntime: async (_env, options) => {
  6036. runtimeStarts += 1;
  6037. // 刷新回调是当前 CLI 装配的一部分,仍验证唯一 Runtime 和旧配置迁移路径。
  6038. assert.equal(typeof options?.standalone?.onBuiltinRefreshError, "function");
  6039. assert.equal(typeof options?.standalone?.onBuiltinRefreshResult, "function");
  6040. assert.deepEqual(
  6041. {
  6042. standalone: {
  6043. legacyCliUserConfigFilePath: options?.standalone?.legacyCliUserConfigFilePath,
  6044. },
  6045. },
  6046. {
  6047. standalone: {
  6048. legacyCliUserConfigFilePath: "/tmp/zcode-legacy-tui.json",
  6049. },
  6050. },
  6051. );
  6052. return {
  6053. accountSource: {} as never,
  6054. dispose: () => {
  6055. selectionRepositoryDisposals += 1;
  6056. runtimeDisposals += 1;
  6057. },
  6058. configuredDefaultModelSelection: { providerId: "provider-a", modelId: "model-a" },
  6059. modelSelectionConfigRepository: {
  6060. dispose: () => {
  6061. selectionRepositoryDisposals += 1;
  6062. },
  6063. read: async () => ({ providerId: "provider-a", modelId: "model-a" }),
  6064. },
  6065. providerRuntimeHeadersPort,
  6066. snapshot: {} as never,
  6067. runtime: {
  6068. dispose: () => {
  6069. runtimeDisposals += 1;
  6070. },
  6071. registryService: providerRegistry,
  6072. },
  6073. } as never;
  6074. },
  6075. createZCodeApp: (options) => {
  6076. appCreations += 1;
  6077. assert.equal(options?.providerRegistry, providerRegistry);
  6078. assert.equal(options?.providerRuntimeHeadersPort, providerRuntimeHeadersPort);
  6079. assert.deepEqual(options?.configuredDefaultModelSelection, {
  6080. providerId: "provider-a",
  6081. modelId: "model-a",
  6082. });
  6083. return {
  6084. close: async () => {},
  6085. getLocale: () => "en-US",
  6086. getModel: () => "openai/gpt-test",
  6087. getThoughtLevel: () => "medium",
  6088. runtime: {} as never,
  6089. sessionId: `session-registry-tui-${appCreations}`,
  6090. submitPrompt: async (prompt: string) => ({
  6091. events: [],
  6092. projection: fakeProjection as never,
  6093. response: prompt,
  6094. traceId: "trace-registry-tui" as never,
  6095. turnId: "turn-registry-tui" as never,
  6096. }),
  6097. traceId: "trace-registry-tui",
  6098. } as never;
  6099. },
  6100. runTui: async (options) => {
  6101. await loadTuiStartup(options);
  6102. await options.submitPrompt("/new", {
  6103. abortSignal: new AbortController().signal,
  6104. });
  6105. return 0;
  6106. },
  6107. });
  6108. assert.equal(exitCode, 0);
  6109. assert.equal(appCreations, 2);
  6110. assert.equal(runtimeStarts, 1);
  6111. assert.equal(runtimeDisposals, 1);
  6112. assert.equal(selectionRepositoryDisposals, 1);
  6113. });
  6114. test("rejects an invalid explicit browser executable before creating the app", async () => {
  6115. const ctx = createContext([
  6116. "--browser-use=headless",
  6117. "--browser-executable",
  6118. "/definitely/missing/zcode-chromium",
  6119. "--prompt",
  6120. "browser smoke",
  6121. ]);
  6122. let appCreated = false;
  6123. const exitCode = await run(ctx, {
  6124. ...createPromptDeps(),
  6125. createZCodeApp: () => {
  6126. appCreated = true;
  6127. throw new Error("app must not be created");
  6128. },
  6129. });
  6130. assert.equal(exitCode, 1);
  6131. assert.equal(appCreated, false);
  6132. assert.match(ctx.stderr.output(), /missing or not executable/u);
  6133. });
  6134. test("rejects tui when stdio is not interactive", async () => {
  6135. const ctx = createContext(["tui"]);
  6136. const exitCode = await run(ctx);
  6137. assert.equal(exitCode, 1);
  6138. // Locale can come from user config; the invariant is that non-interactive TUI exits.
  6139. assert.match(ctx.stderr.output(), /TUI requires an interactive terminal|TUI 需要交互式终端/);
  6140. });
  6141. const createRuntimeEvent = (type: string, payload: Record<string, unknown>): never =>
  6142. ({
  6143. id: `event-${type}`,
  6144. payload,
  6145. sequenceNumber: 0,
  6146. sessionId: "session-test",
  6147. timestamp: new Date(),
  6148. traceId: "trace-test",
  6149. type,
  6150. }) as never;
  6151. const createPermissionRequest = (): never =>
  6152. ({
  6153. input: { command: "touch demo.txt" },
  6154. mode: "build",
  6155. reason: "Tool has side effects and requires approval",
  6156. requestId: "perm_test",
  6157. requestedAt: new Date(),
  6158. riskLevel: "medium",
  6159. ruleId: "mode.build.sideEffect",
  6160. sessionId: "session-test",
  6161. sideEffectScope: "workspace",
  6162. toolCallId: "tool_bash",
  6163. toolName: "Bash",
  6164. traceId: "trace-test",
  6165. turnId: "turn-test",
  6166. }) as never;
  6167. function createDeferred<T>() {
  6168. let resolve: (value: T) => void = () => undefined;
  6169. let reject: (reason?: unknown) => void = () => undefined;
  6170. const promise = new Promise<T>((promiseResolve, promiseReject) => {
  6171. resolve = promiseResolve;
  6172. reject = promiseReject;
  6173. });
  6174. return { promise, reject, resolve };
  6175. }
  6176. function createTestShutdownProcess(platform: NodeJS.Platform): CliShutdownProcess & {
  6177. emitSignal(signal: NodeJS.Signals): void;
  6178. } {
  6179. const listeners = new Map<NodeJS.Signals, Set<() => void>>();
  6180. const target = {
  6181. platform,
  6182. off(signal: NodeJS.Signals, listener: () => void) {
  6183. listeners.get(signal)?.delete(listener);
  6184. return target;
  6185. },
  6186. once(signal: NodeJS.Signals, listener: () => void) {
  6187. const signalListeners = listeners.get(signal) ?? new Set<() => void>();
  6188. signalListeners.add(listener);
  6189. listeners.set(signal, signalListeners);
  6190. return target;
  6191. },
  6192. emitSignal(signal: NodeJS.Signals) {
  6193. const signalListeners = Array.from(listeners.get(signal) ?? []);
  6194. listeners.set(signal, new Set());
  6195. for (const listener of signalListeners) {
  6196. listener();
  6197. }
  6198. },
  6199. };
  6200. return target;
  6201. }
  6202. test("headless prompt reports exact Workspace Hook pretrust diagnostics without failing the task", async () => {
  6203. const ctx = createContext(["--prompt", "hello"]);
  6204. const deps = createPromptDeps();
  6205. const exitCode = await run(ctx, {
  6206. ...deps,
  6207. createZCodeApp: () =>
  6208. ({
  6209. getModel: () => "openai/gpt-test",
  6210. getLocale: () => "en-US",
  6211. getThoughtLevel: () => "medium",
  6212. sessionId: "session-test",
  6213. traceId: "trace-test",
  6214. runtime: {} as never,
  6215. submitPrompt: async () => ({
  6216. events: [
  6217. {
  6218. type: "hook_run_blocked",
  6219. payload: {
  6220. errorCode: "workspace_hooks_pending_trust",
  6221. descriptor: { sourceKind: "project" },
  6222. },
  6223. },
  6224. ],
  6225. projection: fakeProjection as never,
  6226. response: "ok",
  6227. traceId: "trace-test" as never,
  6228. turnId: "turn-test" as never,
  6229. }),
  6230. }) as never,
  6231. inspectWorkspaceHookTrust: async () => ({
  6232. workspacePath: "/workspace",
  6233. workspaceIdentity: "/workspace",
  6234. bundleDigest: "b".repeat(64),
  6235. reasonCode: "workspace_hooks_pending_trust",
  6236. items: [
  6237. {
  6238. reviewItemId: "item-1",
  6239. event: "SessionStart",
  6240. matcher: null,
  6241. displayCommand: "./start.sh",
  6242. sourcePath: ".zcode/config.json",
  6243. configuredEnabled: true,
  6244. hookDeclarationDigest: "a".repeat(64),
  6245. trustState: "pending_trust",
  6246. },
  6247. ],
  6248. }),
  6249. });
  6250. assert.equal(exitCode, 0);
  6251. assert.equal(ctx.stdout.output(), "ok\n");
  6252. assert.match(ctx.stderr.output(), /Workspace Hooks skipped: workspace_hooks_pending_trust/);
  6253. assert.match(ctx.stderr.output(), new RegExp("a{64}"));
  6254. assert.match(ctx.stderr.output(), /zcode hooks trust review/);
  6255. });
  6256. test("headless rollout-off diagnostics preserve the runtime feature-disabled reason", async () => {
  6257. const ctx = createContext(["--prompt", "hello"]);
  6258. const deps = createPromptDeps();
  6259. const exitCode = await run(ctx, {
  6260. ...deps,
  6261. createZCodeApp: () =>
  6262. ({
  6263. getModel: () => "openai/gpt-test",
  6264. getLocale: () => "en-US",
  6265. getThoughtLevel: () => "medium",
  6266. sessionId: "session-test",
  6267. traceId: "trace-test",
  6268. runtime: {} as never,
  6269. submitPrompt: async () => ({
  6270. events: [
  6271. {
  6272. type: "hook_run_blocked",
  6273. payload: {
  6274. errorCode: "workspace_hooks_feature_disabled",
  6275. descriptor: { sourceKind: "project" },
  6276. },
  6277. },
  6278. ],
  6279. projection: fakeProjection as never,
  6280. response: "ok",
  6281. traceId: "trace-test" as never,
  6282. turnId: "turn-test" as never,
  6283. }),
  6284. }) as never,
  6285. inspectWorkspaceHookTrust: async () => ({
  6286. workspacePath: "/workspace",
  6287. workspaceIdentity: "/workspace",
  6288. bundleDigest: "b".repeat(64),
  6289. reasonCode: "workspace_hooks_pending_trust",
  6290. items: [],
  6291. }),
  6292. });
  6293. assert.equal(exitCode, 0);
  6294. assert.match(ctx.stderr.output(), /Workspace Hooks skipped: workspace_hooks_feature_disabled/);
  6295. });
  6296. for (const mode of [undefined, "off", "auto", "local"] as const) {
  6297. test(`passes ToolSearch mode ${mode ?? "default off"} into prompt runtime`, async () => {
  6298. let observed = false;
  6299. const ctx = createContext([...(mode ? ["--toolsearch-mode", mode] : []), "--prompt", "hello"]);
  6300. const deps = createPromptDeps();
  6301. const original = deps.createZCodeApp;
  6302. const code = await run(ctx, {
  6303. ...deps,
  6304. createZCodeApp: (options) => {
  6305. observed = true;
  6306. assert.deepEqual((options?.runtimeConfig as any)?.toolSearch, { mode: mode ?? "off" });
  6307. return original!(options);
  6308. },
  6309. });
  6310. assert.equal(code, 0);
  6311. assert.equal(observed, true);
  6312. });
  6313. }
  6314. for (const value of [undefined, "off", "on"] as const) {
  6315. test(`passes total-tokens reminder ${value ?? "default off"} into prompt runtime`, async () => {
  6316. let observed = false;
  6317. const ctx = createContext([
  6318. ...(value ? ["--total-tokens-reminder", value] : []),
  6319. "--prompt",
  6320. "hello",
  6321. ]);
  6322. const deps = createPromptDeps();
  6323. const original = deps.createZCodeApp;
  6324. const code = await run(ctx, {
  6325. ...deps,
  6326. createZCodeApp: (options) => {
  6327. observed = true;
  6328. assert.deepEqual((options?.runtimeConfig as any)?.totalTokensReminder, {
  6329. enabled: value === "on",
  6330. });
  6331. return original!(options);
  6332. },
  6333. });
  6334. assert.equal(code, 0);
  6335. assert.equal(observed, true);
  6336. });
  6337. }
  6338. for (const value of [undefined, "off", "on"] as const) {
  6339. test(`passes the Agent always-background switch ${value ?? "default on"} into prompt runtime`, async () => {
  6340. let observed = false;
  6341. const ctx = createContext([
  6342. ...(value ? ["--agent-always-background", value] : []),
  6343. "--prompt",
  6344. "hello",
  6345. ]);
  6346. const deps = createPromptDeps();
  6347. const original = deps.createZCodeApp;
  6348. const code = await run(ctx, {
  6349. ...deps,
  6350. createZCodeApp: (options) => {
  6351. observed = true;
  6352. assert.deepEqual((options?.runtimeConfig as any)?.subagents, {
  6353. alwaysBackground: value !== "off",
  6354. });
  6355. return original!(options);
  6356. },
  6357. });
  6358. assert.equal(code, 0);
  6359. assert.equal(observed, true);
  6360. });
  6361. }
  6362. test("rejects invalid launch-only option values and the removed enable flag before creating an app", async () => {
  6363. const reminderValueError = /--total-tokens-reminder must be one of on, off/;
  6364. const agentBackgroundValueError = /--agent-always-background must be one of on, off/;
  6365. for (const [args, message] of [
  6366. [["--toolsearch-mode", "force"], /toolsearch/],
  6367. [["--toolsearch-mode", "typo"], /toolsearch/],
  6368. [["--enable-toolsearch"], /toolsearch/],
  6369. [["--total-tokens-reminder", "true"], reminderValueError],
  6370. [["--total-tokens-reminder", "ON"], reminderValueError],
  6371. [["--agent-always-background", "false"], agentBackgroundValueError],
  6372. ] as const) {
  6373. let created = false;
  6374. const ctx = createContext([...args, "-p", "hello"]);
  6375. const code = await run(ctx, {
  6376. createZCodeApp: () => {
  6377. created = true;
  6378. throw new Error("unreachable");
  6379. },
  6380. });
  6381. assert.equal(code, 1);
  6382. assert.equal(created, false);
  6383. assert.match(ctx.stderr.output(), message);
  6384. }
  6385. });
  6386. test("passes explicit Native ToolSearch and the total-tokens reminder into TUI runtime config", async () => {
  6387. const ctx = createContext([
  6388. "tui",
  6389. "--toolsearch-mode",
  6390. "native",
  6391. "--total-tokens-reminder",
  6392. "on",
  6393. "--agent-always-background",
  6394. "off",
  6395. ]);
  6396. let runtimeConfig: any;
  6397. const exitCode = await run(ctx, {
  6398. ...createPromptDeps(),
  6399. createZCodeApp: (options) => {
  6400. // TUI 启动会吞掉建 App 时的异常,断言放到 run 之后,不放在工厂里。
  6401. runtimeConfig = options?.runtimeConfig;
  6402. return {
  6403. getLocale: () => "en-US",
  6404. getModel: () => "openai/gpt-test",
  6405. getThoughtLevel: () => "medium",
  6406. sessionId: "session-test",
  6407. traceId: "trace-test",
  6408. runtime: {} as never,
  6409. submitPrompt: async (prompt: string) => ({
  6410. events: [],
  6411. projection: fakeProjection as never,
  6412. response: prompt,
  6413. traceId: "trace-test" as never,
  6414. turnId: "turn-test" as never,
  6415. }),
  6416. } as never;
  6417. },
  6418. runTui: async (options) => {
  6419. // 启动数据要读当前模型,会创建首个 App;只返回 0 时不会创建 App。
  6420. await loadTuiStartup(options);
  6421. return 0;
  6422. },
  6423. });
  6424. assert.equal(exitCode, 0);
  6425. assert.deepEqual(runtimeConfig?.toolSearch, { mode: "native" });
  6426. assert.deepEqual(runtimeConfig?.totalTokensReminder, { enabled: true });
  6427. assert.deepEqual(runtimeConfig?.subagents, { alwaysBackground: false });
  6428. });
  6429. test("passes explicit Native ToolSearch and the total-tokens reminder into target runtime config", async () => {
  6430. const ctx = createContext([
  6431. "--toolsearch-mode",
  6432. "native",
  6433. "--total-tokens-reminder",
  6434. "on",
  6435. "--agent-always-background",
  6436. "off",
  6437. "--target",
  6438. "Ship target MVP",
  6439. ]);
  6440. let continued = false;
  6441. const exitCode = await run(ctx, {
  6442. ...createPromptDeps(),
  6443. createZCodeApp: (options) => {
  6444. assert.deepEqual((options?.runtimeConfig as any)?.toolSearch, {
  6445. mode: "native",
  6446. });
  6447. assert.deepEqual((options?.runtimeConfig as any)?.totalTokensReminder, { enabled: true });
  6448. assert.deepEqual((options?.runtimeConfig as any)?.subagents, { alwaysBackground: false });
  6449. return {
  6450. clearTarget: async () => false,
  6451. continueActiveTarget: async () => {
  6452. continued = true;
  6453. return {
  6454. projection: fakeProjection as never,
  6455. response: "continued target",
  6456. traceId: "trace-target-toolsearch" as never,
  6457. turnId: "turn-target-toolsearch" as never,
  6458. };
  6459. },
  6460. readTarget: async () => null,
  6461. sessionId: "session-target-toolsearch",
  6462. setTarget: async ({ objective, status = "active" }) => ({
  6463. objective,
  6464. sessionID: "session-target-toolsearch",
  6465. status,
  6466. targetID: "target-toolsearch",
  6467. time: { created: 1, updated: 1 },
  6468. }),
  6469. traceId: "trace-target-toolsearch",
  6470. runtime: {} as never,
  6471. submitPrompt: async () => {
  6472. throw new Error("prompt should not run");
  6473. },
  6474. updateTargetStatus: async () => null,
  6475. } as never;
  6476. },
  6477. });
  6478. assert.equal(exitCode, 0);
  6479. assert.equal(continued, true);
  6480. assert.equal(ctx.stdout.output(), "continued target\n");
  6481. assert.equal(ctx.stderr.output(), "");
  6482. });
  6483. test("passes explicit Native ToolSearch into headless runtime config", async () => {
  6484. const ctx = createContext(["--toolsearch-mode", "native", "--prompt", "hello enable toolsearch"]);
  6485. const exitCode = await run(ctx, {
  6486. ...createPromptDeps(),
  6487. createZCodeApp: (options) => {
  6488. assert.deepEqual((options?.runtimeConfig as any)?.toolSearch, {
  6489. mode: "native",
  6490. });
  6491. return {
  6492. sessionId: "session-test",
  6493. traceId: "trace-test",
  6494. runtime: {} as never,
  6495. submitPrompt: async (prompt: string) => ({
  6496. events: [],
  6497. projection: fakeProjection as never,
  6498. response: prompt,
  6499. traceId: "trace-test" as never,
  6500. turnId: "turn-test" as never,
  6501. }),
  6502. } as never;
  6503. },
  6504. });
  6505. assert.equal(exitCode, 0);
  6506. assert.equal(ctx.stdout.output(), "hello enable toolsearch\n");
  6507. });
  6508. // 只对本次启动生效的参数;App 侧由 Host 设置决定,app-server 不接受。
  6509. const LAUNCH_ONLY_FLAGS = [
  6510. ["--toolsearch-mode", "native"],
  6511. ["--total-tokens-reminder", "on"],
  6512. ["--agent-always-background", "off"],
  6513. ] as const;
  6514. test("rejects launch-only flags outside prompt, target, or TUI commands", async () => {
  6515. for (const flag of LAUNCH_ONLY_FLAGS) {
  6516. const ctx = createContext(["doctor", ...flag]);
  6517. const exitCode = await run(ctx);
  6518. assert.equal(exitCode, 1);
  6519. assert.match(
  6520. ctx.stderr.output(),
  6521. new RegExp(`${flag[0]} can only be used with --prompt, --target, or tui`),
  6522. );
  6523. assert.equal(ctx.stdout.output(), "");
  6524. }
  6525. });
  6526. test("rejects launch-only flags before starting the protocol app server", async () => {
  6527. for (const flag of LAUNCH_ONLY_FLAGS) {
  6528. const ctx = createContext(["app-server", "--stdio", ...flag]);
  6529. let called = false;
  6530. const exitCode = await run(ctx, {
  6531. runZCodeProtocolAgent: async () => {
  6532. called = true;
  6533. },
  6534. });
  6535. assert.equal(exitCode, 1);
  6536. assert.equal(called, false);
  6537. assert.match(
  6538. ctx.stderr.output(),
  6539. new RegExp(`${flag[0]} can only be used with --prompt, --target, or tui`),
  6540. );
  6541. assert.equal(ctx.stdout.output(), "");
  6542. }
  6543. });
  6544. test("passes explicit Native ToolSearch and explicit resume session into prompt app creation", async () => {
  6545. const ctx = createContext([
  6546. "--toolsearch-mode",
  6547. "native",
  6548. "--resume",
  6549. "sess_existing",
  6550. "--prompt",
  6551. "hello resume",
  6552. ]);
  6553. const exitCode = await run(ctx, {
  6554. ...createPromptDeps(),
  6555. createZCodeApp: (options) => {
  6556. assert.equal(options?.resume, true);
  6557. assert.deepEqual((options?.runtimeConfig as any)?.toolSearch, { mode: "native" });
  6558. assert.equal(options?.sessionId, "sess_existing");
  6559. return {
  6560. sessionId: "sess_existing",
  6561. traceId: "trace-test",
  6562. runtime: {} as never,
  6563. submitPrompt: async (prompt: string) => ({
  6564. events: [],
  6565. projection: fakeProjection as never,
  6566. response: prompt,
  6567. traceId: "trace-test" as never,
  6568. turnId: "turn-test" as never,
  6569. }),
  6570. } as never;
  6571. },
  6572. });
  6573. assert.equal(exitCode, 0);
  6574. assert.equal(ctx.stdout.output(), "hello resume\n");
  6575. });
  6576. test("passes explicit Native ToolSearch while resolving latest session for continue prompts", async () => {
  6577. const ctx = createContext([
  6578. "--toolsearch-mode",
  6579. "native",
  6580. "--continue",
  6581. "--prompt",
  6582. "hello continue",
  6583. ]);
  6584. const cwd = join(tmpdir(), "zcode-cli-continue-test");
  6585. let resolved = false;
  6586. const exitCode = await run(ctx, {
  6587. ...createPromptDeps(),
  6588. cwd: () => cwd,
  6589. resolveLatestSession: async (options) => {
  6590. resolved = true;
  6591. assert.equal(options.directory, cwd);
  6592. return { id: "sess_latest" } as never;
  6593. },
  6594. createZCodeApp: (options) => {
  6595. assert.equal(options?.resume, true);
  6596. assert.deepEqual((options?.runtimeConfig as any)?.toolSearch, { mode: "native" });
  6597. assert.equal(options?.sessionId, "sess_latest");
  6598. return {
  6599. sessionId: "sess_latest",
  6600. traceId: "trace-test",
  6601. runtime: {} as never,
  6602. submitPrompt: async (prompt: string) => ({
  6603. events: [],
  6604. projection: fakeProjection as never,
  6605. response: prompt,
  6606. traceId: "trace-test" as never,
  6607. turnId: "turn-test" as never,
  6608. }),
  6609. } as never;
  6610. },
  6611. });
  6612. assert.equal(exitCode, 0);
  6613. assert.equal(resolved, true);
  6614. assert.equal(ctx.stdout.output(), "hello continue\n");
  6615. });
  6616. test("storage-migrate executes only the migration port and emits strict completion JSON", async () => {
  6617. const ctx = createContext(["storage-migrate"]);
  6618. let calls = 0;
  6619. const result = await run(ctx, {
  6620. migrateStorage: async () => {
  6621. calls++;
  6622. return { applied: ["0020"], backupSkipped: true };
  6623. },
  6624. runZCodeProtocolAgent: async () => {
  6625. throw new Error("must not start runtime");
  6626. },
  6627. createZCodeApp: () => {
  6628. throw new Error("must not create session");
  6629. },
  6630. });
  6631. assert.equal(result, 0);
  6632. assert.equal(calls, 1);
  6633. assert.deepEqual(JSON.parse(ctx.stdout.output()), {
  6634. version: 1,
  6635. kind: "storage-migrated",
  6636. applied: ["0020"],
  6637. backupSkipped: true,
  6638. });
  6639. });
  6640. test("storage-migrate reports failure and rejects extra flags without starting runtime", async () => {
  6641. for (const argv of [["storage-migrate"], ["storage-migrate", "--prompt", "do not run"]]) {
  6642. const ctx = createContext(argv);
  6643. const result = await run(ctx, {
  6644. migrateStorage: async () => {
  6645. throw new Error("checksum mismatch");
  6646. },
  6647. });
  6648. assert.equal(result, 1);
  6649. assert.equal(ctx.stdout.output(), "");
  6650. assert.ok(ctx.stderr.output().length > 0);
  6651. }
  6652. });
  6653. test("storage-migrate real entrypoint honors an isolated custom database and rejects checksum drift", async () => {
  6654. const directory = await mkdtemp(join(tmpdir(), "zcode-cli-storage-migration-"));
  6655. const database = join(directory, "custom storage", "sessions.sqlite");
  6656. const cliEntry = fileURLToPath(new URL("../src/main.ts", import.meta.url));
  6657. const tsxLoader = fileURLToPath(import.meta.resolve("tsx"));
  6658. const invoke = async () => {
  6659. const child = spawn(process.execPath, ["--import", tsxLoader, cliEntry, "storage-migrate"], {
  6660. cwd: directory,
  6661. env: {
  6662. ...process.env,
  6663. HOME: directory,
  6664. USERPROFILE: directory,
  6665. ZCODE_DATA_BASE_DIR: directory,
  6666. ZCODE_SESSION_DB_PATH: database,
  6667. },
  6668. stdio: ["ignore", "pipe", "pipe"],
  6669. });
  6670. let stdout = "";
  6671. let stderr = "";
  6672. child.stdout.on("data", (data) => {
  6673. stdout += data;
  6674. });
  6675. child.stderr.on("data", (data) => {
  6676. stderr += data;
  6677. });
  6678. const [code] = await once(child, "close");
  6679. return { code, stdout, stderr };
  6680. };
  6681. try {
  6682. const first = await invoke();
  6683. assert.equal(first.code, 0, first.stderr);
  6684. const report = JSON.parse(first.stdout);
  6685. assert.equal(report.kind, "storage-migrated");
  6686. assert.ok(report.applied.includes("0023_session_soft_delete_outcome"));
  6687. const second = await invoke();
  6688. assert.equal(second.code, 0, second.stderr);
  6689. assert.deepEqual(JSON.parse(second.stdout).applied, []);
  6690. const { DatabaseSync } = await import("node:sqlite");
  6691. const db = new DatabaseSync(database);
  6692. try {
  6693. assert.equal(db.prepare("SELECT count(*) AS total FROM session").get()?.total, 0);
  6694. db.prepare("UPDATE schema_migration SET checksum='invalid' WHERE id=?").run(
  6695. "0023_session_soft_delete_outcome",
  6696. );
  6697. } finally {
  6698. db.close();
  6699. }
  6700. const failed = await invoke();
  6701. assert.equal(failed.code, 1);
  6702. assert.equal(failed.stdout, "");
  6703. assert.match(failed.stderr, /checksum mismatch/i);
  6704. } finally {
  6705. await rm(directory, { recursive: true, force: true });
  6706. }
  6707. });