cli.unit.test.ts 224 KB

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