cli.unit.test.ts 209 KB

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