cli.unit.test.ts 221 KB

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