cli.unit.test.ts 220 KB

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