tui-app.test.ts 415 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464
  1. import { describe, expect, it, vi } from "vitest";
  2. import { mkdtemp, readFile, rm, writeFile, mkdir } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import type { TerminalCapabilities } from "../../src/tui/platform/terminal-capabilities.js";
  6. import {
  7. TuiAltScreen,
  8. VStack,
  9. type Terminal,
  10. } from "../../src/tui/engine/public.js";
  11. import { createTuiProgram } from "../../src/cli/program.js";
  12. import { resolveTuiStartupEnvironmentOption } from "../../src/cli/environment.js";
  13. import { runTuiCli } from "../../src/cli/main.js";
  14. import { launchTui } from "../../src/tui/launcher.js";
  15. import { createTuiApp } from "../../src/tui/app.js";
  16. import type {
  17. TuiModel,
  18. TuiQuestionnaireRequest,
  19. TuiQueuedMessage,
  20. TuiRuntimeEvent,
  21. TuiRuntime,
  22. TuiSessionForkPort,
  23. TuiStreamEvent,
  24. } from "../../src/runtime/port.js";
  25. import {
  26. normalizeTuiRuntimeEvent,
  27. type RawTuiRuntimeEvent,
  28. } from "../../src/runtime/event-normalizer.js";
  29. import type { SendMessageReq } from "@mavis/local-runtime-v2/cli-service";
  30. import type { TuiObservability } from "../../src/observability/local-observability.js";
  31. import type { McodeAuthProgress } from "../../src/auth/application.js";
  32. import { formatTuiShortcut } from "../../src/tui/shell/shortcut-labels.js";
  33. import { createTuiHostKeybindings } from "../../src/tui/shell/keybindings.js";
  34. import { stripAnsi } from "../../src/tui/rendering/text.js";
  35. import {
  36. TuiDraftRecovery,
  37. TuiDraftRecoveryError,
  38. } from "../../src/tui/features/composer/draft-recovery.js";
  39. import { composerText } from "../../src/tui/features/composer/copy.js";
  40. import type {
  41. McodeBusinessEvent,
  42. McodeBusinessTelemetry,
  43. } from "../../src/analytics/business-telemetry.js";
  44. import { VirtualTerminalScreen } from "../helpers/virtual-terminal.js";
  45. import { TuiFailure } from "../../src/failure.js";
  46. const runtimeEvent = (event: RawTuiRuntimeEvent): TuiRuntimeEvent =>
  47. normalizeTuiRuntimeEvent(event);
  48. function planReviewEventRequest(id: string) {
  49. return {
  50. schemaVersion: 2,
  51. id,
  52. mode: "plan",
  53. modePayload: {
  54. planReview: {
  55. markdown: "# Frozen plan\n\nImplement and verify the change.",
  56. path: "/history/session-1/artifacts/plan.md",
  57. },
  58. },
  59. presentation: {
  60. replaceComposer: true,
  61. showProgress: true,
  62. allowBackNavigation: true,
  63. },
  64. steps: [
  65. {
  66. id: "plan-review",
  67. question: "Approve?",
  68. selectionMode: "single",
  69. options: [{ id: "approve", label: "Approve" }],
  70. allowOther: true,
  71. required: true,
  72. },
  73. ],
  74. } as const;
  75. }
  76. function planEntryEventRequest(id: string) {
  77. return {
  78. schemaVersion: 2,
  79. id,
  80. mode: "plan",
  81. presentation: {
  82. replaceComposer: true,
  83. showProgress: true,
  84. allowBackNavigation: true,
  85. },
  86. steps: [
  87. {
  88. id: "plan-enter",
  89. question: "Enter Plan Mode for this task?",
  90. selectionMode: "single",
  91. options: [
  92. { id: "confirm", label: "Confirm" },
  93. { id: "decline", label: "Decline" },
  94. ],
  95. allowOther: true,
  96. otherPlaceholder: "Others...",
  97. required: true,
  98. },
  99. ],
  100. } as const;
  101. }
  102. function createObservability(): TuiObservability {
  103. return {
  104. recordStartup: vi.fn(),
  105. recordAccess: vi.fn(),
  106. recordEventStream: vi.fn(),
  107. recordTerminal: vi.fn(),
  108. recordProcessStop: vi.fn(),
  109. observeRender: vi.fn(),
  110. snapshot: vi.fn(() => ({
  111. filePath: "/tmp/mcode-observability.jsonl",
  112. eventCounts: {
  113. startup: 0,
  114. runtimeAccess: 0,
  115. eventStream: 0,
  116. terminal: 0,
  117. },
  118. accessSources: {},
  119. reconnects: 0,
  120. render: {
  121. frames: 0,
  122. averageDurationMs: 0,
  123. maxDurationMs: 0,
  124. p95DurationMs: 0,
  125. },
  126. })),
  127. flush: vi.fn(async () => undefined),
  128. };
  129. }
  130. class FakeTerminal implements Terminal {
  131. columns = 80;
  132. rows = 18;
  133. kittyProtocolActive = false;
  134. started = false;
  135. stopped = false;
  136. startCount = 0;
  137. stopCount = 0;
  138. drainCount = 0;
  139. title = "";
  140. titleUpdates: string[] = [];
  141. mouseTracking = false;
  142. mouseTrackingUpdates: boolean[] = [];
  143. writes: string[] = [];
  144. input?: (data: string) => void;
  145. start(onInput: (data: string) => void): void {
  146. this.started = true;
  147. this.stopped = false;
  148. this.startCount += 1;
  149. this.input = onInput;
  150. }
  151. stop(): void {
  152. this.stopped = true;
  153. this.stopCount += 1;
  154. }
  155. drainInput(): Promise<void> {
  156. this.drainCount += 1;
  157. return Promise.resolve();
  158. }
  159. write(data: string): void {
  160. this.writes.push(data);
  161. }
  162. moveBy(): void {}
  163. hideCursor(): void {}
  164. showCursor(): void {}
  165. clearLine(): void {}
  166. clearFromCursor(): void {}
  167. clearScreen(): void {}
  168. setProgress(): void {}
  169. setMouseTracking(enabled: boolean): void {
  170. this.mouseTracking = enabled;
  171. this.mouseTrackingUpdates.push(enabled);
  172. }
  173. setTitle(title: string): void {
  174. this.title = title;
  175. this.titleUpdates.push(title);
  176. }
  177. }
  178. function renderTerminalViewport(
  179. app: ReturnType<typeof createTuiApp>,
  180. terminal: FakeTerminal,
  181. ): string {
  182. app.tui.renderNow();
  183. const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
  184. try {
  185. for (const write of terminal.writes) screen.feed(write);
  186. return screen.viewportText();
  187. } finally {
  188. screen.dispose();
  189. }
  190. }
  191. function createRuntime(): TuiRuntime {
  192. const abortSession = vi.fn(async () => true);
  193. let currentGoal: Awaited<ReturnType<TuiRuntime["getGoal"]>>;
  194. let createdSession:
  195. | {
  196. sessionId: string;
  197. title: string;
  198. workspaceDir: string;
  199. interactionMode?: "plan";
  200. }
  201. | undefined;
  202. const runtime: TuiRuntime = {
  203. createSession: vi.fn(async () => {
  204. createdSession = {
  205. sessionId: "session-1",
  206. title: "New session",
  207. workspaceDir: "/workspace",
  208. };
  209. return { ...createdSession };
  210. }),
  211. listSessions: vi.fn(async () => []),
  212. listSessionPage: vi.fn(async () => ({
  213. sessions: [],
  214. hasMore: false,
  215. })),
  216. getSession: vi.fn(async (sessionId: string) =>
  217. createdSession?.sessionId === sessionId
  218. ? { ...createdSession }
  219. : {
  220. sessionId,
  221. title: "Existing session",
  222. workspaceDir: "/workspace",
  223. },
  224. ),
  225. getMessages: vi.fn(async () => []),
  226. listMessagePage: vi.fn(async () => ({ messages: [], hasMore: false })),
  227. getSessionForkOptions: vi.fn(async () => ({
  228. canFork: true,
  229. worktreeVisible: false,
  230. worktreeEligible: false,
  231. })),
  232. forkSession: vi.fn(async () => ({
  233. session: {
  234. sessionId: "session-fork",
  235. parentSessionId: "session-1",
  236. title: "New session (fork 1)",
  237. workspaceDir: "/workspace",
  238. },
  239. })),
  240. getWorkspaceGitMetadata: vi.fn(async () => ({
  241. isGitRepo: false,
  242. branch: "",
  243. detached: false,
  244. isWorktree: false,
  245. })),
  246. renameSession: vi.fn(async (sessionId: string, title: string) => ({
  247. sessionId,
  248. title,
  249. workspaceDir: "/workspace",
  250. })),
  251. archiveSession: vi.fn(async () => undefined),
  252. listSessionInputSummaries: vi.fn(async () => []),
  253. getSessionRewindPreview: vi.fn(async () => ({ turns: [] })),
  254. rewindSession: vi.fn(async () => ({ rewound: true })),
  255. editSessionMessage: vi.fn(async () => ({
  256. rewound: true,
  257. turnId: "turn-edit-1",
  258. userMessageId: "msg-user-v1-edited",
  259. })),
  260. isGoalEnabled: vi.fn(() => true),
  261. getGoal: vi.fn(async () => currentGoal),
  262. createGoal: vi.fn(async ({ sessionId, objective, attachments }) => {
  263. currentGoal = {
  264. goalId: "goal-1",
  265. sessionId,
  266. objective,
  267. status: "active",
  268. createdAt: 10,
  269. updatedAt: 10,
  270. tokensUsed: 0,
  271. turnsUsed: 0,
  272. timeUsedSeconds: 0,
  273. tokenBudget: null,
  274. statusReason: null,
  275. hasKickoffAttachments: Boolean(attachments?.length),
  276. };
  277. return currentGoal;
  278. }),
  279. patchGoal: vi.fn(async (_sessionId, patch) => {
  280. if (!currentGoal) throw new Error("Goal not found");
  281. currentGoal = {
  282. ...currentGoal,
  283. ...patch,
  284. updatedAt: currentGoal.updatedAt + 1,
  285. };
  286. return currentGoal;
  287. }),
  288. clearGoal: vi.fn(async () => {
  289. const existed = Boolean(currentGoal);
  290. currentGoal = undefined;
  291. return existed;
  292. }),
  293. getInstructionSources: vi.fn(async () => []),
  294. getRuntimeDiagnostics: vi.fn(async () => ({
  295. status: "ok",
  296. surface: "cli-standalone",
  297. runtimeMode: "clean",
  298. runtimeOwnerKind: "cli",
  299. runtimeOwnerId: "minimax-code",
  300. dataDir: "/home/dev/.minimax",
  301. configPath: "/home/dev/.minimax/config.yaml",
  302. configPresent: true,
  303. authCachePresent: true,
  304. defaultModel: "minimax/MiniMax-M2.7",
  305. providerId: "minimax",
  306. modelId: "MiniMax-M2.7",
  307. authMode: "managed-login",
  308. authModeSource: "explicit",
  309. managedTokenPresent: true,
  310. apiKeyPresent: false,
  311. customProviderCount: 0,
  312. warnings: [],
  313. })),
  314. prepareFeedback: vi.fn(async ({ description, sessionId }) => ({
  315. schemaVersion: 1 as const,
  316. draftId: "feedback-draft-1",
  317. description,
  318. diagnostics: [
  319. { label: "Client", value: "mcode 0.1.0" },
  320. { label: "Runtime", value: "clean · cli" },
  321. { label: "Session", value: sessionId ?? "not included" },
  322. ],
  323. included: ["redacted feedback description"],
  324. excluded: ["credentials and tokens", "conversation prompts and messages"],
  325. expiresAtMs: Date.now() + 60_000,
  326. })),
  327. submitFeedback: vi.fn(async () => ({
  328. schemaVersion: 1 as const,
  329. ticketId: "ticket-1",
  330. status: "processing" as const,
  331. createdAtMs: Date.now(),
  332. })),
  333. cancelFeedback: vi.fn(async () => true),
  334. runDailyCheckin: vi.fn(async () => ({
  335. status: "claimed" as const,
  336. dayNo: 2,
  337. points: 20,
  338. expireAtMs: 1_800_000_000_000,
  339. panel: {
  340. scene: 2,
  341. days: Array.from({ length: 7 }, (_, index) => ({
  342. day_no: index + 1,
  343. points: (index + 1) * 10,
  344. status: index <= 1 ? 3 : 1,
  345. is_today: index === 1,
  346. })),
  347. },
  348. })),
  349. getAccountStatus: vi.fn(async () => ({
  350. status: "ready",
  351. defaultModel: "minimax/MiniMax-M2.7",
  352. providerId: "minimax",
  353. modelId: "MiniMax-M2.7",
  354. authMode: "managed-login",
  355. managedTokenPresent: true,
  356. warnings: [],
  357. })),
  358. listProviderPresets: vi.fn(async () => []),
  359. getCodexOAuthStatus: vi.fn(async () => ({
  360. state: "hidden" as const,
  361. providerId: "openai-codex" as const,
  362. })),
  363. startCodexOAuthLogin: vi.fn(async () => ({
  364. state: "hidden" as const,
  365. providerId: "openai-codex" as const,
  366. })),
  367. getPermissionMode: vi.fn(async () => "auto" as const),
  368. setPermissionMode: vi.fn(async (mode) => mode),
  369. getPlanModeCapabilities: vi.fn(async () => ({ entryEnabled: true })),
  370. getPendingQuestionnaire: vi.fn(async () => undefined),
  371. getLatestPlanReview: vi.fn(async () => undefined),
  372. replyQuestionnaire: vi.fn(async () => true),
  373. dismissQuestionnaire: vi.fn(async () => true),
  374. listPendingPermissions: vi.fn(async () => []),
  375. replyPermission: vi.fn(async () => true),
  376. listModels: vi.fn(async () => [
  377. {
  378. providerId: "minimax",
  379. modelId: "MiniMax-M2.7",
  380. displayName: "MiniMax M2.7",
  381. providerKind: "minimax-managed",
  382. selected: true,
  383. },
  384. ]),
  385. selectModel: vi.fn(async () => true),
  386. getSessionUsage: vi.fn(async () => ({
  387. summary: {
  388. inputTokens: 100,
  389. outputTokens: 20,
  390. totalTokens: 120,
  391. turns: 1,
  392. },
  393. rows: [],
  394. })),
  395. requestCompaction: vi.fn(async () => ({
  396. success: true,
  397. sessionId: "session-1",
  398. compactionId: "compact-1",
  399. messagesBefore: 12,
  400. messagesAfter: 4,
  401. tokensBefore: 4000,
  402. tokensAfter: 1200,
  403. })),
  404. getContextSnapshot: vi.fn(async () => ({ status: "empty" as const })),
  405. getActiveRun: vi.fn(async (sessionId: string) => ({
  406. schemaVersion: 1 as const,
  407. sessionId,
  408. state: "idle" as const,
  409. actions: { steer: false },
  410. })),
  411. getDelegationSnapshot: vi.fn(async (rootSessionId: string) => ({
  412. schemaVersion: 1 as const,
  413. rootSessionId,
  414. members: [],
  415. })),
  416. stopDelegation: vi.fn(async (rootSessionId: string) => ({
  417. schemaVersion: 1 as const,
  418. rootSessionId,
  419. rootStopped: await abortSession({ id: rootSessionId }),
  420. stoppedSessionIds: [],
  421. activeSessionIds: [],
  422. failedSessionIds: [],
  423. })),
  424. steer: vi.fn(async (input) => ({
  425. turnId: input.requestedTurnId ?? "turn-steer",
  426. mode: input.requestedTurnId
  427. ? ("steered" as const)
  428. : ("activated" as const),
  429. ...(input.requestedTurnId
  430. ? {}
  431. : {
  432. completion:
  433. (async function* completion(): AsyncGenerator<TuiStreamEvent> {
  434. yield { type: "done", turnId: "turn-steer" };
  435. })(),
  436. }),
  437. })),
  438. listSkills: vi.fn(async () => ({
  439. skills: [
  440. {
  441. name: "docs",
  442. displayName: "Docs",
  443. description: "Read project docs",
  444. enabled: true,
  445. sourceKind: "builtin",
  446. },
  447. ],
  448. hasMore: false,
  449. })),
  450. inspectProjectMcp: vi.fn(async () => undefined),
  451. listMcpServers: vi.fn(async () => [
  452. {
  453. name: "browser",
  454. enabled: true,
  455. transport: "stdio",
  456. description: "Browser tools",
  457. configJson: '{"env":{"TOKEN":"hidden"}}',
  458. },
  459. ]),
  460. listQueuedMessages: vi.fn(async () => []),
  461. getQueueSnapshot: vi.fn(async (sessionId: string) => {
  462. const items = await runtime.listQueuedMessages(sessionId);
  463. return {
  464. items,
  465. paused: items.some((item) => item.status === "paused"),
  466. pendingCount: items.length,
  467. };
  468. }),
  469. continueQueue: vi.fn(async () => undefined),
  470. steerQueuedMessage: vi.fn(async (_sessionId: string, itemId: string) => ({
  471. queueItemId: itemId,
  472. turnId: "turn-steered-queue",
  473. })),
  474. enqueueMessage: vi.fn(async () => ({
  475. itemId: "queue-1",
  476. status: "queued",
  477. position: 1,
  478. })),
  479. updateQueuedMessageContent: vi.fn(async () => undefined),
  480. deleteQueuedMessage: vi.fn(async () => undefined),
  481. watchEvents: vi.fn(async function* watchEvents(signal) {
  482. await new Promise<void>((resolve) => {
  483. signal.addEventListener("abort", resolve, { once: true });
  484. });
  485. for (const event of [] as TuiRuntimeEvent[]) yield event;
  486. }),
  487. watchSessionTurn: vi.fn(async function* watchSessionTurn() {}),
  488. sendMessage: vi.fn(
  489. async function* sendMessage(request): AsyncGenerator<TuiStreamEvent> {
  490. if (createdSession?.sessionId === request.id) {
  491. if (request.clientIntent === "plan-entry")
  492. createdSession.interactionMode = "plan";
  493. if (request.clientIntent === "plan-exit")
  494. delete createdSession.interactionMode;
  495. }
  496. yield { type: "delta", content: "Hello from the Agent" };
  497. yield { type: "done" };
  498. },
  499. ),
  500. abortSession,
  501. };
  502. return runtime;
  503. }
  504. describe("createTuiApp", () => {
  505. it.each(["regular", "fullscreen"] as const)(
  506. "configures /statusline from terminal input and reopens the saved selection in %s mode",
  507. async (tuiMode) => {
  508. const terminal = new FakeTerminal();
  509. const runtime = createRuntime();
  510. const persistStatusLineItems = vi.fn(async () => undefined);
  511. const app = createTuiApp({
  512. runtime,
  513. terminal,
  514. version: "test",
  515. workspaceDir: "/workspace",
  516. tuiMode,
  517. statusLineItems: ["current-dir"],
  518. persistStatusLineItems,
  519. });
  520. try {
  521. app.start();
  522. await app.ready;
  523. app.editor.setText("/statusline");
  524. terminal.input?.("\r");
  525. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  526. expect(stripAnsi(app.interaction.render(80).join("\n"))).toContain(
  527. "[x] current-dir",
  528. );
  529. terminal.input?.(" ");
  530. terminal.input?.("\r");
  531. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  532. expect(persistStatusLineItems).toHaveBeenCalledWith([]);
  533. app.editor.setText("/statusline");
  534. terminal.input?.("\r");
  535. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  536. expect(stripAnsi(app.interaction.render(80).join("\n"))).toContain(
  537. "[ ] current-dir",
  538. );
  539. terminal.input?.("\x1b");
  540. expect(app.interaction.isActive()).toBe(false);
  541. expect(persistStatusLineItems).toHaveBeenCalledOnce();
  542. expect(runtime.sendMessage).not.toHaveBeenCalled();
  543. } finally {
  544. await app.stop();
  545. }
  546. },
  547. );
  548. it.each([
  549. ["regular", false],
  550. ["regular", true],
  551. ["fullscreen", false],
  552. ["fullscreen", true],
  553. ] as const)(
  554. "runs ls unchanged in %s mode after empty-prefix Tab: %s",
  555. async (tuiMode, pressTab) => {
  556. const directory = await mkdtemp(join(tmpdir(), "tui-ls-enter-"));
  557. await mkdir(join(directory, "aaa-directory"));
  558. await writeFile(join(directory, "root-only.txt"), "root");
  559. const terminal = new FakeTerminal();
  560. const runtime = createRuntime();
  561. const app = createTuiApp({
  562. runtime,
  563. terminal,
  564. version: "0.1.0",
  565. workspaceDir: directory,
  566. tuiMode,
  567. });
  568. try {
  569. app.start();
  570. await app.ready;
  571. app.editor.setText("!ls");
  572. terminal.input?.(" ");
  573. expect(stripAnsi(app.editor.render(100).join("\n"))).not.toContain(
  574. "aaa-directory/",
  575. );
  576. if (pressTab) {
  577. terminal.input?.("\t");
  578. await vi.waitFor(() =>
  579. expect(stripAnsi(app.editor.render(100).join("\n"))).toContain(
  580. "aaa-directory/",
  581. ),
  582. );
  583. }
  584. expect(app.editor.getText()).toBe("!ls ");
  585. terminal.input?.("\r");
  586. await vi.waitFor(
  587. () =>
  588. expect(
  589. app.transcript.snapshot().find((cell) => cell.kind === "shell")
  590. ?.status,
  591. ).toBe("succeeded"),
  592. { timeout: 5000 },
  593. );
  594. expect(
  595. app.transcript.snapshot().find((cell) => cell.kind === "shell"),
  596. ).toMatchObject({
  597. title: "! ls",
  598. content: expect.stringContaining("root-only.txt"),
  599. });
  600. expect(runtime.sendMessage).not.toHaveBeenCalled();
  601. } finally {
  602. await app.stop();
  603. await rm(directory, { recursive: true, force: true });
  604. }
  605. },
  606. );
  607. it.each(["regular", "fullscreen"] as const)(
  608. "completes a shell path from terminal input in %s mode before executing",
  609. async (tuiMode) => {
  610. const directory = await mkdtemp(
  611. join(tmpdir(), "tui-shell-completion-app-"),
  612. );
  613. await writeFile(
  614. join(directory, "report file.txt"),
  615. "completed-shell-output",
  616. );
  617. const terminal = new FakeTerminal();
  618. const runtime = createRuntime();
  619. const app = createTuiApp({
  620. runtime,
  621. terminal,
  622. version: "0.1.0",
  623. workspaceDir: directory,
  624. tuiMode,
  625. });
  626. try {
  627. app.start();
  628. await app.ready;
  629. app.editor.setText(
  630. process.platform === "win32" ? "!Get-Content " : "!cat ",
  631. );
  632. for (const char of "rep") terminal.input?.(char);
  633. expect(app.editor.getText()).toBe(
  634. process.platform === "win32" ? "!Get-Content rep" : "!cat rep",
  635. );
  636. terminal.input?.("\t");
  637. await vi.waitFor(() =>
  638. expect(app.editor.getText()).toBe(
  639. process.platform === "win32"
  640. ? "!Get-Content report` file.txt "
  641. : "!cat report\\ file.txt ",
  642. ),
  643. );
  644. expect(
  645. app.transcript
  646. .snapshot()
  647. .some((cell) => cell.id.startsWith("local:bash:")),
  648. ).toBe(false);
  649. terminal.input?.("\r");
  650. await vi.waitFor(
  651. () =>
  652. expect(
  653. app.transcript
  654. .snapshot()
  655. .some(
  656. (cell) =>
  657. cell.id.startsWith("local:bash:") &&
  658. cell.status === "succeeded" &&
  659. cell.content.includes("completed-shell-output"),
  660. ),
  661. ).toBe(true),
  662. { timeout: 5000 },
  663. );
  664. expect(runtime.sendMessage).not.toHaveBeenCalled();
  665. } finally {
  666. await app.stop();
  667. await rm(directory, { recursive: true, force: true });
  668. }
  669. },
  670. );
  671. it("runs an editor ! command locally and carries its result into the next model message", async () => {
  672. const directory = await mkdtemp(join(tmpdir(), "tui-bash-app-"));
  673. const runtime = createRuntime();
  674. const app = createTuiApp({
  675. runtime,
  676. terminal: new FakeTerminal(),
  677. version: "0.1.0",
  678. workspaceDir: directory,
  679. });
  680. try {
  681. await app.ready;
  682. app.editor.setText(
  683. process.platform === "win32"
  684. ? "!Write-Output shell-result"
  685. : "!printf shell-result",
  686. );
  687. app.editor.submit();
  688. await vi.waitFor(
  689. () =>
  690. expect(
  691. app.transcript
  692. .snapshot()
  693. .some(
  694. (cell) =>
  695. cell.id.startsWith("local:bash:") &&
  696. cell.status === "succeeded",
  697. ),
  698. ).toBe(true),
  699. { timeout: 5000 },
  700. );
  701. expect(runtime.sendMessage).not.toHaveBeenCalled();
  702. expect(
  703. app.transcript
  704. .snapshot()
  705. .find((cell) => cell.id.startsWith("local:bash:"))?.content,
  706. ).toContain("shell-result");
  707. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain(
  708. "shell-result",
  709. );
  710. await app.submit("Explain the output");
  711. expect(runtime.sendMessage).toHaveBeenCalledWith(
  712. expect.objectContaining({
  713. content: expect.stringContaining("shell-result"),
  714. }),
  715. expect.anything(),
  716. );
  717. } finally {
  718. await app.stop();
  719. await rm(directory, { recursive: true, force: true });
  720. }
  721. });
  722. it("shows shell output before the command exits and drains it when the app stops", async () => {
  723. const directory = await mkdtemp(join(tmpdir(), "tui-bash-stream-"));
  724. const app = createTuiApp({
  725. runtime: createRuntime(),
  726. terminal: new FakeTerminal(),
  727. version: "0.1.0",
  728. workspaceDir: directory,
  729. });
  730. try {
  731. await app.ready;
  732. const running = app.submit(
  733. process.platform === "win32"
  734. ? "!Write-Output streamed-result; Start-Sleep -Seconds 30"
  735. : "!printf streamed-result; sleep 30",
  736. );
  737. await vi.waitFor(
  738. () =>
  739. expect(
  740. app.transcript
  741. .snapshot()
  742. .some(
  743. (cell) =>
  744. cell.status === "running" &&
  745. cell.content.includes("streamed-result"),
  746. ),
  747. ).toBe(true),
  748. { timeout: 5000 },
  749. );
  750. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain(
  751. "streamed-result",
  752. );
  753. await app.stop();
  754. await running;
  755. expect(
  756. app.transcript
  757. .snapshot()
  758. .find((cell) => cell.id.startsWith("local:bash:"))?.status,
  759. ).toBe("cancelled");
  760. } finally {
  761. await app.stop();
  762. await rm(directory, { recursive: true, force: true });
  763. }
  764. });
  765. it("continues a restored paused Queue from its manager without sending a new message", async () => {
  766. const terminal = new FakeTerminal();
  767. const runtime = createRuntime();
  768. let paused = true;
  769. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  770. {
  771. itemId: "paused-follow-up",
  772. sessionId: "session-1",
  773. status: paused ? "paused" : "queued",
  774. content: "Existing queued work",
  775. },
  776. ]);
  777. vi.mocked(runtime.continueQueue).mockImplementation(async () => {
  778. paused = false;
  779. });
  780. const app = createTuiApp({
  781. runtime,
  782. terminal,
  783. version: "test",
  784. workspaceDir: "/workspace",
  785. productFeatures: { queue: true },
  786. });
  787. app.start();
  788. try {
  789. await app.ready;
  790. await app.openSession("session-1");
  791. await app.submit("/queue");
  792. expect(app.tui.render(120).join("\n")).toContain("c continue queue");
  793. terminal.input?.("c");
  794. await vi.waitFor(() =>
  795. expect(runtime.continueQueue).toHaveBeenCalledWith("session-1"),
  796. );
  797. await vi.waitFor(() =>
  798. expect(app.tui.render(120).join("\n")).toContain("Queue continued."),
  799. );
  800. expect(runtime.sendMessage).not.toHaveBeenCalled();
  801. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  802. expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
  803. } finally {
  804. await app.stop();
  805. }
  806. });
  807. it.each(["keep", "clear", "cancel-enter", "cancel-escape"] as const)(
  808. "recovers a restored paused Queue when sending a message: %s",
  809. async (decision) => {
  810. const dataDir = await mkdtemp(join(tmpdir(), "tui-paused-queue-draft-"));
  811. const terminal = new FakeTerminal();
  812. const runtime = createRuntime();
  813. let items: TuiQueuedMessage[] = [
  814. {
  815. itemId: "paused-follow-up",
  816. sessionId: "session-1",
  817. status: "paused",
  818. content: "Existing queued work",
  819. },
  820. ];
  821. let emitQueueChange:
  822. | ((event: TuiRuntimeEvent | undefined) => void)
  823. | undefined;
  824. vi.mocked(runtime.watchEvents).mockImplementation(
  825. async function* (signal) {
  826. const event = await new Promise<TuiRuntimeEvent | undefined>(
  827. (resolve) => {
  828. emitQueueChange = resolve;
  829. signal.addEventListener("abort", () => resolve(undefined), {
  830. once: true,
  831. });
  832. },
  833. );
  834. if (!event || signal.aborted) return;
  835. yield event;
  836. if (!signal.aborted) {
  837. await new Promise<void>((resolve) => {
  838. signal.addEventListener("abort", () => resolve(), { once: true });
  839. });
  840. }
  841. },
  842. );
  843. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  844. ...items,
  845. ]);
  846. vi.mocked(runtime.sendMessage).mockImplementation(
  847. async function* (request, _signal, options) {
  848. if (!options?.pausedQueueAction) {
  849. throw new TuiFailure("runtime", "Queue paused", {
  850. code: "local_session_queue_paused",
  851. });
  852. }
  853. items =
  854. options.pausedQueueAction === "clear"
  855. ? []
  856. : items.map((item) => ({ ...item, status: "queued" }));
  857. emitQueueChange?.({
  858. type: "session.queue.updated",
  859. sessionId: "session-1",
  860. source: "runtime-v2",
  861. timestampMs: Date.now(),
  862. });
  863. yield { type: "done", turnId: request.turnId };
  864. },
  865. );
  866. const appOptions = {
  867. runtime,
  868. terminal,
  869. version: "test",
  870. dataDir,
  871. workspaceDir: "/workspace",
  872. productFeatures: { queue: true },
  873. };
  874. let app = createTuiApp(appOptions);
  875. app.start();
  876. try {
  877. await app.ready;
  878. await app.openSession("session-1");
  879. await vi.waitFor(() => expect(emitQueueChange).toBeTypeOf("function"));
  880. await vi.waitFor(() =>
  881. expect(app.tui.render(120).join("\n")).toContain(
  882. "Existing queued work",
  883. ),
  884. );
  885. terminal.input?.("Resume safely");
  886. terminal.input?.("\r");
  887. await vi.waitFor(() =>
  888. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  889. );
  890. const cancelled = decision.startsWith("cancel");
  891. if (decision === "cancel-escape") terminal.input?.("\u001b");
  892. else {
  893. if (decision === "clear") terminal.input?.("\u001b[B");
  894. if (decision === "cancel-enter") {
  895. terminal.input?.("\u001b[B");
  896. terminal.input?.("\u001b[B");
  897. }
  898. terminal.input?.("\r");
  899. }
  900. await vi.waitFor(() =>
  901. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  902. );
  903. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  904. if (cancelled) {
  905. await vi.waitFor(() =>
  906. expect(app.editor.getText()).toBe("Resume safely"),
  907. );
  908. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  909. expect(runtime.continueQueue).not.toHaveBeenCalled();
  910. expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
  911. expect(
  912. app.transcript.snapshot().filter((cell) => cell.kind === "user"),
  913. ).toEqual([]);
  914. expect(
  915. app.transcript.snapshot().filter((cell) => cell.kind === "error"),
  916. ).toEqual([]);
  917. expect(app.tui.render(120).join("\n")).toContain("Queue paused");
  918. expect(app.tui.render(120).join("\n")).not.toContain("Keep my draft");
  919. await vi.waitFor(async () => {
  920. const recovered = await new TuiDraftRecovery({
  921. dataDir,
  922. workspaceDir: "/workspace",
  923. sessionKey: "session-1",
  924. }).load();
  925. expect(recovered?.editor.text).toBe("Resume safely");
  926. expect(recovered?.retrySubmissions ?? []).toEqual([]);
  927. });
  928. app.editor.setText("Edited draft");
  929. await app.stop();
  930. app = createTuiApp(appOptions);
  931. app.start();
  932. await app.ready;
  933. await app.openSession("session-1");
  934. await vi.waitFor(() =>
  935. expect(app.editor.getText()).toBe("Edited draft"),
  936. );
  937. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  938. terminal.input?.("\r");
  939. await vi.waitFor(() =>
  940. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  941. );
  942. terminal.input?.("\r");
  943. await vi.waitFor(() =>
  944. expect(runtime.sendMessage).toHaveBeenCalledTimes(3),
  945. );
  946. await vi.waitFor(() =>
  947. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  948. );
  949. expect(
  950. vi.mocked(runtime.sendMessage).mock.calls[2]?.[0],
  951. ).toMatchObject({
  952. content: "Edited draft",
  953. });
  954. expect(vi.mocked(runtime.sendMessage).mock.calls[2]?.[2]).toEqual({
  955. pausedQueueAction: "keep",
  956. });
  957. await vi.waitFor(() =>
  958. expect(app.tui.render(120).join("\n")).not.toContain(
  959. "Queue paused",
  960. ),
  961. );
  962. expect(app.editor.getText()).toBe("");
  963. expect(app.tui.render(120).join("\n")).toContain(
  964. "Existing queued work",
  965. );
  966. } else {
  967. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  968. expect(
  969. vi.mocked(runtime.sendMessage).mock.calls[1]?.[0],
  970. ).toMatchObject({
  971. content: "Resume safely",
  972. });
  973. expect(vi.mocked(runtime.sendMessage).mock.calls[1]?.[2]).toEqual({
  974. pausedQueueAction: decision,
  975. });
  976. await vi.waitFor(() =>
  977. expect(app.tui.render(120).join("\n")).not.toContain(
  978. "Queue paused",
  979. ),
  980. );
  981. const rendered = app.tui.render(120).join("\n");
  982. if (decision === "clear")
  983. expect(rendered).not.toContain("Existing queued work");
  984. else expect(rendered).toContain("Existing queued work");
  985. }
  986. } finally {
  987. await app.stop();
  988. await rm(dataDir, { recursive: true, force: true });
  989. }
  990. },
  991. );
  992. it.each([
  993. ["plan-entry", "keep"],
  994. ["plan-entry", "clear"],
  995. ["plan-entry", "cancel"],
  996. ["plan-entry", "busy"],
  997. ["plan-exit", "keep"],
  998. ["plan-exit", "clear"],
  999. ["plan-exit", "cancel"],
  1000. ["plan-exit", "busy"],
  1001. ] as const)(
  1002. "recovers a paused Queue with %s and decision %s",
  1003. async (clientIntent, decision) => {
  1004. const terminal = new FakeTerminal();
  1005. const runtime = createRuntime();
  1006. let interactionMode: "plan" | undefined =
  1007. clientIntent === "plan-exit" ? "plan" : undefined;
  1008. let rejectRecovery = decision === "busy";
  1009. vi.mocked(runtime.getSession).mockImplementation(async () => ({
  1010. sessionId: "session-1",
  1011. interactionMode,
  1012. }));
  1013. vi.mocked(runtime.listQueuedMessages).mockResolvedValue([
  1014. {
  1015. itemId: "paused-work",
  1016. sessionId: "session-1",
  1017. status: "paused",
  1018. content: "Existing work",
  1019. },
  1020. ]);
  1021. vi.mocked(runtime.sendMessage).mockImplementation(
  1022. async function* (request, _signal, options) {
  1023. if (!options?.pausedQueueAction || rejectRecovery) {
  1024. throw new TuiFailure("runtime", "Admission rejected", {
  1025. code: options?.pausedQueueAction
  1026. ? "local_session_busy"
  1027. : "local_session_queue_paused",
  1028. });
  1029. }
  1030. interactionMode =
  1031. request.clientIntent === "plan-entry" ? "plan" : undefined;
  1032. yield { type: "done", turnId: request.turnId };
  1033. },
  1034. );
  1035. const app = createTuiApp({
  1036. runtime,
  1037. terminal,
  1038. version: "test",
  1039. workspaceDir: "/workspace",
  1040. productFeatures: { queue: true },
  1041. });
  1042. app.start();
  1043. try {
  1044. await app.ready;
  1045. await app.openSession("session-1");
  1046. await app.submit(
  1047. clientIntent === "plan-entry" ? "/plan on" : "/plan off",
  1048. );
  1049. terminal.input?.("Change mode and continue");
  1050. terminal.input?.("\r");
  1051. await vi.waitFor(() =>
  1052. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  1053. );
  1054. if (decision === "clear" || decision === "cancel")
  1055. terminal.input?.("\u001b[B");
  1056. if (decision === "cancel") terminal.input?.("\u001b[B");
  1057. terminal.input?.("\r");
  1058. await vi.waitFor(() =>
  1059. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  1060. );
  1061. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  1062. if (decision === "cancel" || decision === "busy") {
  1063. await vi.waitFor(() =>
  1064. expect(app.editor.getText()).toBe("Change mode and continue"),
  1065. );
  1066. expect(interactionMode === "plan").toBe(clientIntent === "plan-exit");
  1067. rejectRecovery = false;
  1068. app.editor.setText("Edited mode instruction");
  1069. terminal.input?.("\r");
  1070. await vi.waitFor(() =>
  1071. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  1072. );
  1073. terminal.input?.("\r");
  1074. await vi.waitFor(() =>
  1075. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  1076. );
  1077. }
  1078. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  1079. expect.objectContaining({ clientIntent }),
  1080. expect.any(AbortSignal),
  1081. { pausedQueueAction: decision === "clear" ? "clear" : "keep" },
  1082. );
  1083. expect(interactionMode === "plan").toBe(clientIntent === "plan-entry");
  1084. expect(app.editor.getText()).toBe("");
  1085. } finally {
  1086. await app.stop();
  1087. }
  1088. },
  1089. );
  1090. it("shows the MCode prompt in an empty Composer and hides it after input", async () => {
  1091. const app = createTuiApp({
  1092. runtime: createRuntime(),
  1093. terminal: new FakeTerminal(),
  1094. version: "0.1.0",
  1095. workspaceDir: "/workspace",
  1096. });
  1097. try {
  1098. app.start();
  1099. await app.ready;
  1100. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  1101. "Ask Mcode to do anything",
  1102. );
  1103. app.editor.handleInput("R");
  1104. expect(stripAnsi(app.tui.render(80).join("\n"))).not.toContain(
  1105. "Ask Mcode to do anything",
  1106. );
  1107. expect(app.editor.getText()).toBe("R");
  1108. } finally {
  1109. await app.stop();
  1110. }
  1111. });
  1112. it("copies the last Assistant reply to the client clipboard over SSH", async () => {
  1113. vi.stubEnv("SSH_CONNECTION", "10.0.0.1 50100 10.0.0.2 22");
  1114. vi.stubEnv("SSH_TTY", "/dev/pts/1");
  1115. Object.defineProperty(process.stdin, "isTTY", {
  1116. configurable: true,
  1117. value: true,
  1118. });
  1119. Object.defineProperty(process.stdout, "isTTY", {
  1120. configurable: true,
  1121. value: true,
  1122. });
  1123. const terminal = new FakeTerminal();
  1124. let app: ReturnType<typeof createTuiApp> | undefined;
  1125. try {
  1126. app = createTuiApp({
  1127. runtime: createRuntime(),
  1128. terminal,
  1129. version: "0.1.0",
  1130. workspaceDir: "/workspace",
  1131. });
  1132. app.start();
  1133. await app.ready;
  1134. await app.submit("Say hello");
  1135. await app.submit("/copy");
  1136. expect(terminal.writes).toContain(
  1137. "\u001B]52;c;SGVsbG8gZnJvbSB0aGUgQWdlbnQ=\u0007",
  1138. );
  1139. } finally {
  1140. await app?.stop();
  1141. Reflect.deleteProperty(process.stdin, "isTTY");
  1142. Reflect.deleteProperty(process.stdout, "isTTY");
  1143. vi.unstubAllEnvs();
  1144. }
  1145. });
  1146. it("runs /goal through Runtime ownership and renders the active Goal above the Composer", async () => {
  1147. const runtime = createRuntime();
  1148. const app = createTuiApp({
  1149. runtime,
  1150. terminal: new FakeTerminal(),
  1151. version: "0.1.0",
  1152. workspaceDir: "/workspace",
  1153. });
  1154. app.start();
  1155. await app.ready;
  1156. await app.submit("/goal Ship TUI Goal support");
  1157. expect(runtime.createSession).toHaveBeenCalledOnce();
  1158. expect(runtime.createGoal).toHaveBeenCalledWith({
  1159. sessionId: "session-1",
  1160. objective: "Ship TUI Goal support",
  1161. });
  1162. expect(runtime.sendMessage).not.toHaveBeenCalled();
  1163. expect(app.surfaceHost.render(100).join("\n")).toContain("Goal · Active");
  1164. expect(app.surfaceHost.render(100).join("\n")).toContain(
  1165. "Ship TUI Goal support",
  1166. );
  1167. await app.submit("/goal pause");
  1168. expect(runtime.patchGoal).toHaveBeenCalledWith("session-1", {
  1169. status: "paused",
  1170. });
  1171. expect(app.surfaceHost.render(100).join("\n")).toContain("Goal · Paused");
  1172. await app.stop();
  1173. });
  1174. it("wires complete chat and autocomplete business events into the TUI surface", async () => {
  1175. const events: McodeBusinessEvent[] = [];
  1176. const businessTelemetry: McodeBusinessTelemetry = {
  1177. track: (event, properties) =>
  1178. events.push({ event, properties } as McodeBusinessEvent),
  1179. flush: async () => undefined,
  1180. };
  1181. const app = createTuiApp({
  1182. runtime: createRuntime(),
  1183. terminal: new FakeTerminal(),
  1184. version: "0.1.0",
  1185. workspaceDir: "/workspace/agent-archon",
  1186. businessTelemetry,
  1187. });
  1188. await app.ready;
  1189. await app.submit("First prompt");
  1190. await app.submit("Second prompt");
  1191. for (const character of "/he") app.editor.handleInput(character);
  1192. await vi.waitFor(() =>
  1193. expect(
  1194. events.some((item) => item.event === "slash_command_menu_view"),
  1195. ).toBe(true),
  1196. );
  1197. app.editor.handleInput("\r");
  1198. expect(events.filter((item) => item.event === "chat_send")).toEqual([
  1199. {
  1200. event: "chat_send",
  1201. properties: {
  1202. chat_type: "chat",
  1203. is_first_message: 1,
  1204. is_attachment: "text",
  1205. },
  1206. },
  1207. {
  1208. event: "chat_send",
  1209. properties: {
  1210. chat_type: "chat",
  1211. is_first_message: 0,
  1212. is_attachment: "text",
  1213. },
  1214. },
  1215. ]);
  1216. expect(events).toContainEqual({
  1217. event: "slash_command_click",
  1218. properties: {
  1219. chat_type: "chat",
  1220. command_type: "other",
  1221. },
  1222. });
  1223. await app.stop();
  1224. });
  1225. it("releases the terminal on suspend and reconciles Runtime state after resume", async () => {
  1226. const terminal = new FakeTerminal();
  1227. const runtime = createRuntime();
  1228. const requestProcessSuspend = vi.fn();
  1229. vi.mocked(runtime.watchEvents).mockImplementation(
  1230. async function* watchEvents(signal) {
  1231. await new Promise<void>((resolve) => {
  1232. signal.addEventListener("abort", resolve, { once: true });
  1233. });
  1234. yield* [];
  1235. },
  1236. );
  1237. const app = createTuiApp({
  1238. runtime,
  1239. terminal,
  1240. version: "0.1.0",
  1241. workspaceDir: "/workspace",
  1242. requestProcessSuspend,
  1243. });
  1244. app.start();
  1245. await app.ready;
  1246. await app.openSession("session-1");
  1247. await vi.waitFor(() => expect(runtime.watchEvents).toHaveBeenCalledOnce());
  1248. terminal.input?.("\x1a");
  1249. expect(requestProcessSuspend).toHaveBeenCalledOnce();
  1250. await app.suspend();
  1251. expect(terminal.stopCount).toBe(1);
  1252. expect(app.controller.snapshot().status).not.toBe("error");
  1253. await app.resume();
  1254. expect(terminal.startCount).toBe(2);
  1255. await vi.waitFor(() =>
  1256. expect(runtime.watchEvents).toHaveBeenCalledTimes(2),
  1257. );
  1258. expect(runtime.getActiveRun).toHaveBeenCalled();
  1259. await app.stop();
  1260. });
  1261. it.each(["regular", "fullscreen"] as const)(
  1262. "restores %s Composer input after Ctrl+G returns from the external editor",
  1263. async (tuiMode) => {
  1264. const terminal = new FakeTerminal();
  1265. const stopTerminal = vi.spyOn(terminal, "stop");
  1266. const startTerminal = vi.spyOn(terminal, "start");
  1267. const editDraftInExternalEditor = vi.fn(
  1268. async () => "edited in the external editor",
  1269. );
  1270. const app = createTuiApp({
  1271. runtime: createRuntime(),
  1272. terminal,
  1273. version: "0.1.0",
  1274. workspaceDir: "/workspace",
  1275. tuiMode,
  1276. externalEditorCommand: "code --wait",
  1277. editDraftInExternalEditor,
  1278. });
  1279. app.start();
  1280. await app.ready;
  1281. const longPaste = Array.from(
  1282. { length: 12 },
  1283. (_, index) => `line ${String(index + 1)}`,
  1284. ).join("\n");
  1285. terminal.input?.(`\x1b[200~${longPaste}\x1b[201~`);
  1286. expect(app.editor.getText()).toBe("[paste #1 +12 lines]");
  1287. terminal.input?.("\x07");
  1288. await vi.waitFor(() =>
  1289. expect(editDraftInExternalEditor).toHaveBeenCalledOnce(),
  1290. );
  1291. expect(editDraftInExternalEditor).toHaveBeenCalledWith({
  1292. command: "code --wait",
  1293. draft: longPaste,
  1294. cwd: "/workspace",
  1295. });
  1296. await vi.waitFor(() =>
  1297. expect(app.editor.getText()).toBe("edited in the external editor"),
  1298. );
  1299. expect(stopTerminal).toHaveBeenCalledOnce();
  1300. expect(startTerminal).toHaveBeenCalledTimes(2);
  1301. terminal.input?.("!");
  1302. expect(app.editor.getText()).toBe("edited in the external editor!");
  1303. await app.stop();
  1304. },
  1305. );
  1306. it("loads Runtime-owned Git context into the status rail without blocking startup", async () => {
  1307. const runtime = createRuntime();
  1308. vi.mocked(runtime.getWorkspaceGitMetadata).mockResolvedValue({
  1309. isGitRepo: true,
  1310. branch: "feat/status-context",
  1311. detached: false,
  1312. isWorktree: true,
  1313. });
  1314. const app = createTuiApp({
  1315. runtime,
  1316. terminal: new FakeTerminal(),
  1317. version: "0.1.0",
  1318. workspaceDir: "/Users/dev/github/agent-archon",
  1319. homeDir: "/Users/dev",
  1320. });
  1321. await app.ready;
  1322. await vi.waitFor(() => {
  1323. expect(runtime.getWorkspaceGitMetadata).toHaveBeenCalledWith(
  1324. "/Users/dev/github/agent-archon",
  1325. );
  1326. const rendered = app.tui.render(120).join("\n");
  1327. expect(rendered).toContain("~/github/agent-archon");
  1328. expect(rendered).toContain("⎇ feat/status-context · worktree");
  1329. });
  1330. await app.stop();
  1331. });
  1332. it("keeps Pi clear-on-shrink disabled for the inline product by default", async () => {
  1333. const app = createTuiApp({
  1334. runtime: createRuntime(),
  1335. terminal: new FakeTerminal(),
  1336. version: "0.1.0",
  1337. workspaceDir: "/workspace",
  1338. });
  1339. expect(app.tui.getClearOnShrink()).toBe(false);
  1340. await app.ready;
  1341. await app.stop();
  1342. });
  1343. it("drains Pi terminal input before restoring the terminal on shutdown", async () => {
  1344. const terminal = new FakeTerminal();
  1345. const drainInput = vi.spyOn(terminal, "drainInput");
  1346. const stopTerminal = vi.spyOn(terminal, "stop");
  1347. const app = createTuiApp({
  1348. runtime: createRuntime(),
  1349. terminal,
  1350. version: "0.1.0",
  1351. workspaceDir: "/workspace",
  1352. });
  1353. app.start();
  1354. await app.ready;
  1355. await app.stop();
  1356. expect(drainInput).toHaveBeenCalledWith(1000);
  1357. expect(stopTerminal).toHaveBeenCalledOnce();
  1358. expect(drainInput.mock.invocationCallOrder[0]).toBeLessThan(
  1359. stopTerminal.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
  1360. );
  1361. });
  1362. it("shows the Runtime initialization error text when the Session catalog is unavailable", async () => {
  1363. const runtime = createRuntime();
  1364. vi.mocked(runtime.listSessions).mockRejectedValue(
  1365. new Error("Unable to connect to the Runtime on port 1234"),
  1366. );
  1367. const app = createTuiApp({
  1368. runtime,
  1369. terminal: new FakeTerminal(),
  1370. version: "0.1.0",
  1371. workspaceDir: "/workspace",
  1372. });
  1373. await app.ready;
  1374. expect(app.controller.snapshot()).toMatchObject({
  1375. status: "error",
  1376. error:
  1377. "Couldn't load sessions: Unable to connect to the Runtime on port 1234. Retry.",
  1378. sessions: [],
  1379. });
  1380. expect(app.tui.render(80).join("\n")).toContain(
  1381. "Error · Couldn't load sessions:",
  1382. );
  1383. await app.stop();
  1384. });
  1385. it("shows an available update as a dedicated startup notice", async () => {
  1386. const terminal = new FakeTerminal();
  1387. const checkForUpdate = vi.fn(async () => ({ latestVersion: "1.2.4" }));
  1388. const app = createTuiApp({
  1389. runtime: createRuntime(),
  1390. terminal,
  1391. version: "1.2.3",
  1392. workspaceDir: "/workspace",
  1393. checkForUpdate,
  1394. });
  1395. app.start();
  1396. await app.ready;
  1397. await vi.waitFor(() => {
  1398. expect(terminal.writes.join("")).toContain(
  1399. "A new version of MCode is available",
  1400. );
  1401. });
  1402. const rendered = terminal.writes.join("");
  1403. expect(checkForUpdate).toHaveBeenCalledTimes(1);
  1404. expect(rendered).toContain("Run '/update' to install MCode 1.2.4");
  1405. await app.submit("Start working");
  1406. expect(app.getSurface()).toBe("conversation");
  1407. expect(app.tui.render(80).join("\n")).not.toContain(
  1408. "A new version of MCode is available",
  1409. );
  1410. await app.submit("/new");
  1411. expect(app.getSurface()).toBe("welcome");
  1412. expect(app.tui.render(80).join("\n")).toContain(
  1413. "A new version of MCode is available",
  1414. );
  1415. await app.stop();
  1416. });
  1417. it("keeps the Welcome handoff out of the primary hint and submits it on Ctrl+U", async () => {
  1418. const terminal = new FakeTerminal();
  1419. const runtime = createRuntime();
  1420. vi.mocked(runtime.listSkills).mockResolvedValue({
  1421. skills: [
  1422. {
  1423. name: "resume-codex",
  1424. displayName: "Resume Codex",
  1425. description: "Continue a Codex session",
  1426. enabled: true,
  1427. sourceKind: "builtin",
  1428. },
  1429. ],
  1430. hasMore: false,
  1431. });
  1432. const sessionId = "01a02373-25ae-76a1-880c-9253ba939cdc";
  1433. const findRecentCodexSession = vi.fn(async () => ({
  1434. sessionId,
  1435. updatedAtMs: Date.now() - 60_000,
  1436. source: "cli" as const,
  1437. }));
  1438. const app = createTuiApp({
  1439. runtime,
  1440. terminal,
  1441. version: "0.1.0",
  1442. workspaceDir: "/workspace",
  1443. findRecentCodexSession,
  1444. });
  1445. app.start();
  1446. await app.ready;
  1447. await vi.waitFor(() =>
  1448. expect(findRecentCodexSession).toHaveBeenCalledOnce(),
  1449. );
  1450. const welcome = app.tui.render(100).join("\n");
  1451. expect(welcome).toContain("Start");
  1452. expect(welcome).not.toContain("Coming from Codex?");
  1453. terminal.input?.("\x15");
  1454. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  1455. expect(runtime.sendMessage).toHaveBeenCalledWith(
  1456. expect.objectContaining({
  1457. id: "session-1",
  1458. content: `/resume-codex ${sessionId}`,
  1459. }),
  1460. expect.any(AbortSignal),
  1461. );
  1462. expect(app.tui.render(100).join("\n")).not.toContain("Coming from Codex?");
  1463. await app.stop();
  1464. });
  1465. it("invalidates an in-flight Codex handoff scan after the user starts typing", async () => {
  1466. const terminal = new FakeTerminal();
  1467. const runtime = createRuntime();
  1468. vi.mocked(runtime.listSkills).mockResolvedValue({
  1469. skills: [
  1470. {
  1471. name: "resume-codex",
  1472. displayName: "Resume Codex",
  1473. description: "Continue a Codex session",
  1474. enabled: true,
  1475. sourceKind: "builtin",
  1476. },
  1477. ],
  1478. hasMore: false,
  1479. });
  1480. let resolveRecent:
  1481. | ((session: {
  1482. sessionId: string;
  1483. updatedAtMs: number;
  1484. source: "cli";
  1485. }) => void)
  1486. | undefined;
  1487. const findRecentCodexSession = vi.fn(
  1488. async () =>
  1489. await new Promise<{
  1490. sessionId: string;
  1491. updatedAtMs: number;
  1492. source: "cli";
  1493. }>((resolve) => {
  1494. resolveRecent = resolve;
  1495. }),
  1496. );
  1497. const app = createTuiApp({
  1498. runtime,
  1499. terminal,
  1500. version: "0.1.0",
  1501. workspaceDir: "/workspace",
  1502. findRecentCodexSession,
  1503. });
  1504. app.start();
  1505. terminal.input?.("x");
  1506. await vi.waitFor(() =>
  1507. expect(findRecentCodexSession).toHaveBeenCalledOnce(),
  1508. );
  1509. resolveRecent?.({
  1510. sessionId: "01a02373-25ae-76a1-880c-9253ba939cdc",
  1511. updatedAtMs: Date.now(),
  1512. source: "cli",
  1513. });
  1514. await Promise.resolve();
  1515. await Promise.resolve();
  1516. expect(app.editor.getText()).toBe("x");
  1517. expect(app.tui.render(100).join("\n")).not.toContain("Coming from Codex?");
  1518. await app.stop();
  1519. });
  1520. it("does not inspect Codex storage when the resume Skill is unavailable", async () => {
  1521. const runtime = createRuntime();
  1522. const findRecentCodexSession = vi.fn(async () => ({
  1523. sessionId: "01a02373-25ae-76a1-880c-9253ba939cdc",
  1524. updatedAtMs: Date.now(),
  1525. source: "cli" as const,
  1526. }));
  1527. const app = createTuiApp({
  1528. runtime,
  1529. terminal: new FakeTerminal(),
  1530. version: "0.1.0",
  1531. workspaceDir: "/workspace",
  1532. findRecentCodexSession,
  1533. });
  1534. app.start();
  1535. await app.ready;
  1536. await vi.waitFor(() => expect(runtime.listSkills).toHaveBeenCalledOnce());
  1537. await Promise.resolve();
  1538. expect(findRecentCodexSession).not.toHaveBeenCalled();
  1539. expect(app.tui.render(100).join("\n")).not.toContain("Coming from Codex?");
  1540. await app.stop();
  1541. });
  1542. it.each(["unsupported result", "blank version", "rejected check"] as const)(
  1543. "keeps a %s startup update result out of the notice and transcript",
  1544. async (scenario) => {
  1545. const terminal = new FakeTerminal();
  1546. const checkForUpdate = vi.fn(async () => {
  1547. if (scenario === "rejected check")
  1548. throw new Error("registry unavailable");
  1549. if (scenario === "unsupported result") return undefined;
  1550. return { latestVersion: " " };
  1551. });
  1552. const app = createTuiApp({
  1553. runtime: createRuntime(),
  1554. terminal,
  1555. version: "1.2.3",
  1556. workspaceDir: "/workspace",
  1557. checkForUpdate,
  1558. });
  1559. app.start();
  1560. await app.ready;
  1561. await vi.waitFor(() => expect(checkForUpdate).toHaveBeenCalledOnce());
  1562. await app.stop();
  1563. expect(terminal.writes.join("")).not.toContain(
  1564. "A new version of MCode is available",
  1565. );
  1566. expect(
  1567. app.transcript.snapshot().filter((cell) => cell.kind === "error"),
  1568. ).toEqual([]);
  1569. },
  1570. );
  1571. it("routes /update through the in-process update confirmation flow", async () => {
  1572. const plan = {
  1573. kind: "available" as const,
  1574. source: "managed-installer" as const,
  1575. currentVersion: "1.2.3",
  1576. latestVersion: "1.2.4",
  1577. channel: "stable" as const,
  1578. };
  1579. const inspectUpdate = vi.fn(async () => plan);
  1580. const applyUpdate = vi.fn(async () => ({
  1581. applied: true,
  1582. message:
  1583. "MCode 1.2.4 is installed. Restart running MCode sessions to use it.",
  1584. }));
  1585. const app = createTuiApp({
  1586. runtime: createRuntime(),
  1587. terminal: new FakeTerminal(),
  1588. version: "1.2.3",
  1589. workspaceDir: "/workspace",
  1590. inspectUpdate,
  1591. applyUpdate,
  1592. });
  1593. await app.ready;
  1594. await app.submit("/update");
  1595. expect(inspectUpdate).toHaveBeenCalledOnce();
  1596. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  1597. "MCode update",
  1598. );
  1599. app.interaction.current()?.handleInput?.("\r");
  1600. await vi.waitFor(() =>
  1601. expect(applyUpdate).toHaveBeenCalledWith(
  1602. plan,
  1603. expect.objectContaining({
  1604. onOutput: expect.any(Function),
  1605. }),
  1606. ),
  1607. );
  1608. await vi.waitFor(() =>
  1609. expect(
  1610. app.transcript
  1611. .snapshot()
  1612. .some((cell) => cell.content.includes("MCode update completed")),
  1613. ).toBe(true),
  1614. );
  1615. await app.stop();
  1616. });
  1617. it("leaves the current TUI after /update stages an npm-prefix replacement", async () => {
  1618. const plan = {
  1619. kind: "package-manager" as const,
  1620. source: "npm-prefix" as const,
  1621. currentVersion: "1.2.3",
  1622. latestVersion: "1.2.4",
  1623. packageTag: "latest" as const,
  1624. command: {
  1625. executable: "npm",
  1626. args: ["install"],
  1627. display: "npm install",
  1628. },
  1629. };
  1630. const requestRestart = vi.fn();
  1631. const app = createTuiApp({
  1632. runtime: createRuntime(),
  1633. terminal: new FakeTerminal(),
  1634. version: "1.2.3",
  1635. workspaceDir: "/workspace",
  1636. inspectUpdate: async () => plan,
  1637. applyUpdate: async () => ({
  1638. applied: true,
  1639. restartRequired: true,
  1640. message: "MCode 1.2.4 is staged safely.",
  1641. }),
  1642. requestRestart,
  1643. });
  1644. app.start();
  1645. await app.ready;
  1646. await app.submit("/update");
  1647. app.interaction.current()?.handleInput?.("\r");
  1648. await vi.waitFor(() => expect(requestRestart).toHaveBeenCalledOnce());
  1649. await app.stopped;
  1650. });
  1651. it("rechecks local and Runtime work before applying an update", async () => {
  1652. const runtime = createRuntime();
  1653. const applyUpdate = vi.fn(async () => ({
  1654. applied: true,
  1655. message: "updated",
  1656. }));
  1657. const app = createTuiApp({
  1658. runtime,
  1659. terminal: new FakeTerminal(),
  1660. version: "1.2.3",
  1661. workspaceDir: "/workspace",
  1662. inspectUpdate: async () => ({
  1663. kind: "available",
  1664. source: "managed-installer",
  1665. currentVersion: "1.2.3",
  1666. latestVersion: "1.2.4",
  1667. channel: "stable",
  1668. }),
  1669. applyUpdate,
  1670. });
  1671. await app.ready;
  1672. await app.openSession("session-1");
  1673. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  1674. schemaVersion: 1,
  1675. sessionId: "session-1",
  1676. state: "running",
  1677. turnId: "turn-active",
  1678. actions: { steer: true },
  1679. });
  1680. await app.submit("/update");
  1681. app.interaction.current()?.handleInput?.("\r");
  1682. await vi.waitFor(() =>
  1683. expect(
  1684. app.transcript
  1685. .snapshot()
  1686. .some((cell) =>
  1687. cell.content.includes(
  1688. "MCode update failed: Finish or stop the active response before updating.",
  1689. ),
  1690. ),
  1691. ).toBe(true),
  1692. );
  1693. expect(applyUpdate).not.toHaveBeenCalled();
  1694. await app.stop();
  1695. });
  1696. it("fails the update gate closed when Runtime state cannot be verified", async () => {
  1697. const runtime = createRuntime();
  1698. const applyUpdate = vi.fn(async () => ({
  1699. applied: true,
  1700. message: "updated",
  1701. }));
  1702. const app = createTuiApp({
  1703. runtime,
  1704. terminal: new FakeTerminal(),
  1705. version: "1.2.3",
  1706. workspaceDir: "/workspace",
  1707. inspectUpdate: async () => ({
  1708. kind: "available",
  1709. source: "managed-installer",
  1710. currentVersion: "1.2.3",
  1711. latestVersion: "1.2.4",
  1712. channel: "stable",
  1713. }),
  1714. applyUpdate,
  1715. });
  1716. await app.ready;
  1717. await app.openSession("session-1");
  1718. vi.mocked(runtime.getActiveRun).mockRejectedValue(
  1719. new Error("Runtime unavailable"),
  1720. );
  1721. await app.submit("/update");
  1722. app.interaction.current()?.handleInput?.("\r");
  1723. await vi.waitFor(() =>
  1724. expect(
  1725. app.transcript
  1726. .snapshot()
  1727. .some((cell) =>
  1728. cell.content.includes("Unable to verify that this Session is idle"),
  1729. ),
  1730. ).toBe(true),
  1731. );
  1732. expect(applyUpdate).not.toHaveBeenCalled();
  1733. await app.stop();
  1734. });
  1735. it("does not expose the TUI before base hydration has settled", async () => {
  1736. const terminal = new FakeTerminal();
  1737. const runtime = createRuntime();
  1738. let releaseSessions: (() => void) | undefined;
  1739. vi.mocked(runtime.listSessions).mockImplementation(
  1740. async () =>
  1741. await new Promise((resolve) => {
  1742. releaseSessions = () => resolve([]);
  1743. }),
  1744. );
  1745. const app = createTuiApp({
  1746. runtime,
  1747. terminal,
  1748. version: "0.1.0",
  1749. workspaceDir: "/workspace",
  1750. });
  1751. let settled = false;
  1752. void app.ready.then(() => {
  1753. settled = true;
  1754. });
  1755. await Promise.resolve();
  1756. expect(settled).toBe(false);
  1757. releaseSessions?.();
  1758. await app.ready;
  1759. app.start();
  1760. const rendered = app.tui.render(80).join("\n");
  1761. expect(rendered).not.toContain("Starting MiniMax Code");
  1762. expect(rendered).not.toContain("Loading session");
  1763. await app.stop();
  1764. });
  1765. it("renders server startup in the welcome composer header until hydration settles", async () => {
  1766. const runtime = createRuntime();
  1767. let releaseSessions: (() => void) | undefined;
  1768. vi.mocked(runtime.listSessions).mockImplementation(
  1769. async () =>
  1770. await new Promise((resolve) => {
  1771. releaseSessions = () => resolve([]);
  1772. }),
  1773. );
  1774. const app = createTuiApp({
  1775. runtime,
  1776. terminal: new FakeTerminal(),
  1777. version: "0.1.0",
  1778. workspaceDir: "/workspace",
  1779. });
  1780. try {
  1781. app.setStartupStatus("⠋ Starting server...");
  1782. app.start();
  1783. const starting = app.tui.render(80).join("\n");
  1784. expect(starting).toContain("⠋ Starting server...");
  1785. expect(starting).not.toContain("Start · @ file · / autocomplete");
  1786. expect(starting).not.toContain("Loading session");
  1787. releaseSessions?.();
  1788. await app.ready;
  1789. app.setStartupStatus(undefined);
  1790. expect(app.tui.render(80).join("\n")).toContain(
  1791. "Start · @ file · / autocomplete",
  1792. );
  1793. } finally {
  1794. releaseSessions?.();
  1795. await app.stop();
  1796. }
  1797. });
  1798. it("waits for account hydration before allowing the first message", async () => {
  1799. const runtime = createRuntime();
  1800. let resolveAccount!: (
  1801. account: Awaited<ReturnType<typeof runtime.getAccountStatus>>,
  1802. ) => void;
  1803. vi.mocked(runtime.getAccountStatus).mockReturnValue(
  1804. new Promise((resolve) => {
  1805. resolveAccount = resolve;
  1806. }),
  1807. );
  1808. const app = createTuiApp({
  1809. runtime,
  1810. terminal: new FakeTerminal(),
  1811. version: "0.1.0",
  1812. workspaceDir: "/workspace",
  1813. });
  1814. try {
  1815. const readiness = await Promise.race([
  1816. app.ready.then(() => "ready" as const),
  1817. new Promise<"blocked">((resolve) =>
  1818. setTimeout(() => resolve("blocked"), 100),
  1819. ),
  1820. ]);
  1821. expect(readiness).toBe("blocked");
  1822. expect(runtime.createSession).not.toHaveBeenCalled();
  1823. resolveAccount({
  1824. status: "ready",
  1825. defaultModel: "minimax/MiniMax-M2.7",
  1826. managedTokenPresent: true,
  1827. warnings: [],
  1828. });
  1829. await app.ready;
  1830. const submission = app.submit("Send after account hydration");
  1831. await submission;
  1832. expect(runtime.createSession).toHaveBeenCalledWith({
  1833. workspaceDir: "/workspace",
  1834. });
  1835. expect(app.transcript.snapshot()).toEqual(
  1836. expect.arrayContaining([
  1837. expect.objectContaining({
  1838. kind: "user",
  1839. content: "Send after account hydration",
  1840. }),
  1841. expect.objectContaining({
  1842. kind: "assistant",
  1843. content: "Hello from the Agent",
  1844. }),
  1845. ]),
  1846. );
  1847. } finally {
  1848. resolveAccount({
  1849. status: "ready",
  1850. defaultModel: "minimax/MiniMax-M2.7",
  1851. managedTokenPresent: true,
  1852. warnings: [],
  1853. });
  1854. await app.ready;
  1855. await app.stop();
  1856. }
  1857. });
  1858. it("does not wait for Token Plan membership hydration before App readiness", async () => {
  1859. const runtime = createRuntime();
  1860. const baseAccount = {
  1861. status: "ready" as const,
  1862. defaultModel: "minimax/MiniMax-M2.7",
  1863. providerId: "minimax",
  1864. modelId: "MiniMax-M2.7",
  1865. authMode: "managed-login",
  1866. managedTokenPresent: true,
  1867. modelSource: "token-plan" as const,
  1868. warnings: [],
  1869. };
  1870. const hydratedAccount = {
  1871. ...baseAccount,
  1872. tokenPlanQuotaState: "available" as const,
  1873. tokenPlanQuota: {
  1874. fiveHour: { remainingPercent: 90, unlimited: false },
  1875. weekly: { remainingPercent: 80, unlimited: false },
  1876. },
  1877. };
  1878. let resolveMembership!: (account: typeof hydratedAccount) => void;
  1879. vi.mocked(runtime.getAccountStatus).mockImplementation(
  1880. async (_sessionId, options) => {
  1881. if (options?.includeMembership === true) {
  1882. return await new Promise((resolve) => {
  1883. resolveMembership = resolve;
  1884. });
  1885. }
  1886. return baseAccount;
  1887. },
  1888. );
  1889. const app = createTuiApp({
  1890. runtime,
  1891. terminal: new FakeTerminal(),
  1892. version: "0.1.0",
  1893. workspaceDir: "/workspace",
  1894. });
  1895. try {
  1896. await app.ready;
  1897. expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
  1898. includeMembership: false,
  1899. });
  1900. expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
  1901. includeMembership: true,
  1902. });
  1903. expect(app.controller.snapshot().account).toMatchObject(baseAccount);
  1904. resolveMembership(hydratedAccount);
  1905. await vi.waitFor(() =>
  1906. expect(app.controller.snapshot().account).toMatchObject({
  1907. tokenPlanQuotaState: "available",
  1908. }),
  1909. );
  1910. } finally {
  1911. resolveMembership(hydratedAccount);
  1912. await app.stop();
  1913. }
  1914. });
  1915. it("waits for permission mode hydration before reporting App readiness", async () => {
  1916. const runtime = createRuntime();
  1917. let resolvePermissionMode!: (mode: "auto") => void;
  1918. vi.mocked(runtime.getPermissionMode).mockReturnValue(
  1919. new Promise((resolve) => {
  1920. resolvePermissionMode = resolve;
  1921. }),
  1922. );
  1923. const app = createTuiApp({
  1924. runtime,
  1925. terminal: new FakeTerminal(),
  1926. version: "0.1.0",
  1927. workspaceDir: "/workspace",
  1928. });
  1929. const readiness = Promise.race([
  1930. app.ready.then(() => "ready" as const),
  1931. new Promise<"blocked">((resolve) =>
  1932. setTimeout(() => resolve("blocked"), 100),
  1933. ),
  1934. ]);
  1935. await expect(readiness).resolves.toBe("blocked");
  1936. resolvePermissionMode("auto");
  1937. await app.ready;
  1938. await app.stop();
  1939. });
  1940. it("accepts modeled account and optional permission degradation at the ready boundary", async () => {
  1941. const runtime = createRuntime();
  1942. vi.mocked(runtime.getAccountStatus).mockRejectedValue(
  1943. new Error("account offline"),
  1944. );
  1945. vi.mocked(runtime.getPermissionMode).mockRejectedValue(
  1946. new Error("config unavailable"),
  1947. );
  1948. const app = createTuiApp({
  1949. runtime,
  1950. terminal: new FakeTerminal(),
  1951. version: "0.1.0",
  1952. workspaceDir: "/workspace",
  1953. });
  1954. await expect(app.ready).resolves.toBeUndefined();
  1955. expect(app.controller.snapshot().account).toEqual({
  1956. status: "unknown",
  1957. warnings: [],
  1958. });
  1959. await app.stop();
  1960. });
  1961. it("hydrates the selected model display name into the status rail on startup", async () => {
  1962. const terminal = new FakeTerminal();
  1963. const runtime = createRuntime();
  1964. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  1965. status: "ready",
  1966. defaultModel: "custom_provider:innerTest/MiniMax-M3",
  1967. providerId: "custom_provider:innerTest",
  1968. modelId: "MiniMax-M3",
  1969. authMode: "byok",
  1970. managedTokenPresent: true,
  1971. warnings: [],
  1972. });
  1973. vi.mocked(runtime.listModels).mockResolvedValue([
  1974. {
  1975. providerId: "custom_provider:innerTest",
  1976. modelId: "MiniMax-M3",
  1977. displayName: "m3.05",
  1978. selected: true,
  1979. },
  1980. ]);
  1981. const app = createTuiApp({
  1982. runtime,
  1983. terminal,
  1984. version: "0.1.0",
  1985. workspaceDir: "/workspace",
  1986. });
  1987. app.start();
  1988. await app.ready;
  1989. await vi.waitFor(() =>
  1990. expect(app.tui.render(120).join("\n")).toContain("✦ m3.05"),
  1991. );
  1992. await app.stop();
  1993. });
  1994. it("restores a managed-login failure to the Composer", async () => {
  1995. const terminal = new FakeTerminal();
  1996. const runtime = createRuntime();
  1997. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  1998. status: "ready",
  1999. defaultModel: "minimax/MiniMax-M2.7",
  2000. authMode: "managed-login",
  2001. modelSource: "token-plan",
  2002. managedTokenPresent: false,
  2003. warnings: [],
  2004. });
  2005. const app = createTuiApp({
  2006. runtime,
  2007. terminal,
  2008. version: "0.1.0",
  2009. workspaceDir: "/workspace",
  2010. });
  2011. app.start();
  2012. await app.ready;
  2013. await vi.waitFor(() =>
  2014. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login"),
  2015. );
  2016. terminal.input?.("Keep this until login");
  2017. terminal.input?.("\r");
  2018. await vi.waitFor(() =>
  2019. expect(app.editor.getText()).toBe("Keep this until login"),
  2020. );
  2021. expect(app.tui.render(80).join("\n")).toContain("Keep this until login");
  2022. expect(app.transcript.snapshot()).toEqual(
  2023. expect.arrayContaining([
  2024. expect.objectContaining({
  2025. kind: "warning",
  2026. content:
  2027. "Sign in to MiniMax to use Agent features. Run /login, then retry.",
  2028. }),
  2029. ]),
  2030. );
  2031. expect(runtime.createSession).not.toHaveBeenCalled();
  2032. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2033. await app.stop();
  2034. });
  2035. it("renders an Enter submission before the asynchronous login preflight settles", async () => {
  2036. const terminal = new FakeTerminal();
  2037. const runtime = createRuntime();
  2038. const app = createTuiApp({
  2039. runtime,
  2040. terminal,
  2041. version: "0.1.0",
  2042. workspaceDir: "/workspace",
  2043. });
  2044. app.start();
  2045. await app.ready;
  2046. let resolveAccount:
  2047. | ((
  2048. account: Awaited<ReturnType<typeof runtime.getAccountStatus>>,
  2049. ) => void)
  2050. | undefined;
  2051. vi.mocked(runtime.getAccountStatus).mockImplementationOnce(
  2052. () =>
  2053. new Promise((resolve) => {
  2054. resolveAccount = resolve;
  2055. }),
  2056. );
  2057. const writesBeforeSubmission = terminal.writes.length;
  2058. terminal.input?.("Show this immediately");
  2059. terminal.input?.("\r");
  2060. expect(app.editor.getText()).toBe("");
  2061. expect(
  2062. app.transcript.snapshot().filter((cell) => cell.kind === "user"),
  2063. ).toEqual([
  2064. expect.objectContaining({
  2065. status: "pending",
  2066. content: "Show this immediately",
  2067. }),
  2068. ]);
  2069. await vi.waitFor(() =>
  2070. expect(terminal.writes.length).toBeGreaterThan(writesBeforeSubmission),
  2071. );
  2072. expect(runtime.createSession).not.toHaveBeenCalled();
  2073. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2074. await vi.waitFor(() => expect(resolveAccount).toBeTypeOf("function"));
  2075. resolveAccount?.({
  2076. status: "ready",
  2077. defaultModel: "minimax/MiniMax-M2.7",
  2078. providerId: "minimax",
  2079. modelId: "MiniMax-M2.7",
  2080. authMode: "managed-login",
  2081. managedTokenPresent: true,
  2082. warnings: [],
  2083. });
  2084. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  2085. await app.stop();
  2086. });
  2087. it("keeps a login-blocked submission editable after current-region sign-in", async () => {
  2088. const terminal = new FakeTerminal();
  2089. const runtime = createRuntime();
  2090. let authenticated = false;
  2091. vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
  2092. authenticated
  2093. ? {
  2094. status: "ready",
  2095. defaultModel: "minimax/MiniMax-M2.7",
  2096. providerId: "minimax",
  2097. modelId: "MiniMax-M2.7",
  2098. authMode: "managed-login",
  2099. modelSource: "token-plan",
  2100. managedTokenPresent: true,
  2101. warnings: [],
  2102. }
  2103. : {
  2104. status: "needs-login",
  2105. authMode: "managed-login",
  2106. modelSource: "token-plan",
  2107. managedTokenPresent: false,
  2108. warnings: [],
  2109. },
  2110. );
  2111. const auth = {
  2112. login: vi.fn(async () => {
  2113. authenticated = true;
  2114. return {
  2115. state: "authenticated" as const,
  2116. message: "Signed in with MiniMax.",
  2117. };
  2118. }),
  2119. logout: vi.fn(async () => ({
  2120. state: "signed-out" as const,
  2121. message: "Signed out of MiniMax.",
  2122. })),
  2123. };
  2124. const app = createTuiApp({
  2125. runtime,
  2126. auth,
  2127. terminal,
  2128. version: "0.1.0",
  2129. workspaceDir: "/workspace",
  2130. });
  2131. app.start();
  2132. await app.ready;
  2133. terminal.input?.("Send this after login");
  2134. terminal.input?.("\r");
  2135. await vi.waitFor(() =>
  2136. expect(app.editor.getText()).toBe("Send this after login"),
  2137. );
  2138. await app.submit("/login");
  2139. app.interaction.current()?.handleInput("\r");
  2140. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2141. app.editor.handleInput("\r");
  2142. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  2143. expect(runtime.sendMessage).toHaveBeenCalledWith(
  2144. expect.objectContaining({
  2145. id: "session-1",
  2146. content: "Send this after login",
  2147. turnId: expect.any(String),
  2148. }),
  2149. expect.any(AbortSignal),
  2150. );
  2151. expect(app.transcript.snapshot()).toEqual(
  2152. expect.arrayContaining([
  2153. expect.objectContaining({
  2154. kind: "user",
  2155. content: "Send this after login",
  2156. }),
  2157. ]),
  2158. );
  2159. await app.stop();
  2160. });
  2161. it("runs /checkin immediately for a signed-in MiniMax account", async () => {
  2162. const runtime = createRuntime();
  2163. const app = createTuiApp({
  2164. runtime,
  2165. terminal: new FakeTerminal(),
  2166. version: "0.1.0",
  2167. workspaceDir: "/workspace",
  2168. });
  2169. app.start();
  2170. await app.ready;
  2171. await app.submit("/checkin");
  2172. expect(runtime.runDailyCheckin).toHaveBeenCalledOnce();
  2173. expect(app.transcript.snapshot()).toEqual(
  2174. expect.arrayContaining([
  2175. expect.objectContaining({
  2176. kind: "final-summary",
  2177. content: expect.stringContaining(
  2178. "Checked in: Cycle day 2, +20 Credits",
  2179. ),
  2180. }),
  2181. ]),
  2182. );
  2183. await app.stop();
  2184. });
  2185. it("shows a generic /checkin failure without backend details", async () => {
  2186. const runtime = createRuntime();
  2187. vi.mocked(runtime.runDailyCheckin).mockRejectedValue(
  2188. new Error("internal signin shard rejected request"),
  2189. );
  2190. const app = createTuiApp({
  2191. runtime,
  2192. terminal: new FakeTerminal(),
  2193. version: "0.1.0",
  2194. workspaceDir: "/workspace",
  2195. });
  2196. app.start();
  2197. await app.ready;
  2198. await app.submit("/checkin");
  2199. const transcript = app.transcript
  2200. .snapshot()
  2201. .map((cell) => cell.content)
  2202. .join("\n");
  2203. expect(transcript).toContain("Couldn't complete daily check-in.");
  2204. expect(transcript).not.toContain("internal signin shard");
  2205. await app.stop();
  2206. });
  2207. it("does not open login when /checkin cannot verify account status", async () => {
  2208. const runtime = createRuntime();
  2209. const auth = {
  2210. login: vi.fn(),
  2211. logout: vi.fn(async () => ({
  2212. state: "signed-out" as const,
  2213. message: "Signed out of MiniMax.",
  2214. })),
  2215. };
  2216. const app = createTuiApp({
  2217. runtime,
  2218. auth,
  2219. terminal: new FakeTerminal(),
  2220. version: "0.1.0",
  2221. workspaceDir: "/workspace",
  2222. });
  2223. app.start();
  2224. await app.ready;
  2225. vi.mocked(runtime.getAccountStatus).mockRejectedValue(
  2226. new Error("status unavailable"),
  2227. );
  2228. await app.submit("/checkin");
  2229. expect(app.interaction.current()).toBeUndefined();
  2230. expect(auth.login).not.toHaveBeenCalled();
  2231. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2232. await app.stop();
  2233. });
  2234. it("starts MiniMax login and resumes /checkin once after authentication", async () => {
  2235. const runtime = createRuntime();
  2236. let authenticated = false;
  2237. vi.mocked(runtime.getAccountStatus).mockImplementation(async () => ({
  2238. status: authenticated ? "ready" : "needs-login",
  2239. authMode: "managed-login",
  2240. modelSource: "byok",
  2241. managedTokenPresent: authenticated,
  2242. warnings: [],
  2243. }));
  2244. const auth = {
  2245. login: vi.fn(async () => {
  2246. authenticated = true;
  2247. return {
  2248. state: "authenticated" as const,
  2249. message: "Signed in with MiniMax.",
  2250. };
  2251. }),
  2252. logout: vi.fn(async () => ({
  2253. state: "signed-out" as const,
  2254. message: "Signed out of MiniMax.",
  2255. })),
  2256. };
  2257. const app = createTuiApp({
  2258. runtime,
  2259. auth,
  2260. terminal: new FakeTerminal(),
  2261. version: "0.1.0",
  2262. workspaceDir: "/workspace",
  2263. });
  2264. app.start();
  2265. await app.ready;
  2266. await app.submit("/checkin");
  2267. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2268. app.interaction.current()?.handleInput("\r");
  2269. await vi.waitFor(() =>
  2270. expect(runtime.runDailyCheckin).toHaveBeenCalledOnce(),
  2271. );
  2272. expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "cn");
  2273. await app.stop();
  2274. });
  2275. it("does not resume /checkin when the login picker is cancelled", async () => {
  2276. const runtime = createRuntime();
  2277. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2278. status: "needs-login",
  2279. authMode: "managed-login",
  2280. modelSource: "byok",
  2281. managedTokenPresent: false,
  2282. warnings: [],
  2283. });
  2284. const auth = {
  2285. login: vi.fn(),
  2286. logout: vi.fn(async () => ({
  2287. state: "signed-out" as const,
  2288. message: "Signed out of MiniMax.",
  2289. })),
  2290. };
  2291. const app = createTuiApp({
  2292. runtime,
  2293. auth,
  2294. terminal: new FakeTerminal(),
  2295. version: "0.1.0",
  2296. workspaceDir: "/workspace",
  2297. });
  2298. app.start();
  2299. await app.ready;
  2300. await app.submit("/checkin");
  2301. app.interaction.current()?.handleInput("\u001b");
  2302. expect(auth.login).not.toHaveBeenCalled();
  2303. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2304. await app.stop();
  2305. });
  2306. it("does not resume /checkin when browser login fails", async () => {
  2307. const runtime = createRuntime();
  2308. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2309. status: "needs-login",
  2310. managedTokenPresent: false,
  2311. warnings: [],
  2312. });
  2313. const auth = {
  2314. login: vi.fn(async () => {
  2315. throw new Error("browser login failed");
  2316. }),
  2317. logout: vi.fn(async () => ({
  2318. state: "signed-out" as const,
  2319. message: "Signed out of MiniMax.",
  2320. })),
  2321. };
  2322. const app = createTuiApp({
  2323. runtime,
  2324. auth,
  2325. terminal: new FakeTerminal(),
  2326. version: "0.1.0",
  2327. workspaceDir: "/workspace",
  2328. });
  2329. app.start();
  2330. await app.ready;
  2331. await app.submit("/checkin");
  2332. app.interaction.current()?.handleInput("\r");
  2333. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  2334. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2335. await app.stop();
  2336. });
  2337. it("carries /checkin through a cross-region login restart", async () => {
  2338. const runtime = createRuntime();
  2339. const requestRestart = vi.fn();
  2340. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2341. status: "needs-login",
  2342. managedTokenPresent: false,
  2343. warnings: [],
  2344. });
  2345. const auth = {
  2346. login: vi.fn(async () => ({
  2347. state: "authenticated" as const,
  2348. restartRequired: true,
  2349. message: "Signed in with MiniMax Global.",
  2350. })),
  2351. logout: vi.fn(async () => ({
  2352. state: "signed-out" as const,
  2353. message: "Signed out of MiniMax.",
  2354. })),
  2355. };
  2356. const app = createTuiApp({
  2357. runtime,
  2358. auth,
  2359. terminal: new FakeTerminal(),
  2360. version: "0.1.0",
  2361. workspaceDir: "/workspace",
  2362. requestRestart,
  2363. });
  2364. app.start();
  2365. await app.ready;
  2366. await app.submit("/checkin");
  2367. app.interaction.current()?.handleInput("\u001b[B");
  2368. app.interaction.current()?.handleInput("\r");
  2369. await vi.waitFor(() =>
  2370. expect(requestRestart).toHaveBeenCalledWith("en", "/checkin"),
  2371. );
  2372. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2373. await app.stopped;
  2374. });
  2375. it("restarts after cross-region login while keeping the blocked submission", async () => {
  2376. const terminal = new FakeTerminal();
  2377. const runtime = createRuntime();
  2378. const requestRestart = vi.fn();
  2379. const notifyAuthContextChanged = vi.fn(async () => undefined);
  2380. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2381. status: "needs-login",
  2382. authMode: "managed-login",
  2383. modelSource: "token-plan",
  2384. managedTokenPresent: false,
  2385. warnings: [],
  2386. });
  2387. const auth = {
  2388. login: vi.fn(async () => ({
  2389. state: "authenticated" as const,
  2390. restartRequired: true,
  2391. message: "Signed in with MiniMax Global.",
  2392. })),
  2393. logout: vi.fn(async () => ({
  2394. state: "signed-out" as const,
  2395. message: "Signed out of MiniMax.",
  2396. })),
  2397. };
  2398. const app = createTuiApp({
  2399. runtime,
  2400. auth,
  2401. terminal,
  2402. version: "0.1.0",
  2403. workspaceDir: "/workspace",
  2404. requestRestart,
  2405. notifyAuthContextChanged,
  2406. });
  2407. app.start();
  2408. await app.ready;
  2409. terminal.input?.("Keep this through restart");
  2410. terminal.input?.("\r");
  2411. await vi.waitFor(() =>
  2412. expect(app.editor.getText()).toBe("Keep this through restart"),
  2413. );
  2414. await app.submit("/login");
  2415. app.interaction.current()?.handleInput("\u001b[B");
  2416. app.interaction.current()?.handleInput("\r");
  2417. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  2418. expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "en");
  2419. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2420. await vi.waitFor(() => expect(requestRestart).toHaveBeenCalledOnce());
  2421. expect(requestRestart).toHaveBeenCalledWith("en");
  2422. expect(notifyAuthContextChanged).not.toHaveBeenCalled();
  2423. await app.stopped;
  2424. expect(app.editor.getText()).toBe("Keep this through restart");
  2425. });
  2426. it("offers MiniMax login without blocking an unauthenticated builtin BYOK Turn", async () => {
  2427. const runtime = createRuntime();
  2428. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2429. status: "ready",
  2430. defaultModel: "minimax/MiniMax-M3",
  2431. providerId: "minimax",
  2432. authMode: "managed-login",
  2433. modelSource: "byok",
  2434. managedTokenPresent: false,
  2435. warnings: [],
  2436. });
  2437. const app = createTuiApp({
  2438. runtime,
  2439. terminal: new FakeTerminal(),
  2440. version: "0.1.0",
  2441. workspaceDir: "/workspace",
  2442. });
  2443. app.start();
  2444. await app.ready;
  2445. await vi.waitFor(() =>
  2446. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login"),
  2447. );
  2448. await app.submit("BYOK still runs");
  2449. expect(runtime.createSession).toHaveBeenCalledWith({
  2450. workspaceDir: "/workspace",
  2451. });
  2452. expect(app.transcript.snapshot()).toEqual(
  2453. expect.arrayContaining([
  2454. expect.objectContaining({ kind: "user", content: "BYOK still runs" }),
  2455. expect.objectContaining({
  2456. kind: "assistant",
  2457. content: "Hello from the Agent",
  2458. }),
  2459. ]),
  2460. );
  2461. await app.stop();
  2462. });
  2463. it("starts a terminal-native workbench and submits messages through the Agent runtime", async () => {
  2464. const terminal = new FakeTerminal();
  2465. const runtime = createRuntime();
  2466. const app = createTuiApp({
  2467. runtime,
  2468. terminal,
  2469. version: "0.1.0",
  2470. workspaceDir: "/workspace",
  2471. homeDir: "/home/dev",
  2472. });
  2473. app.start();
  2474. await app.ready;
  2475. expect(app.getSurface()).toBe("welcome");
  2476. await app.submit("Say hello");
  2477. expect(app.getSurface()).toBe("conversation");
  2478. const conversation = app.tui.render(80).join("\n");
  2479. expect(conversation).toContain("Tips for getting started");
  2480. expect(conversation).toContain("Say hello");
  2481. expect(conversation).toContain("Hello from the Agent");
  2482. expect(terminal.started).toBe(true);
  2483. expect(terminal.title).toBe("Minimax Code");
  2484. expect(runtime.createSession).toHaveBeenCalledWith({
  2485. workspaceDir: "/workspace",
  2486. });
  2487. expect(app.transcript.snapshot()).toEqual([
  2488. expect.objectContaining({ kind: "user", content: "Say hello" }),
  2489. expect.objectContaining({
  2490. kind: "assistant",
  2491. status: "succeeded",
  2492. content: "Hello from the Agent",
  2493. }),
  2494. expect.objectContaining({ kind: "turn-duration", status: "succeeded" }),
  2495. ]);
  2496. await app.stop();
  2497. expect(terminal.stopped).toBe(true);
  2498. });
  2499. it("syncs the generated Session title to the terminal without duplicate writes", async () => {
  2500. const terminal = new FakeTerminal();
  2501. const runtime = createRuntime();
  2502. let sessionTitle = "New session";
  2503. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  2504. vi.mocked(runtime.listSessions).mockImplementation(async () => [
  2505. {
  2506. sessionId: "session-1",
  2507. title: sessionTitle,
  2508. workspaceDir: "/workspace",
  2509. },
  2510. ]);
  2511. vi.mocked(runtime.watchEvents).mockImplementation(
  2512. async function* watchEvents(signal) {
  2513. const event = await new Promise<TuiRuntimeEvent | undefined>(
  2514. (resolve) => {
  2515. emitEvent = resolve;
  2516. signal.addEventListener("abort", () => resolve(undefined), {
  2517. once: true,
  2518. });
  2519. },
  2520. );
  2521. if (event) yield event;
  2522. await new Promise<void>((resolve) => {
  2523. signal.addEventListener("abort", resolve, { once: true });
  2524. });
  2525. },
  2526. );
  2527. const app = createTuiApp({
  2528. runtime,
  2529. terminal,
  2530. version: "0.1.0",
  2531. workspaceDir: "/workspace",
  2532. });
  2533. app.start();
  2534. await app.ready;
  2535. await app.submit("Review uncommitted work");
  2536. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  2537. sessionTitle = "Review uncommitted work";
  2538. emitEvent?.(
  2539. runtimeEvent({
  2540. type: "session.title_updated",
  2541. timestamp: Date.now(),
  2542. source: "runtime",
  2543. payload: {
  2544. sessionId: "session-1",
  2545. title: sessionTitle,
  2546. },
  2547. }),
  2548. );
  2549. await vi.waitFor(() => expect(terminal.title).toBe(sessionTitle));
  2550. await app.submit("/status");
  2551. expect(terminal.titleUpdates).toEqual(["Minimax Code", sessionTitle]);
  2552. await app.stop();
  2553. });
  2554. it("keeps chat state alive while a regular feature overlay owns the viewport", async () => {
  2555. const terminal = new FakeTerminal();
  2556. terminal.rows = 6;
  2557. const runtime = createRuntime();
  2558. const app = createTuiApp({
  2559. runtime,
  2560. terminal,
  2561. version: "0.1.0",
  2562. workspaceDir: "/workspace",
  2563. });
  2564. const featureInput = vi.fn();
  2565. const featureContent = {
  2566. render: () => ["feature-header", "feature-body"],
  2567. invalidate: () => undefined,
  2568. };
  2569. const feature = {
  2570. id: "sessions",
  2571. layoutRoot: new VStack([{ component: featureContent }]),
  2572. render: featureContent.render,
  2573. invalidate: () => undefined,
  2574. handleInput: featureInput,
  2575. };
  2576. app.start();
  2577. await app.ready;
  2578. const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
  2579. let writeIndex = 0;
  2580. const flushWrites = (): void => {
  2581. for (; writeIndex < terminal.writes.length; writeIndex += 1) {
  2582. screen.feed(terminal.writes[writeIndex] ?? "");
  2583. }
  2584. };
  2585. flushWrites();
  2586. app.editor.setText("preserved draft");
  2587. const handle = app.surfaceHost.pushFeature({ screen: feature });
  2588. app.tui.renderNow();
  2589. flushWrites();
  2590. expect(app.surfaceHost.getActiveSurface()).toEqual({
  2591. kind: "feature",
  2592. id: "sessions",
  2593. });
  2594. expect(app.surfaceHost.render(80).join("\n")).toContain("preserved draft");
  2595. expect(screen.viewportText()).toContain("feature-header");
  2596. expect(screen.viewportText()).toContain("feature-body");
  2597. expect(app.tui.mode).toBe("regular");
  2598. expect(terminal.startCount).toBe(1);
  2599. expect(terminal.stopCount).toBe(0);
  2600. terminal.input?.("j");
  2601. expect(featureInput).toHaveBeenCalledWith("j");
  2602. expect(handle.close()).toBe(true);
  2603. app.tui.renderNow();
  2604. flushWrites();
  2605. expect(app.surfaceHost.getActiveSurface()).toEqual({
  2606. kind: "chat",
  2607. id: "chat",
  2608. });
  2609. expect(app.editor.getText()).toBe("preserved draft");
  2610. expect(app.surfaceHost.render(80).join("\n")).toContain("preserved draft");
  2611. expect(screen.viewportText()).toContain("preserved draft");
  2612. expect(screen.viewportText()).not.toContain("feature-header");
  2613. await app.stop();
  2614. screen.dispose();
  2615. });
  2616. it("switches /settings through explicit choices and closes after applying", async () => {
  2617. const terminal = new FakeTerminal();
  2618. const persistTuiMode = vi.fn();
  2619. const app = createTuiApp({
  2620. runtime: createRuntime(),
  2621. terminal,
  2622. version: "0.2.0",
  2623. workspaceDir: "/workspace",
  2624. tuiMode: "regular",
  2625. persistTuiMode,
  2626. });
  2627. app.start();
  2628. await app.ready;
  2629. expect(app.surfaceHost.getChatMode()).toBe("regular");
  2630. expect(app.tui.mode).toBe("regular");
  2631. await app.submit("/settings");
  2632. const fullscreenSettings = app.interaction.current();
  2633. expect(app.tui.getFocusedComponent()).toBe(fullscreenSettings);
  2634. expect(app.surfaceHost.render(80).join("\n")).toContain(
  2635. "TUI mode · Regular",
  2636. );
  2637. terminal.input?.("\u001b[B");
  2638. terminal.input?.("\r");
  2639. expect(app.surfaceHost.getChatMode()).toBe("fullscreen");
  2640. expect(app.tui.mode).toBe("fullscreen");
  2641. expect(app.interaction.isActive()).toBe(false);
  2642. expect(app.tui.getFocusedComponent()).toBe(app.editor);
  2643. expect(persistTuiMode).toHaveBeenLastCalledWith("fullscreen");
  2644. expect(app.editor.focused).toBe(true);
  2645. terminal.input?.("/");
  2646. await vi.waitFor(() =>
  2647. expect(app.editor.render(60).join("\n")).toContain(
  2648. "Show available commands",
  2649. ),
  2650. );
  2651. terminal.input?.("\u001b");
  2652. app.editor.setText("");
  2653. await app.submit("/settings");
  2654. const regularSettings = app.interaction.current();
  2655. expect(app.tui.getFocusedComponent()).toBe(regularSettings);
  2656. expect(app.surfaceHost.render(80).join("\n")).toContain(
  2657. "TUI mode · Fullscreen",
  2658. );
  2659. terminal.input?.("\u001b[A");
  2660. terminal.input?.("\r");
  2661. expect(app.surfaceHost.getChatMode()).toBe("regular");
  2662. expect(app.tui.mode).toBe("regular");
  2663. expect(app.interaction.isActive()).toBe(false);
  2664. expect(app.tui.getFocusedComponent()).toBe(app.editor);
  2665. expect(persistTuiMode).toHaveBeenLastCalledWith("regular");
  2666. await app.stop();
  2667. });
  2668. it("keeps the Pi Editor and Slash Command autocomplete active in fullscreen chat", async () => {
  2669. const terminal = new FakeTerminal();
  2670. terminal.rows = 8;
  2671. const app = createTuiApp({
  2672. runtime: createRuntime(),
  2673. terminal,
  2674. version: "0.2.0",
  2675. workspaceDir: "/workspace",
  2676. tuiMode: "fullscreen",
  2677. });
  2678. app.start();
  2679. await app.ready;
  2680. terminal.input?.("/");
  2681. await vi.waitFor(() =>
  2682. expect(app.editor.render(60).join("\n")).toContain(
  2683. "Show available commands",
  2684. ),
  2685. );
  2686. expect(app.editor.getText()).toBe("/");
  2687. terminal.input?.("\u001B[B");
  2688. expect(app.editor.getText()).toBe("/");
  2689. terminal.input?.("\u001B");
  2690. expect(app.editor.getText()).toBe("/");
  2691. expect(app.editor.focused).toBe(true);
  2692. await app.stop();
  2693. });
  2694. it("renders regular-mode Slash Command autocomplete on the first keypress and every update", async () => {
  2695. const terminal = new FakeTerminal();
  2696. const app = createTuiApp({
  2697. runtime: createRuntime(),
  2698. terminal,
  2699. version: "0.2.0",
  2700. workspaceDir: "/workspace",
  2701. tuiMode: "regular",
  2702. });
  2703. app.start();
  2704. await app.ready;
  2705. const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
  2706. let writeIndex = 0;
  2707. const flushWrites = (): void => {
  2708. for (; writeIndex < terminal.writes.length; writeIndex += 1) {
  2709. screen.feed(terminal.writes[writeIndex] ?? "");
  2710. }
  2711. };
  2712. flushWrites();
  2713. terminal.input?.("/");
  2714. await vi.waitFor(() => {
  2715. flushWrites();
  2716. expect(screen.viewportText()).toContain("Show available commands");
  2717. });
  2718. expect(screen.viewportText()).toContain("/");
  2719. terminal.input?.("m");
  2720. await vi.waitFor(() => {
  2721. flushWrites();
  2722. expect(screen.viewportText()).toContain("Choose a model");
  2723. });
  2724. expect(screen.viewportText()).toContain("/m");
  2725. screen.dispose();
  2726. await app.stop();
  2727. });
  2728. it("resumes fullscreen tail following when submitting from scrolled history", async () => {
  2729. const terminal = new FakeTerminal();
  2730. terminal.rows = 6;
  2731. const app = createTuiApp({
  2732. runtime: createRuntime(),
  2733. terminal,
  2734. version: "0.2.0",
  2735. workspaceDir: "/workspace",
  2736. tuiMode: "fullscreen",
  2737. });
  2738. app.start();
  2739. await app.ready;
  2740. for (let index = 1; index <= 4; index += 1) {
  2741. await app.submit(`Prompt ${String(index)}`);
  2742. }
  2743. app.tui.renderNow();
  2744. terminal.input?.("\u001B[5~");
  2745. expect((app.tui as TuiAltScreen).isFollowingOutput).toBe(false);
  2746. await app.submit("Latest prompt");
  2747. expect((app.tui as TuiAltScreen).isFollowingOutput).toBe(true);
  2748. await app.stop();
  2749. });
  2750. it("stops the terminal without waiting for a stalled Desktop event stream", async () => {
  2751. const terminal = new FakeTerminal();
  2752. const runtime = createRuntime();
  2753. vi.mocked(runtime.watchEvents).mockImplementation(
  2754. async function* watchEvents() {
  2755. await new Promise<void>(() => undefined);
  2756. yield runtimeEvent({
  2757. type: "unreachable",
  2758. timestamp: 0,
  2759. source: "test",
  2760. payload: {},
  2761. });
  2762. },
  2763. );
  2764. const app = createTuiApp({
  2765. runtime,
  2766. terminal,
  2767. version: "0.1.0",
  2768. workspaceDir: "/workspace",
  2769. });
  2770. app.start();
  2771. await app.ready;
  2772. const stopping = app.stop();
  2773. await vi.waitFor(() => expect(terminal.stopped).toBe(true));
  2774. await stopping;
  2775. });
  2776. it("restores the terminal before a stalled remote turn abort finishes", async () => {
  2777. const terminal = new FakeTerminal();
  2778. const runtime = createRuntime();
  2779. let finishRemoteAbort: ((value: boolean) => void) | undefined;
  2780. vi.mocked(runtime.sendMessage).mockImplementation(
  2781. async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
  2782. await new Promise<void>((resolve) => {
  2783. signal?.addEventListener("abort", () => resolve(), { once: true });
  2784. });
  2785. yield { type: "done" };
  2786. },
  2787. );
  2788. vi.mocked(runtime.abortSession).mockImplementation(
  2789. async () =>
  2790. await new Promise<boolean>((resolve) => {
  2791. finishRemoteAbort = resolve;
  2792. }),
  2793. );
  2794. const app = createTuiApp({
  2795. runtime,
  2796. terminal,
  2797. version: "0.1.0",
  2798. workspaceDir: "/workspace",
  2799. });
  2800. app.start();
  2801. await app.ready;
  2802. const submitting = app.submit("Keep running");
  2803. await vi.waitFor(() =>
  2804. expect(app.controller.snapshot().status).toBe("running"),
  2805. );
  2806. const stopping = app.stop();
  2807. await vi.waitFor(() => expect(terminal.stopped).toBe(true));
  2808. finishRemoteAbort?.(true);
  2809. await Promise.all([submitting, stopping]);
  2810. });
  2811. it("stops the active turn before leaving the UI", async () => {
  2812. const terminal = new FakeTerminal();
  2813. const runtime = createRuntime();
  2814. let finishTurn: (() => void) | undefined;
  2815. vi.mocked(runtime.sendMessage).mockImplementation(
  2816. async function* sendMessage() {
  2817. yield {
  2818. type: "delta",
  2819. turnId: "turn-detached",
  2820. role: "assistant",
  2821. content: "Still running",
  2822. };
  2823. await new Promise<void>((resolve) => {
  2824. finishTurn = resolve;
  2825. });
  2826. yield { type: "done", turnId: "turn-detached" };
  2827. },
  2828. );
  2829. const app = createTuiApp({
  2830. runtime,
  2831. terminal,
  2832. version: "0.1.0",
  2833. workspaceDir: "/workspace",
  2834. });
  2835. app.start();
  2836. await app.ready;
  2837. const submitting = app.submit("Keep running after the UI leaves");
  2838. await vi.waitFor(() =>
  2839. expect(app.controller.snapshot().status).toBe("running"),
  2840. );
  2841. await app.leaveUi();
  2842. expect(terminal.stopped).toBe(true);
  2843. expect(runtime.abortSession).toHaveBeenCalledWith(
  2844. expect.objectContaining({ id: "session-1" }),
  2845. );
  2846. finishTurn?.();
  2847. await submitting;
  2848. });
  2849. it("resumes a launcher-selected Session and exposes its ID for the exit hint", async () => {
  2850. const terminal = new FakeTerminal();
  2851. const runtime = createRuntime();
  2852. const app = createTuiApp({
  2853. runtime,
  2854. terminal,
  2855. version: "0.1.0",
  2856. workspaceDir: "/workspace",
  2857. });
  2858. app.start();
  2859. await app.ready;
  2860. expect(app.controller.snapshot().session?.sessionId).toBeUndefined();
  2861. await app.openSession("session-existing");
  2862. expect(runtime.getSession).toHaveBeenCalledWith("session-existing");
  2863. expect(runtime.getMessages).toHaveBeenCalledWith("session-existing");
  2864. expect(app.controller.snapshot().session?.sessionId).toBe(
  2865. "session-existing",
  2866. );
  2867. await app.leaveUi();
  2868. });
  2869. it("reports a launcher continue hydration failure in the Transcript", async () => {
  2870. const terminal = new FakeTerminal();
  2871. const runtime = createRuntime();
  2872. vi.mocked(runtime.listSessions).mockResolvedValue([
  2873. {
  2874. sessionId: "session-existing",
  2875. title: "Existing session",
  2876. workspaceDir: "/workspace",
  2877. },
  2878. ]);
  2879. vi.mocked(runtime.getSession).mockRejectedValue(
  2880. new Error("Session hydration failed"),
  2881. );
  2882. const app = createTuiApp({
  2883. runtime,
  2884. terminal,
  2885. version: "0.1.0",
  2886. workspaceDir: "/workspace",
  2887. });
  2888. await app.ready;
  2889. await expect(app.continueLatestSession()).rejects.toThrow(
  2890. "Session hydration failed",
  2891. );
  2892. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  2893. kind: "error",
  2894. content:
  2895. "Couldn't continue the latest conversation: Session hydration failed. Retry after the connection recovers.",
  2896. });
  2897. await app.leaveUi();
  2898. });
  2899. it("can disable queue UI and preserve the next draft while a turn is running", async () => {
  2900. const terminal = new FakeTerminal();
  2901. const runtime = createRuntime();
  2902. let finishTool: (() => void) | undefined;
  2903. vi.mocked(runtime.sendMessage).mockImplementation(
  2904. async function* sendMessage() {
  2905. yield {
  2906. type: "delta",
  2907. turnId: "turn-running-tool",
  2908. toolCalls: [
  2909. {
  2910. id: "read-1",
  2911. name: "read",
  2912. status: "running",
  2913. input: { path: "src/cart/price.ts" },
  2914. },
  2915. ],
  2916. };
  2917. await new Promise<void>((resolve) => {
  2918. finishTool = resolve;
  2919. });
  2920. yield { type: "done", turnId: "turn-running-tool" };
  2921. },
  2922. );
  2923. const app = createTuiApp({
  2924. runtime,
  2925. terminal,
  2926. version: "0.1.0",
  2927. workspaceDir: "/workspace",
  2928. productFeatures: { queue: false },
  2929. });
  2930. await app.ready;
  2931. const submission = app.submit("Inspect the pricing logic");
  2932. await vi.waitFor(() => {
  2933. const rendered = app.tui.render(80).join("\n");
  2934. expect(rendered).toContain("Reading (src/cart/price.ts)");
  2935. expect(rendered).toContain("Running");
  2936. expect(rendered).not.toContain("Running · 0s");
  2937. expect(rendered).not.toContain("Running · Read");
  2938. expect(rendered).not.toContain("MCode · Running");
  2939. expect(rendered).toContain("Ctrl+O details");
  2940. expect(rendered).toContain("Esc stop");
  2941. expect(rendered).not.toContain("Enter run next");
  2942. expect(rendered).not.toContain("Message · Enter send");
  2943. expect(rendered).not.toContain("Follow-up");
  2944. expect(rendered).not.toContain("waiting");
  2945. });
  2946. await app.submit("Review the tests next");
  2947. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  2948. expect(app.editor.getText()).toBe("Review the tests next");
  2949. expect(app.tui.render(80).join("\n")).toContain("Esc to interrupt");
  2950. finishTool?.();
  2951. await submission;
  2952. });
  2953. it("refreshes the running queue hint from the same bindings as the hotkeys panel", async () => {
  2954. const keybindings = createTuiHostKeybindings({
  2955. platform: "linux",
  2956. suspendSupported: true,
  2957. });
  2958. const runtime = createRuntime();
  2959. let finishTurn: (() => void) | undefined;
  2960. vi.mocked(runtime.sendMessage).mockImplementation(
  2961. async function* sendMessage() {
  2962. yield {
  2963. type: "delta",
  2964. turnId: "turn-custom-queue",
  2965. thinking: "Inspecting the repository",
  2966. };
  2967. await new Promise<void>((resolve) => {
  2968. finishTurn = resolve;
  2969. });
  2970. yield { type: "done", turnId: "turn-custom-queue" };
  2971. },
  2972. );
  2973. const app = createTuiApp({
  2974. runtime,
  2975. terminal: new FakeTerminal(),
  2976. version: "0.1.0",
  2977. workspaceDir: "/workspace",
  2978. keybindings: keybindings.registry,
  2979. });
  2980. await app.ready;
  2981. keybindings.manager.setUserBindings({ "run.queue-draft": "ctrl+enter" });
  2982. const submission = app.submit("Inspect the repository");
  2983. try {
  2984. await vi.waitFor(() => {
  2985. const rendered = stripAnsi(app.tui.render(100).join("\n"));
  2986. expect(rendered).toContain("Running");
  2987. expect(rendered).toContain("Ctrl+Enter queue");
  2988. expect(rendered).not.toContain("Alt+Enter queue");
  2989. expect(
  2990. keybindings.registry
  2991. .helpRows()
  2992. .find((row) => row.ids.includes("run.queue-draft"))?.keys,
  2993. ).toBe("Ctrl+Enter");
  2994. });
  2995. } finally {
  2996. finishTurn?.();
  2997. await submission;
  2998. await app.stop();
  2999. }
  3000. });
  3001. it("shows running Thinking in chat and opens the full Transcript with /transcript", async () => {
  3002. const terminal = new FakeTerminal();
  3003. const runtime = createRuntime();
  3004. let finishThinking: (() => void) | undefined;
  3005. vi.mocked(runtime.sendMessage).mockImplementation(
  3006. async function* sendMessage() {
  3007. yield {
  3008. type: "delta",
  3009. turnId: "turn-running-thinking",
  3010. thinking: "Inspecting the repository",
  3011. };
  3012. await new Promise<void>((resolve) => {
  3013. finishThinking = resolve;
  3014. });
  3015. yield { type: "done", turnId: "turn-running-thinking" };
  3016. },
  3017. );
  3018. const app = createTuiApp({
  3019. runtime,
  3020. terminal,
  3021. version: "0.1.0",
  3022. workspaceDir: "/workspace",
  3023. });
  3024. app.start();
  3025. await app.ready;
  3026. const submission = app.submit("Inspect the repository");
  3027. const countThinkingBodyRows = (rendered: string): number =>
  3028. rendered
  3029. .split("\n")
  3030. .filter(
  3031. (line) =>
  3032. line.includes("Inspecting the repository") &&
  3033. !line.includes("MCode"),
  3034. ).length;
  3035. let expandedThinkingRows = 0;
  3036. try {
  3037. await vi.waitFor(() => {
  3038. const thinking = app.transcript
  3039. .snapshot()
  3040. .find((cell) => cell.kind === "thinking");
  3041. expect(thinking?.content).toBe("Inspecting the repository");
  3042. expect(thinking?.expanded).toBeUndefined();
  3043. const rendered = app.tui.render(80).join("\n");
  3044. expect(rendered).toContain("Running");
  3045. expect(rendered).not.toContain("Running · 0s");
  3046. expect(rendered).toContain(`${formatTuiShortcut("alt+enter")} queue`);
  3047. expect(rendered).toContain("Enter steer");
  3048. expect(rendered).not.toContain(`${formatTuiShortcut("ctrl+x")} steer`);
  3049. expect(rendered).toContain("Ctrl+O details");
  3050. expect(rendered).toContain("Esc stop");
  3051. expect(rendered).toContain("Thinking…");
  3052. expect(rendered).not.toContain("MCode ·");
  3053. expect(rendered).not.toContain("Thinking · Inspecting the repository");
  3054. expandedThinkingRows = countThinkingBodyRows(rendered);
  3055. expect(expandedThinkingRows).toBeGreaterThan(0);
  3056. });
  3057. await app.submit("/transcript");
  3058. await vi.waitFor(() => {
  3059. const rendered = renderTerminalViewport(app, terminal);
  3060. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3061. kind: "feature",
  3062. id: "transcript",
  3063. });
  3064. expect(rendered).toContain("Transcript");
  3065. expect(rendered).not.toContain("Inspecting the repository");
  3066. expect(countThinkingBodyRows(rendered)).toBeLessThan(
  3067. expandedThinkingRows,
  3068. );
  3069. });
  3070. terminal.input?.("\x14");
  3071. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3072. kind: "feature",
  3073. id: "transcript",
  3074. });
  3075. finishThinking?.();
  3076. finishThinking = undefined;
  3077. await submission;
  3078. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3079. kind: "feature",
  3080. id: "transcript",
  3081. });
  3082. expect(app.controller.snapshot().activeTurnId).toBeUndefined();
  3083. expect(
  3084. app.transcript.snapshot().find((cell) => cell.kind === "thinking"),
  3085. ).toMatchObject({
  3086. status: "succeeded",
  3087. });
  3088. terminal.input?.("\u001B");
  3089. await vi.waitFor(() => {
  3090. const rendered = app.tui.render(80).join("\n");
  3091. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3092. kind: "chat",
  3093. id: "chat",
  3094. });
  3095. expect(rendered).toContain("Message · Enter send");
  3096. expect(rendered).not.toContain("Running");
  3097. });
  3098. } finally {
  3099. finishThinking?.();
  3100. await submission;
  3101. await app.stop();
  3102. }
  3103. });
  3104. it("toggles hidden and full inline Tool output with Ctrl+O", async () => {
  3105. const terminal = new FakeTerminal();
  3106. const app = createTuiApp({
  3107. runtime: createRuntime(),
  3108. terminal,
  3109. version: "0.1.0",
  3110. workspaceDir: "/workspace",
  3111. });
  3112. app.start();
  3113. await app.ready;
  3114. app.transcript.upsert({
  3115. id: "tool-detail-toggle",
  3116. kind: "tool",
  3117. status: "succeeded",
  3118. title: "bash",
  3119. content: '{"command":"pnpm test"}',
  3120. detail: [
  3121. "result line 1",
  3122. "result line 2",
  3123. "result line 3",
  3124. "result line 4",
  3125. ].join("\n"),
  3126. createdAtMs: 1,
  3127. });
  3128. expect(app.tui.render(80).join("\n")).not.toContain("result line 1");
  3129. expect(app.tui.render(80).join("\n")).not.toContain("result line 4");
  3130. terminal.input?.("\x0f");
  3131. const detailed = app.tui.render(80).join("\n");
  3132. expect(detailed).toContain("result line 1");
  3133. expect(detailed).toContain("result line 3");
  3134. expect(detailed).toContain("result line 4");
  3135. expect(detailed).not.toContain("Details expanded");
  3136. terminal.input?.("\x0f");
  3137. const compact = app.tui.render(80).join("\n");
  3138. expect(compact).not.toContain("result line 1");
  3139. expect(compact).not.toContain("result line 3");
  3140. expect(compact).not.toContain("result line 4");
  3141. expect(compact).not.toContain("Details collapsed");
  3142. await app.stop();
  3143. });
  3144. it("uses Ctrl+T for tasks while Ctrl+O remains scoped to transcript details", async () => {
  3145. const terminal = new FakeTerminal();
  3146. const app = createTuiApp({
  3147. runtime: createRuntime(),
  3148. terminal,
  3149. version: "0.1.0",
  3150. workspaceDir: "/workspace",
  3151. });
  3152. app.start();
  3153. await app.ready;
  3154. app.controller.applyRuntimeTurnEvent("turn-todo", {
  3155. type: "generic",
  3156. eventType: "todo_updated",
  3157. turnId: "turn-todo",
  3158. data: {
  3159. todos: [
  3160. { content: "Inspect Desktop behavior", status: "completed" },
  3161. { content: "Polish the task rail", status: "in_progress" },
  3162. { content: "Run focused tests", status: "pending" },
  3163. { content: "Review narrow layouts", status: "pending" },
  3164. { content: "Update user documentation", status: "pending" },
  3165. { content: "Publish the test package", status: "pending" },
  3166. ],
  3167. },
  3168. });
  3169. const compact = app.tui.render(80).join("\n");
  3170. expect(compact).toContain("✓ Inspect Desktop behavior");
  3171. expect(compact).toContain("● Polish the task rail");
  3172. expect(compact).toContain("Ctrl+T expand");
  3173. expect(compact).not.toContain("Publish the test package");
  3174. expect(compact).not.toContain("todo_updated");
  3175. terminal.input?.("\x0f");
  3176. const transcriptDetailed = app.tui.render(80).join("\n");
  3177. expect(transcriptDetailed).toContain("Ctrl+T expand");
  3178. expect(transcriptDetailed).not.toContain("Publish the test package");
  3179. terminal.input?.("\x14");
  3180. const tasksExpanded = app.tui.render(80).join("\n");
  3181. expect(tasksExpanded).toContain(
  3182. "Todo list 1/6 · 5 remaining · Ctrl+T compact",
  3183. );
  3184. expect(tasksExpanded).toContain("Publish the test package");
  3185. terminal.input?.("\x0f");
  3186. expect(app.tui.render(80).join("\n")).toContain("Publish the test package");
  3187. app.controller.applyRuntimeTurnEvent("turn-todo", {
  3188. type: "generic",
  3189. eventType: "todo_updated",
  3190. turnId: "turn-todo",
  3191. data: {
  3192. todos: [
  3193. { content: "Inspect Desktop behavior", status: "completed" },
  3194. { content: "Polish the task rail", status: "completed" },
  3195. { content: "Run focused tests", status: "completed" },
  3196. { content: "Review narrow layouts", status: "completed" },
  3197. { content: "Update user documentation", status: "completed" },
  3198. { content: "Publish the test package", status: "completed" },
  3199. ],
  3200. },
  3201. });
  3202. expect(app.tui.render(80).join("\n")).toContain(
  3203. "✓ Todo list 6/6 completed",
  3204. );
  3205. await app.stop();
  3206. });
  3207. it("keeps settled Thinking hidden until Ctrl+O requests transcript details", async () => {
  3208. const terminal = new FakeTerminal();
  3209. const app = createTuiApp({
  3210. runtime: createRuntime(),
  3211. terminal,
  3212. version: "0.1.0",
  3213. workspaceDir: "/workspace",
  3214. });
  3215. app.start();
  3216. await app.ready;
  3217. app.transcript.upsert({
  3218. id: "thinking-detail-toggle",
  3219. kind: "thinking",
  3220. status: "succeeded",
  3221. content: "Private settled reasoning",
  3222. durationMs: 3_200,
  3223. createdAtMs: 1,
  3224. updatedAtMs: 3_201,
  3225. });
  3226. const compact = app.tui.render(80).join("\n");
  3227. expect(compact).toContain("Thought for 3.2s");
  3228. expect(compact).not.toContain("Private settled reasoning");
  3229. terminal.input?.("\x0f");
  3230. expect(app.tui.render(80).join("\n")).toContain(
  3231. "Private settled reasoning",
  3232. );
  3233. terminal.input?.("\x0f");
  3234. expect(app.tui.render(80).join("\n")).not.toContain(
  3235. "Private settled reasoning",
  3236. );
  3237. await app.stop();
  3238. });
  3239. it("returns from the conversation surface to Welcome after /new", async () => {
  3240. const terminal = new FakeTerminal();
  3241. const runtime = createRuntime();
  3242. const app = createTuiApp({
  3243. runtime,
  3244. terminal,
  3245. version: "0.1.0",
  3246. workspaceDir: "/workspace",
  3247. });
  3248. await app.ready;
  3249. await app.submit("Start a conversation");
  3250. expect(app.getSurface()).toBe("conversation");
  3251. await app.submit("/new");
  3252. expect(app.getSurface()).toBe("welcome");
  3253. expect(app.transcript.snapshot()).toEqual([]);
  3254. });
  3255. it("clears into a fresh conversation while keeping the previous session resumable", async () => {
  3256. const terminal = new FakeTerminal();
  3257. const runtime = createRuntime();
  3258. const app = createTuiApp({
  3259. runtime,
  3260. terminal,
  3261. version: "0.1.0",
  3262. workspaceDir: "/workspace",
  3263. });
  3264. await app.ready;
  3265. await app.submit("Keep this conversation");
  3266. expect(app.controller.snapshot().session?.sessionId).toBe("session-1");
  3267. await app.submit("/clear");
  3268. expect(app.getSurface()).toBe("welcome");
  3269. expect(app.transcript.snapshot()).toEqual([]);
  3270. expect(app.controller.snapshot()).toMatchObject({
  3271. status: "idle",
  3272. session: undefined,
  3273. sessions: [expect.objectContaining({ sessionId: "session-1" })],
  3274. });
  3275. expect(runtime.archiveSession).not.toHaveBeenCalled();
  3276. });
  3277. it("opens read-only Help above the Composer without using a TUI overlay", async () => {
  3278. const terminal = new FakeTerminal();
  3279. const runtime = createRuntime();
  3280. const app = createTuiApp({
  3281. runtime,
  3282. terminal,
  3283. version: "0.1.0",
  3284. workspaceDir: "/workspace",
  3285. });
  3286. const showOverlay = vi.spyOn(app.tui, "showOverlay");
  3287. app.start();
  3288. await app.ready;
  3289. const modelRequestsBeforeHelp = vi.mocked(runtime.listModels).mock.calls
  3290. .length;
  3291. const activeRunRequestsBeforeHelp = vi.mocked(runtime.getActiveRun).mock
  3292. .calls.length;
  3293. await app.submit("/help");
  3294. expect(runtime.sendMessage).not.toHaveBeenCalled();
  3295. expect(app.transcript.snapshot()).toEqual([]);
  3296. expect(app.tui.hasOverlay()).toBe(false);
  3297. expect(app.interaction.isActive()).toBe(true);
  3298. expect(terminal.mouseTracking).toBe(false);
  3299. terminal.input?.("m");
  3300. terminal.input?.("\r");
  3301. expect(app.tui.hasOverlay()).toBe(false);
  3302. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  3303. expect(app.editor.getText()).toBe("");
  3304. expect(runtime.listModels).toHaveBeenCalledTimes(modelRequestsBeforeHelp);
  3305. expect(runtime.getActiveRun).toHaveBeenCalledTimes(
  3306. activeRunRequestsBeforeHelp,
  3307. );
  3308. expect(showOverlay).not.toHaveBeenCalled();
  3309. await app.stop();
  3310. });
  3311. it("lets Help use the available terminal height instead of capping it at twelve rows", async () => {
  3312. const terminal = new FakeTerminal();
  3313. terminal.rows = 30;
  3314. const app = createTuiApp({
  3315. runtime: createRuntime(),
  3316. terminal,
  3317. version: "0.1.0",
  3318. workspaceDir: "/workspace",
  3319. });
  3320. app.start();
  3321. await app.submit("/help");
  3322. expect(app.interaction.current()?.render?.(terminal.columns)).toHaveLength(
  3323. 24,
  3324. );
  3325. terminal.rows = 18;
  3326. expect(app.interaction.current()?.render?.(terminal.columns)).toHaveLength(
  3327. 12,
  3328. );
  3329. await app.stop();
  3330. });
  3331. it("keeps steer executable and exposes it in slash-command discovery", async () => {
  3332. const terminal = new FakeTerminal();
  3333. const runtime = createRuntime();
  3334. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  3335. schemaVersion: 1,
  3336. sessionId,
  3337. state: "running",
  3338. turnId: "turn-active",
  3339. actions: { steer: true },
  3340. }));
  3341. vi.mocked(runtime.steer).mockResolvedValue({
  3342. turnId: "turn-active",
  3343. mode: "steered",
  3344. });
  3345. const app = createTuiApp({
  3346. runtime,
  3347. terminal,
  3348. version: "0.1.0",
  3349. workspaceDir: "/workspace",
  3350. });
  3351. app.start();
  3352. await app.submit("Create session");
  3353. await app.submit("/help");
  3354. const helpPanel = app.interaction.current();
  3355. expect(helpPanel).toBeDefined();
  3356. expect(app.tui.hasOverlay()).toBe(false);
  3357. const helpPages: string[] = [];
  3358. for (let page = 0; page < 20; page += 1) {
  3359. const current = helpPanel?.render?.(100).join("\n") ?? "";
  3360. if (current === helpPages.at(-1)) break;
  3361. helpPages.push(current);
  3362. helpPanel?.handleInput?.("\x1b[6~");
  3363. }
  3364. const help = helpPages.join("\n");
  3365. expect(help).toContain("/steer <message>");
  3366. expect(help).not.toContain("/send-now");
  3367. expect(help).not.toContain("/retry");
  3368. helpPanel?.handleInput?.("\x1b");
  3369. await app.submit("/steer focus on the failing test");
  3370. expect(runtime.steer).toHaveBeenCalledWith(
  3371. expect.objectContaining({
  3372. sessionId: "session-1",
  3373. source: "api",
  3374. message: { content: "focus on the failing test" },
  3375. producerId: "mcode",
  3376. idempotencyKey: expect.stringMatching(/^run_action_/u),
  3377. }),
  3378. );
  3379. await app.stop();
  3380. });
  3381. it("refreshes Runtime steer capability before Enter submits the active Draft", async () => {
  3382. const terminal = new FakeTerminal();
  3383. const runtime = createRuntime();
  3384. let finishTurn: (() => void) | undefined;
  3385. let consumeSteer: (() => void) | undefined;
  3386. const steerConsumptionReady = new Promise<void>((resolve) => {
  3387. consumeSteer = resolve;
  3388. });
  3389. let steerAvailable = false;
  3390. vi.mocked(runtime.sendMessage).mockImplementation(
  3391. async function* sendMessage() {
  3392. yield {
  3393. type: "delta",
  3394. turnId: "turn-active",
  3395. content: "Working on it",
  3396. };
  3397. await steerConsumptionReady;
  3398. yield {
  3399. type: "message",
  3400. message: {
  3401. id: "message-steer",
  3402. turnId: "turn-active",
  3403. role: "user",
  3404. content: "focus on the failing test",
  3405. },
  3406. };
  3407. await new Promise<void>((resolve) => {
  3408. finishTurn = resolve;
  3409. });
  3410. yield { type: "done", turnId: "turn-active" };
  3411. },
  3412. );
  3413. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) =>
  3414. steerAvailable
  3415. ? {
  3416. schemaVersion: 1,
  3417. sessionId,
  3418. state: "running",
  3419. turnId: "turn-active",
  3420. actions: { steer: true },
  3421. }
  3422. : {
  3423. schemaVersion: 1,
  3424. sessionId,
  3425. state: "idle",
  3426. actions: { steer: false },
  3427. },
  3428. );
  3429. vi.mocked(runtime.steer).mockResolvedValue({
  3430. turnId: "turn-active",
  3431. mode: "steered",
  3432. });
  3433. const app = createTuiApp({
  3434. runtime,
  3435. terminal,
  3436. version: "0.1.0",
  3437. workspaceDir: "/workspace",
  3438. });
  3439. app.start();
  3440. await app.ready;
  3441. const submission = app.submit("Inspect the failure");
  3442. try {
  3443. await vi.waitFor(() =>
  3444. expect(app.tui.render(80).join("\n")).toContain("Running"),
  3445. );
  3446. steerAvailable = true;
  3447. terminal.input?.("focus on the failing test");
  3448. terminal.input?.("\r");
  3449. expect(app.editor.getText()).toBe("");
  3450. await vi.waitFor(() =>
  3451. expect(runtime.steer).toHaveBeenCalledWith(
  3452. expect.objectContaining({
  3453. sessionId: "session-1",
  3454. source: "api",
  3455. message: { content: "focus on the failing test" },
  3456. producerId: "mcode",
  3457. idempotencyKey: expect.stringMatching(/^run_action_/u),
  3458. requestedTurnId: "turn-active",
  3459. }),
  3460. ),
  3461. );
  3462. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  3463. kind: "user",
  3464. status: "pending",
  3465. content: "focus on the failing test",
  3466. userPresentation: "pending-steer",
  3467. });
  3468. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  3469. "↳ Next · focus on the failing test",
  3470. );
  3471. consumeSteer?.();
  3472. await vi.waitFor(() =>
  3473. expect(
  3474. app.transcript.snapshot().filter((cell) => cell.kind === "user"),
  3475. ).toEqual([
  3476. expect.objectContaining({ content: "Inspect the failure" }),
  3477. expect.objectContaining({
  3478. status: "succeeded",
  3479. content: "focus on the failing test",
  3480. sourceMessageId: "message-steer",
  3481. userPresentation: undefined,
  3482. }),
  3483. ]),
  3484. );
  3485. const rendered = app.tui.render(80).join("\n");
  3486. expect(rendered).toContain("Inspect the failure");
  3487. expect(rendered).toContain("focus on the failing test");
  3488. expect(stripAnsi(rendered)).not.toContain("↳ Next ·");
  3489. expect(app.editor.getText()).toBe("");
  3490. } finally {
  3491. consumeSteer?.();
  3492. await vi.waitFor(() => expect(finishTurn).toEqual(expect.any(Function)));
  3493. finishTurn?.();
  3494. await submission;
  3495. await app.stop();
  3496. }
  3497. });
  3498. it("queues with Alt+Enter, restores with Option+Up, then steers with Enter", async () => {
  3499. const terminal = new FakeTerminal();
  3500. const runtime = createRuntime();
  3501. const queuedItems: TuiQueuedMessage[] = [];
  3502. let finishTurn: (() => void) | undefined;
  3503. vi.mocked(runtime.sendMessage).mockImplementation(
  3504. async function* sendMessage() {
  3505. yield {
  3506. type: "delta",
  3507. turnId: "turn-active",
  3508. content: "Working on it",
  3509. };
  3510. await new Promise<void>((resolve) => {
  3511. finishTurn = resolve;
  3512. });
  3513. yield { type: "done", turnId: "turn-active" };
  3514. },
  3515. );
  3516. vi.mocked(runtime.enqueueMessage).mockImplementation(
  3517. async (sessionId, content) => {
  3518. const item: TuiQueuedMessage = {
  3519. itemId: "queue-guidance",
  3520. sessionId,
  3521. status: "queued",
  3522. source: "api",
  3523. content,
  3524. };
  3525. queuedItems.push(item);
  3526. return {
  3527. itemId: item.itemId,
  3528. status: item.status,
  3529. position: queuedItems.length,
  3530. };
  3531. },
  3532. );
  3533. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  3534. ...queuedItems,
  3535. ]);
  3536. vi.mocked(runtime.deleteQueuedMessage).mockImplementation(
  3537. async (_sessionId, itemId) => {
  3538. const index = queuedItems.findIndex((item) => item.itemId === itemId);
  3539. return index >= 0 ? queuedItems.splice(index, 1)[0] : undefined;
  3540. },
  3541. );
  3542. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  3543. schemaVersion: 1,
  3544. sessionId,
  3545. state: "running",
  3546. turnId: "turn-active",
  3547. actions: { steer: true },
  3548. }));
  3549. const app = createTuiApp({
  3550. runtime,
  3551. terminal,
  3552. version: "0.1.0",
  3553. workspaceDir: "/workspace",
  3554. });
  3555. app.start();
  3556. await app.ready;
  3557. const submission = app.submit("Inspect the failure");
  3558. try {
  3559. await vi.waitFor(() =>
  3560. expect(app.tui.render(80).join("\n")).toContain("Running"),
  3561. );
  3562. terminal.input?.("Use the preview branch directly");
  3563. terminal.input?.("\x1b\r");
  3564. await vi.waitFor(() =>
  3565. expect(app.tui.render(80).join("\n")).toContain(
  3566. "Use the preview branch directly",
  3567. ),
  3568. );
  3569. await vi.waitFor(() =>
  3570. expect(runtime.listQueuedMessages).toHaveBeenCalledWith("session-1"),
  3571. );
  3572. expect(app.editor.getText()).toBe("");
  3573. terminal.input?.("\x1b[1;3A");
  3574. await vi.waitFor(() =>
  3575. expect(app.editor.getText()).toBe("Use the preview branch directly"),
  3576. );
  3577. expect(runtime.deleteQueuedMessage).toHaveBeenCalledWith(
  3578. "session-1",
  3579. "queue-guidance",
  3580. );
  3581. expect(runtime.steerQueuedMessage).not.toHaveBeenCalled();
  3582. await vi.waitFor(() =>
  3583. expect(app.tui.render(80).join("\n")).not.toContain("Queued ·"),
  3584. );
  3585. terminal.input?.("\r");
  3586. await vi.waitFor(() =>
  3587. expect(runtime.steer).toHaveBeenCalledWith(
  3588. expect.objectContaining({
  3589. sessionId: "session-1",
  3590. message: { content: "Use the preview branch directly" },
  3591. requestedTurnId: "turn-active",
  3592. }),
  3593. ),
  3594. );
  3595. expect(app.editor.getText()).toBe("");
  3596. } finally {
  3597. finishTurn?.();
  3598. await submission;
  3599. await app.stop();
  3600. }
  3601. });
  3602. it("renders /context from the Runtime-owned persisted context usage", async () => {
  3603. const runtime = createRuntime();
  3604. vi.mocked(runtime.getContextSnapshot).mockResolvedValue({
  3605. status: "live",
  3606. model: { provider: "minimax", id: "MiniMax-M3", contextWindow: 10_000 },
  3607. contextUsage: {
  3608. contextWindowTokens: 10_000,
  3609. usedTokens: 3_000,
  3610. totalCountSource: "PROVIDER_USAGE_ANCHORED",
  3611. components: [
  3612. { kind: "SYSTEM_PROMPT", tokens: 1_000 },
  3613. { kind: "MEMORY", tokens: 0 },
  3614. { kind: "TOOLS", tokens: 0 },
  3615. { kind: "SKILLS", tokens: 0 },
  3616. { kind: "MESSAGES", tokens: 2_000 },
  3617. { kind: "OTHER", tokens: 0 },
  3618. ],
  3619. },
  3620. });
  3621. const app = createTuiApp({
  3622. runtime,
  3623. terminal: new FakeTerminal(),
  3624. version: "0.1.0",
  3625. workspaceDir: "/workspace",
  3626. });
  3627. await app.submit("Create session");
  3628. const transcriptBeforeContext = app.transcript.snapshot();
  3629. await app.submit("/context");
  3630. expect(app.transcript.snapshot()).toEqual(transcriptBeforeContext);
  3631. expect(app.interaction.current()).toBeDefined();
  3632. const rendered = app.tui.render(80).join("\n");
  3633. expect(rendered).toContain("Context");
  3634. expect(rendered).toContain("3k/10k tokens (30% used)");
  3635. expect(rendered).toContain("Usage by category");
  3636. expect(rendered).toContain("Messages");
  3637. expect(rendered).toMatch(/[⛁⛀⛶]/u);
  3638. app.interaction.current()?.handleInput?.("\x1b");
  3639. expect(app.interaction.current()).toBeUndefined();
  3640. expect(app.transcript.snapshot()).toEqual(transcriptBeforeContext);
  3641. });
  3642. it("routes /init through the Runtime-owned init Skill and the normal Agent turn", async () => {
  3643. const terminal = new FakeTerminal();
  3644. const runtime = createRuntime();
  3645. vi.mocked(runtime.listSkills).mockResolvedValue({
  3646. skills: [
  3647. {
  3648. name: "init",
  3649. displayName: "Init",
  3650. description: "Analyze the codebase and generate AGENTS.md",
  3651. enabled: true,
  3652. sourceKind: "builtin",
  3653. },
  3654. ],
  3655. hasMore: false,
  3656. });
  3657. const app = createTuiApp({
  3658. runtime,
  3659. terminal,
  3660. version: "0.1.0",
  3661. workspaceDir: "/workspace",
  3662. });
  3663. app.start();
  3664. await app.ready;
  3665. await vi.waitFor(() => expect(runtime.listSkills).toHaveBeenCalled());
  3666. await app.submit("/init");
  3667. expect(runtime.sendMessage).toHaveBeenCalledWith(
  3668. expect.objectContaining({ id: "session-1", content: "/init" }),
  3669. expect.any(AbortSignal),
  3670. );
  3671. });
  3672. it("forwards literal slash-prefixed prompts without invoking local commands", async () => {
  3673. const runtime = createRuntime();
  3674. const app = createTuiApp({
  3675. runtime,
  3676. terminal: new FakeTerminal(),
  3677. version: "0.1.0",
  3678. workspaceDir: "/workspace",
  3679. });
  3680. const prompts = [
  3681. "/commands",
  3682. "/diff",
  3683. "/tool",
  3684. "/tools",
  3685. "/resumex",
  3686. "/renamex Renamed by a typo",
  3687. "/clearx",
  3688. "/tmp/sample-photo.JPG 用 read 工具直接读这个图片,告诉我是什么",
  3689. "/not-a-command explain what this text means",
  3690. "/context 这样还是会显示上下文信息",
  3691. ];
  3692. try {
  3693. app.start();
  3694. await app.ready;
  3695. for (const prompt of prompts) {
  3696. await app.submit(prompt);
  3697. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  3698. expect.objectContaining({ id: "session-1", content: prompt }),
  3699. expect.any(AbortSignal),
  3700. );
  3701. expect(app.interaction.current()).toBeUndefined();
  3702. expect(app.tui.hasOverlay()).toBe(false);
  3703. }
  3704. expect(runtime.sendMessage).toHaveBeenCalledTimes(prompts.length);
  3705. expect(runtime.renameSession).not.toHaveBeenCalled();
  3706. // Context metrics refresh independently; the overlay assertions above verify no local command ran.
  3707. expect(app.transcript.snapshot()).not.toContainEqual(
  3708. expect.objectContaining({ content: "Unknown command. Use /help." }),
  3709. );
  3710. } finally {
  3711. await app.stop();
  3712. }
  3713. });
  3714. it("keeps contextual commands local and submits other legacy names as prompts", async () => {
  3715. const terminal = new FakeTerminal();
  3716. const runtime = createRuntime();
  3717. const app = createTuiApp({
  3718. runtime,
  3719. terminal,
  3720. version: "0.1.0",
  3721. workspaceDir: "/workspace",
  3722. });
  3723. await app.submit("/queue");
  3724. expect(runtime.listQueuedMessages).not.toHaveBeenCalled();
  3725. expect(app.transcript.snapshot()).toEqual([]);
  3726. expect(app.tui.render(80).join("\n")).toContain(
  3727. "No messages are waiting and no response is currently running.",
  3728. );
  3729. await app.submit("/queue-clear");
  3730. expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
  3731. await app.submit("/send-now do this first");
  3732. await app.submit("/retry");
  3733. expect(
  3734. vi
  3735. .mocked(runtime.sendMessage)
  3736. .mock.calls.map(([request]) => request.content),
  3737. ).toEqual(["/queue-clear", "/send-now do this first"]);
  3738. expect(app.tui.render(80).join("\n")).toContain(
  3739. "There is no failed response to retry in this Session.",
  3740. );
  3741. });
  3742. it("resends the failed user submission through /retry instead of sending the command as text", async () => {
  3743. const terminal = new FakeTerminal();
  3744. const runtime = createRuntime();
  3745. let attempt = 0;
  3746. vi.mocked(runtime.sendMessage).mockImplementation(
  3747. async function* sendMessage() {
  3748. attempt += 1;
  3749. if (attempt === 1) {
  3750. yield { type: "error", message: "terminated" };
  3751. return;
  3752. }
  3753. yield { type: "delta", content: "Recovered response" };
  3754. yield { type: "done" };
  3755. },
  3756. );
  3757. const app = createTuiApp({
  3758. runtime,
  3759. terminal,
  3760. version: "0.1.0",
  3761. workspaceDir: "/workspace",
  3762. });
  3763. await app.submit("Explain this failure");
  3764. expect(app.tui.render(100).join("\n")).toContain(
  3765. "The model connection ended before the response was completed.",
  3766. );
  3767. expect(app.tui.render(100).join("\n")).toContain(
  3768. "Run /retry to resend your last message.",
  3769. );
  3770. await app.submit("/retry");
  3771. expect(
  3772. vi
  3773. .mocked(runtime.sendMessage)
  3774. .mock.calls.map(([request]) => request.content),
  3775. ).toEqual(["Explain this failure", "Explain this failure"]);
  3776. expect(
  3777. vi
  3778. .mocked(runtime.sendMessage)
  3779. .mock.calls.some(([request]) => request.content === "/retry"),
  3780. ).toBe(false);
  3781. expect(app.transcript.snapshot()).toContainEqual(
  3782. expect.objectContaining({
  3783. kind: "assistant",
  3784. content: "Recovered response",
  3785. }),
  3786. );
  3787. await app.stop();
  3788. });
  3789. it("uses Runtime retry-continuation when a terminal failure has no local submission snapshot", async () => {
  3790. const terminal = new FakeTerminal();
  3791. const runtime = createRuntime();
  3792. const restoredSession = {
  3793. sessionId: "session-1",
  3794. title: "Restored session",
  3795. workspaceDir: "/workspace",
  3796. status: "error",
  3797. errorMessage: "terminated",
  3798. };
  3799. vi.mocked(runtime.listSessions).mockResolvedValue([restoredSession]);
  3800. vi.mocked(runtime.getSession).mockResolvedValue(restoredSession);
  3801. const app = createTuiApp({
  3802. runtime,
  3803. terminal,
  3804. version: "0.1.0",
  3805. workspaceDir: "/workspace",
  3806. });
  3807. app.start();
  3808. await app.ready;
  3809. await app.submit("/resume session-1");
  3810. expect(app.tui.render(100).join("\n")).toContain(
  3811. "The model connection ended before the response was completed.",
  3812. );
  3813. await app.submit("/retry");
  3814. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  3815. expect.objectContaining({
  3816. id: "session-1",
  3817. content: "",
  3818. clientIntent: "retry-continuation",
  3819. }),
  3820. expect.any(AbortSignal),
  3821. );
  3822. await app.stop();
  3823. });
  3824. it("reports service authentication failures without assuming the user needs to sign in", async () => {
  3825. const runtime = createRuntime();
  3826. vi.mocked(runtime.sendMessage).mockImplementation(
  3827. async function* sendMessage() {
  3828. yield { type: "error", message: "authentication failed" };
  3829. },
  3830. );
  3831. const app = createTuiApp({
  3832. runtime,
  3833. terminal: new FakeTerminal(),
  3834. version: "0.1.0",
  3835. workspaceDir: "/workspace",
  3836. });
  3837. await app.submit("Use the protected model");
  3838. expect(app.tui.render(100).join("\n")).toContain(
  3839. "The service rejected request authentication.",
  3840. );
  3841. expect(app.tui.render(100).join("\n")).not.toContain("Run /login");
  3842. expect(app.tui.render(100).join("\n")).not.toContain("Run /retry");
  3843. await app.submit("/retry");
  3844. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  3845. await app.stop();
  3846. });
  3847. it("cycles the shared permission mode with Alt+M without repeating the shortcut", async () => {
  3848. const terminal = new FakeTerminal();
  3849. const runtime = createRuntime();
  3850. const app = createTuiApp({
  3851. runtime,
  3852. terminal,
  3853. version: "0.1.0",
  3854. workspaceDir: "/workspace",
  3855. });
  3856. app.start();
  3857. await app.ready;
  3858. expect(app.tui.render(80).join("\n")).toContain("Auto");
  3859. expect(app.tui.render(80).join("\n")).not.toContain("Shift+Tab");
  3860. expect(app.tui.render(80).join("\n")).not.toContain(
  3861. "Shift+Tab switch mode",
  3862. );
  3863. terminal.input?.("\x1bm");
  3864. await vi.waitFor(() => {
  3865. expect(runtime.setPermissionMode).toHaveBeenCalledWith(
  3866. "bypassPermissions",
  3867. );
  3868. const rendered = app.tui.render(80).join("\n");
  3869. expect(rendered).toContain("Full access");
  3870. expect(rendered).not.toContain("Shift+Tab");
  3871. expect(rendered.match(/Full access/g)).toHaveLength(1);
  3872. expect(rendered).not.toContain("Desktop permissions:");
  3873. });
  3874. await app.stop();
  3875. });
  3876. it("projects Token Plan warnings into the status rail", async () => {
  3877. const terminal = new FakeTerminal();
  3878. const runtime = createRuntime();
  3879. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  3880. status: "ready",
  3881. defaultModel: "minimax/MiniMax-M2.7",
  3882. providerId: "minimax",
  3883. modelId: "MiniMax-M2.7",
  3884. authMode: "managed-login",
  3885. managedTokenPresent: true,
  3886. modelSource: "token-plan",
  3887. tokenPlanQuotaState: "available",
  3888. tokenPlanQuota: {
  3889. fiveHour: { remainingPercent: 30, unlimited: false },
  3890. weekly: { remainingPercent: 64, unlimited: false },
  3891. },
  3892. warnings: [],
  3893. });
  3894. const app = createTuiApp({
  3895. runtime,
  3896. terminal,
  3897. version: "0.1.0",
  3898. workspaceDir: "/workspace",
  3899. });
  3900. app.start();
  3901. await app.ready;
  3902. await app.submit("Measure this turn");
  3903. await vi.waitFor(() => {
  3904. const rendered = app.tui.render(120).join("\n");
  3905. expect(rendered).toContain("5h 30%");
  3906. expect(rendered).not.toContain("Week 64%");
  3907. });
  3908. await app.stop();
  3909. });
  3910. it("keeps Token Plan subscription state out of the status rail when no quota exists", async () => {
  3911. const terminal = new FakeTerminal();
  3912. const runtime = createRuntime();
  3913. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  3914. status: "ready",
  3915. defaultModel: "minimax/MiniMax-M3",
  3916. providerId: "minimax",
  3917. modelId: "MiniMax-M3",
  3918. authMode: "managed-login",
  3919. managedTokenPresent: true,
  3920. modelSource: "token-plan",
  3921. tokenPlanQuotaState: "not-subscribed",
  3922. warnings: [],
  3923. });
  3924. const app = createTuiApp({
  3925. runtime,
  3926. terminal,
  3927. version: "0.1.0",
  3928. workspaceDir: "/workspace",
  3929. });
  3930. app.start();
  3931. await app.ready;
  3932. await app.submit("Measure this turn");
  3933. await vi.waitFor(() => {
  3934. const rendered = app.tui.render(120).join("\n");
  3935. expect(rendered).toContain("✦ MiniMax M2.7");
  3936. expect(rendered).not.toMatch(/Context 5%|Quota|Plan|5h|Week/u);
  3937. });
  3938. await app.stop();
  3939. });
  3940. it("keeps the current permission mode when an Alt+M update fails", async () => {
  3941. const terminal = new FakeTerminal();
  3942. const runtime = createRuntime();
  3943. vi.mocked(runtime.setPermissionMode).mockRejectedValueOnce(
  3944. new Error("config is read-only"),
  3945. );
  3946. const app = createTuiApp({
  3947. runtime,
  3948. terminal,
  3949. version: "0.1.0",
  3950. workspaceDir: "/workspace",
  3951. });
  3952. app.start();
  3953. await app.ready;
  3954. terminal.input?.("\x1bm");
  3955. await vi.waitFor(() => {
  3956. expect(app.tui.render(80).join("\n")).toContain("Auto");
  3957. expect(app.tui.render(80).join("\n")).not.toContain("FULL");
  3958. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  3959. kind: "warning",
  3960. content:
  3961. "Permission mode was not changed: config is read-only. Retry /permission or Alt+M.",
  3962. });
  3963. });
  3964. await app.stop();
  3965. });
  3966. it("arms Plan with Shift+Tab and sends the one-shot Runtime intent", async () => {
  3967. const terminal = new FakeTerminal();
  3968. const runtime = createRuntime();
  3969. const app = createTuiApp({
  3970. runtime,
  3971. terminal,
  3972. version: "0.1.0",
  3973. workspaceDir: "/workspace",
  3974. });
  3975. app.start();
  3976. await app.ready;
  3977. terminal.input?.("\x1b[Z");
  3978. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  3979. expect(app.tui.render(100).join("\n")).toContain(
  3980. "Plan Mode · next message enters Plan",
  3981. );
  3982. terminal.input?.("计");
  3983. expect(app.tui.render(100).join("\n")).toContain(
  3984. "Plan Mode · next message enters Plan",
  3985. );
  3986. expect(app.tui.render(32).join("\n")).toContain("Plan Mode");
  3987. terminal.input?.("\x7f");
  3988. expect(app.editor.getText()).toBe("");
  3989. expect(app.tui.render(100).join("\n")).toContain(
  3990. "Plan Mode · next message enters Plan",
  3991. );
  3992. terminal.input?.("计");
  3993. terminal.input?.("划");
  3994. expect(app.editor.getText()).toBe("计划");
  3995. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  3996. expect(app.tui.render(100).join("\n")).toContain(
  3997. "Plan Mode · next message enters Plan",
  3998. );
  3999. terminal.input?.("\r");
  4000. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  4001. await app.controller.whenIdle();
  4002. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4003. expect.objectContaining({
  4004. content: "计划",
  4005. clientIntent: "plan-entry",
  4006. }),
  4007. expect.any(AbortSignal),
  4008. );
  4009. expect(app.tui.render(100).join("\n")).toContain("PLAN");
  4010. expect(app.tui.render(100).join("\n")).toContain("Auto");
  4011. await app.stop();
  4012. });
  4013. it("keeps ordinary messages in Plan and exits only with an explicit one-shot intent", async () => {
  4014. const runtime = createRuntime();
  4015. const app = createTuiApp({
  4016. runtime,
  4017. terminal: new FakeTerminal(),
  4018. version: "0.1.0",
  4019. workspaceDir: "/workspace",
  4020. });
  4021. app.start();
  4022. await app.ready;
  4023. await app.submit("/plan on");
  4024. await app.submit("Draft the implementation plan");
  4025. await app.submit("Refine the verification section");
  4026. expect(runtime.sendMessage).toHaveBeenNthCalledWith(
  4027. 2,
  4028. expect.not.objectContaining({ clientIntent: expect.anything() }),
  4029. expect.any(AbortSignal),
  4030. );
  4031. expect(app.tui.render(100).join("\n")).toContain(
  4032. "/workspace │ PLAN │ Auto",
  4033. );
  4034. await app.submit("/plan off");
  4035. await app.submit("Implement the approved direction");
  4036. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  4037. expect.objectContaining({ clientIntent: "plan-exit" }),
  4038. expect.any(AbortSignal),
  4039. );
  4040. expect(app.tui.render(100).join("\n")).not.toContain("PLAN");
  4041. await app.stop();
  4042. });
  4043. it("keeps the one-shot Plan intent armed when direct admission rejects it", async () => {
  4044. const runtime = createRuntime();
  4045. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  4046. async function* rejectedAdmission() {
  4047. yield* [] as TuiStreamEvent[];
  4048. throw Object.assign(new Error("Plan entry is disabled"), {
  4049. code: "local_plan_entry_disabled",
  4050. });
  4051. },
  4052. );
  4053. const app = createTuiApp({
  4054. runtime,
  4055. terminal: new FakeTerminal(),
  4056. version: "0.1.0",
  4057. workspaceDir: "/workspace",
  4058. });
  4059. app.start();
  4060. await app.ready;
  4061. await app.submit("/plan on");
  4062. await app.submit("Plan this after the feature is enabled");
  4063. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  4064. await app.submit("Retry the same Plan intent");
  4065. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  4066. expect.objectContaining({ clientIntent: "plan-entry" }),
  4067. expect.any(AbortSignal),
  4068. );
  4069. await app.stop();
  4070. });
  4071. it("settles a Plan transition from authoritative Session metadata when the stream is empty", async () => {
  4072. const runtime = createRuntime();
  4073. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  4074. async function* emptyAcceptedStream() {
  4075. yield* [] as TuiStreamEvent[];
  4076. },
  4077. );
  4078. vi.mocked(runtime.getSession).mockResolvedValue({
  4079. sessionId: "session-1",
  4080. workspace: "/workspace",
  4081. interactionMode: "plan",
  4082. });
  4083. const app = createTuiApp({
  4084. runtime,
  4085. terminal: new FakeTerminal(),
  4086. version: "0.1.0",
  4087. workspaceDir: "/workspace",
  4088. });
  4089. app.start();
  4090. await app.ready;
  4091. await app.submit("/plan on");
  4092. await app.submit("Plan without emitting a stream event");
  4093. expect(runtime.getSession).toHaveBeenCalledWith("session-1");
  4094. expect(app.tui.render(100).join("\n")).toContain(
  4095. "/workspace │ PLAN │ Auto",
  4096. );
  4097. expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
  4098. await app.stop();
  4099. });
  4100. it("clears accepted Plan entry while authoritative metadata refresh is unavailable", async () => {
  4101. const runtime = createRuntime();
  4102. vi.mocked(runtime.getSession).mockRejectedValue(
  4103. new Error("metadata temporarily unavailable"),
  4104. );
  4105. const app = createTuiApp({
  4106. runtime,
  4107. terminal: new FakeTerminal(),
  4108. version: "0.1.0",
  4109. workspaceDir: "/workspace",
  4110. });
  4111. app.start();
  4112. await app.ready;
  4113. await app.submit("/plan on");
  4114. await app.submit("OK");
  4115. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4116. expect.objectContaining({ content: "OK", clientIntent: "plan-entry" }),
  4117. expect.any(AbortSignal),
  4118. );
  4119. expect(app.tui.render(100).join("\n")).not.toContain("/workspace │ PLAN");
  4120. expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
  4121. await app.stop();
  4122. });
  4123. it("preserves Plan intent through direct busy fallback into the Runtime Queue", async () => {
  4124. const runtime = createRuntime();
  4125. vi.mocked(runtime.listModels).mockResolvedValue([
  4126. {
  4127. providerId: "minimax",
  4128. modelId: "MiniMax-M2.7",
  4129. selected: true,
  4130. variant: "",
  4131. },
  4132. ]);
  4133. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  4134. async function* busyAdmission() {
  4135. yield* [] as TuiStreamEvent[];
  4136. throw Object.assign(new Error("Session is busy"), {
  4137. code: "local_session_busy",
  4138. });
  4139. },
  4140. );
  4141. const app = createTuiApp({
  4142. runtime,
  4143. terminal: new FakeTerminal(),
  4144. version: "0.1.0",
  4145. workspaceDir: "/workspace",
  4146. });
  4147. app.start();
  4148. await app.ready;
  4149. await app.submit("/plan on");
  4150. await app.submit("Queue this Plan request");
  4151. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  4152. "session-1",
  4153. "Queue this Plan request",
  4154. {
  4155. attachments: [],
  4156. clientIntent: "plan-entry",
  4157. model: { providerId: "minimax", modelId: "MiniMax-M2.7", variant: "" },
  4158. },
  4159. );
  4160. expect(app.tui.render(100).join("\n")).not.toContain("PLAN queued");
  4161. await app.stop();
  4162. });
  4163. it("binds a one-shot Plan intent to only the first concurrent submission", async () => {
  4164. let releaseFirstEvent: (() => void) | undefined;
  4165. const firstEventGate = new Promise<void>((resolve) => {
  4166. releaseFirstEvent = resolve;
  4167. });
  4168. const runtime = createRuntime();
  4169. vi.mocked(runtime.sendMessage).mockImplementation(
  4170. async function* delayedAdmission() {
  4171. await firstEventGate;
  4172. yield { type: "delta", content: "Planning" };
  4173. yield { type: "done" };
  4174. },
  4175. );
  4176. const app = createTuiApp({
  4177. runtime,
  4178. terminal: new FakeTerminal(),
  4179. version: "0.1.0",
  4180. workspaceDir: "/workspace",
  4181. });
  4182. app.start();
  4183. await app.ready;
  4184. await app.submit("/plan on");
  4185. const first = app.submit("Plan the implementation");
  4186. await vi.waitFor(() =>
  4187. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  4188. );
  4189. await app.submit("Queue a follow-up while admission is quiet");
  4190. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4191. expect.objectContaining({ clientIntent: "plan-entry" }),
  4192. expect.any(AbortSignal),
  4193. );
  4194. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  4195. "session-1",
  4196. "Queue a follow-up while admission is quiet",
  4197. {
  4198. attachments: [],
  4199. model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
  4200. },
  4201. );
  4202. releaseFirstEvent?.();
  4203. await first;
  4204. await app.stop();
  4205. });
  4206. it("shows the Desktop-aligned confirmation when the Agent calls EnterPlanMode", async () => {
  4207. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  4208. const runtime = createRuntime();
  4209. vi.mocked(runtime.watchEvents).mockImplementation(
  4210. async function* watchEvents(signal) {
  4211. const event = await new Promise<TuiRuntimeEvent | undefined>(
  4212. (resolve) => {
  4213. emitEvent = resolve;
  4214. signal.addEventListener("abort", () => resolve(undefined), {
  4215. once: true,
  4216. });
  4217. },
  4218. );
  4219. if (event) yield event;
  4220. await new Promise<void>((resolve) => {
  4221. signal.addEventListener("abort", resolve, { once: true });
  4222. });
  4223. },
  4224. );
  4225. const app = createTuiApp({
  4226. runtime,
  4227. terminal: new FakeTerminal(),
  4228. version: "0.1.0",
  4229. workspaceDir: "/workspace",
  4230. });
  4231. app.start();
  4232. await app.ready;
  4233. await app.submit("Plan a complex change");
  4234. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  4235. const askEvent = runtimeEvent({
  4236. type: "questionnaire.ask",
  4237. timestamp: Date.now(),
  4238. source: "runtime",
  4239. payload: {
  4240. sessionId: "session-1",
  4241. agentName: "mavis",
  4242. request: planEntryEventRequest("plan-entry-agent-tool"),
  4243. },
  4244. });
  4245. expect(askEvent).toMatchObject({
  4246. type: "questionnaire.ask",
  4247. sessionId: "session-1",
  4248. request: { id: "plan-entry-agent-tool", mode: "plan" },
  4249. });
  4250. emitEvent?.(askEvent);
  4251. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4252. const panel = app.interaction.current();
  4253. const rendered = panel?.render?.(100).join("\n") ?? "";
  4254. expect(rendered).toContain("Use Plan mode?");
  4255. expect(rendered).toContain(
  4256. "Plan mode structures complex tasks before execution.",
  4257. );
  4258. expect(rendered).toContain("Continue with plan");
  4259. expect(rendered).toContain("Deny");
  4260. panel?.handleInput?.("\r");
  4261. await vi.waitFor(() =>
  4262. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  4263. "mavis",
  4264. "plan-entry-agent-tool",
  4265. [
  4266. {
  4267. stepId: "plan-enter",
  4268. selectedOptionIds: ["confirm"],
  4269. selectedOther: false,
  4270. },
  4271. ],
  4272. ),
  4273. );
  4274. await app.stop();
  4275. });
  4276. it("keeps a pending Plan exit armed when steer guides the current Plan Turn", async () => {
  4277. let finishTurn: (() => void) | undefined;
  4278. let interactionMode: "plan" | undefined;
  4279. const runtime = createRuntime();
  4280. vi.mocked(runtime.getSession).mockImplementation(async () => ({
  4281. sessionId: "session-1",
  4282. workspace: "/workspace",
  4283. ...(interactionMode ? { interactionMode } : {}),
  4284. }));
  4285. vi.mocked(runtime.sendMessage).mockImplementation(
  4286. async function* activePlanTurn() {
  4287. interactionMode = "plan";
  4288. yield { type: "delta", content: "Drafting the plan" };
  4289. await new Promise<void>((resolve) => {
  4290. finishTurn = resolve;
  4291. });
  4292. yield { type: "done" };
  4293. },
  4294. );
  4295. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  4296. schemaVersion: 1,
  4297. sessionId,
  4298. state: "running",
  4299. turnId: "turn-plan",
  4300. actions: { steer: true },
  4301. }));
  4302. vi.mocked(runtime.steer).mockResolvedValue({
  4303. turnId: "turn-plan",
  4304. mode: "steered",
  4305. });
  4306. const app = createTuiApp({
  4307. runtime,
  4308. terminal: new FakeTerminal(),
  4309. version: "0.1.0",
  4310. workspaceDir: "/workspace",
  4311. });
  4312. app.start();
  4313. await app.ready;
  4314. await app.submit("/plan on");
  4315. const planTurn = app.submit("Draft a plan");
  4316. await vi.waitFor(() =>
  4317. expect(app.tui.render(100).join("\n")).toContain(
  4318. "/workspace │ PLAN │ Auto",
  4319. ),
  4320. );
  4321. await app.submit("/plan off");
  4322. await app.submit("/steer include rollback checks");
  4323. expect(runtime.steer).toHaveBeenCalledWith(
  4324. expect.objectContaining({
  4325. sessionId: "session-1",
  4326. message: { content: "include rollback checks" },
  4327. }),
  4328. );
  4329. expect(app.tui.render(100).join("\n")).toContain("DEFAULT next");
  4330. finishTurn?.();
  4331. await planTurn;
  4332. await app.stop();
  4333. });
  4334. it("does not arm a mode transition while a Plan Review is pending", async () => {
  4335. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  4336. const runtime = createRuntime();
  4337. vi.mocked(runtime.watchEvents).mockImplementation(
  4338. async function* watchEvents(signal) {
  4339. const event = await new Promise<TuiRuntimeEvent | undefined>(
  4340. (resolve) => {
  4341. emitEvent = resolve;
  4342. signal.addEventListener("abort", () => resolve(undefined), {
  4343. once: true,
  4344. });
  4345. },
  4346. );
  4347. if (event) yield event;
  4348. await new Promise<void>((resolve) => {
  4349. signal.addEventListener("abort", resolve, { once: true });
  4350. });
  4351. },
  4352. );
  4353. const terminal = new FakeTerminal();
  4354. const app = createTuiApp({
  4355. runtime,
  4356. terminal,
  4357. version: "0.1.0",
  4358. workspaceDir: "/workspace",
  4359. });
  4360. app.start();
  4361. await app.ready;
  4362. await app.submit("/plan on");
  4363. await app.submit("Draft a plan");
  4364. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  4365. emitEvent?.(
  4366. runtimeEvent({
  4367. type: "questionnaire.ask",
  4368. timestamp: Date.now(),
  4369. source: "runtime",
  4370. payload: {
  4371. sessionId: "session-1",
  4372. agentName: "mavis",
  4373. request: planReviewEventRequest("plan-review-mode-guard"),
  4374. },
  4375. }),
  4376. );
  4377. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4378. // The compact panel owns the decision; the frozen plan is projected to the Transcript.
  4379. expect(app.interaction.current()?.render?.(100).join("\n")).toContain(
  4380. "Plan complete. What would you like to do?",
  4381. );
  4382. expect(app.tui.render(100).join("\n")).toContain("Frozen plan");
  4383. terminal.input?.("\x1b[Z");
  4384. expect(app.interaction.isActive()).toBe(true);
  4385. expect(app.tui.render(100).join("\n")).toContain(
  4386. "/workspace │ PLAN │ Auto",
  4387. );
  4388. expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
  4389. await app.submit("/plan off");
  4390. expect(app.interaction.isActive()).toBe(true);
  4391. expect(app.tui.render(100).join("\n")).toContain(
  4392. "/workspace │ PLAN │ Auto",
  4393. );
  4394. expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
  4395. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  4396. await app.submit("/steer bypass the review");
  4397. expect(app.interaction.isActive()).toBe(true);
  4398. expect(runtime.steer).not.toHaveBeenCalled();
  4399. app.interaction.current()?.handleInput?.("\u001b");
  4400. await vi.waitFor(() =>
  4401. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  4402. "mavis",
  4403. "plan-review-mode-guard",
  4404. [expect.objectContaining({ skipped: true })],
  4405. ),
  4406. );
  4407. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  4408. expect(app.tui.render(100).join("\n")).toContain(
  4409. "/workspace │ PLAN │ Auto",
  4410. );
  4411. await app.stop();
  4412. });
  4413. it("streams Plan feedback and replaces it with the revised Plan Review", async () => {
  4414. let emitReview: ((event: TuiRuntimeEvent) => void) | undefined;
  4415. let releaseContinuation: (() => void) | undefined;
  4416. let finishReply: ((value: boolean) => void) | undefined;
  4417. const runtime = createRuntime();
  4418. vi.mocked(runtime.replyQuestionnaire).mockImplementation(
  4419. async () =>
  4420. await new Promise<boolean>((resolve) => {
  4421. finishReply = resolve;
  4422. }),
  4423. );
  4424. vi.mocked(runtime.watchEvents).mockImplementation(
  4425. async function* watchEvents(signal) {
  4426. const review = await new Promise<TuiRuntimeEvent | undefined>(
  4427. (resolve) => {
  4428. emitReview = resolve;
  4429. signal.addEventListener("abort", () => resolve(undefined), {
  4430. once: true,
  4431. });
  4432. },
  4433. );
  4434. if (!review || signal.aborted) return;
  4435. yield review;
  4436. await new Promise<void>((resolve) => {
  4437. releaseContinuation = resolve;
  4438. signal.addEventListener("abort", resolve, { once: true });
  4439. });
  4440. if (signal.aborted) return;
  4441. const turnId = "turn-runtime-plan-feedback";
  4442. yield runtimeEvent({
  4443. type: "session.start",
  4444. timestamp: Date.now(),
  4445. source: "runtime",
  4446. payload: { sessionId: "session-1", turnId },
  4447. });
  4448. vi.mocked(runtime.getMessages).mockResolvedValue([
  4449. {
  4450. id: "assistant-revised-plan",
  4451. role: "assistant",
  4452. content: "I revised the plan with rollback coverage.",
  4453. },
  4454. ]);
  4455. yield runtimeEvent({
  4456. type: "questionnaire.ask",
  4457. timestamp: Date.now(),
  4458. source: "runtime",
  4459. payload: {
  4460. sessionId: "session-1",
  4461. agentName: "mavis",
  4462. request: {
  4463. ...planReviewEventRequest("plan-review-feedback-revised"),
  4464. modePayload: {
  4465. planReview: {
  4466. markdown:
  4467. "# Revised frozen plan\n\nIncludes rollback coverage.",
  4468. path: "/history/session-1/artifacts/plan.md",
  4469. },
  4470. },
  4471. },
  4472. },
  4473. });
  4474. yield runtimeEvent({
  4475. type: "session.finish",
  4476. timestamp: Date.now(),
  4477. source: "runtime",
  4478. payload: { sessionId: "session-1", turnId },
  4479. });
  4480. finishReply?.(true);
  4481. await new Promise<void>((resolve) => {
  4482. signal.addEventListener("abort", resolve, { once: true });
  4483. });
  4484. },
  4485. );
  4486. const terminal = new FakeTerminal();
  4487. const app = createTuiApp({
  4488. runtime,
  4489. terminal,
  4490. version: "0.1.0",
  4491. workspaceDir: "/workspace",
  4492. });
  4493. app.start();
  4494. await app.ready;
  4495. await app.submit("/plan on");
  4496. await app.submit("Draft a plan");
  4497. await vi.waitFor(() => expect(emitReview).toBeTypeOf("function"));
  4498. emitReview?.(
  4499. runtimeEvent({
  4500. type: "questionnaire.ask",
  4501. timestamp: Date.now(),
  4502. source: "runtime",
  4503. payload: {
  4504. sessionId: "session-1",
  4505. agentName: "mavis",
  4506. request: planReviewEventRequest("plan-review-feedback-live"),
  4507. },
  4508. }),
  4509. );
  4510. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4511. terminal.input?.("\u001b[B");
  4512. terminal.input?.("\u001b[B");
  4513. terminal.input?.("\r");
  4514. for (const character of "Add rollback coverage")
  4515. terminal.input?.(character);
  4516. terminal.input?.("\r");
  4517. await vi.waitFor(() => expect(finishReply).toBeTypeOf("function"));
  4518. releaseContinuation?.();
  4519. await vi.waitFor(() =>
  4520. expect(
  4521. app.transcript
  4522. .snapshot()
  4523. .map((cell) => cell.content)
  4524. .join("\n"),
  4525. ).toContain("I revised the plan with rollback coverage."),
  4526. );
  4527. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  4528. "session-1",
  4529. "turn-runtime-plan-feedback",
  4530. expect.any(AbortSignal),
  4531. );
  4532. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4533. // The revised plan is projected to the Transcript; the panel stays the compact decision.
  4534. expect(app.interaction.current()?.render?.(100).join("\n")).toContain(
  4535. "Plan complete. What would you like to do?",
  4536. );
  4537. expect(app.tui.render(100).join("\n")).toContain("Revised frozen plan");
  4538. expect(app.tui.render(100).join("\n")).not.toContain(
  4539. "Message · Enter send",
  4540. );
  4541. await app.stop();
  4542. });
  4543. it("supports explicit /plan and /permission mode commands", async () => {
  4544. const runtime = createRuntime();
  4545. const app = createTuiApp({
  4546. runtime,
  4547. terminal: new FakeTerminal(),
  4548. version: "0.1.0",
  4549. workspaceDir: "/workspace",
  4550. });
  4551. app.start();
  4552. await app.ready;
  4553. await app.submit("/plan on");
  4554. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  4555. await app.submit("/permission full");
  4556. expect(runtime.setPermissionMode).toHaveBeenCalledWith("bypassPermissions");
  4557. expect(app.tui.render(100).join("\n")).toContain("Full access");
  4558. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4559. await app.submit("Plan with Full access");
  4560. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4561. expect.objectContaining({ clientIntent: "plan-entry" }),
  4562. expect.any(AbortSignal),
  4563. );
  4564. expect(app.tui.render(100).join("\n")).toContain("PLAN");
  4565. expect(app.tui.render(100).join("\n")).toContain("Full access");
  4566. await app.stop();
  4567. });
  4568. it("opens a permission mode selector for bare /permission", async () => {
  4569. const runtime = createRuntime();
  4570. const terminal = new FakeTerminal();
  4571. const app = createTuiApp({
  4572. runtime,
  4573. terminal,
  4574. version: "0.1.0",
  4575. workspaceDir: "/workspace",
  4576. });
  4577. app.start();
  4578. await app.ready;
  4579. await app.submit("/permission");
  4580. expect(app.interaction.isActive()).toBe(true);
  4581. const rendered = app.interaction.current()?.render?.(100).join("\n") ?? "";
  4582. expect(rendered).toContain("╭─ Permission");
  4583. expect(rendered).toContain("Current · Auto");
  4584. expect(rendered).toContain("ASK");
  4585. expect(rendered).toContain("› AUTO");
  4586. expect(rendered).toContain("FULL");
  4587. expect(runtime.setPermissionMode).not.toHaveBeenCalled();
  4588. terminal.input?.("\u001b[B");
  4589. terminal.input?.("\r");
  4590. await vi.waitFor(() =>
  4591. expect(runtime.setPermissionMode).toHaveBeenCalledWith(
  4592. "bypassPermissions",
  4593. ),
  4594. );
  4595. expect(app.interaction.isActive()).toBe(false);
  4596. expect(app.tui.render(100).join("\n")).toContain("Full access");
  4597. await app.submit("/permission status");
  4598. expect(app.interaction.isActive()).toBe(false);
  4599. expect(
  4600. app.transcript
  4601. .snapshot()
  4602. .map((cell) => cell.content)
  4603. .join("\n"),
  4604. ).toContain("Permission mode: Full access.");
  4605. await app.stop();
  4606. });
  4607. it("opens the latest settled Plan as a read-only full snapshot", async () => {
  4608. const runtime = createRuntime();
  4609. vi.mocked(runtime.getLatestPlanReview).mockResolvedValue(
  4610. planReviewEventRequest("plan-review-settled"),
  4611. );
  4612. const app = createTuiApp({
  4613. runtime,
  4614. terminal: new FakeTerminal(),
  4615. version: "0.1.0",
  4616. workspaceDir: "/workspace",
  4617. });
  4618. app.start();
  4619. await app.ready;
  4620. await app.openSession("session-1");
  4621. await app.submit("/plan view");
  4622. expect(runtime.getLatestPlanReview).toHaveBeenCalledWith(
  4623. "mavis",
  4624. "session-1",
  4625. );
  4626. const rendered = app.interaction.current()?.render?.(100).join("\n") ?? "";
  4627. expect(rendered).toContain("Frozen plan");
  4628. expect(rendered).toContain("/history/session-1/artifacts/plan.md");
  4629. expect(rendered).not.toContain("Agree and start implementation");
  4630. app.interaction.current()?.handleInput?.("\u001b");
  4631. expect(app.interaction.isActive()).toBe(false);
  4632. await app.stop();
  4633. });
  4634. it("does not open a settled Plan after the active Session changes", async () => {
  4635. let resolveReview:
  4636. | ((request: TuiQuestionnaireRequest | undefined) => void)
  4637. | undefined;
  4638. const runtime = createRuntime();
  4639. vi.mocked(runtime.getLatestPlanReview).mockImplementation(
  4640. async () =>
  4641. await new Promise<TuiQuestionnaireRequest | undefined>((resolve) => {
  4642. resolveReview = resolve;
  4643. }),
  4644. );
  4645. const app = createTuiApp({
  4646. runtime,
  4647. terminal: new FakeTerminal(),
  4648. version: "0.1.0",
  4649. workspaceDir: "/workspace",
  4650. });
  4651. app.start();
  4652. await app.ready;
  4653. await app.openSession("session-1");
  4654. const viewing = app.submit("/plan view");
  4655. await vi.waitFor(() => expect(resolveReview).toBeTypeOf("function"));
  4656. await app.openSession("session-2");
  4657. resolveReview?.(planReviewEventRequest("stale-plan-review"));
  4658. await viewing;
  4659. expect(app.interaction.isActive()).toBe(false);
  4660. expect(app.tui.render(100).join("\n")).not.toContain("Frozen plan");
  4661. await app.stop();
  4662. });
  4663. it("blocks Plan entry but still allows Plan exit when the Runtime capability is disabled", async () => {
  4664. const runtime = createRuntime();
  4665. vi.mocked(runtime.getPlanModeCapabilities).mockResolvedValue({
  4666. entryEnabled: false,
  4667. });
  4668. const terminal = new FakeTerminal();
  4669. const app = createTuiApp({
  4670. runtime,
  4671. terminal,
  4672. version: "0.1.0",
  4673. workspaceDir: "/workspace",
  4674. });
  4675. app.start();
  4676. await app.ready;
  4677. await app.openSession("session-1");
  4678. terminal.input?.("\x1b[Z");
  4679. await app.submit("/plan on");
  4680. expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
  4681. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4682. vi.mocked(runtime.getSession).mockResolvedValue({
  4683. sessionId: "session-1",
  4684. workspace: "/workspace",
  4685. interactionMode: "plan",
  4686. });
  4687. await app.controller.refreshSessionMetadata("session-1");
  4688. terminal.input?.("\x1b[Z");
  4689. expect(app.tui.render(100).join("\n")).toContain("DEFAULT next");
  4690. await app.stop();
  4691. });
  4692. it("fails closed when the Runtime Plan capability cannot be loaded", async () => {
  4693. const runtime = createRuntime();
  4694. vi.mocked(runtime.getPlanModeCapabilities).mockRejectedValue(
  4695. new Error("Runtime unavailable"),
  4696. );
  4697. const terminal = new FakeTerminal();
  4698. const app = createTuiApp({
  4699. runtime,
  4700. terminal,
  4701. version: "0.1.0",
  4702. workspaceDir: "/workspace",
  4703. });
  4704. app.start();
  4705. await app.ready;
  4706. terminal.input?.("\x1b[Z");
  4707. await app.submit("/plan on");
  4708. expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
  4709. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4710. await app.stop();
  4711. });
  4712. it("submits the hidden Runtime engineering log command name as an ordinary prompt", async () => {
  4713. const terminal = new FakeTerminal();
  4714. const runtime = createRuntime();
  4715. const app = createTuiApp({
  4716. runtime,
  4717. terminal,
  4718. version: "0.1.0",
  4719. workspaceDir: "/workspace",
  4720. runtimeLogDirectory: "/home/dev/.minimax/v2/observability/logs",
  4721. });
  4722. await app.submit("/logs");
  4723. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4724. expect.objectContaining({ id: "session-1", content: "/logs" }),
  4725. expect.any(AbortSignal),
  4726. );
  4727. });
  4728. it("exposes sanitized checks and submits the hidden /config name as ordinary text", async () => {
  4729. const terminal = new FakeTerminal();
  4730. const runtime = createRuntime();
  4731. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  4732. {
  4733. requestId: "permission-1",
  4734. sessionId: "session-1",
  4735. toolName: "bash",
  4736. toolDescription: "Run tests",
  4737. },
  4738. ]);
  4739. const app = createTuiApp({
  4740. runtime,
  4741. terminal,
  4742. version: "0.1.0",
  4743. workspaceDir: "/workspace",
  4744. });
  4745. await app.submit("/doctor");
  4746. const doctorOutput = app.transcript.snapshot().at(-1)?.content ?? "";
  4747. expect(app.interaction.current()).toBeUndefined();
  4748. await app.submit("/config");
  4749. expect(app.interaction.current()).toBeUndefined();
  4750. await app.submit("/skills docs");
  4751. const skillsPanel = app.interaction.current();
  4752. const skillsOutput = skillsPanel?.render(80).join("\n") ?? "";
  4753. expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
  4754. skillsPanel?.handleInput?.("\x1b");
  4755. await app.submit("/mcp browser");
  4756. const mcpPanel = app.interaction.current();
  4757. const mcpOutput = mcpPanel?.render(80).join("\n") ?? "";
  4758. expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
  4759. mcpPanel?.handleInput?.("\x1b");
  4760. await app.submit("/permissions");
  4761. const output = app.transcript
  4762. .snapshot()
  4763. .map((cell) => cell.content)
  4764. .join("\n");
  4765. expect(runtime.getRuntimeDiagnostics).toHaveBeenCalledTimes(1);
  4766. expect(runtime.listSkills).toHaveBeenCalledWith("mavis", "docs");
  4767. expect(runtime.listMcpServers).toHaveBeenCalledWith("browser", "session-1");
  4768. expect(runtime.listPendingPermissions).toHaveBeenCalled();
  4769. expect(doctorOutput).toContain("Configuration check");
  4770. expect(doctorOutput).toContain("Status: Valid");
  4771. expect(doctorOutput).not.toContain("/doctor");
  4772. expect(output).toContain("Configuration check");
  4773. expect(output).not.toContain("Effective configuration");
  4774. expect(skillsOutput).toContain("Skills");
  4775. expect(skillsOutput).toContain("Built-in · 1");
  4776. expect(skillsOutput).toContain("Docs");
  4777. expect(skillsOutput).toContain("● available · builtin");
  4778. expect(mcpOutput).toContain("MCP servers");
  4779. expect(mcpOutput).toContain("browser");
  4780. expect(mcpOutput).toContain("◆ configured · stdio");
  4781. expect(output).toContain("bash · Run tests");
  4782. expect(output).not.toContain("TOKEN");
  4783. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  4784. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4785. expect.objectContaining({ id: "session-1", content: "/config" }),
  4786. expect.any(AbortSignal),
  4787. );
  4788. });
  4789. it("previews /feedback without uploading until Enter confirms the Runtime draft", async () => {
  4790. const terminal = new FakeTerminal();
  4791. terminal.rows = 30;
  4792. const runtime = createRuntime();
  4793. const app = createTuiApp({
  4794. runtime,
  4795. terminal,
  4796. version: "0.1.0",
  4797. workspaceDir: "/workspace",
  4798. });
  4799. app.start();
  4800. await app.ready;
  4801. await app.submit("/feedback Upload failed token=****");
  4802. expect(runtime.prepareFeedback).toHaveBeenCalledWith({
  4803. description: "Upload failed token=****",
  4804. });
  4805. expect(runtime.submitFeedback).not.toHaveBeenCalled();
  4806. expect(app.tui.hasOverlay()).toBe(false);
  4807. expect(app.interaction.isActive()).toBe(true);
  4808. const panel = app.interaction.current();
  4809. expect(panel?.render(80).join("\n")).toContain("Review feedback");
  4810. panel?.handleInput?.("d");
  4811. expect(panel?.render(80).join("\n")).toContain("Client mcode 0.1.0");
  4812. terminal.input?.("\r");
  4813. await vi.waitFor(() =>
  4814. expect(runtime.submitFeedback).toHaveBeenCalledWith(
  4815. "feedback-draft-1",
  4816. expect.objectContaining({ onPhase: expect.any(Function) }),
  4817. ),
  4818. );
  4819. expect(panel?.render(80).join("\n")).toContain("ticket-1");
  4820. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4821. terminal.input?.("\x1b");
  4822. expect(app.interaction.isActive()).toBe(false);
  4823. await app.stop();
  4824. });
  4825. it("cancels /feedback without uploading and keeps missing descriptions out of the Agent", async () => {
  4826. const terminal = new FakeTerminal();
  4827. const runtime = createRuntime();
  4828. const app = createTuiApp({
  4829. runtime,
  4830. terminal,
  4831. version: "0.1.0",
  4832. workspaceDir: "/workspace",
  4833. });
  4834. app.start();
  4835. await app.ready;
  4836. await app.submit("/feedback");
  4837. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  4838. kind: "final-summary",
  4839. content: "Usage: /feedback <message>",
  4840. });
  4841. expect(runtime.prepareFeedback).not.toHaveBeenCalled();
  4842. await app.submit("/feedback Cancel this report");
  4843. terminal.input?.("\x1b");
  4844. await vi.waitFor(() =>
  4845. expect(runtime.cancelFeedback).toHaveBeenCalledWith("feedback-draft-1"),
  4846. );
  4847. expect(runtime.submitFeedback).not.toHaveBeenCalled();
  4848. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4849. await app.stop();
  4850. });
  4851. it("keeps the status report local and submits the hidden /config name as text", async () => {
  4852. const terminal = new FakeTerminal();
  4853. terminal.rows = 24;
  4854. const runtime = createRuntime();
  4855. const app = createTuiApp({
  4856. runtime,
  4857. terminal,
  4858. version: "0.1.0",
  4859. workspaceDir: "/workspace",
  4860. });
  4861. app.start();
  4862. await app.ready;
  4863. const transcriptBeforeStatus = app.transcript.snapshot();
  4864. await app.submit("/status");
  4865. expect(app.tui.hasOverlay()).toBe(false);
  4866. expect(app.interaction.isActive()).toBe(true);
  4867. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  4868. const statusOutput = app.tui.render(80).join("\n");
  4869. expect(statusOutput).toContain("MCode status");
  4870. expect(statusOutput).toContain("Model");
  4871. expect(statusOutput).not.toContain("/status");
  4872. expect(statusOutput).toContain("/workspace");
  4873. expect(statusOutput).toMatch(/Branch:\s+Not a Git repository/u);
  4874. expect(statusOutput).toContain("Not applicable");
  4875. expect(statusOutput).toContain("Session");
  4876. expect(statusOutput).toContain("Permissions");
  4877. expect(statusOutput).toContain("Auto");
  4878. app.interaction.current()?.handleInput?.("\x1b");
  4879. expect(app.interaction.isActive()).toBe(false);
  4880. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  4881. await app.submit("/config");
  4882. expect(app.tui.hasOverlay()).toBe(false);
  4883. expect(app.interaction.isActive()).toBe(false);
  4884. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4885. expect.objectContaining({ id: "session-1", content: "/config" }),
  4886. expect.any(AbortSignal),
  4887. );
  4888. expect(runtime.getRuntimeDiagnostics).not.toHaveBeenCalled();
  4889. await app.stop();
  4890. });
  4891. it("commits the first frame immediately when the Pi renderer starts", async () => {
  4892. const terminal = new FakeTerminal();
  4893. const app = createTuiApp({
  4894. runtime: createRuntime(),
  4895. terminal,
  4896. version: "0.1.0",
  4897. workspaceDir: "/workspace",
  4898. });
  4899. let firstFrameCommitted = false;
  4900. void app.firstFrame.then(() => {
  4901. firstFrameCommitted = true;
  4902. });
  4903. app.start();
  4904. await app.firstFrame;
  4905. expect(terminal.started).toBe(true);
  4906. expect(firstFrameCommitted).toBe(true);
  4907. expect(terminal.writes.join("")).toContain("Tips for getting started");
  4908. await app.stop();
  4909. });
  4910. it("chooses the account region before routing login through the auth application", async () => {
  4911. const runtime = createRuntime();
  4912. const openedTargets: string[] = [];
  4913. const logoutUrl =
  4914. "https://agent.minimax.io/auth/logout?logout_redirect_uri=https%3A%2F%2Fagent.minimax.io";
  4915. let authenticated = false;
  4916. vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
  4917. authenticated
  4918. ? {
  4919. status: "ready",
  4920. defaultModel: "minimax/MiniMax-M2.7",
  4921. providerId: "minimax",
  4922. modelId: "MiniMax-M2.7",
  4923. authMode: "managed-login",
  4924. managedTokenPresent: true,
  4925. warnings: [],
  4926. }
  4927. : {
  4928. status: "needs-login",
  4929. authMode: "managed-login",
  4930. managedTokenPresent: false,
  4931. warnings: [],
  4932. },
  4933. );
  4934. const auth = {
  4935. login: vi.fn(
  4936. async (
  4937. onProgress?: (progress: McodeAuthProgress) => void,
  4938. _region?: "cn" | "en",
  4939. ) => {
  4940. authenticated = true;
  4941. onProgress?.({
  4942. state: "device-authorization",
  4943. userCode: "ABCD-EFGH",
  4944. verificationUri: "https://account.example.test/device",
  4945. expiresInSec: 300,
  4946. });
  4947. return {
  4948. state: "authenticated" as const,
  4949. message:
  4950. _region === "en"
  4951. ? "Signed in with MiniMax Global. Restart MCode to use this account region."
  4952. : "Signed in with MiniMax.",
  4953. };
  4954. },
  4955. ),
  4956. logout: vi.fn(async () => {
  4957. authenticated = false;
  4958. return {
  4959. state: "signed-out" as const,
  4960. message: "Signed out of MiniMax.",
  4961. logoutUrl,
  4962. };
  4963. }),
  4964. };
  4965. const notifyAuthContextChanged = vi.fn(async () => {
  4966. throw new Error("Hook lifecycle cleanup failed");
  4967. });
  4968. const app = createTuiApp({
  4969. runtime,
  4970. auth,
  4971. terminal: new FakeTerminal(),
  4972. version: "0.1.0",
  4973. workspaceDir: "/workspace",
  4974. openExternalTarget: async (target) => {
  4975. openedTargets.push(target);
  4976. throw new Error("no desktop session");
  4977. },
  4978. notifyAuthContextChanged,
  4979. });
  4980. app.start();
  4981. await app.ready;
  4982. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
  4983. await app.submit("/login");
  4984. expect(auth.login).not.toHaveBeenCalled();
  4985. expect(app.interaction.render(80).join("\n")).toContain("China (CN)");
  4986. expect(app.interaction.render(80).join("\n")).toContain("Global");
  4987. app.interaction.current()?.handleInput("\u001b[B");
  4988. app.interaction.current()?.handleInput("\r");
  4989. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  4990. await vi.waitFor(() =>
  4991. expect(app.controller.snapshot().account?.managedTokenPresent).toBe(true),
  4992. );
  4993. expect(app.getSurface()).toBe("conversation");
  4994. expect(app.tui.render(80).join("\n")).not.toContain("Sign in with /login");
  4995. expect(app.tui.render(80).join("\n")).not.toContain("Login required");
  4996. await app.submit("/logout");
  4997. await vi.waitFor(() =>
  4998. expect(app.controller.snapshot().account?.managedTokenPresent).toBe(
  4999. false,
  5000. ),
  5001. );
  5002. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
  5003. expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "en");
  5004. expect(openedTargets).toEqual([
  5005. "https://account.example.test/device?client_surface=tui&download_source=mcode-internal",
  5006. logoutUrl,
  5007. ]);
  5008. await vi.waitFor(() =>
  5009. expect(app.transcript.snapshot()).toEqual(
  5010. expect.arrayContaining([
  5011. expect.objectContaining({
  5012. kind: "warning",
  5013. content:
  5014. "Couldn't open the default browser. Open the authorization URL above manually.",
  5015. }),
  5016. expect.objectContaining({
  5017. kind: "warning",
  5018. content:
  5019. "Couldn't open the default browser. Open the sign-out URL above manually.",
  5020. }),
  5021. ]),
  5022. ),
  5023. );
  5024. expect(app.transcript.snapshot().slice(-6)).toMatchObject([
  5025. {
  5026. kind: "final-summary",
  5027. content:
  5028. "Complete MiniMax login in your browser:\nhttps://account.example.test/device?client_surface=tui&download_source=mcode-internal\nCode: ABCD-EFGH",
  5029. },
  5030. {
  5031. kind: "warning",
  5032. content:
  5033. "Couldn't open the default browser. Open the authorization URL above manually.",
  5034. },
  5035. {
  5036. kind: "final-summary",
  5037. content:
  5038. "Signed in with MiniMax Global. Restart MCode to use this account region.",
  5039. },
  5040. {
  5041. kind: "final-summary",
  5042. content: "Signed out of MiniMax.",
  5043. },
  5044. {
  5045. kind: "final-summary",
  5046. content: `Finish signing out in your browser:\n${logoutUrl}`,
  5047. },
  5048. {
  5049. kind: "warning",
  5050. content:
  5051. "Couldn't open the default browser. Open the sign-out URL above manually.",
  5052. },
  5053. ]);
  5054. expect(auth.login).toHaveBeenCalledOnce();
  5055. expect(auth.logout).toHaveBeenCalledOnce();
  5056. expect(notifyAuthContextChanged.mock.calls).toEqual([
  5057. ["authenticated"],
  5058. ["logged_out"],
  5059. ]);
  5060. expect(
  5061. app.transcript
  5062. .snapshot()
  5063. .map((cell) => cell.content)
  5064. .join("\n"),
  5065. ).not.toContain("Sign-in wasn't completed");
  5066. expect(
  5067. app.transcript
  5068. .snapshot()
  5069. .map((cell) => cell.content)
  5070. .join("\n"),
  5071. ).not.toContain("Couldn't sign out");
  5072. expect(runtime.sendMessage).not.toHaveBeenCalled();
  5073. await app.stop();
  5074. });
  5075. it("clears Runtime auth context when the shared account is already signed out", async () => {
  5076. const notifyAuthContextChanged = vi.fn(async () => undefined);
  5077. const logoutUrl =
  5078. "https://agent.minimax.cn/auth/logout?logout_redirect_uri=https%3A%2F%2Fagent.minimax.cn";
  5079. const openExternalTarget = vi.fn(() => new Promise<void>(() => {}));
  5080. const app = createTuiApp({
  5081. runtime: createRuntime(),
  5082. auth: {
  5083. login: vi.fn(),
  5084. logout: vi.fn(async () => ({
  5085. state: "already-signed-out" as const,
  5086. message: "Already signed out of MiniMax.",
  5087. logoutUrl,
  5088. })),
  5089. },
  5090. terminal: new FakeTerminal(),
  5091. version: "0.1.0",
  5092. workspaceDir: "/workspace",
  5093. notifyAuthContextChanged,
  5094. openExternalTarget,
  5095. });
  5096. app.start();
  5097. await app.ready;
  5098. await app.submit("/logout");
  5099. expect(notifyAuthContextChanged).toHaveBeenCalledOnce();
  5100. expect(notifyAuthContextChanged).toHaveBeenCalledWith("logged_out");
  5101. expect(openExternalTarget).toHaveBeenCalledWith(logoutUrl);
  5102. expect(app.transcript.snapshot()).toEqual(
  5103. expect.arrayContaining([
  5104. expect.objectContaining({
  5105. content: `Finish signing out in your browser:\n${logoutUrl}`,
  5106. }),
  5107. ]),
  5108. );
  5109. await app.stop();
  5110. });
  5111. it("refreshes Runtime auth context when login renews an existing account", async () => {
  5112. const runtime = createRuntime();
  5113. let authenticated = false;
  5114. vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
  5115. authenticated
  5116. ? {
  5117. status: "ready",
  5118. defaultModel: "minimax/MiniMax-M2.7",
  5119. providerId: "minimax",
  5120. modelId: "MiniMax-M2.7",
  5121. authMode: "managed-login",
  5122. managedTokenPresent: true,
  5123. warnings: [],
  5124. }
  5125. : {
  5126. status: "needs-login",
  5127. authMode: "managed-login",
  5128. managedTokenPresent: false,
  5129. warnings: [],
  5130. },
  5131. );
  5132. const notifyAuthContextChanged = vi.fn(async () => undefined);
  5133. const auth = {
  5134. login: vi.fn(async () => {
  5135. authenticated = true;
  5136. return {
  5137. state: "already-authenticated" as const,
  5138. message: "Already signed in with MiniMax.",
  5139. };
  5140. }),
  5141. logout: vi.fn(async () => ({
  5142. state: "signed-out" as const,
  5143. message: "Signed out of MiniMax.",
  5144. })),
  5145. };
  5146. const app = createTuiApp({
  5147. runtime,
  5148. auth,
  5149. notifyAuthContextChanged,
  5150. terminal: new FakeTerminal(),
  5151. version: "0.1.0",
  5152. workspaceDir: "/workspace",
  5153. });
  5154. app.start();
  5155. await app.ready;
  5156. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
  5157. await app.submit("/login");
  5158. app.interaction.current()?.handleInput("\u001b[B");
  5159. app.interaction.current()?.handleInput("\r");
  5160. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  5161. expect(notifyAuthContextChanged).toHaveBeenCalledOnce();
  5162. expect(notifyAuthContextChanged).toHaveBeenCalledWith("authenticated");
  5163. await vi.waitFor(() =>
  5164. expect(app.controller.snapshot().account?.managedTokenPresent).toBe(true),
  5165. );
  5166. expect(app.getSurface()).toBe("conversation");
  5167. expect(app.tui.render(80).join("\n")).not.toContain("Sign in with /login");
  5168. expect(app.tui.render(80).join("\n")).not.toContain("Login required");
  5169. await app.stop();
  5170. });
  5171. it("exits immediately through /quit without aborting the shared Runtime turn", async () => {
  5172. const terminal = new FakeTerminal();
  5173. const runtime = createRuntime();
  5174. const abortSession = vi.spyOn(runtime, "abortSession");
  5175. const app = createTuiApp({
  5176. runtime,
  5177. terminal,
  5178. version: "0.1.0",
  5179. workspaceDir: "/workspace",
  5180. });
  5181. app.start();
  5182. await app.ready;
  5183. await app.submit("/quit");
  5184. await app.stopped;
  5185. expect(terminal.stopped).toBe(true);
  5186. expect(abortSession).not.toHaveBeenCalled();
  5187. });
  5188. it("does not restore /quit after reopening the exited Session", async () => {
  5189. const dataDir = await mkdtemp(join(tmpdir(), "mcode-quit-draft-"));
  5190. try {
  5191. const first = createTuiApp({
  5192. runtime: createRuntime(),
  5193. terminal: new FakeTerminal(),
  5194. version: "0.1.0",
  5195. dataDir,
  5196. workspaceDir: "/workspace",
  5197. });
  5198. await first.ready;
  5199. await first.openSession("session-1");
  5200. first.editor.setText("/quit");
  5201. first.editor.handleInput("\r");
  5202. await first.stopped;
  5203. const restored = createTuiApp({
  5204. runtime: createRuntime(),
  5205. terminal: new FakeTerminal(),
  5206. version: "0.1.0",
  5207. dataDir,
  5208. workspaceDir: "/workspace",
  5209. });
  5210. await restored.ready;
  5211. await restored.openSession("session-1");
  5212. expect(restored.editor.getText()).toBe("");
  5213. await restored.stop();
  5214. } finally {
  5215. await rm(dataDir, { recursive: true, force: true });
  5216. }
  5217. });
  5218. it("keeps warning status details visible until the local panel closes", async () => {
  5219. const terminal = new FakeTerminal();
  5220. terminal.rows = 40;
  5221. const runtime = createRuntime();
  5222. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  5223. status: "warning",
  5224. defaultModel: "minimax/MiniMax-M2.7",
  5225. providerId: "minimax",
  5226. modelId: "MiniMax-M2.7",
  5227. authMode: "managed-login",
  5228. managedTokenPresent: true,
  5229. warnings: ["Desktop login should be refreshed soon."],
  5230. });
  5231. const app = createTuiApp({
  5232. runtime,
  5233. terminal,
  5234. version: "0.1.0",
  5235. workspaceDir: "/workspace",
  5236. });
  5237. app.start();
  5238. await app.ready;
  5239. const transcriptBeforeStatus = app.transcript.snapshot();
  5240. await app.submit("/status");
  5241. const rendered = app.tui.render(80).join("\n");
  5242. expect(app.interaction.current()).toBeDefined();
  5243. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  5244. expect(rendered).toContain("Needs attention");
  5245. expect(rendered).toContain("Connected with warnings");
  5246. expect(rendered).toContain("Model");
  5247. expect(rendered).toContain("Desktop login should be refreshed");
  5248. expect(rendered).toContain("soon.");
  5249. app.interaction.current()?.handleInput?.("\x1b");
  5250. expect(app.interaction.current()).toBeUndefined();
  5251. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  5252. expect(app.tui.render(80).join("\n")).not.toContain(
  5253. "Desktop login should be refreshed",
  5254. );
  5255. await app.stop();
  5256. });
  5257. it("reports doctor failures and submits the hidden /config name as text", async () => {
  5258. const runtime = createRuntime();
  5259. vi.mocked(runtime.getRuntimeDiagnostics).mockRejectedValue(
  5260. new Error("Diagnostics unavailable"),
  5261. );
  5262. const app = createTuiApp({
  5263. runtime,
  5264. terminal: new FakeTerminal(),
  5265. version: "0.1.0",
  5266. workspaceDir: "/workspace",
  5267. });
  5268. await app.submit("/doctor");
  5269. expect(app.tui.hasOverlay()).toBe(false);
  5270. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  5271. kind: "error",
  5272. content:
  5273. "Couldn't load configuration check: Diagnostics unavailable. Retry.",
  5274. });
  5275. await app.submit("/config");
  5276. expect(app.tui.hasOverlay()).toBe(false);
  5277. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5278. expect.objectContaining({ id: "session-1", content: "/config" }),
  5279. expect.any(AbortSignal),
  5280. );
  5281. expect(runtime.getRuntimeDiagnostics).toHaveBeenCalledTimes(1);
  5282. });
  5283. it("lets an async Session card replace a local status panel", async () => {
  5284. const terminal = new FakeTerminal();
  5285. const runtime = createRuntime();
  5286. let resolveSessionPage:
  5287. | ((page: {
  5288. sessions: Array<{
  5289. sessionId: string;
  5290. title: string;
  5291. workspaceDir: string;
  5292. updatedAt: number;
  5293. }>;
  5294. hasMore: boolean;
  5295. }) => void)
  5296. | undefined;
  5297. vi.mocked(runtime.listSessionPage).mockImplementationOnce(
  5298. async () =>
  5299. await new Promise((resolve) => {
  5300. resolveSessionPage = resolve;
  5301. }),
  5302. );
  5303. const app = createTuiApp({
  5304. runtime,
  5305. terminal,
  5306. version: "0.1.0",
  5307. workspaceDir: "/workspace",
  5308. });
  5309. await app.ready;
  5310. const transcriptBeforeStatus = app.transcript.snapshot();
  5311. const sessionCard = app.submit("/sessions");
  5312. await vi.waitFor(() =>
  5313. expect(runtime.listSessionPage).toHaveBeenCalledOnce(),
  5314. );
  5315. await app.submit("/status");
  5316. expect(app.tui.hasOverlay()).toBe(false);
  5317. expect(app.interaction.isActive()).toBe(true);
  5318. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  5319. expect(app.tui.render(80).join("\n")).toContain("MCode status");
  5320. resolveSessionPage?.({
  5321. sessions: [
  5322. {
  5323. sessionId: "session-race",
  5324. title: "Session opened after status",
  5325. workspaceDir: "/workspace",
  5326. updatedAt: Date.now(),
  5327. },
  5328. ],
  5329. hasMore: false,
  5330. });
  5331. await sessionCard;
  5332. expect(app.tui.hasOverlay()).toBe(false);
  5333. expect(app.interaction.isActive()).toBe(true);
  5334. app.interaction.current()?.handleInput?.("\x03");
  5335. expect(runtime.getSession).not.toHaveBeenCalled();
  5336. expect(app.interaction.isActive()).toBe(false);
  5337. expect(app.tui.hasOverlay()).toBe(false);
  5338. await app.stop();
  5339. });
  5340. it("keeps unsupported standalone MCP inspection concise and recoverable", async () => {
  5341. const runtime = createRuntime();
  5342. vi.mocked(runtime.listMcpServers).mockRejectedValue(
  5343. Object.assign(new Error("DesktopService implementation detail"), {
  5344. status: 501,
  5345. code: "NOT_IMPLEMENTED",
  5346. }),
  5347. );
  5348. const app = createTuiApp({
  5349. runtime,
  5350. terminal: new FakeTerminal(),
  5351. version: "0.1.0",
  5352. workspaceDir: "/workspace",
  5353. });
  5354. await app.submit("/mcp");
  5355. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  5356. kind: "warning",
  5357. content:
  5358. "MCP status is not available in this build. Configured MCP tools remain available.",
  5359. });
  5360. });
  5361. it("registers enabled Skills as discoverable slash commands without shadowing built-ins", async () => {
  5362. const terminal = new FakeTerminal();
  5363. const runtime = createRuntime();
  5364. vi.mocked(runtime.listSkills).mockResolvedValue({
  5365. skills: [
  5366. {
  5367. name: "docs",
  5368. displayName: "Docs",
  5369. description: "Read project docs",
  5370. enabled: true,
  5371. sourceKind: "builtin",
  5372. },
  5373. {
  5374. name: "disabled-skill",
  5375. enabled: false,
  5376. },
  5377. {
  5378. name: "help",
  5379. enabled: true,
  5380. },
  5381. ...Array.from({ length: 14 }, (_, index) => ({
  5382. name: `skill-${index}`,
  5383. description: `Generated skill ${index}`,
  5384. enabled: true,
  5385. })),
  5386. ],
  5387. hasMore: false,
  5388. });
  5389. const app = createTuiApp({
  5390. runtime,
  5391. terminal,
  5392. version: "0.1.0",
  5393. workspaceDir: "/workspace",
  5394. });
  5395. app.start();
  5396. await app.ready;
  5397. app.editor.setText("/docs summarize this repository");
  5398. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5399. "Skill · instructions · Enter invoke",
  5400. );
  5401. app.editor.setText("/context");
  5402. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5403. "Command · Enter run",
  5404. );
  5405. app.editor.setText("/context explain this repository");
  5406. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5407. "Prompt · Enter send",
  5408. );
  5409. app.editor.setText("/stop");
  5410. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5411. "Command · Enter run",
  5412. );
  5413. app.editor.setText("/config");
  5414. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5415. "Prompt · Enter send",
  5416. );
  5417. app.editor.setText("");
  5418. await app.submit("/help");
  5419. expect(app.transcript.snapshot()).toEqual([]);
  5420. expect(app.tui.hasOverlay()).toBe(false);
  5421. expect(app.interaction.isActive()).toBe(true);
  5422. for (const character of "docs") terminal.input?.(character);
  5423. terminal.input?.("\r");
  5424. expect(app.tui.hasOverlay()).toBe(false);
  5425. expect(app.interaction.isActive()).toBe(false);
  5426. expect(app.editor.getText()).toBe("");
  5427. await app.submit("/docs summarize this repository");
  5428. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5429. expect.objectContaining({
  5430. id: "session-1",
  5431. content: "/docs summarize this repository",
  5432. }),
  5433. expect.any(AbortSignal),
  5434. );
  5435. vi.mocked(runtime.sendMessage).mockClear();
  5436. await app.submit("/disabled-skill");
  5437. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5438. expect.objectContaining({ id: "session-1", content: "/disabled-skill" }),
  5439. expect.any(AbortSignal),
  5440. );
  5441. await app.stop();
  5442. });
  5443. it("deduplicates configured Skills case-insensitively and reserves built-in names", async () => {
  5444. const terminal = new FakeTerminal();
  5445. const runtime = createRuntime();
  5446. vi.mocked(runtime.listSkills).mockResolvedValue({
  5447. skills: [
  5448. {
  5449. name: "HELP",
  5450. description: "A Skill that must not shadow /help",
  5451. enabled: true,
  5452. },
  5453. {
  5454. name: "Docs",
  5455. description: "Read project docs",
  5456. enabled: true,
  5457. },
  5458. {
  5459. name: "docs",
  5460. description: "Duplicate project docs command",
  5461. enabled: true,
  5462. },
  5463. ],
  5464. hasMore: false,
  5465. });
  5466. const app = createTuiApp({
  5467. runtime,
  5468. terminal,
  5469. version: "0.1.0",
  5470. workspaceDir: "/workspace",
  5471. });
  5472. app.start();
  5473. await app.ready;
  5474. await app.submit("/help");
  5475. const helpPanel = app.interaction.current();
  5476. expect(helpPanel).toBeDefined();
  5477. helpPanel?.handleInput?.("\x1b");
  5478. await app.submit("/help [arguments]");
  5479. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5480. expect.objectContaining({
  5481. id: "session-1",
  5482. content: "/help [arguments]",
  5483. }),
  5484. expect.any(AbortSignal),
  5485. );
  5486. vi.mocked(runtime.sendMessage).mockClear();
  5487. await app.submit("/docs explain this repository");
  5488. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5489. expect.objectContaining({
  5490. id: "session-1",
  5491. content: "/docs explain this repository",
  5492. }),
  5493. expect.any(AbortSignal),
  5494. );
  5495. await app.stop();
  5496. });
  5497. it("uses public Runtime owners for Session inspection commands", async () => {
  5498. const terminal = new FakeTerminal();
  5499. terminal.rows = 40;
  5500. const runtime = createRuntime();
  5501. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  5502. status: "ready",
  5503. defaultModel: "minimax/MiniMax-M3",
  5504. providerId: "minimax-cn-coding-plan",
  5505. authMode: "managed-login",
  5506. managedTokenPresent: true,
  5507. modelSource: "token-plan",
  5508. tokenPlanQuotaState: "available",
  5509. tokenPlanSummary: { tier: "Ultra Plan", creditBalance: "0" },
  5510. tokenPlanQuota: {
  5511. fiveHour: { remainingPercent: 100, unlimited: false },
  5512. weekly: { remainingPercent: 99, unlimited: false },
  5513. video: { remainingCount: 5, totalCount: 5, unlimited: false },
  5514. },
  5515. warnings: [],
  5516. });
  5517. const app = createTuiApp({
  5518. runtime,
  5519. terminal,
  5520. version: "0.1.0",
  5521. workspaceDir: "/workspace",
  5522. });
  5523. await app.submit("Create a session");
  5524. vi.mocked(runtime.sendMessage).mockClear();
  5525. vi.mocked(runtime.getSessionUsage).mockClear();
  5526. vi.mocked(runtime.getContextSnapshot).mockResolvedValueOnce({
  5527. status: "live",
  5528. contextUsage: {
  5529. contextWindowTokens: 10_000,
  5530. usedTokens: 3_000,
  5531. totalCountSource: "PROVIDER_USAGE_ANCHORED",
  5532. components: [],
  5533. },
  5534. });
  5535. const transcriptBeforeUsage = app.transcript.snapshot();
  5536. await app.submit("/usage");
  5537. const usageOutput = app.tui.render(80).join("\n");
  5538. expect(app.interaction.current()).toBeDefined();
  5539. expect(app.transcript.snapshot()).toEqual(transcriptBeforeUsage);
  5540. expect(usageOutput).toContain("Usage");
  5541. expect(usageOutput).toContain("120 total");
  5542. expect(usageOutput).toContain("30% used · 70% free");
  5543. expect(usageOutput).toContain("Ultra Plan");
  5544. expect(usageOutput).toContain("100% left");
  5545. app.interaction.current()?.handleInput?.("\x1b");
  5546. expect(app.interaction.current()).toBeUndefined();
  5547. expect(app.transcript.snapshot()).toEqual(transcriptBeforeUsage);
  5548. await app.submit("/compact keep test evidence");
  5549. expect(runtime.getSessionUsage).toHaveBeenCalledWith("session-1");
  5550. expect(runtime.getContextSnapshot).toHaveBeenCalledWith("session-1");
  5551. expect(runtime.getAccountStatus).toHaveBeenCalledWith("session-1", {
  5552. includeMembership: true,
  5553. forceRefresh: true,
  5554. });
  5555. expect(runtime.requestCompaction).toHaveBeenCalledWith(
  5556. "session-1",
  5557. "mavis",
  5558. "keep test evidence",
  5559. );
  5560. expect(runtime.sendMessage).not.toHaveBeenCalled();
  5561. const output = app.transcript
  5562. .snapshot()
  5563. .map((cell) => cell.content)
  5564. .join("\n");
  5565. expect(output).not.toContain("Session usage");
  5566. expect(output).not.toMatch(
  5567. /Turns|Total tokens|Cost|Reasoning|Cache|Runtime|source|compaction|snapshot/i,
  5568. );
  5569. expect(output).not.toContain("Compaction completed");
  5570. expect(output).not.toContain("4,000 → 1,200 tokens");
  5571. expect(output).not.toContain("compact-1");
  5572. });
  5573. it("shows compaction as live activity until the Runtime request settles", async () => {
  5574. const runtime = createRuntime();
  5575. let resolveCompaction:
  5576. | ((result: {
  5577. success: true;
  5578. sessionId: string;
  5579. compactionId: string;
  5580. }) => void)
  5581. | undefined;
  5582. vi.mocked(runtime.requestCompaction).mockImplementationOnce(
  5583. async () =>
  5584. await new Promise((resolve) => {
  5585. resolveCompaction = resolve;
  5586. }),
  5587. );
  5588. const app = createTuiApp({
  5589. runtime,
  5590. terminal: new FakeTerminal(),
  5591. version: "0.1.0",
  5592. workspaceDir: "/workspace",
  5593. });
  5594. await app.submit("Create a session");
  5595. const pending = app.submit("/compact keep decisions");
  5596. await vi.waitFor(() =>
  5597. expect(app.tui.render(80).join("\n")).toContain("Compacting context"),
  5598. );
  5599. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  5600. resolveCompaction?.({
  5601. success: true,
  5602. sessionId: "session-1",
  5603. compactionId: "compact-1",
  5604. });
  5605. await pending;
  5606. expect(app.tui.render(80).join("\n")).not.toContain("Compacting context");
  5607. });
  5608. it("treats Runtime NOTHING_TO_COMPACT as a recoverable Session state", async () => {
  5609. const runtime = createRuntime();
  5610. vi.mocked(runtime.requestCompaction).mockRejectedValue(
  5611. Object.assign(new Error("HTTP 400 implementation detail"), {
  5612. status: 400,
  5613. code: "NOTHING_TO_COMPACT",
  5614. }),
  5615. );
  5616. const app = createTuiApp({
  5617. runtime,
  5618. terminal: new FakeTerminal(),
  5619. version: "0.1.0",
  5620. workspaceDir: "/workspace",
  5621. });
  5622. await app.submit("Create a session");
  5623. await app.submit("/compact");
  5624. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  5625. kind: "final-summary",
  5626. content: "No compaction is needed for this conversation yet.",
  5627. });
  5628. });
  5629. it("shows account usage before a Session exists and keeps Session-only inspection recoverable", async () => {
  5630. const runtime = createRuntime();
  5631. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  5632. status: "ready",
  5633. authMode: "byok",
  5634. managedTokenPresent: false,
  5635. modelSource: "byok",
  5636. tokenPlanQuotaState: "available",
  5637. tokenPlanSummary: { tier: "Pro Plan" },
  5638. tokenPlanQuota: {
  5639. fiveHour: { remainingPercent: 75, unlimited: false },
  5640. weekly: { remainingPercent: 50, unlimited: false },
  5641. },
  5642. warnings: [],
  5643. });
  5644. const terminal = new FakeTerminal();
  5645. terminal.rows = 40;
  5646. const app = createTuiApp({
  5647. runtime,
  5648. terminal,
  5649. version: "0.1.0",
  5650. workspaceDir: "/workspace",
  5651. });
  5652. await app.submit("/usage");
  5653. const usageOutput = app.tui.render(80).join("\n");
  5654. expect(app.interaction.current()).toBeDefined();
  5655. expect(app.transcript.snapshot()).toEqual([]);
  5656. expect(usageOutput).toContain("Usage");
  5657. expect(usageOutput).toContain("Account only");
  5658. expect(usageOutput).toContain("Pro Plan");
  5659. expect(usageOutput).toContain("75% left");
  5660. app.interaction.current()?.handleInput?.("\x1b");
  5661. expect(app.interaction.current()).toBeUndefined();
  5662. expect(app.transcript.snapshot()).toEqual([]);
  5663. await app.submit("/compact");
  5664. expect(runtime.getSessionUsage).not.toHaveBeenCalled();
  5665. expect(runtime.getContextSnapshot).not.toHaveBeenCalled();
  5666. expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
  5667. includeMembership: true,
  5668. forceRefresh: true,
  5669. });
  5670. expect(app.transcript.snapshot()).toEqual([]);
  5671. expect(app.tui.render(80).join("\n")).toContain(
  5672. "Start or resume a Session before compacting it.",
  5673. );
  5674. });
  5675. it("keeps prompt history and long bracketed paste intact in the Composer", async () => {
  5676. const terminal = new FakeTerminal();
  5677. const runtime = createRuntime();
  5678. const app = createTuiApp({
  5679. runtime,
  5680. terminal,
  5681. version: "0.1.0",
  5682. workspaceDir: "/workspace",
  5683. });
  5684. app.start();
  5685. await app.ready;
  5686. terminal.input?.("first prompt");
  5687. terminal.input?.("\r");
  5688. await vi.waitFor(() =>
  5689. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  5690. );
  5691. terminal.input?.("second prompt");
  5692. terminal.input?.("\r");
  5693. await vi.waitFor(() =>
  5694. expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
  5695. );
  5696. terminal.input?.("\x1b[A");
  5697. expect(app.editor.getText()).toBe("second prompt");
  5698. terminal.input?.("\x1b[A");
  5699. expect(app.editor.getText()).toBe("first prompt");
  5700. terminal.input?.("\x1b[B");
  5701. expect(app.editor.getText()).toBe("second prompt");
  5702. app.editor.setText("");
  5703. const pasted = `Explain this payload:\n${"x".repeat(1_200)}`;
  5704. terminal.input?.(`\x1b[200~${pasted}\x1b[201~`);
  5705. expect(app.editor.getText()).toContain("[paste #");
  5706. expect(app.editor.getExpandedText()).toBe(pasted);
  5707. terminal.input?.("\r");
  5708. await vi.waitFor(() =>
  5709. expect(runtime.sendMessage).toHaveBeenCalledTimes(3),
  5710. );
  5711. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  5712. expect.objectContaining({ id: "session-1", content: pasted }),
  5713. expect.any(AbortSignal),
  5714. );
  5715. await app.stop();
  5716. });
  5717. it("trusts bracketed paste and submits dense typed input without a false newline", async () => {
  5718. const terminal = new FakeTerminal();
  5719. Object.defineProperty(terminal, "capabilities", {
  5720. value: {
  5721. terminalId: "unknown",
  5722. platform: "linux",
  5723. isTTY: true,
  5724. transport: "local",
  5725. multiplexer: "none",
  5726. color: true,
  5727. colorLevel: 3,
  5728. } satisfies TerminalCapabilities,
  5729. });
  5730. const runtime = createRuntime();
  5731. const app = createTuiApp({
  5732. runtime,
  5733. terminal,
  5734. version: "0.1.0",
  5735. workspaceDir: "/workspace",
  5736. });
  5737. app.start();
  5738. await app.ready;
  5739. for (const character of "abcdefgh") terminal.input?.(character);
  5740. terminal.input?.("\r");
  5741. await vi.waitFor(() =>
  5742. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  5743. );
  5744. expect(app.editor.getText()).toBe("");
  5745. await app.stop();
  5746. });
  5747. it("projects an otty image paste as an inline editor placeholder", async () => {
  5748. const terminal = new FakeTerminal();
  5749. const resolveAttachment = vi.fn(async () => ({
  5750. type: "image" as const,
  5751. filePath: "/tmp/otty-paste/image-123.png",
  5752. fileName: "image-123.png",
  5753. mimeType: "image/png",
  5754. sizeBytes: 1_024,
  5755. }));
  5756. const app = createTuiApp({
  5757. runtime: createRuntime(),
  5758. terminal,
  5759. version: "0.1.0",
  5760. workspaceDir: "/workspace",
  5761. resolveAttachment,
  5762. });
  5763. app.start();
  5764. await app.ready;
  5765. terminal.input?.("\x1b[200~/tmp/otty-paste/image-123.png\x1b[201~");
  5766. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
  5767. const rendered = app.tui.render(80).join("\n");
  5768. expect(app.editor.getText()).toBe("[Image #1] ");
  5769. expect(rendered).toContain("[Image #1]");
  5770. expect(rendered).not.toContain("/tmp/otty-paste/");
  5771. await app.stop();
  5772. });
  5773. it.each(["regular", "fullscreen"] as const)(
  5774. "keeps image preview controls separate from Enter submission in %s mode",
  5775. async (tuiMode) => {
  5776. const terminal = new FakeTerminal();
  5777. terminal.rows = 40;
  5778. const runtime = createRuntime();
  5779. const app = createTuiApp({
  5780. runtime,
  5781. terminal,
  5782. tuiMode,
  5783. version: "0.1.0",
  5784. workspaceDir: "/workspace",
  5785. resolveAttachment: async () => ({
  5786. type: "image",
  5787. filePath: "/tmp/image-preview-missing.png",
  5788. fileName: "preview.png",
  5789. mimeType: "image/png",
  5790. sizeBytes: 32768,
  5791. }),
  5792. });
  5793. app.start();
  5794. await app.ready;
  5795. terminal.input?.("\x1b[200~/tmp/image-preview-missing.png\x1b[201~");
  5796. await vi.waitFor(() =>
  5797. expect(app.editor.getAttachmentPreview()?.id).toBe(
  5798. "/tmp/image-preview-missing.png",
  5799. ),
  5800. );
  5801. expect(app.editor.getText()).toBe("[Image #1] ");
  5802. expect(app.tui.render(80).join("\n")).toContain("preview.png");
  5803. expect(app.tui.render(80).join("\n")).toContain("32 KB");
  5804. expect(app.tui.render(80).join("\n")).not.toMatch(/Option\+I|Alt\+I/);
  5805. expect(runtime.sendMessage).not.toHaveBeenCalled();
  5806. terminal.input?.("\x1b");
  5807. expect(app.editor.getAttachmentPreview()).toBeUndefined();
  5808. terminal.input?.("\x1b[D");
  5809. expect(app.editor.getAttachmentPreview()?.id).toBe(
  5810. "/tmp/image-preview-missing.png",
  5811. );
  5812. terminal.input?.("\r");
  5813. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalled());
  5814. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5815. expect.objectContaining({
  5816. content: "",
  5817. attachments: [
  5818. expect.objectContaining({
  5819. local: { filePath: "/tmp/image-preview-missing.png" },
  5820. }),
  5821. ],
  5822. }),
  5823. expect.any(AbortSignal),
  5824. );
  5825. expect(app.editor.getAttachmentPreview()).toBeUndefined();
  5826. await app.stop();
  5827. },
  5828. );
  5829. it("projects a pasted absolute WeChat image path as a short inline placeholder", async () => {
  5830. const terminal = new FakeTerminal();
  5831. const runtime = createRuntime();
  5832. const wechatImagePath =
  5833. "D:\\Yingyong\\social\\wechat\\xwechat_files\\wxid_demo\\temp\\RWTemp\\2026-08\\3336519cd4d5351f4bc5a5a68c7fea75.png";
  5834. const resolveAttachment = vi.fn(async () => ({
  5835. type: "image" as const,
  5836. filePath: wechatImagePath,
  5837. fileName: "3336519cd4d5351f4bc5a5a68c7fea75.png",
  5838. mimeType: "image/png",
  5839. sizeBytes: 1_024,
  5840. }));
  5841. const app = createTuiApp({
  5842. runtime,
  5843. terminal,
  5844. version: "0.1.0",
  5845. workspaceDir: "D:\\workspace",
  5846. resolveAttachment,
  5847. });
  5848. app.start();
  5849. await app.ready;
  5850. terminal.input?.(`\x1b[200~'${wechatImagePath}'\x1b[201~`);
  5851. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledOnce());
  5852. expect(resolveAttachment).toHaveBeenCalledWith(`'${wechatImagePath}'`, {
  5853. source: "terminal-paste",
  5854. workspaceDir: "D:\\workspace",
  5855. });
  5856. expect(app.editor.getText()).toBe("[Image #1] ");
  5857. expect(app.tui.render(80).join("\n")).not.toContain("xwechat_files");
  5858. await app.submit("Inspect this image");
  5859. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5860. expect.objectContaining({
  5861. content: "Inspect this image",
  5862. attachments: [
  5863. expect.objectContaining({
  5864. local: { filePath: wechatImagePath },
  5865. }),
  5866. ],
  5867. }),
  5868. expect.any(AbortSignal),
  5869. );
  5870. await app.stop();
  5871. });
  5872. it("keeps an image placeholder visible before a long CJK prompt", async () => {
  5873. const terminal = new FakeTerminal();
  5874. const resolveAttachment = vi.fn(async () => ({
  5875. type: "image" as const,
  5876. filePath: "/tmp/otty-paste/logo.png",
  5877. fileName: "logo.png",
  5878. mimeType: "image/png",
  5879. sizeBytes: 1_024,
  5880. }));
  5881. const app = createTuiApp({
  5882. runtime: createRuntime(),
  5883. terminal,
  5884. version: "0.1.0",
  5885. workspaceDir: "/workspace",
  5886. resolveAttachment,
  5887. });
  5888. app.start();
  5889. await app.ready;
  5890. terminal.input?.("\x1b[200~/tmp/otty-paste/logo.png\x1b[201~");
  5891. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
  5892. app.editor.insertTextAtCursor(
  5893. "logo 不太对还是,还出现了奇怪的--; logo你自己截取把:",
  5894. );
  5895. const rendered = app.tui.render(80).join("\n");
  5896. expect(rendered).toContain("[Image #1]");
  5897. await app.stop();
  5898. });
  5899. it("removes an inline image placeholder and its attachment with Backspace", async () => {
  5900. const terminal = new FakeTerminal();
  5901. const resolveAttachment = vi.fn(async () => ({
  5902. type: "image" as const,
  5903. filePath: "/tmp/otty-paste/image-123.png",
  5904. fileName: "image-123.png",
  5905. mimeType: "image/png",
  5906. sizeBytes: 1_024,
  5907. }));
  5908. const app = createTuiApp({
  5909. runtime: createRuntime(),
  5910. terminal,
  5911. version: "0.1.0",
  5912. workspaceDir: "/workspace",
  5913. resolveAttachment,
  5914. });
  5915. app.start();
  5916. await app.ready;
  5917. app.editor.setText("first line\nsecond line");
  5918. terminal.input?.("\x1b[200~/tmp/otty-paste/image-123.png\x1b[201~");
  5919. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
  5920. expect(app.editor.getText()).toBe("first line\nsecond line [Image #1] ");
  5921. expect(app.tui.render(80).join("\n")).toContain("[Image #1]");
  5922. terminal.input?.("\x7f");
  5923. await vi.waitFor(() =>
  5924. expect(app.editor.getText().trimEnd()).toBe("first line\nsecond line"),
  5925. );
  5926. expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
  5927. await app.stop();
  5928. });
  5929. it("resumes Desktop history, supports rename, and executes the files-unchanged fork flow", async () => {
  5930. const terminal = new FakeTerminal();
  5931. const runtime = createRuntime();
  5932. vi.mocked(runtime.listSessions).mockResolvedValue([
  5933. {
  5934. sessionId: "session-existing",
  5935. title: "Existing session",
  5936. workspaceDir: "/workspace",
  5937. updatedAt: 200,
  5938. },
  5939. ]);
  5940. const history = [
  5941. {
  5942. id: "msg-user-v1-fork-source",
  5943. turnId: "turn-history",
  5944. role: "user" as const,
  5945. content: "Try the original approach",
  5946. timestamp: 90,
  5947. },
  5948. {
  5949. id: "assistant-fork-source",
  5950. turnId: "turn-history",
  5951. role: "assistant" as const,
  5952. content: "Recovered answer",
  5953. timestamp: 100,
  5954. actions: { fork: true },
  5955. },
  5956. ];
  5957. const forkRuntime = runtime as TuiRuntime & TuiSessionForkPort;
  5958. vi.mocked(runtime.getMessages).mockResolvedValue(history);
  5959. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  5960. messages: history,
  5961. hasMore: false,
  5962. });
  5963. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  5964. sessionId === "session-fork"
  5965. ? {
  5966. sessionId,
  5967. parentSessionId: "session-existing",
  5968. title: "Existing session (fork 1)",
  5969. workspaceDir: "/workspace",
  5970. }
  5971. : {
  5972. sessionId,
  5973. title: "Existing session",
  5974. workspaceDir: "/workspace",
  5975. },
  5976. );
  5977. vi.mocked(forkRuntime.getSessionForkOptions).mockResolvedValue({
  5978. canFork: true,
  5979. suggestedTitle: "Existing session (fork 1)",
  5980. worktreeVisible: false,
  5981. worktreeEligible: false,
  5982. });
  5983. vi.mocked(forkRuntime.forkSession).mockResolvedValue({
  5984. session: {
  5985. sessionId: "session-fork",
  5986. parentSessionId: "session-existing",
  5987. title: "Existing session (fork 1)",
  5988. workspaceDir: "/workspace",
  5989. },
  5990. });
  5991. const app = createTuiApp({
  5992. runtime,
  5993. terminal,
  5994. version: "0.1.0",
  5995. workspaceDir: "/workspace",
  5996. });
  5997. app.start();
  5998. await app.ready;
  5999. await app.submit("/sessions");
  6000. expect(app.tui.hasOverlay()).toBe(false);
  6001. expect(app.interaction.isActive()).toBe(true);
  6002. app.interaction.current()?.handleInput?.("\x1b");
  6003. expect(app.interaction.isActive()).toBe(false);
  6004. await app.submit("/resume 1");
  6005. expect(app.getSurface()).toBe("conversation");
  6006. vi.mocked(runtime.renameSession).mockClear();
  6007. await app.submit("/rename");
  6008. expect(runtime.renameSession).not.toHaveBeenCalled();
  6009. expect(app.interaction.isActive()).toBe(true);
  6010. expect(app.tui.render(100).join("\n")).toContain(
  6011. "Sessions / Rename session",
  6012. );
  6013. app.interaction.current()?.handleInput?.("\x1b");
  6014. expect(app.tui.render(100).join("\n")).toContain("Sessions");
  6015. app.interaction.current()?.handleInput?.("\x1b");
  6016. expect(app.interaction.isActive()).toBe(false);
  6017. await app.submit("/rename Renamed session");
  6018. vi.mocked(runtime.createSession).mockClear();
  6019. await app.submit("/fork");
  6020. await vi.waitFor(() =>
  6021. expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
  6022. "session-existing",
  6023. {
  6024. limit: 100,
  6025. },
  6026. ),
  6027. );
  6028. // The new fork flow owns the surface with the history picker, not the
  6029. // generic transcript panel.
  6030. expect(renderTerminalViewport(app, terminal)).toContain(
  6031. "Fork from a previous message",
  6032. );
  6033. expect(renderTerminalViewport(app, terminal)).not.toContain("Transcript");
  6034. // Esc cancels without calling the fork Runtime API.
  6035. const beforeForkCalls = vi.mocked(runtime.forkSession).mock.calls.length;
  6036. app.surfaceHost.popFeature();
  6037. expect(vi.mocked(runtime.forkSession).mock.calls.length).toBe(
  6038. beforeForkCalls,
  6039. );
  6040. const transcriptBeforeStatus = app.transcript.snapshot();
  6041. await app.submit("/status");
  6042. expect(runtime.getSession).toHaveBeenCalledWith("session-existing");
  6043. expect(app.interaction.current()).toBeDefined();
  6044. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  6045. expect(app.tui.render(100).join("\n")).toContain("MCode status");
  6046. expect(runtime.renameSession).toHaveBeenCalledWith(
  6047. "session-existing",
  6048. "Renamed session",
  6049. );
  6050. expect(runtime.createSession).not.toHaveBeenCalled();
  6051. expect(app.transcript.snapshot()).not.toEqual(
  6052. expect.arrayContaining([
  6053. expect.objectContaining({ content: "Unknown command. Use /help." }),
  6054. ]),
  6055. );
  6056. app.interaction.current()?.handleInput?.("\x1b");
  6057. await app.stop();
  6058. });
  6059. it.each(["regular", "fullscreen"] as const)(
  6060. "presents /history in %s mode and returns to chat on cancel",
  6061. async (tuiMode) => {
  6062. const terminal = new FakeTerminal();
  6063. const runtime = createRuntime();
  6064. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6065. {
  6066. userMessageId: "msg-user-history",
  6067. assistantMessageId: "msg-assistant-history",
  6068. contentHead: "Inspect the Session UI",
  6069. timestamp: 1_700_000_000_000,
  6070. fileChangeCount: 1,
  6071. },
  6072. ]);
  6073. const app = createTuiApp({
  6074. runtime,
  6075. terminal,
  6076. version: "0.1.0",
  6077. workspaceDir: "/workspace",
  6078. tuiMode,
  6079. });
  6080. app.start();
  6081. await app.ready;
  6082. await app.submit("Seed the session");
  6083. await app.submit("/history");
  6084. await vi.waitFor(() =>
  6085. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6086. kind: "feature",
  6087. id: "session-history:explorer",
  6088. }),
  6089. );
  6090. expect(renderTerminalViewport(app, terminal)).toContain(
  6091. "Inspect the Session UI",
  6092. );
  6093. expect(renderTerminalViewport(app, terminal)).toContain("Search:");
  6094. expect(renderTerminalViewport(app, terminal)).toContain("Enter actions");
  6095. terminal.input?.("\u001b");
  6096. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6097. kind: "chat",
  6098. id: "chat",
  6099. });
  6100. await app.stop();
  6101. },
  6102. );
  6103. it("forks with the assistant boundary and starts a new operation after a terminal failure", async () => {
  6104. const terminal = new FakeTerminal();
  6105. const runtime = createRuntime();
  6106. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6107. {
  6108. userMessageId: "msg-user-1",
  6109. assistantMessageId: "msg-assistant-1",
  6110. contentHead: "Investigate flaky login tests",
  6111. timestamp: 1_700_000_000_000,
  6112. fileChangeCount: 2,
  6113. },
  6114. {
  6115. userMessageId: "msg-user-2",
  6116. assistantMessageId: "msg-assistant-2",
  6117. contentHead: "Draft a new CLI handler",
  6118. timestamp: 1_699_999_000_000,
  6119. fileChangeCount: 0,
  6120. },
  6121. ]);
  6122. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6123. canFork: true,
  6124. worktreeVisible: false,
  6125. worktreeEligible: false,
  6126. });
  6127. vi.mocked(runtime.forkSession).mockRejectedValueOnce(
  6128. Object.assign(new Error("persisted fork recovery failed"), {
  6129. key: "FORK_RECOVERY_FAILED",
  6130. }),
  6131. );
  6132. const app = createTuiApp({
  6133. runtime,
  6134. terminal,
  6135. version: "0.1.0",
  6136. workspaceDir: "/workspace",
  6137. });
  6138. app.start();
  6139. await app.ready;
  6140. // Submit a message so the controller has an active session id.
  6141. await app.submit("Seed the session");
  6142. await vi.waitFor(() =>
  6143. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6144. );
  6145. const sourceSessionId = app.controller.snapshot().session?.sessionId;
  6146. expect(sourceSessionId).toBe("session-1");
  6147. const transcriptBefore = app.transcript.snapshot();
  6148. vi.mocked(runtime.createSession).mockClear();
  6149. vi.mocked(runtime.forkSession).mockClear();
  6150. vi.mocked(runtime.getSessionForkOptions).mockClear();
  6151. vi.mocked(runtime.listSessionInputSummaries).mockClear();
  6152. await app.submit("/fork");
  6153. // 1. /fork loads input summaries, not the generic transcript.
  6154. await vi.waitFor(() =>
  6155. expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
  6156. sourceSessionId,
  6157. {
  6158. limit: 100,
  6159. },
  6160. ),
  6161. );
  6162. expect(renderTerminalViewport(app, terminal)).toContain(
  6163. "Fork from a previous message",
  6164. );
  6165. expect(renderTerminalViewport(app, terminal)).not.toContain("Transcript");
  6166. // 2. The newest summary (last entry) is selected by default; confirm with Enter.
  6167. await vi.waitFor(() =>
  6168. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6169. kind: "feature",
  6170. id: "session-mutation:history",
  6171. }),
  6172. );
  6173. terminal.input?.("\r");
  6174. // The history selection only fetches options; it must not mutate yet.
  6175. await vi.waitFor(() =>
  6176. expect(runtime.getSessionForkOptions).toHaveBeenCalledWith(
  6177. sourceSessionId,
  6178. "msg-assistant-2",
  6179. ),
  6180. );
  6181. await vi.waitFor(() =>
  6182. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6183. kind: "feature",
  6184. id: "session-mutation:fork-confirm",
  6185. }),
  6186. );
  6187. expect(runtime.forkSession).not.toHaveBeenCalled();
  6188. expect(renderTerminalViewport(app, terminal)).toContain("Confirm fork");
  6189. // 3. Explicit confirmation performs the mutation.
  6190. terminal.input?.("\r");
  6191. await vi.waitFor(() =>
  6192. expect(runtime.forkSession).toHaveBeenCalledWith(
  6193. expect.objectContaining({
  6194. sessionId: sourceSessionId,
  6195. assistantMessageId: "msg-assistant-2",
  6196. useSuggestedTitle: true,
  6197. createIsolatedWorktree: false,
  6198. }),
  6199. ),
  6200. );
  6201. await vi.waitFor(() =>
  6202. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6203. kind: "feature",
  6204. id: "session-mutation:fork-confirm",
  6205. }),
  6206. );
  6207. terminal.input?.("\r");
  6208. await vi.waitFor(() =>
  6209. expect(runtime.forkSession).toHaveBeenCalledTimes(2),
  6210. );
  6211. const forkCalls = vi.mocked(runtime.forkSession).mock.calls;
  6212. const operationIds = forkCalls.map(([input]) => input.clientRequestId);
  6213. expect(operationIds[0]).toBeTruthy();
  6214. expect(operationIds[1]).toBeTruthy();
  6215. expect(operationIds[0]).not.toBe(operationIds[1]);
  6216. // 5. Activation moves the controller to the child session id.
  6217. await vi.waitFor(() =>
  6218. expect(app.controller.snapshot().session?.sessionId).toBe("session-fork"),
  6219. );
  6220. expect(runtime.createSession).not.toHaveBeenCalled();
  6221. // The user message that seeded the source session was already projected
  6222. // into the transcript before the fork ran; the fork flow must not write
  6223. // any new user-typed cell while the picker is open or the mutation runs.
  6224. expect(
  6225. transcriptBefore.filter((cell) => cell.kind === "user").length,
  6226. ).toBeGreaterThan(0);
  6227. });
  6228. it("does not call forkSession when /fork is cancelled, unavailable, or fails", async () => {
  6229. const scenarios: ReadonlyArray<{
  6230. readonly label: string;
  6231. readonly setup: (runtime: ReturnType<typeof createRuntime>) => void;
  6232. readonly interact: (terminal: FakeTerminal) => void | Promise<void>;
  6233. /** When true, expect forkSession to have been called exactly once. */
  6234. readonly expectForkCall: boolean;
  6235. readonly confirmAfterSelection?: boolean;
  6236. }> = [
  6237. {
  6238. label: "esc cancels the picker without invoking fork",
  6239. setup: (runtime) => {
  6240. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6241. {
  6242. userMessageId: "msg-user-1",
  6243. assistantMessageId: "msg-assistant-1",
  6244. contentHead: "Investigate flaky login tests",
  6245. timestamp: 1_700_000_000_000,
  6246. fileChangeCount: 0,
  6247. },
  6248. ]);
  6249. },
  6250. interact: (terminal) => {
  6251. terminal.input?.("\u001b");
  6252. },
  6253. expectForkCall: false,
  6254. },
  6255. {
  6256. label: "unavailable fork surfaces a warning without invoking fork",
  6257. setup: (runtime) => {
  6258. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6259. {
  6260. userMessageId: "msg-user-1",
  6261. assistantMessageId: "msg-assistant-1",
  6262. contentHead: "Investigate flaky login tests",
  6263. timestamp: 1_700_000_000_000,
  6264. fileChangeCount: 0,
  6265. },
  6266. ]);
  6267. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6268. canFork: false,
  6269. unavailableReason: "No persisted user prompts yet.",
  6270. worktreeVisible: false,
  6271. worktreeEligible: false,
  6272. });
  6273. },
  6274. interact: (terminal) => {
  6275. terminal.input?.("\r");
  6276. },
  6277. expectForkCall: false,
  6278. },
  6279. {
  6280. label:
  6281. "forkSession failure preserves the source session and transcript",
  6282. setup: (runtime) => {
  6283. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6284. {
  6285. userMessageId: "msg-user-1",
  6286. assistantMessageId: "msg-assistant-1",
  6287. contentHead: "Investigate flaky login tests",
  6288. timestamp: 1_700_000_000_000,
  6289. fileChangeCount: 0,
  6290. },
  6291. ]);
  6292. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6293. canFork: true,
  6294. worktreeVisible: false,
  6295. worktreeEligible: false,
  6296. });
  6297. vi.mocked(runtime.forkSession).mockRejectedValue(
  6298. new Error("Runtime offline."),
  6299. );
  6300. },
  6301. interact: (terminal) => {
  6302. terminal.input?.("\r");
  6303. },
  6304. expectForkCall: true,
  6305. confirmAfterSelection: true,
  6306. },
  6307. ];
  6308. for (const scenario of scenarios) {
  6309. const terminal = new FakeTerminal();
  6310. const runtime = createRuntime();
  6311. scenario.setup(runtime);
  6312. const app = createTuiApp({
  6313. runtime,
  6314. terminal,
  6315. version: "0.1.0",
  6316. workspaceDir: "/workspace",
  6317. });
  6318. app.start();
  6319. await app.ready;
  6320. await app.submit("Seed the session");
  6321. await vi.waitFor(() =>
  6322. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6323. );
  6324. const sourceSessionId = app.controller.snapshot().session?.sessionId;
  6325. const transcriptBefore = app.transcript.snapshot();
  6326. await app.submit("/fork");
  6327. await vi.waitFor(() =>
  6328. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6329. kind: "feature",
  6330. id: "session-mutation:history",
  6331. }),
  6332. );
  6333. await scenario.interact(terminal);
  6334. if (scenario.expectForkCall || scenario.label.includes("unavailable")) {
  6335. await vi.waitFor(() =>
  6336. expect(runtime.getSessionForkOptions).toHaveBeenCalled(),
  6337. );
  6338. }
  6339. expect(runtime.forkSession).not.toHaveBeenCalled();
  6340. if (scenario.confirmAfterSelection) {
  6341. terminal.input?.("\r");
  6342. }
  6343. // Give the async fork pipeline a chance to settle.
  6344. await new Promise((resolve) => setTimeout(resolve, 40));
  6345. if (scenario.expectForkCall) {
  6346. expect(
  6347. vi.mocked(runtime.forkSession).mock.calls.length,
  6348. `${scenario.label} should call forkSession once`,
  6349. ).toBe(1);
  6350. } else {
  6351. expect(
  6352. vi.mocked(runtime.forkSession).mock.calls.length,
  6353. `${scenario.label} should not call forkSession`,
  6354. ).toBe(0);
  6355. }
  6356. expect(
  6357. app.controller.snapshot().session?.sessionId,
  6358. `${scenario.label} must not switch sessions`,
  6359. ).toBe(sourceSessionId);
  6360. expect(
  6361. app.transcript.snapshot().filter((cell) => cell.kind === "user").length,
  6362. `${scenario.label} must preserve the source transcript`,
  6363. ).toBe(transcriptBefore.filter((cell) => cell.kind === "user").length);
  6364. await app.stop();
  6365. }
  6366. });
  6367. it("does not call forkSession when the source session changes between summary and selection", async () => {
  6368. const terminal = new FakeTerminal();
  6369. const runtime = createRuntime();
  6370. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6371. {
  6372. userMessageId: "msg-user-1",
  6373. assistantMessageId: "msg-assistant-1",
  6374. contentHead: "Investigate flaky login tests",
  6375. timestamp: 1_700_000_000_000,
  6376. fileChangeCount: 0,
  6377. },
  6378. ]);
  6379. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6380. canFork: true,
  6381. worktreeVisible: false,
  6382. worktreeEligible: false,
  6383. });
  6384. const app = createTuiApp({
  6385. runtime,
  6386. terminal,
  6387. version: "0.1.0",
  6388. workspaceDir: "/workspace",
  6389. });
  6390. app.start();
  6391. await app.ready;
  6392. await app.submit("Seed the session");
  6393. await vi.waitFor(() =>
  6394. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6395. );
  6396. await app.submit("/fork");
  6397. await vi.waitFor(() =>
  6398. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6399. kind: "feature",
  6400. id: "session-mutation:history",
  6401. }),
  6402. );
  6403. // Simulate the source session changing while the picker is open.
  6404. const otherSession = {
  6405. sessionId: "session-other",
  6406. title: "Other session",
  6407. workspaceDir: "/workspace",
  6408. };
  6409. vi.mocked(runtime.listSessions).mockResolvedValue([otherSession]);
  6410. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  6411. sessionId === otherSession.sessionId
  6412. ? otherSession
  6413. : { sessionId, workspaceDir: "/workspace" },
  6414. );
  6415. await app.openSession(otherSession.sessionId);
  6416. expect(app.controller.snapshot().session?.sessionId).toBe(
  6417. otherSession.sessionId,
  6418. );
  6419. // Confirming the picker now must not call forkSession.
  6420. terminal.input?.("\r");
  6421. await new Promise((resolve) => setTimeout(resolve, 20));
  6422. expect(vi.mocked(runtime.forkSession)).not.toHaveBeenCalled();
  6423. expect(vi.mocked(runtime.getSessionForkOptions).mock.calls.length).toBe(0);
  6424. });
  6425. it("preserves the /fork command draft and skips mutation when a turn is running", async () => {
  6426. const terminal = new FakeTerminal();
  6427. const runtime = createRuntime();
  6428. let finishTurn: (() => void) | undefined;
  6429. vi.mocked(runtime.sendMessage).mockImplementation(
  6430. async function* sendMessage() {
  6431. await new Promise<void>((resolve) => {
  6432. finishTurn = resolve;
  6433. });
  6434. yield { type: "done" };
  6435. },
  6436. );
  6437. const app = createTuiApp({
  6438. runtime,
  6439. terminal,
  6440. version: "0.1.0",
  6441. workspaceDir: "/workspace",
  6442. });
  6443. app.start();
  6444. await app.ready;
  6445. const submission = app.submit("Seed the session");
  6446. await vi.waitFor(() =>
  6447. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6448. );
  6449. await vi.waitFor(() =>
  6450. expect(vi.mocked(runtime.sendMessage)).toHaveBeenCalled(),
  6451. );
  6452. const summariesBefore = vi.mocked(runtime.listSessionInputSummaries).mock
  6453. .calls.length;
  6454. const forkOptionsBefore = vi.mocked(runtime.getSessionForkOptions).mock
  6455. .calls.length;
  6456. const forkBefore = vi.mocked(runtime.forkSession).mock.calls.length;
  6457. // While the turn is still running, /fork should preserve the draft and
  6458. // skip every runtime mutation method.
  6459. app.editor.setText("/fork");
  6460. await app.submit("/fork");
  6461. expect(app.editor.getText()).toBe("/fork");
  6462. expect(vi.mocked(runtime.listSessionInputSummaries).mock.calls.length).toBe(
  6463. summariesBefore,
  6464. );
  6465. expect(vi.mocked(runtime.getSessionForkOptions).mock.calls.length).toBe(
  6466. forkOptionsBefore,
  6467. );
  6468. expect(vi.mocked(runtime.forkSession).mock.calls.length).toBe(forkBefore);
  6469. // The fork surface should not have been pushed either.
  6470. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6471. kind: "chat",
  6472. id: "chat",
  6473. });
  6474. finishTurn?.();
  6475. await submission;
  6476. await app.stop();
  6477. });
  6478. it.each([
  6479. ["conversation", []],
  6480. ["conversation_and_files", ["\u001b[B"]],
  6481. ] as const)(
  6482. "runs /rewind with explicit %s scope and stable operation id",
  6483. async (scope, navigation) => {
  6484. const terminal = new FakeTerminal();
  6485. const runtime = createRuntime();
  6486. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6487. {
  6488. userMessageId: "msg-user-rewind",
  6489. contentHead: "Undo this point",
  6490. timestamp: 1_700_000_000_000,
  6491. fileChangeCount: 2,
  6492. },
  6493. ]);
  6494. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  6495. turns: [
  6496. {
  6497. turnId: "turn-1",
  6498. files: [
  6499. { filePath: "src/ready.ts", action: "modified", skipped: false },
  6500. { filePath: "src/skipped.ts", action: "deleted", skipped: true },
  6501. ],
  6502. },
  6503. ],
  6504. });
  6505. vi.mocked(runtime.rewindSession).mockResolvedValue(
  6506. scope === "conversation"
  6507. ? { rewound: true }
  6508. : {
  6509. rewound: true,
  6510. turnDiffRewind: {
  6511. status: "rewound",
  6512. revertedTurnIds: ["turn-1"],
  6513. },
  6514. },
  6515. );
  6516. const app = createTuiApp({
  6517. runtime,
  6518. terminal,
  6519. version: "0.1.0",
  6520. workspaceDir: "/workspace",
  6521. });
  6522. app.start();
  6523. await app.ready;
  6524. await app.submit("Seed rewind session");
  6525. await vi.waitFor(() =>
  6526. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6527. );
  6528. expect(
  6529. app.transcript.snapshot().some((cell) => cell.kind === "turn-duration"),
  6530. ).toBe(true);
  6531. vi.mocked(runtime.getMessages).mockResolvedValue([]);
  6532. await app.submit("/rewind");
  6533. await vi.waitFor(() =>
  6534. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6535. kind: "feature",
  6536. id: "session-mutation:history",
  6537. }),
  6538. );
  6539. terminal.input?.("\r");
  6540. await vi.waitFor(() =>
  6541. expect(runtime.getSessionRewindPreview).toHaveBeenCalledWith({
  6542. sessionId: "session-1",
  6543. userMessageId: "msg-user-rewind",
  6544. }),
  6545. );
  6546. await vi.waitFor(() =>
  6547. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6548. kind: "feature",
  6549. id: "session-mutation:rewind-preview",
  6550. }),
  6551. );
  6552. expect(renderTerminalViewport(app, terminal)).toContain("src/ready.ts");
  6553. expect(renderTerminalViewport(app, terminal)).toContain("src/skipped.ts");
  6554. terminal.input?.("\r");
  6555. await vi.waitFor(() =>
  6556. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6557. kind: "feature",
  6558. id: "session-mutation:scope",
  6559. }),
  6560. );
  6561. for (const key of navigation) terminal.input?.(key);
  6562. terminal.input?.("\r");
  6563. await vi.waitFor(() =>
  6564. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6565. kind: "feature",
  6566. id: "session-mutation:rewind-confirm",
  6567. }),
  6568. );
  6569. expect(runtime.rewindSession).not.toHaveBeenCalled();
  6570. terminal.input?.("\r");
  6571. await vi.waitFor(() =>
  6572. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  6573. );
  6574. const input = vi.mocked(runtime.rewindSession).mock.calls[0]?.[0];
  6575. expect(input).toEqual({
  6576. sessionId: "session-1",
  6577. userMessageId: "msg-user-rewind",
  6578. clientRequestId: expect.stringMatching(/^tui-rewind_/),
  6579. ...(scope === "conversation_and_files" ? { rewindTurnDiff: true } : {}),
  6580. });
  6581. expect(input?.clientRequestId).toMatch(/^tui-rewind_/);
  6582. await vi.waitFor(() => expect(runtime.getMessages).toHaveBeenCalled());
  6583. await vi.waitFor(() =>
  6584. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6585. kind: "chat",
  6586. id: "chat",
  6587. }),
  6588. );
  6589. expect(
  6590. app.transcript
  6591. .snapshot()
  6592. .some((cell) => cell.content === "Rewind completed."),
  6593. ).toBe(false);
  6594. expect(app.transcript.snapshot()).toEqual([]);
  6595. await app.stop();
  6596. },
  6597. );
  6598. it("edits only the latest user turn, hides that turn while editing, and adds no completion cell", async () => {
  6599. const terminal = new FakeTerminal();
  6600. const runtime = createRuntime();
  6601. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6602. {
  6603. userMessageId: "msg-user-older",
  6604. assistantMessageId: "msg-assistant-older",
  6605. contentHead: "Older prompt",
  6606. timestamp: 1,
  6607. fileChangeCount: 0,
  6608. },
  6609. {
  6610. userMessageId: "msg-user-latest",
  6611. assistantMessageId: "msg-assistant-latest",
  6612. contentHead: "Latest prompt",
  6613. timestamp: 2,
  6614. fileChangeCount: 0,
  6615. },
  6616. ]);
  6617. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6618. messages: [
  6619. {
  6620. id: "msg-user-older",
  6621. role: "user",
  6622. content: "Older prompt",
  6623. timestamp: 1,
  6624. },
  6625. {
  6626. id: "msg-user-latest",
  6627. role: "user",
  6628. content: "Latest prompt",
  6629. timestamp: 2,
  6630. },
  6631. ],
  6632. hasMore: false,
  6633. });
  6634. const app = createTuiApp({
  6635. runtime,
  6636. terminal,
  6637. version: "0.1.0",
  6638. workspaceDir: "/workspace",
  6639. });
  6640. app.start();
  6641. await app.ready;
  6642. await app.submit("Seed edit session");
  6643. await vi.waitFor(() =>
  6644. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6645. );
  6646. app.transcript.upsert({
  6647. id: "older-user-cell",
  6648. kind: "user",
  6649. status: "succeeded",
  6650. content: "Older prompt",
  6651. sourceMessageId: "msg-user-older",
  6652. turnId: "turn-older",
  6653. createdAtMs: 1,
  6654. });
  6655. app.transcript.upsert({
  6656. id: "latest-user-cell",
  6657. kind: "user",
  6658. status: "succeeded",
  6659. content: "Latest prompt",
  6660. sourceMessageId: "msg-user-latest",
  6661. turnId: "turn-latest",
  6662. createdAtMs: 2,
  6663. });
  6664. app.transcript.upsert({
  6665. id: "latest-assistant-cell",
  6666. kind: "assistant",
  6667. status: "succeeded",
  6668. content: "Latest response",
  6669. sourceMessageId: "msg-assistant-latest",
  6670. turnId: "turn-latest",
  6671. createdAtMs: 3,
  6672. });
  6673. await app.submit("/edit");
  6674. await vi.waitFor(() =>
  6675. expect(app.editor.getExpandedText()).toBe("Latest prompt"),
  6676. );
  6677. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6678. kind: "chat",
  6679. id: "chat",
  6680. });
  6681. const editingFrame = app.tui.render(100).join("\n");
  6682. expect(editingFrame).toContain("Older prompt");
  6683. expect(editingFrame).not.toContain("Latest response");
  6684. const historyRefreshCount = vi.mocked(runtime.getMessages).mock.calls
  6685. .length;
  6686. app.editor.setText("Edited latest prompt");
  6687. app.editor.handleInput("\r");
  6688. await vi.waitFor(() =>
  6689. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  6690. );
  6691. await vi.waitFor(() =>
  6692. expect(vi.mocked(runtime.getMessages).mock.calls.length).toBeGreaterThan(
  6693. historyRefreshCount,
  6694. ),
  6695. );
  6696. expect(
  6697. app.transcript
  6698. .snapshot()
  6699. .some(
  6700. (cell) =>
  6701. cell.content ===
  6702. "Edited message submitted; regenerating from this point.",
  6703. ),
  6704. ).toBe(false);
  6705. expect(runtime.editSessionMessage).toHaveBeenCalledWith(
  6706. expect.objectContaining({
  6707. userMessageId: "msg-user-latest",
  6708. content: "Edited latest prompt",
  6709. }),
  6710. );
  6711. await app.stop();
  6712. });
  6713. it("restores the hidden latest turn when Edit is cancelled", async () => {
  6714. const terminal = new FakeTerminal();
  6715. const runtime = createRuntime();
  6716. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6717. {
  6718. userMessageId: "msg-user-latest",
  6719. assistantMessageId: "msg-assistant-latest",
  6720. contentHead: "Latest prompt",
  6721. timestamp: 2,
  6722. fileChangeCount: 0,
  6723. },
  6724. ]);
  6725. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6726. messages: [
  6727. {
  6728. id: "msg-user-latest",
  6729. role: "user",
  6730. content: "Latest prompt",
  6731. timestamp: 2,
  6732. },
  6733. ],
  6734. hasMore: false,
  6735. });
  6736. const app = createTuiApp({
  6737. runtime,
  6738. terminal,
  6739. version: "0.1.0",
  6740. workspaceDir: "/workspace",
  6741. });
  6742. app.start();
  6743. await app.ready;
  6744. await app.submit("Seed edit session");
  6745. app.transcript.upsert({
  6746. id: "latest-user-cell",
  6747. kind: "user",
  6748. status: "succeeded",
  6749. content: "Latest prompt",
  6750. sourceMessageId: "msg-user-latest",
  6751. turnId: "turn-latest",
  6752. createdAtMs: 2,
  6753. });
  6754. app.transcript.upsert({
  6755. id: "latest-assistant-cell",
  6756. kind: "assistant",
  6757. status: "succeeded",
  6758. content: "Latest response restored on cancel",
  6759. sourceMessageId: "msg-assistant-latest",
  6760. turnId: "turn-latest",
  6761. createdAtMs: 3,
  6762. });
  6763. await app.submit("/edit");
  6764. await vi.waitFor(() =>
  6765. expect(app.editor.getExpandedText()).toBe("Latest prompt"),
  6766. );
  6767. expect(app.tui.render(100).join("\n")).not.toContain(
  6768. "Latest response restored on cancel",
  6769. );
  6770. terminal.input?.("\u001b");
  6771. await vi.waitFor(() => expect(app.editor.getExpandedText()).toBe(""));
  6772. expect(app.tui.render(100).join("\n")).toContain(
  6773. "Latest response restored on cancel",
  6774. );
  6775. expect(runtime.editSessionMessage).not.toHaveBeenCalled();
  6776. await app.stop();
  6777. });
  6778. it.each([
  6779. { reference: "filePath", action: "cancel" },
  6780. { reference: "assetId", action: "send" },
  6781. { reference: "assetId", action: "delete" },
  6782. { reference: "filePath", action: "undo" },
  6783. { reference: "assetId", action: "add" },
  6784. { reference: "filePath", action: "clear-restore" },
  6785. { reference: "filePath", action: "cached" },
  6786. ] as const)(
  6787. "restores editable image chips after double Escape and retry ($reference / $action)",
  6788. async ({ reference, action }) => {
  6789. const terminal = new FakeTerminal();
  6790. const runtime = createRuntime();
  6791. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6792. {
  6793. userMessageId: "msg-user-latest",
  6794. assistantMessageId: "msg-assistant-latest",
  6795. contentHead: "Latest prompt from shortcut",
  6796. timestamp: 2,
  6797. fileChangeCount: 0,
  6798. },
  6799. ]);
  6800. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6801. messages: [
  6802. {
  6803. id: "msg-user-latest",
  6804. role: "user",
  6805. content: "Latest prompt from shortcut",
  6806. attachments: [
  6807. {
  6808. type: "image",
  6809. fileName: "edit-reference.png",
  6810. mimeType: "image/png",
  6811. [reference]:
  6812. reference === "filePath"
  6813. ? "/workspace/edit-reference.png"
  6814. : "asset-edit-image",
  6815. },
  6816. ],
  6817. timestamp: 2,
  6818. },
  6819. ],
  6820. hasMore: false,
  6821. });
  6822. const app = createTuiApp({
  6823. runtime,
  6824. terminal,
  6825. version: "0.1.0",
  6826. workspaceDir: "/workspace",
  6827. resolveAttachment: async (path) => ({
  6828. type: "image",
  6829. filePath: path,
  6830. fileName: path.endsWith("new.png") ? "new.png" : "edit-reference.png",
  6831. mimeType: "image/png",
  6832. sizeBytes: 123,
  6833. }),
  6834. });
  6835. app.start();
  6836. await app.ready;
  6837. let restoredText = "Latest prompt from shortcut [Image #1] ";
  6838. if (action === "cached") {
  6839. terminal.input?.("\x1b[200~/workspace/edit-reference.png\x1b[201~");
  6840. await vi.waitFor(() =>
  6841. expect(app.editor.getText()).toContain("[Image #1]"),
  6842. );
  6843. app.editor.handleInput("Latest prompt from shortcut");
  6844. restoredText = app.editor.getText();
  6845. app.editor.handleInput("\r");
  6846. await vi.waitFor(() =>
  6847. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  6848. );
  6849. await vi.waitFor(() =>
  6850. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  6851. );
  6852. } else {
  6853. await app.submit("Seed edit session");
  6854. }
  6855. terminal.input?.("\u001b");
  6856. terminal.input?.("\u001b");
  6857. await vi.waitFor(() =>
  6858. expect(app.editor.getExpandedText()).toBe(restoredText),
  6859. );
  6860. expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
  6861. "session-1",
  6862. { limit: 100 },
  6863. );
  6864. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6865. kind: "chat",
  6866. id: "chat",
  6867. });
  6868. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain("[Image #1]");
  6869. vi.mocked(runtime.editSessionMessage).mockRejectedValueOnce(
  6870. new Error("Temporary failure"),
  6871. );
  6872. app.editor.handleInput("\r");
  6873. await vi.waitFor(() =>
  6874. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  6875. );
  6876. await vi.waitFor(() =>
  6877. expect(app.editor.getExpandedText()).toBe(restoredText),
  6878. );
  6879. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain("[Image #1]");
  6880. expect(runtime.editSessionMessage).toHaveBeenCalledWith(
  6881. expect.objectContaining({
  6882. content: "Latest prompt from shortcut",
  6883. attachments: [
  6884. expect.objectContaining({
  6885. fileName: "edit-reference.png",
  6886. [reference]:
  6887. reference === "filePath"
  6888. ? "/workspace/edit-reference.png"
  6889. : "asset-edit-image",
  6890. }),
  6891. ],
  6892. }),
  6893. );
  6894. if (action === "delete" || action === "undo") {
  6895. app.editor.handleInput("\x05");
  6896. app.editor.handleInput("\x7f");
  6897. await vi.waitFor(() =>
  6898. expect(app.editor.getText()).not.toContain("[Image #1]"),
  6899. );
  6900. if (action === "undo") {
  6901. app.editor.handleInput("\x1f");
  6902. expect(app.editor.getText()).toContain("[Image #1]");
  6903. }
  6904. }
  6905. if (action === "add") {
  6906. terminal.input?.("\x1b[200~/workspace/new.png\x1b[201~");
  6907. await vi.waitFor(() =>
  6908. expect(app.editor.getText()).toContain("[Image #2]"),
  6909. );
  6910. expect(app.editor.captureDraft().attachmentPlaceholders).toHaveLength(
  6911. 2,
  6912. );
  6913. }
  6914. if (action === "clear-restore") {
  6915. terminal.input?.("\x03");
  6916. expect(app.editor.getText()).toBe("");
  6917. terminal.input?.("\x1f");
  6918. expect(app.editor.getText()).toContain("[Image #1]");
  6919. }
  6920. if (action === "cancel") {
  6921. terminal.input?.("\u001b");
  6922. } else {
  6923. app.editor.handleInput("\r");
  6924. await vi.waitFor(() =>
  6925. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(2),
  6926. );
  6927. const sent = vi.mocked(runtime.editSessionMessage).mock.calls[1]?.[0];
  6928. expect(sent?.content).toBe("Latest prompt from shortcut");
  6929. expect(sent?.attachments ?? []).toHaveLength(
  6930. action === "delete" ? 0 : action === "add" ? 2 : 1,
  6931. );
  6932. if (action !== "delete")
  6933. expect(sent?.attachments?.[0]?.fileName).toBe("edit-reference.png");
  6934. }
  6935. await vi.waitFor(() =>
  6936. expect(stripAnsi(app.tui.render(100).join("\n"))).not.toContain(
  6937. "[Image #1]",
  6938. ),
  6939. );
  6940. await app.stop();
  6941. },
  6942. );
  6943. it("edits the latest committed user turn through the desktop-aligned mutation contract", async () => {
  6944. const terminal = new FakeTerminal();
  6945. const runtime = createRuntime();
  6946. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6947. {
  6948. userMessageId: "msg-user-v1-target",
  6949. assistantMessageId: "msg-assistant-v1-target",
  6950. contentHead: "Original prompt head",
  6951. timestamp: 1_700_000_000_000,
  6952. fileChangeCount: 1,
  6953. },
  6954. ]);
  6955. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6956. messages: [
  6957. {
  6958. id: "msg-user-v1-target",
  6959. role: "user",
  6960. content: "Original complete prompt",
  6961. attachments: [
  6962. {
  6963. type: "file",
  6964. fileName: "spec.md",
  6965. mimeType: "text/markdown",
  6966. sizeBytes: 42,
  6967. filePath: "/workspace/spec.md",
  6968. },
  6969. ],
  6970. timestamp: 1_700_000_000_000,
  6971. },
  6972. ],
  6973. hasMore: false,
  6974. });
  6975. const app = createTuiApp({
  6976. runtime,
  6977. terminal,
  6978. version: "0.1.0",
  6979. workspaceDir: "/workspace",
  6980. });
  6981. app.start();
  6982. await app.ready;
  6983. await app.submit("Seed edit session");
  6984. await vi.waitFor(() =>
  6985. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6986. );
  6987. await app.submit("/edit");
  6988. await vi.waitFor(() =>
  6989. expect(app.editor.getExpandedText()).toBe(
  6990. "Original complete prompt [File #1] ",
  6991. ),
  6992. );
  6993. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6994. kind: "chat",
  6995. id: "chat",
  6996. });
  6997. app.editor.setText("Updated prompt");
  6998. app.editor.handleInput("\r");
  6999. await vi.waitFor(() =>
  7000. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7001. );
  7002. expect(runtime.editSessionMessage).toHaveBeenCalledWith({
  7003. sessionId: "session-1",
  7004. userMessageId: "msg-user-v1-target",
  7005. clientRequestId: expect.stringMatching(/^tui-edit_/u),
  7006. content: "Updated prompt",
  7007. attachments: [
  7008. {
  7009. type: "file",
  7010. fileName: "spec.md",
  7011. mimeType: "text/markdown",
  7012. sizeBytes: 42,
  7013. filePath: "/workspace/spec.md",
  7014. },
  7015. ],
  7016. rewindTurnDiff: true,
  7017. });
  7018. await app.stop();
  7019. });
  7020. it("keeps hidden chat context out of the editor and restores it for Edit transport", async () => {
  7021. const terminal = new FakeTerminal();
  7022. const runtime = createRuntime();
  7023. const transportContent = [
  7024. "<user-provided-context>",
  7025. "Referenced context",
  7026. "</user-provided-context>",
  7027. "",
  7028. "Original visible prompt",
  7029. ].join("\n");
  7030. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7031. {
  7032. userMessageId: "msg-user-v1-context",
  7033. assistantMessageId: "msg-assistant-v1-context",
  7034. contentHead: "Original visible prompt",
  7035. timestamp: 1_700_000_000_000,
  7036. fileChangeCount: 0,
  7037. },
  7038. ]);
  7039. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7040. messages: [
  7041. {
  7042. id: "msg-user-v1-context",
  7043. role: "user",
  7044. content: transportContent,
  7045. timestamp: 1_700_000_000_000,
  7046. },
  7047. ],
  7048. hasMore: false,
  7049. });
  7050. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7051. const app = createTuiApp({
  7052. runtime,
  7053. terminal,
  7054. version: "0.1.0",
  7055. workspaceDir: "/workspace",
  7056. });
  7057. app.start();
  7058. await app.ready;
  7059. await app.submit("Seed edit session");
  7060. await app.submit("/edit");
  7061. await vi.waitFor(() =>
  7062. expect(app.editor.getExpandedText()).toBe("Original visible prompt"),
  7063. );
  7064. expect(app.editor.getExpandedText()).not.toContain("user-provided-context");
  7065. app.editor.setText("Updated visible prompt");
  7066. app.editor.handleInput("\r");
  7067. await vi.waitFor(() =>
  7068. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7069. );
  7070. expect(runtime.editSessionMessage).toHaveBeenCalledWith(
  7071. expect.objectContaining({
  7072. content: [
  7073. "<user-provided-context>",
  7074. "Referenced context",
  7075. "</user-provided-context>",
  7076. "",
  7077. "Updated visible prompt",
  7078. ].join("\n"),
  7079. }),
  7080. );
  7081. await app.stop();
  7082. });
  7083. it("preserves hidden context and attachments when Edit recovery requires a new message", async () => {
  7084. const terminal = new FakeTerminal();
  7085. const runtime = createRuntime();
  7086. const transportContent = [
  7087. "<mavis-chat-context>",
  7088. "Referenced context",
  7089. "</mavis-chat-context>",
  7090. "",
  7091. "Original visible prompt",
  7092. ].join("\n");
  7093. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7094. {
  7095. userMessageId: "msg-user-v1-recovery",
  7096. assistantMessageId: "msg-assistant-v1-recovery",
  7097. contentHead: "Original visible prompt",
  7098. timestamp: 1_700_000_000_000,
  7099. fileChangeCount: 0,
  7100. },
  7101. ]);
  7102. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7103. messages: [
  7104. {
  7105. id: "msg-user-v1-recovery",
  7106. role: "user",
  7107. content: transportContent,
  7108. attachments: [
  7109. {
  7110. type: "file",
  7111. fileName: "context.md",
  7112. mimeType: "text/markdown",
  7113. sizeBytes: 42,
  7114. assetId: "asset-context-md",
  7115. },
  7116. ],
  7117. timestamp: 1_700_000_000_000,
  7118. },
  7119. ],
  7120. hasMore: false,
  7121. });
  7122. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7123. vi.mocked(runtime.editSessionMessage).mockRejectedValueOnce(
  7124. Object.assign(new Error("history already rewound"), {
  7125. key: "EDIT_RESTART_NEEDS_RESUBMIT",
  7126. }),
  7127. );
  7128. const app = createTuiApp({
  7129. runtime,
  7130. terminal,
  7131. version: "0.1.0",
  7132. workspaceDir: "/workspace",
  7133. });
  7134. app.start();
  7135. await app.ready;
  7136. await app.submit("Seed edit session");
  7137. const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
  7138. .length;
  7139. await app.submit("/edit");
  7140. await vi.waitFor(() =>
  7141. expect(app.editor.getExpandedText()).toBe(
  7142. "Original visible prompt [File #1] ",
  7143. ),
  7144. );
  7145. app.editor.setText("/help should remain message text");
  7146. app.editor.handleInput("\r");
  7147. await vi.waitFor(() =>
  7148. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7149. );
  7150. await vi.waitFor(() =>
  7151. expect(app.editor.getExpandedText()).toBe(
  7152. "/help should remain message text [File #1] ",
  7153. ),
  7154. );
  7155. expect(app.editor.getExpandedText()).not.toContain("mavis-chat-context");
  7156. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7157. let releaseAdmission!: () => void;
  7158. vi.mocked(runtime.getAccountStatus).mockImplementationOnce(
  7159. async () =>
  7160. await new Promise((resolve) => {
  7161. releaseAdmission = () =>
  7162. resolve({
  7163. status: "ready",
  7164. defaultModel: "minimax/MiniMax-M2.7",
  7165. providerId: "minimax",
  7166. modelId: "MiniMax-M2.7",
  7167. authMode: "managed-login",
  7168. managedTokenPresent: true,
  7169. warnings: [],
  7170. });
  7171. }),
  7172. );
  7173. app.editor.handleInput("\r");
  7174. await vi.waitFor(() =>
  7175. expect(app.controller.snapshot().activeTurnId).toBeDefined(),
  7176. );
  7177. terminal.input?.("\u001b");
  7178. releaseAdmission();
  7179. await vi.waitFor(() =>
  7180. expect(app.editor.getExpandedText()).toBe(
  7181. "/help should remain message text [File #1] ",
  7182. ),
  7183. );
  7184. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7185. app.editor.handleInput("\r");
  7186. await vi.waitFor(() =>
  7187. expect(runtime.sendMessage).toHaveBeenCalledTimes(
  7188. sendCountBeforeEdit + 1,
  7189. ),
  7190. );
  7191. expect(vi.mocked(runtime.sendMessage).mock.calls.at(-1)?.[0]).toMatchObject(
  7192. {
  7193. content: [
  7194. "<mavis-chat-context>",
  7195. "Referenced context",
  7196. "</mavis-chat-context>",
  7197. "",
  7198. "/help should remain message text",
  7199. ].join("\n"),
  7200. attachments: [
  7201. {
  7202. meta: {
  7203. attachmentType: "file",
  7204. fileName: "context.md",
  7205. mimeType: "text/markdown",
  7206. sizeBytes: 42,
  7207. },
  7208. local: { assetId: "asset-context-md" },
  7209. },
  7210. ],
  7211. },
  7212. );
  7213. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1);
  7214. expect(
  7215. app.transcript
  7216. .snapshot()
  7217. .filter((cell) => cell.kind === "user")
  7218. .map((cell) => cell.content)
  7219. .join("\n"),
  7220. ).toContain("/help should remain message text");
  7221. expect(
  7222. app.transcript
  7223. .snapshot()
  7224. .filter((cell) => cell.kind === "user")
  7225. .map((cell) => cell.content)
  7226. .join("\n"),
  7227. ).not.toContain("mavis-chat-context");
  7228. await app.stop();
  7229. });
  7230. it("allows an attachment-only committed message to enter Edit and gain a body", async () => {
  7231. const terminal = new FakeTerminal();
  7232. const runtime = createRuntime();
  7233. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7234. {
  7235. userMessageId: "msg-user-v1-attachment-only",
  7236. assistantMessageId: "msg-assistant-v1-attachment-only",
  7237. timestamp: 1_700_000_000_000,
  7238. fileChangeCount: 0,
  7239. },
  7240. ]);
  7241. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7242. messages: [
  7243. {
  7244. id: "msg-user-v1-attachment-only",
  7245. role: "user",
  7246. content: "",
  7247. attachments: [
  7248. {
  7249. type: "image",
  7250. fileName: "reference.png",
  7251. mimeType: "image/png",
  7252. filePath: "/workspace/reference.png",
  7253. },
  7254. ],
  7255. timestamp: 1_700_000_000_000,
  7256. },
  7257. ],
  7258. hasMore: false,
  7259. });
  7260. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7261. const app = createTuiApp({
  7262. runtime,
  7263. terminal,
  7264. version: "0.1.0",
  7265. workspaceDir: "/workspace",
  7266. });
  7267. app.start();
  7268. await app.ready;
  7269. await app.submit("Seed edit session");
  7270. const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
  7271. .length;
  7272. await app.submit("/edit");
  7273. await vi.waitFor(() =>
  7274. expect(app.tui.render(100).join("\n")).toContain(
  7275. "Editing the selected message",
  7276. ),
  7277. );
  7278. expect(app.editor.getExpandedText()).toBe("[Image #1] ");
  7279. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7280. kind: "chat",
  7281. id: "chat",
  7282. });
  7283. app.editor.setText("Describe this reference");
  7284. app.editor.handleInput("\r");
  7285. await vi.waitFor(() =>
  7286. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7287. );
  7288. expect(runtime.editSessionMessage).toHaveBeenCalledWith({
  7289. sessionId: "session-1",
  7290. userMessageId: "msg-user-v1-attachment-only",
  7291. clientRequestId: expect.stringMatching(/^tui-edit_/u),
  7292. content: "Describe this reference",
  7293. attachments: [
  7294. {
  7295. type: "image",
  7296. fileName: "reference.png",
  7297. mimeType: "image/png",
  7298. filePath: "/workspace/reference.png",
  7299. },
  7300. ],
  7301. rewindTurnDiff: true,
  7302. });
  7303. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7304. await app.stop();
  7305. });
  7306. it("keeps a second composer submission while an edit request is still in flight", async () => {
  7307. const terminal = new FakeTerminal();
  7308. const runtime = createRuntime();
  7309. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7310. {
  7311. userMessageId: "msg-user-v1-target",
  7312. assistantMessageId: "msg-assistant-v1-target",
  7313. contentHead: "Original prompt",
  7314. timestamp: 1,
  7315. fileChangeCount: 0,
  7316. },
  7317. ]);
  7318. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7319. messages: [
  7320. {
  7321. id: "msg-user-v1-target",
  7322. role: "user",
  7323. content: "Original prompt",
  7324. timestamp: 1,
  7325. },
  7326. ],
  7327. hasMore: false,
  7328. });
  7329. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7330. let resolveEdit!: (value: {
  7331. rewound: boolean;
  7332. turnId: string;
  7333. userMessageId: string;
  7334. }) => void;
  7335. vi.mocked(runtime.editSessionMessage).mockImplementation(
  7336. () =>
  7337. new Promise((resolve) => {
  7338. resolveEdit = resolve;
  7339. }),
  7340. );
  7341. const app = createTuiApp({
  7342. runtime,
  7343. terminal,
  7344. version: "0.1.0",
  7345. workspaceDir: "/workspace",
  7346. });
  7347. app.start();
  7348. await app.ready;
  7349. await app.submit("Seed edit session");
  7350. const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
  7351. .length;
  7352. await app.submit("/edit");
  7353. await vi.waitFor(() =>
  7354. expect(app.editor.getText()).toBe("Original prompt"),
  7355. );
  7356. app.editor.setText("First edited prompt");
  7357. app.editor.handleInput("\r");
  7358. await vi.waitFor(() =>
  7359. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7360. );
  7361. app.editor.setText("Keep this until edit settles");
  7362. app.editor.handleInput("\r");
  7363. await vi.waitFor(() =>
  7364. expect(app.editor.getText()).toBe("Keep this until edit settles"),
  7365. );
  7366. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7367. resolveEdit({
  7368. rewound: true,
  7369. turnId: "turn-edit-1",
  7370. userMessageId: "msg-user-v1-edited",
  7371. });
  7372. await app.stop();
  7373. });
  7374. it("preserves the edit and retries the same operation when submission fails after rewind", async () => {
  7375. const terminal = new FakeTerminal();
  7376. const runtime = createRuntime();
  7377. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7378. {
  7379. userMessageId: "msg-user-v1-target",
  7380. assistantMessageId: "msg-assistant-v1-target",
  7381. contentHead: "Original prompt",
  7382. timestamp: 1,
  7383. fileChangeCount: 0,
  7384. },
  7385. ]);
  7386. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7387. messages: [
  7388. {
  7389. id: "msg-user-v1-target",
  7390. role: "user",
  7391. content: "Original prompt",
  7392. timestamp: 1,
  7393. },
  7394. ],
  7395. hasMore: false,
  7396. });
  7397. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7398. vi.mocked(runtime.editSessionMessage)
  7399. .mockRejectedValueOnce(
  7400. Object.assign(new Error("submit failed"), {
  7401. key: "EDIT_SUBMIT_FAILED_AFTER_REWIND",
  7402. }),
  7403. )
  7404. .mockResolvedValueOnce({
  7405. rewound: true,
  7406. turnId: "turn-edit-retry",
  7407. userMessageId: "msg-user-v1-edited",
  7408. });
  7409. const app = createTuiApp({
  7410. runtime,
  7411. terminal,
  7412. version: "0.1.0",
  7413. workspaceDir: "/workspace",
  7414. });
  7415. app.start();
  7416. await app.ready;
  7417. await app.submit("Seed edit session");
  7418. await app.submit("/edit");
  7419. await vi.waitFor(() =>
  7420. expect(app.editor.getText()).toBe("Original prompt"),
  7421. );
  7422. app.editor.setText("Preserve this edited prompt");
  7423. app.editor.handleInput("\r");
  7424. await vi.waitFor(() =>
  7425. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7426. );
  7427. await vi.waitFor(() =>
  7428. expect(app.editor.getText()).toBe("Preserve this edited prompt"),
  7429. );
  7430. expect(
  7431. app.transcript
  7432. .snapshot()
  7433. .some((cell) => cell.content.includes("History was rewound")),
  7434. ).toBe(true);
  7435. const firstOperationId = vi.mocked(runtime.editSessionMessage).mock
  7436. .calls[0]?.[0].clientRequestId;
  7437. const sendCount = vi.mocked(runtime.sendMessage).mock.calls.length;
  7438. app.editor.handleInput("\r");
  7439. await vi.waitFor(() =>
  7440. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(2),
  7441. );
  7442. expect(runtime.editSessionMessage).toHaveBeenLastCalledWith(
  7443. expect.objectContaining({ clientRequestId: firstOperationId }),
  7444. );
  7445. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCount);
  7446. await app.stop();
  7447. });
  7448. it.each(['/rewind', '/fork'])(
  7449. 'clears the loading hint after %s history loads and stays clear after cancellation',
  7450. async (command) => {
  7451. const terminal = new FakeTerminal();
  7452. const runtime = createRuntime();
  7453. let resolveHistory!: (
  7454. value: Awaited<ReturnType<TuiRuntime['listSessionInputSummaries']>>,
  7455. ) => void;
  7456. vi.mocked(runtime.listSessionInputSummaries).mockImplementation(
  7457. () =>
  7458. new Promise((resolve) => {
  7459. resolveHistory = resolve;
  7460. }),
  7461. );
  7462. const app = createTuiApp({ runtime, terminal, version: '0.1.0', workspaceDir: '/workspace' });
  7463. app.start();
  7464. try {
  7465. await app.ready;
  7466. await app.submit('Seed session');
  7467. await app.submit(command);
  7468. const loadingChat = stripAnsi(app.tui.render(120).join('\n'));
  7469. expect(loadingChat).toMatch(/Loading|Finding/);
  7470. resolveHistory([{ userMessageId: 'history-user', timestamp: 1, fileChangeCount: 0 }]);
  7471. await vi.waitFor(() =>
  7472. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7473. kind: 'feature',
  7474. id: 'session-mutation:history',
  7475. }),
  7476. );
  7477. expect(stripAnsi(app.tui.render(120).join('\n'))).not.toMatch(
  7478. /Loading (?:rewind|fork) history|Finding messages/,
  7479. );
  7480. terminal.input?.('\x1b');
  7481. expect(app.surfaceHost.getActiveSurface()).toEqual({ kind: 'chat', id: 'chat' });
  7482. expect(stripAnsi(app.tui.render(120).join('\n'))).not.toMatch(
  7483. /Loading (?:rewind|fork) history|Finding messages/,
  7484. );
  7485. } finally {
  7486. await app.stop();
  7487. }
  7488. },
  7489. );
  7490. it("cancels /rewind preview and ignores duplicate scope submission", async () => {
  7491. const terminal = new FakeTerminal();
  7492. const runtime = createRuntime();
  7493. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7494. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7495. ]);
  7496. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7497. turns: [
  7498. {
  7499. turnId: "turn-1",
  7500. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7501. },
  7502. ],
  7503. });
  7504. let resolveRewind!: (value: { rewound: boolean }) => void;
  7505. vi.mocked(runtime.rewindSession).mockImplementation(
  7506. () =>
  7507. new Promise((resolve) => {
  7508. resolveRewind = resolve;
  7509. }),
  7510. );
  7511. const app = createTuiApp({
  7512. runtime,
  7513. terminal,
  7514. version: "0.1.0",
  7515. workspaceDir: "/workspace",
  7516. });
  7517. app.start();
  7518. await app.ready;
  7519. await app.submit("Seed rewind session");
  7520. await app.submit("/rewind");
  7521. await vi.waitFor(() =>
  7522. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7523. kind: "feature",
  7524. id: "session-mutation:history",
  7525. }),
  7526. );
  7527. terminal.input?.("\r");
  7528. await vi.waitFor(() =>
  7529. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7530. kind: "feature",
  7531. id: "session-mutation:rewind-preview",
  7532. }),
  7533. );
  7534. terminal.input?.("\u001b");
  7535. expect(runtime.rewindSession).not.toHaveBeenCalled();
  7536. await app.submit("/rewind");
  7537. await vi.waitFor(() =>
  7538. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7539. kind: "feature",
  7540. id: "session-mutation:history",
  7541. }),
  7542. );
  7543. terminal.input?.("\r");
  7544. await vi.waitFor(() =>
  7545. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7546. kind: "feature",
  7547. id: "session-mutation:rewind-preview",
  7548. }),
  7549. );
  7550. terminal.input?.("\r");
  7551. await vi.waitFor(() =>
  7552. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7553. kind: "feature",
  7554. id: "session-mutation:scope",
  7555. }),
  7556. );
  7557. terminal.input?.("\r");
  7558. await vi.waitFor(() =>
  7559. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7560. kind: "feature",
  7561. id: "session-mutation:rewind-confirm",
  7562. }),
  7563. );
  7564. terminal.input?.("\r");
  7565. await vi.waitFor(() =>
  7566. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7567. );
  7568. terminal.input?.("\u001b");
  7569. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7570. kind: "feature",
  7571. id: "session-mutation:rewind-confirm",
  7572. });
  7573. resolveRewind({ rewound: true });
  7574. await vi.waitFor(() => expect(app.surfaceHost.getActiveSurface()).toEqual({ kind: 'chat', id: 'chat' }));
  7575. expect(stripAnsi(app.tui.render(120).join('\n'))).toContain('Rewound 1 turn');
  7576. expect(stripAnsi(app.tui.render(120).join('\n'))).not.toMatch(/Loading rewind history|Finding messages/);
  7577. await app.stop();
  7578. });
  7579. it("invalidates /rewind when the active session switches before mutation", async () => {
  7580. const terminal = new FakeTerminal();
  7581. const runtime = createRuntime();
  7582. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7583. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 0 },
  7584. ]);
  7585. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7586. const app = createTuiApp({
  7587. runtime,
  7588. terminal,
  7589. version: "0.1.0",
  7590. workspaceDir: "/workspace",
  7591. });
  7592. app.start();
  7593. await app.ready;
  7594. await app.submit("Seed rewind session");
  7595. await app.submit("/rewind");
  7596. await vi.waitFor(() =>
  7597. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7598. kind: "feature",
  7599. id: "session-mutation:history",
  7600. }),
  7601. );
  7602. const other = {
  7603. sessionId: "session-other",
  7604. title: "Other",
  7605. workspaceDir: "/workspace",
  7606. };
  7607. vi.mocked(runtime.getSession).mockResolvedValue(other);
  7608. await app.openSession(other.sessionId);
  7609. terminal.input?.("\r");
  7610. await new Promise((resolve) => setTimeout(resolve, 20));
  7611. expect(runtime.getSessionRewindPreview).not.toHaveBeenCalled();
  7612. expect(runtime.rewindSession).not.toHaveBeenCalled();
  7613. expect(app.controller.snapshot().session?.sessionId).toBe(other.sessionId);
  7614. await app.stop();
  7615. });
  7616. it("retries a failed file rewind with the same operation id", async () => {
  7617. const terminal = new FakeTerminal();
  7618. const runtime = createRuntime();
  7619. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7620. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7621. ]);
  7622. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7623. turns: [
  7624. {
  7625. turnId: "turn-1",
  7626. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7627. },
  7628. ],
  7629. });
  7630. vi.mocked(runtime.rewindSession)
  7631. .mockRejectedValueOnce(new Error("temporary conflict"))
  7632. .mockResolvedValueOnce({
  7633. rewound: true,
  7634. turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
  7635. });
  7636. const app = createTuiApp({
  7637. runtime,
  7638. terminal,
  7639. version: "0.1.0",
  7640. workspaceDir: "/workspace",
  7641. });
  7642. app.start();
  7643. await app.ready;
  7644. await app.submit("Seed rewind session");
  7645. await app.submit("/rewind");
  7646. await vi.waitFor(() =>
  7647. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7648. kind: "feature",
  7649. id: "session-mutation:history",
  7650. }),
  7651. );
  7652. terminal.input?.("\r");
  7653. await vi.waitFor(() =>
  7654. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7655. kind: "feature",
  7656. id: "session-mutation:rewind-preview",
  7657. }),
  7658. );
  7659. terminal.input?.("\r");
  7660. await vi.waitFor(() =>
  7661. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7662. kind: "feature",
  7663. id: "session-mutation:scope",
  7664. }),
  7665. );
  7666. terminal.input?.("\u001b[B");
  7667. terminal.input?.("\r");
  7668. await vi.waitFor(() =>
  7669. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7670. kind: "feature",
  7671. id: "session-mutation:rewind-confirm",
  7672. }),
  7673. );
  7674. terminal.input?.("\r");
  7675. await vi.waitFor(() =>
  7676. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7677. );
  7678. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7679. kind: "feature",
  7680. id: "session-mutation:rewind-confirm",
  7681. });
  7682. terminal.input?.("\r");
  7683. await vi.waitFor(() =>
  7684. expect(runtime.rewindSession).toHaveBeenCalledTimes(2),
  7685. );
  7686. const ids = vi
  7687. .mocked(runtime.rewindSession)
  7688. .mock.calls.map(([input]) => input.clientRequestId);
  7689. expect(ids[0]).toBe(ids[1]);
  7690. await app.stop();
  7691. });
  7692. it.each([
  7693. [
  7694. "terminal busy failure",
  7695. "CONVERSATION_MUTATION_BUSY",
  7696. "Stop the running response and try again.",
  7697. false,
  7698. ],
  7699. [
  7700. "pending display publication",
  7701. "REWIND_DISPLAY_COMMIT_FAILED",
  7702. "retry with the same operation id",
  7703. true,
  7704. ],
  7705. ] as const)(
  7706. "keeps a failed conversation rewind open and retries %s with the correct operation id",
  7707. async (_label, errorCode, expectedCopy, reuseOperationId) => {
  7708. const terminal = new FakeTerminal();
  7709. const runtime = createRuntime();
  7710. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7711. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 0 },
  7712. ]);
  7713. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7714. turns: [],
  7715. });
  7716. vi.mocked(runtime.rewindSession)
  7717. .mockRejectedValueOnce(
  7718. Object.assign(new Error("rewind failed"), { key: errorCode }),
  7719. )
  7720. .mockResolvedValueOnce({ rewound: true });
  7721. const app = createTuiApp({
  7722. runtime,
  7723. terminal,
  7724. version: "0.1.0",
  7725. workspaceDir: "/workspace",
  7726. });
  7727. app.start();
  7728. await app.ready;
  7729. await app.submit("Seed rewind session");
  7730. await app.submit("/rewind");
  7731. await vi.waitFor(() =>
  7732. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7733. kind: "feature",
  7734. id: "session-mutation:history",
  7735. }),
  7736. );
  7737. terminal.input?.("\r");
  7738. await vi.waitFor(() =>
  7739. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7740. kind: "feature",
  7741. id: "session-mutation:rewind-preview",
  7742. }),
  7743. );
  7744. terminal.input?.("\r");
  7745. await vi.waitFor(() =>
  7746. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7747. kind: "feature",
  7748. id: "session-mutation:scope",
  7749. }),
  7750. );
  7751. terminal.input?.("\r");
  7752. await vi.waitFor(() =>
  7753. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7754. kind: "feature",
  7755. id: "session-mutation:rewind-confirm",
  7756. }),
  7757. );
  7758. terminal.input?.("\r");
  7759. await vi.waitFor(() =>
  7760. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7761. );
  7762. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7763. kind: "feature",
  7764. id: "session-mutation:rewind-confirm",
  7765. });
  7766. expect(renderTerminalViewport(app, terminal)).toContain(expectedCopy);
  7767. terminal.input?.("\r");
  7768. await vi.waitFor(() =>
  7769. expect(runtime.rewindSession).toHaveBeenCalledTimes(2),
  7770. );
  7771. const ids = vi
  7772. .mocked(runtime.rewindSession)
  7773. .mock.calls.map(([input]) => input.clientRequestId);
  7774. if (reuseOperationId) expect(ids[0]).toBe(ids[1]);
  7775. else expect(ids[0]).not.toBe(ids[1]);
  7776. await app.stop();
  7777. },
  7778. );
  7779. it.each([
  7780. [
  7781. "failed-after-rewind",
  7782. {
  7783. status: "failed-after-rewind",
  7784. revertedTurnIds: ["turn-1"],
  7785. errorCode: "conflict",
  7786. },
  7787. ],
  7788. ["empty-reverted-ids", { status: "rewound", revertedTurnIds: [] }],
  7789. [
  7790. "unknown-status",
  7791. { status: "future-runtime-status", revertedTurnIds: ["turn-1"] },
  7792. ],
  7793. ] as const)(
  7794. "does not report %s as a successful file rewind",
  7795. async (_label, turnDiffRewind) => {
  7796. const terminal = new FakeTerminal();
  7797. const runtime = createRuntime();
  7798. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7799. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7800. ]);
  7801. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7802. turns: [
  7803. {
  7804. turnId: "turn-1",
  7805. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7806. },
  7807. ],
  7808. });
  7809. vi.mocked(runtime.rewindSession).mockResolvedValue({
  7810. rewound: true,
  7811. turnDiffRewind,
  7812. });
  7813. const app = createTuiApp({
  7814. runtime,
  7815. terminal,
  7816. version: "0.1.0",
  7817. workspaceDir: "/workspace",
  7818. });
  7819. app.start();
  7820. await app.ready;
  7821. await app.submit("Seed rewind session");
  7822. await app.submit("/rewind");
  7823. await vi.waitFor(() =>
  7824. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7825. kind: "feature",
  7826. id: "session-mutation:history",
  7827. }),
  7828. );
  7829. terminal.input?.("\r");
  7830. await vi.waitFor(() =>
  7831. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7832. kind: "feature",
  7833. id: "session-mutation:rewind-preview",
  7834. }),
  7835. );
  7836. terminal.input?.("\r");
  7837. await vi.waitFor(() =>
  7838. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7839. kind: "feature",
  7840. id: "session-mutation:scope",
  7841. }),
  7842. );
  7843. terminal.input?.("\u001b[B");
  7844. terminal.input?.("\r");
  7845. await vi.waitFor(() =>
  7846. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7847. kind: "feature",
  7848. id: "session-mutation:rewind-confirm",
  7849. }),
  7850. );
  7851. terminal.input?.("\r");
  7852. await vi.waitFor(() =>
  7853. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7854. );
  7855. await vi.waitFor(() =>
  7856. expect(app.transcript.snapshot().at(-1)?.content).toMatch(
  7857. /did not complete|No file changes/,
  7858. ),
  7859. );
  7860. expect(app.transcript.snapshot().at(-1)?.content).not.toContain(
  7861. "Files rewound; conversation history was kept.",
  7862. );
  7863. await app.stop();
  7864. },
  7865. );
  7866. it.each([
  7867. [
  7868. "MESSAGE_BOUNDARY_INVALID",
  7869. "This conversation point is no longer available.",
  7870. ],
  7871. [
  7872. "CONVERSATION_MUTATION_REQUEST_CONFLICT",
  7873. "This action was already submitted or became stale.",
  7874. ],
  7875. ["CONVERSATION_MUTATION_BUSY", "Stop the running response and try again."],
  7876. ] as const)(
  7877. "maps rewind Runtime error %s to stable copy",
  7878. async (code, expected) => {
  7879. const terminal = new FakeTerminal();
  7880. const runtime = createRuntime();
  7881. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7882. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7883. ]);
  7884. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7885. turns: [
  7886. {
  7887. turnId: "turn-1",
  7888. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7889. },
  7890. ],
  7891. });
  7892. vi.mocked(runtime.rewindSession).mockRejectedValue(
  7893. Object.assign(new Error("raw prompt token=secret"), { key: code }),
  7894. );
  7895. const app = createTuiApp({
  7896. runtime,
  7897. terminal,
  7898. version: "0.1.0",
  7899. workspaceDir: "/workspace",
  7900. });
  7901. app.start();
  7902. await app.ready;
  7903. await app.submit("Seed rewind session");
  7904. await app.submit("/rewind");
  7905. await vi.waitFor(() =>
  7906. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7907. kind: "feature",
  7908. id: "session-mutation:history",
  7909. }),
  7910. );
  7911. terminal.input?.("\r");
  7912. await vi.waitFor(() =>
  7913. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7914. kind: "feature",
  7915. id: "session-mutation:rewind-preview",
  7916. }),
  7917. );
  7918. terminal.input?.("\r");
  7919. await vi.waitFor(() =>
  7920. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7921. kind: "feature",
  7922. id: "session-mutation:scope",
  7923. }),
  7924. );
  7925. terminal.input?.("\u001b[B");
  7926. terminal.input?.("\r");
  7927. await vi.waitFor(() =>
  7928. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7929. kind: "feature",
  7930. id: "session-mutation:rewind-confirm",
  7931. }),
  7932. );
  7933. terminal.input?.("\r");
  7934. await vi.waitFor(() =>
  7935. expect(
  7936. app.transcript.snapshot().some((cell) => cell.content === expected),
  7937. ),
  7938. );
  7939. expect(
  7940. app.transcript
  7941. .snapshot()
  7942. .some((cell) => cell.content.includes("raw prompt token")),
  7943. ).toBe(false);
  7944. await app.stop();
  7945. },
  7946. );
  7947. it("reports refresh failure without unhandled rejection after conversation-and-files rewind", async () => {
  7948. const terminal = new FakeTerminal();
  7949. const runtime = createRuntime();
  7950. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7951. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7952. ]);
  7953. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7954. turns: [
  7955. {
  7956. turnId: "turn-1",
  7957. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7958. },
  7959. ],
  7960. });
  7961. vi.mocked(runtime.rewindSession).mockResolvedValue({
  7962. rewound: true,
  7963. turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
  7964. });
  7965. vi.mocked(runtime.getMessages).mockRejectedValueOnce(
  7966. new Error("refresh unavailable"),
  7967. );
  7968. const app = createTuiApp({
  7969. runtime,
  7970. terminal,
  7971. version: "0.1.0",
  7972. workspaceDir: "/workspace",
  7973. });
  7974. app.start();
  7975. await app.ready;
  7976. await app.submit("Seed rewind session");
  7977. await app.submit("/rewind");
  7978. await vi.waitFor(() =>
  7979. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7980. kind: "feature",
  7981. id: "session-mutation:history",
  7982. }),
  7983. );
  7984. terminal.input?.("\r");
  7985. await vi.waitFor(() =>
  7986. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7987. kind: "feature",
  7988. id: "session-mutation:rewind-preview",
  7989. }),
  7990. );
  7991. terminal.input?.("\r");
  7992. await vi.waitFor(() =>
  7993. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7994. kind: "feature",
  7995. id: "session-mutation:scope",
  7996. }),
  7997. );
  7998. terminal.input?.("\u001b[B");
  7999. terminal.input?.("\r");
  8000. await vi.waitFor(() =>
  8001. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8002. kind: "feature",
  8003. id: "session-mutation:rewind-confirm",
  8004. }),
  8005. );
  8006. terminal.input?.("\r");
  8007. await vi.waitFor(() =>
  8008. expect(
  8009. app.transcript
  8010. .snapshot()
  8011. .some((cell) => cell.content.includes("could not be refreshed")),
  8012. ),
  8013. );
  8014. await app.stop();
  8015. });
  8016. it("does not apply a pending rewind refresh result after switching sessions", async () => {
  8017. const terminal = new FakeTerminal();
  8018. const runtime = createRuntime();
  8019. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  8020. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  8021. ]);
  8022. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  8023. turns: [
  8024. {
  8025. turnId: "turn-1",
  8026. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  8027. },
  8028. ],
  8029. });
  8030. vi.mocked(runtime.rewindSession).mockResolvedValue({
  8031. rewound: true,
  8032. turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
  8033. });
  8034. let resolveRefresh!: (messages: readonly TuiMessage[]) => void;
  8035. const refreshPromise = new Promise<readonly TuiMessage[]>((resolve) => {
  8036. resolveRefresh = resolve;
  8037. });
  8038. const app = createTuiApp({
  8039. runtime,
  8040. terminal,
  8041. version: "0.1.0",
  8042. workspaceDir: "/workspace",
  8043. });
  8044. app.start();
  8045. await app.ready;
  8046. await app.submit("Seed rewind session");
  8047. vi.mocked(runtime.getMessages).mockImplementationOnce(() => refreshPromise);
  8048. await app.submit("/rewind");
  8049. await vi.waitFor(() =>
  8050. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8051. kind: "feature",
  8052. id: "session-mutation:history",
  8053. }),
  8054. );
  8055. terminal.input?.("\r");
  8056. await vi.waitFor(() =>
  8057. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8058. kind: "feature",
  8059. id: "session-mutation:rewind-preview",
  8060. }),
  8061. );
  8062. terminal.input?.("\r");
  8063. await vi.waitFor(() =>
  8064. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8065. kind: "feature",
  8066. id: "session-mutation:scope",
  8067. }),
  8068. );
  8069. terminal.input?.("\u001b[B");
  8070. terminal.input?.("\r");
  8071. await vi.waitFor(() =>
  8072. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8073. kind: "feature",
  8074. id: "session-mutation:rewind-confirm",
  8075. }),
  8076. );
  8077. terminal.input?.("\r");
  8078. await vi.waitFor(() =>
  8079. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  8080. );
  8081. const other = {
  8082. sessionId: "session-other",
  8083. title: "Other",
  8084. workspaceDir: "/workspace",
  8085. };
  8086. vi.mocked(runtime.getSession).mockResolvedValue(other);
  8087. vi.mocked(runtime.getMessages).mockResolvedValue([]);
  8088. const open = app.openSession(other.sessionId);
  8089. resolveRefresh([
  8090. {
  8091. id: "stale-message",
  8092. role: "assistant",
  8093. content: "stale",
  8094. timestamp: 3,
  8095. },
  8096. ]);
  8097. await open;
  8098. expect(app.controller.snapshot().session?.sessionId).toBe(other.sessionId);
  8099. expect(
  8100. app.transcript
  8101. .snapshot()
  8102. .some((cell) => cell.content.includes("Files rewound")),
  8103. ).toBe(false);
  8104. await app.stop();
  8105. });
  8106. it("redirects a hidden task child to its parent before rendering", async () => {
  8107. const runtime = createRuntime();
  8108. const parent = {
  8109. sessionId: "session-parent",
  8110. title: "CLI integration",
  8111. workspaceDir: "/workspace",
  8112. };
  8113. const child = {
  8114. sessionId: "session-child",
  8115. parentSessionId: parent.sessionId,
  8116. title: "Review recent CLI changes",
  8117. workspaceDir: "/workspace",
  8118. sessionType: "branch",
  8119. sessionKind: "task",
  8120. visibility: "hidden",
  8121. purpose: "local-task:turn-1:tool-1",
  8122. agentName: "verifier",
  8123. };
  8124. vi.mocked(runtime.listSessions).mockResolvedValue([parent]);
  8125. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  8126. sessionId === child.sessionId ? child : parent,
  8127. );
  8128. const app = createTuiApp({
  8129. runtime,
  8130. terminal: new FakeTerminal(),
  8131. version: "0.1.0",
  8132. workspaceDir: "/workspace",
  8133. });
  8134. await app.ready;
  8135. await app.openSession(child.sessionId);
  8136. expect(runtime.getSession).toHaveBeenLastCalledWith(parent.sessionId);
  8137. expect(app.controller.snapshot().session?.sessionId).toBe(parent.sessionId);
  8138. expect(app.tui.render(140).join("\n")).not.toContain("Sub: verifier");
  8139. expect(app.transcript.snapshot().at(-1)?.content).toBe(
  8140. "Sub-agent Sessions are internal. Opened the parent Session instead.",
  8141. );
  8142. await app.stop();
  8143. });
  8144. it("shows compact Agent Team status without exposing child details or commands", async () => {
  8145. const terminal = new FakeTerminal();
  8146. terminal.rows = 24;
  8147. const runtime = createRuntime();
  8148. const parent = {
  8149. sessionId: "session-parent",
  8150. title: "Agent Team parent",
  8151. workspaceDir: "/workspace",
  8152. };
  8153. const child = {
  8154. sessionId: "session-child",
  8155. parentSessionId: parent.sessionId,
  8156. title: "Verify the TUI",
  8157. workspaceDir: "/workspace",
  8158. sessionType: "branch" as const,
  8159. sessionKind: "task",
  8160. visibility: "hidden" as const,
  8161. purpose: "local-task:turn-1:tool-1",
  8162. agentName: "verifier",
  8163. status: "finished",
  8164. };
  8165. vi.mocked(runtime.listSessions).mockResolvedValue([parent]);
  8166. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  8167. sessionId === child.sessionId ? child : parent,
  8168. );
  8169. vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
  8170. schemaVersion: 1,
  8171. rootSessionId: parent.sessionId,
  8172. members: [
  8173. {
  8174. sessionId: child.sessionId,
  8175. parentSessionId: parent.sessionId,
  8176. agentName: child.agentName,
  8177. task: child.title,
  8178. status: "running",
  8179. createdAtMs: 100,
  8180. updatedAtMs: 200,
  8181. },
  8182. ],
  8183. });
  8184. vi.mocked(runtime.getMessages).mockImplementation(async (sessionId) =>
  8185. sessionId === child.sessionId
  8186. ? [
  8187. {
  8188. id: "child-answer",
  8189. turnId: "turn-child",
  8190. role: "assistant",
  8191. content: "Child verification result",
  8192. timestamp: 200,
  8193. },
  8194. ]
  8195. : [],
  8196. );
  8197. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  8198. schemaVersion: 1,
  8199. sessionId,
  8200. state: sessionId === child.sessionId ? "running" : "idle",
  8201. ...(sessionId === child.sessionId ? { turnId: "turn-child" } : {}),
  8202. actions: { steer: false },
  8203. }));
  8204. const app = createTuiApp({
  8205. runtime,
  8206. terminal,
  8207. version: "0.1.0",
  8208. workspaceDir: "/workspace",
  8209. });
  8210. await app.ready;
  8211. await app.openSession(parent.sessionId);
  8212. app.start();
  8213. const summary = app.tui.render(100).join("\n");
  8214. expect(summary).toContain("Tasks · 1 agent active · /tasks details");
  8215. expect(summary).not.toContain("verifier");
  8216. expect(summary).not.toContain("/agents");
  8217. expect(
  8218. app.transcript.snapshot().some((cell) => cell.kind === "agent-team"),
  8219. ).toBe(false);
  8220. await app.submit("/agents");
  8221. await app.submit("/team");
  8222. expect(app.controller.snapshot().session?.sessionId).toBe(parent.sessionId);
  8223. expect(app.tui.hasOverlay()).toBe(false);
  8224. expect(app.interaction.isActive()).toBe(false);
  8225. expect(app.tui.render(100).join("\n")).not.toContain(
  8226. "Child verification result",
  8227. );
  8228. expect(
  8229. vi
  8230. .mocked(runtime.sendMessage)
  8231. .mock.calls.map(([request]) => request.content),
  8232. ).toEqual(["/agents", "/team"]);
  8233. await app.stop();
  8234. });
  8235. it("allocates enough standard-terminal space for ten session choices", async () => {
  8236. const terminal = new FakeTerminal();
  8237. terminal.rows = 24;
  8238. const runtime = createRuntime();
  8239. vi.mocked(runtime.listSessionPage).mockResolvedValue({
  8240. sessions: Array.from({ length: 12 }, (_, index) => ({
  8241. sessionId: `session-${String(index + 1).padStart(2, "0")}`,
  8242. title: `Session ${String(index + 1).padStart(2, "0")}`,
  8243. workspaceDir: "/workspace",
  8244. updatedAt: 12 - index,
  8245. })),
  8246. hasMore: false,
  8247. });
  8248. const app = createTuiApp({
  8249. runtime,
  8250. terminal,
  8251. version: "0.1.0",
  8252. workspaceDir: "/workspace",
  8253. });
  8254. await app.submit("/sessions");
  8255. const lines = app.interaction.current()?.render(80) ?? [];
  8256. const rendered = lines.join("\n");
  8257. expect(lines.length).toBeLessThanOrEqual(terminal.rows);
  8258. expect(rendered).toContain("Session 10");
  8259. expect(rendered).not.toContain("Session 11");
  8260. });
  8261. it("switches, restores, and resumes archived Desktop sessions from the session manager", async () => {
  8262. const terminal = new FakeTerminal();
  8263. const runtime = createRuntime();
  8264. let archived = true;
  8265. const activeSession = {
  8266. sessionId: "session-active",
  8267. title: "Active session",
  8268. workspaceDir: "/workspace",
  8269. updatedAt: 200,
  8270. };
  8271. const archivedSession = {
  8272. sessionId: "session-archived",
  8273. title: "Archived session",
  8274. workspaceDir: "/workspace",
  8275. updatedAt: 100,
  8276. archived: true,
  8277. };
  8278. vi.mocked(runtime.listSessions).mockResolvedValue([activeSession]);
  8279. vi.mocked(runtime.listSessionPage).mockResolvedValue({
  8280. sessions: [activeSession, archivedSession],
  8281. hasMore: false,
  8282. });
  8283. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) => ({
  8284. ...(sessionId === archivedSession.sessionId
  8285. ? archivedSession
  8286. : activeSession),
  8287. archived: sessionId === archivedSession.sessionId ? archived : false,
  8288. }));
  8289. vi.mocked(runtime.archiveSession).mockImplementation(
  8290. async (_sessionId, value) => {
  8291. archived = value;
  8292. },
  8293. );
  8294. const app = createTuiApp({
  8295. runtime,
  8296. terminal,
  8297. version: "0.1.0",
  8298. workspaceDir: "/workspace",
  8299. });
  8300. app.start();
  8301. await app.ready;
  8302. await app.submit("/sessions");
  8303. expect(runtime.listSessionPage).toHaveBeenCalledWith({
  8304. allAgents: true,
  8305. workspaceDir: "/workspace",
  8306. limit: 50,
  8307. includeArchived: true,
  8308. includeHidden: true,
  8309. });
  8310. expect(app.tui.hasOverlay()).toBe(false);
  8311. expect(app.interaction.isActive()).toBe(true);
  8312. terminal.input?.("\t");
  8313. terminal.input?.("\r");
  8314. await vi.waitFor(() =>
  8315. expect(runtime.archiveSession).toHaveBeenCalledWith(
  8316. "session-archived",
  8317. false,
  8318. ),
  8319. );
  8320. await vi.waitFor(() =>
  8321. expect(runtime.getMessages).toHaveBeenCalledWith("session-archived"),
  8322. );
  8323. expect(app.getSurface()).toBe("conversation");
  8324. expect(app.controller.snapshot().session?.sessionId).toBe(
  8325. "session-archived",
  8326. );
  8327. expect(app.tui.hasOverlay()).toBe(false);
  8328. await app.stop();
  8329. });
  8330. it("uses the resume alias to search every Desktop session page", async () => {
  8331. const terminal = new FakeTerminal();
  8332. const runtime = createRuntime();
  8333. vi.mocked(runtime.listSessionPage)
  8334. .mockResolvedValueOnce({
  8335. sessions: [
  8336. {
  8337. sessionId: "session-page-1",
  8338. title: "First page",
  8339. workspaceDir: "/workspace",
  8340. updatedAt: 200,
  8341. },
  8342. ],
  8343. hasMore: true,
  8344. nextCursor: "session-page-1",
  8345. })
  8346. .mockResolvedValueOnce({
  8347. sessions: [
  8348. {
  8349. sessionId: "session-page-2",
  8350. title: "Second page",
  8351. workspaceDir: "/workspace",
  8352. updatedAt: 100,
  8353. },
  8354. ],
  8355. hasMore: false,
  8356. });
  8357. const app = createTuiApp({
  8358. runtime,
  8359. terminal,
  8360. version: "0.1.0",
  8361. workspaceDir: "/workspace",
  8362. });
  8363. app.start();
  8364. await app.ready;
  8365. await app.submit("/resume Second page");
  8366. await vi.waitFor(() =>
  8367. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(2, {
  8368. allAgents: true,
  8369. workspaceDir: "/workspace",
  8370. limit: 50,
  8371. cursor: "session-page-1",
  8372. includeArchived: true,
  8373. includeHidden: true,
  8374. }),
  8375. );
  8376. expect(app.tui.hasOverlay()).toBe(false);
  8377. expect(app.interaction.isActive()).toBe(true);
  8378. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8379. "Second page",
  8380. );
  8381. await app.stop();
  8382. });
  8383. it("queries the current workspace first and reloads the global catalog on Ctrl+A", async () => {
  8384. const terminal = new FakeTerminal();
  8385. const runtime = createRuntime();
  8386. vi.mocked(runtime.listSessionPage).mockImplementation(
  8387. async (input = {}) => {
  8388. if (input.cursor === "all-page-2") {
  8389. return {
  8390. sessions: [
  8391. {
  8392. sessionId: "session-other-older",
  8393. title: "Older session elsewhere",
  8394. workspaceDir: "/other-workspace",
  8395. updatedAt: 50,
  8396. },
  8397. ],
  8398. hasMore: false,
  8399. };
  8400. }
  8401. return input.workspaceDir
  8402. ? {
  8403. sessions: [
  8404. {
  8405. sessionId: "session-workspace-old",
  8406. title: "Older workspace session",
  8407. workspaceDir: "/workspace",
  8408. updatedAt: 100,
  8409. },
  8410. ],
  8411. hasMore: false,
  8412. }
  8413. : {
  8414. sessions: [
  8415. {
  8416. sessionId: "session-other-new",
  8417. title: "Newer session elsewhere",
  8418. workspaceDir: "/other-workspace",
  8419. updatedAt: 200,
  8420. },
  8421. {
  8422. sessionId: "session-workspace-old",
  8423. title: "Older workspace session",
  8424. workspaceDir: "/workspace",
  8425. updatedAt: 100,
  8426. },
  8427. ],
  8428. hasMore: true,
  8429. nextCursor: "all-page-2",
  8430. };
  8431. },
  8432. );
  8433. const app = createTuiApp({
  8434. runtime,
  8435. terminal,
  8436. version: "0.1.0",
  8437. workspaceDir: "/workspace",
  8438. });
  8439. app.start();
  8440. await app.ready;
  8441. await app.submit("/sessions");
  8442. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(1, {
  8443. allAgents: true,
  8444. workspaceDir: "/workspace",
  8445. limit: 50,
  8446. includeArchived: true,
  8447. includeHidden: true,
  8448. });
  8449. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8450. "Older workspace session",
  8451. );
  8452. terminal.input?.("\x01");
  8453. await vi.waitFor(() =>
  8454. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(2, {
  8455. allAgents: true,
  8456. limit: 50,
  8457. includeArchived: true,
  8458. includeHidden: true,
  8459. }),
  8460. );
  8461. await vi.waitFor(() =>
  8462. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8463. "Newer session elsewhere",
  8464. ),
  8465. );
  8466. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8467. "All sessions",
  8468. );
  8469. terminal.input?.("\x0c");
  8470. await vi.waitFor(() =>
  8471. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(3, {
  8472. allAgents: true,
  8473. limit: 50,
  8474. cursor: "all-page-2",
  8475. includeArchived: true,
  8476. includeHidden: true,
  8477. }),
  8478. );
  8479. await vi.waitFor(() =>
  8480. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8481. "Older session elsewhere",
  8482. ),
  8483. );
  8484. await app.stop();
  8485. });
  8486. it("shows account status and resolves pending permission and questionnaire decisions", async () => {
  8487. const terminal = new FakeTerminal();
  8488. const runtime = createRuntime();
  8489. vi.mocked(runtime.listSessions).mockResolvedValue([
  8490. {
  8491. sessionId: "session-existing",
  8492. title: "Existing session",
  8493. workspaceDir: "/workspace",
  8494. },
  8495. ]);
  8496. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  8497. {
  8498. requestId: "permission-1",
  8499. sessionId: "session-existing",
  8500. agentName: "mavis",
  8501. toolName: "bash",
  8502. reason: "Run tests",
  8503. allowAlwaysSupported: true,
  8504. },
  8505. ]);
  8506. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8507. id: "question-1",
  8508. title: "Choose",
  8509. steps: [
  8510. {
  8511. id: "step-1",
  8512. question: "Proceed?",
  8513. selectionMode: "single",
  8514. options: [
  8515. { id: "yes", label: "Yes" },
  8516. { id: "no", label: "No" },
  8517. ],
  8518. },
  8519. ],
  8520. });
  8521. const app = createTuiApp({
  8522. runtime,
  8523. terminal,
  8524. version: "0.1.0",
  8525. workspaceDir: "/workspace",
  8526. });
  8527. await app.ready;
  8528. await app.submit("/resume session-existing");
  8529. expect(app.transcript.snapshot()).toEqual(
  8530. expect.arrayContaining([
  8531. expect.objectContaining({ kind: "permission", status: "blocked" }),
  8532. expect.objectContaining({ kind: "question", status: "blocked" }),
  8533. ]),
  8534. );
  8535. expect(app.transcript.get("permission:permission-1")).toMatchObject({
  8536. title: "bash",
  8537. content: "Run tests",
  8538. });
  8539. expect(
  8540. app.transcript.get("permission:permission-1")?.content,
  8541. ).not.toContain("decision panel");
  8542. expect(app.transcript.get("permission:permission-1")?.content).not.toMatch(
  8543. /\/(?:allow|always|deny)\b/u,
  8544. );
  8545. expect(app.transcript.get("question:question-1")?.content).toBe("");
  8546. await app.submit("/q1 1");
  8547. expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
  8548. expect(app.tui.hasOverlay()).toBe(false);
  8549. expect(app.interaction.isActive()).toBe(true);
  8550. expect(terminal.mouseTracking).toBe(false);
  8551. await app.submit("/allow");
  8552. await app.submit("/q1 1");
  8553. await app.submit("/status");
  8554. expect(runtime.replyPermission).toHaveBeenCalledWith(
  8555. "mavis",
  8556. "permission-1",
  8557. "allowOnce",
  8558. );
  8559. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8560. "mavis",
  8561. "question-1",
  8562. [
  8563. {
  8564. stepId: "step-1",
  8565. selectedOptionIds: ["yes"],
  8566. selectedOther: false,
  8567. },
  8568. ],
  8569. );
  8570. expect(terminal.mouseTracking).toBe(false);
  8571. expect(app.transcript.get("question:question-1")).toMatchObject({
  8572. status: "resolved",
  8573. title: "Answers sent",
  8574. content: "Proceed? Yes",
  8575. });
  8576. expect(app.interaction.current()).toBeDefined();
  8577. expect(app.tui.render(80).join("\n")).toContain("MCode status");
  8578. expect(app.transcript.snapshot()).not.toEqual(
  8579. expect.arrayContaining([
  8580. expect.objectContaining({
  8581. kind: "inspection",
  8582. inspection: expect.objectContaining({
  8583. visualization: { kind: "status" },
  8584. }),
  8585. }),
  8586. ]),
  8587. );
  8588. });
  8589. it("does not let a stale permission response hide a newer decision surface", async () => {
  8590. const terminal = new FakeTerminal();
  8591. const runtime = createRuntime();
  8592. vi.mocked(runtime.listSessions).mockResolvedValue([
  8593. {
  8594. sessionId: "session-race",
  8595. title: "Decision race",
  8596. workspaceDir: "/workspace",
  8597. },
  8598. ]);
  8599. const firstPermission = {
  8600. requestId: "permission-first",
  8601. sessionId: "session-race",
  8602. agentName: "mavis",
  8603. toolName: "bash",
  8604. reason: "First request",
  8605. allowAlwaysSupported: true,
  8606. };
  8607. const secondPermission = {
  8608. requestId: "permission-second",
  8609. sessionId: "session-race",
  8610. agentName: "mavis",
  8611. toolName: "write_file",
  8612. reason: "Newer request",
  8613. allowAlwaysSupported: false,
  8614. };
  8615. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  8616. firstPermission,
  8617. ]);
  8618. let finishReply: ((value: boolean) => void) | undefined;
  8619. vi.mocked(runtime.replyPermission).mockImplementation(
  8620. async () =>
  8621. await new Promise<boolean>((resolve) => {
  8622. finishReply = resolve;
  8623. }),
  8624. );
  8625. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  8626. vi.mocked(runtime.watchEvents).mockImplementation(
  8627. async function* watchEvents(signal) {
  8628. const event = await new Promise<TuiRuntimeEvent | undefined>(
  8629. (resolve) => {
  8630. emitEvent = resolve;
  8631. signal.addEventListener("abort", () => resolve(undefined), {
  8632. once: true,
  8633. });
  8634. },
  8635. );
  8636. if (event) yield event;
  8637. await new Promise<void>((resolve) => {
  8638. signal.addEventListener("abort", resolve, { once: true });
  8639. });
  8640. },
  8641. );
  8642. const app = createTuiApp({
  8643. runtime,
  8644. terminal,
  8645. version: "0.1.0",
  8646. workspaceDir: "/workspace",
  8647. });
  8648. app.start();
  8649. await app.ready;
  8650. await app.submit("/resume session-race");
  8651. const resolving = app.submit("/allow");
  8652. await vi.waitFor(() => expect(runtime.replyPermission).toHaveBeenCalled());
  8653. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  8654. emitEvent?.(
  8655. runtimeEvent({
  8656. type: "permission.ask",
  8657. timestamp: Date.now(),
  8658. source: "test",
  8659. payload: secondPermission,
  8660. }),
  8661. );
  8662. await vi.waitFor(() =>
  8663. expect(app.tui.render(80).join("\n")).toContain("Newer request"),
  8664. );
  8665. finishReply?.(true);
  8666. await resolving;
  8667. const rendered = app.tui.render(80).join("\n");
  8668. expect(rendered).toContain("Write file");
  8669. expect(rendered).toContain("Newer request");
  8670. expect(runtime.replyPermission).toHaveBeenCalledTimes(1);
  8671. await app.stop();
  8672. });
  8673. it("closes a permission that another surface resolved before the reply arrived", async () => {
  8674. const terminal = new FakeTerminal();
  8675. const runtime = createRuntime();
  8676. const permission = {
  8677. requestId: "permission-stale",
  8678. sessionId: "session-permission-stale",
  8679. agentName: "mavis",
  8680. toolName: "bash",
  8681. reason: "Run tests",
  8682. allowAlwaysSupported: true,
  8683. };
  8684. vi.mocked(runtime.listSessions).mockResolvedValue([
  8685. {
  8686. sessionId: "session-permission-stale",
  8687. title: "Permission race",
  8688. workspaceDir: "/workspace",
  8689. },
  8690. ]);
  8691. vi.mocked(runtime.listPendingPermissions)
  8692. .mockResolvedValueOnce([permission])
  8693. .mockResolvedValue([]);
  8694. vi.mocked(runtime.replyPermission).mockResolvedValue(false);
  8695. const app = createTuiApp({
  8696. runtime,
  8697. terminal,
  8698. version: "0.1.0",
  8699. workspaceDir: "/workspace",
  8700. });
  8701. await app.ready;
  8702. await app.submit("/resume session-permission-stale");
  8703. await app.submit("/allow");
  8704. expect(app.transcript.get("permission:permission-stale")).toMatchObject({
  8705. status: "resolved",
  8706. detail: "Resolved on another surface.",
  8707. });
  8708. expect(app.interaction.isActive()).toBe(false);
  8709. });
  8710. it("keeps an option-only questionnaire pending after an invalid slash answer", async () => {
  8711. const terminal = new FakeTerminal();
  8712. const runtime = createRuntime();
  8713. vi.mocked(runtime.listSessions).mockResolvedValue([
  8714. {
  8715. sessionId: "session-questionnaire",
  8716. title: "Questionnaire session",
  8717. workspaceDir: "/workspace",
  8718. },
  8719. ]);
  8720. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8721. id: "question-options-only",
  8722. title: "Choose",
  8723. steps: [
  8724. {
  8725. id: "channel",
  8726. question: "Choose a release channel",
  8727. selectionMode: "single",
  8728. options: [
  8729. { id: "preview", label: "Preview" },
  8730. { id: "stable", label: "Stable" },
  8731. ],
  8732. allowOther: false,
  8733. },
  8734. ],
  8735. });
  8736. const app = createTuiApp({
  8737. runtime,
  8738. terminal,
  8739. version: "0.1.0",
  8740. workspaceDir: "/workspace",
  8741. });
  8742. await app.ready;
  8743. await app.submit("/resume session-questionnaire");
  8744. await app.submit("/q1 nightly");
  8745. expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
  8746. expect(app.transcript.get("question:question-options-only")).toMatchObject({
  8747. status: "blocked",
  8748. });
  8749. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  8750. kind: "warning",
  8751. content:
  8752. "/q1 accepts only listed options. Use an option number, ID, or label.",
  8753. });
  8754. await app.submit("/q1 1");
  8755. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8756. "mavis",
  8757. "question-options-only",
  8758. [
  8759. {
  8760. stepId: "channel",
  8761. selectedOptionIds: ["preview"],
  8762. selectedOther: false,
  8763. },
  8764. ],
  8765. );
  8766. });
  8767. it("shows the first AskUser answer immediately while later questions remain pending", async () => {
  8768. const terminal = new FakeTerminal();
  8769. const runtime = createRuntime();
  8770. vi.mocked(runtime.listSessions).mockResolvedValue([
  8771. {
  8772. sessionId: "session-multi-question",
  8773. title: "Multi question",
  8774. workspaceDir: "/workspace",
  8775. },
  8776. ]);
  8777. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8778. id: "question-multi-step",
  8779. title: "Preferences",
  8780. steps: [
  8781. {
  8782. id: "animal",
  8783. question: "Favorite animal?",
  8784. selectionMode: "single",
  8785. options: [
  8786. { id: "cat", label: "Cat" },
  8787. { id: "dog", label: "Dog" },
  8788. ],
  8789. },
  8790. {
  8791. id: "color",
  8792. question: "Favorite color?",
  8793. selectionMode: "single",
  8794. options: [
  8795. { id: "blue", label: "Blue" },
  8796. { id: "green", label: "Green" },
  8797. ],
  8798. },
  8799. ],
  8800. });
  8801. const app = createTuiApp({
  8802. runtime,
  8803. terminal,
  8804. version: "0.1.0",
  8805. workspaceDir: "/workspace",
  8806. });
  8807. await app.ready;
  8808. app.start();
  8809. await app.submit("/resume session-multi-question");
  8810. const picker = app.interaction.current();
  8811. expect(picker).toBeDefined();
  8812. terminal.input?.("1");
  8813. expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
  8814. expect(app.interaction.current()).toBe(picker);
  8815. expect(app.transcript.get("question:question-multi-step")).toMatchObject({
  8816. status: "blocked",
  8817. content: "Favorite animal? Cat",
  8818. detail: "1 of 2 answered",
  8819. });
  8820. const rendered = app.tui.render(80).join("\n");
  8821. expect(rendered).toContain("Answers so far");
  8822. expect(rendered).toContain("Favorite animal? Cat");
  8823. expect(rendered).toContain("Favorite color?");
  8824. terminal.input?.("\u001B[B");
  8825. expect(app.tui.render(80).join("\n")).toContain("› 2 Green");
  8826. terminal.input?.("\r");
  8827. await vi.waitFor(() => {
  8828. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8829. "mavis",
  8830. "question-multi-step",
  8831. [
  8832. {
  8833. stepId: "animal",
  8834. selectedOptionIds: ["cat"],
  8835. selectedOther: false,
  8836. },
  8837. {
  8838. stepId: "color",
  8839. selectedOptionIds: ["green"],
  8840. selectedOther: false,
  8841. },
  8842. ],
  8843. );
  8844. });
  8845. await app.stop();
  8846. });
  8847. it("sends the selected answer immediately and refreshes the Agent continuation", async () => {
  8848. const terminal = new FakeTerminal();
  8849. const runtime = createRuntime();
  8850. vi.mocked(runtime.listSessions).mockResolvedValue([
  8851. {
  8852. sessionId: "session-review",
  8853. title: "Questionnaire review",
  8854. workspaceDir: "/workspace",
  8855. },
  8856. ]);
  8857. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8858. id: "question-review",
  8859. title: "Release setup",
  8860. steps: [
  8861. {
  8862. id: "channel",
  8863. question: "Choose a channel",
  8864. selectionMode: "single",
  8865. options: [
  8866. { id: "preview", label: "Preview" },
  8867. { id: "stable", label: "Stable" },
  8868. ],
  8869. },
  8870. ],
  8871. });
  8872. const previousMessages = [
  8873. {
  8874. id: "previous-question-answer",
  8875. role: "user" as const,
  8876. content: [
  8877. "<questionnaire-response>",
  8878. " <requestId>question-previous</requestId>",
  8879. " <answers />",
  8880. "</questionnaire-response>",
  8881. "",
  8882. "Q: Choose a channel",
  8883. "A: Preview",
  8884. ].join("\n"),
  8885. },
  8886. ];
  8887. vi.mocked(runtime.getMessages).mockResolvedValue(previousMessages);
  8888. const app = createTuiApp({
  8889. runtime,
  8890. terminal,
  8891. version: "0.1.0",
  8892. workspaceDir: "/workspace",
  8893. });
  8894. let releaseReply: ((result: boolean) => void) | undefined;
  8895. let releaseContinuation: (() => void) | undefined;
  8896. vi.mocked(runtime.replyQuestionnaire).mockImplementation(
  8897. async () =>
  8898. await new Promise<boolean>((resolve) => {
  8899. releaseReply = resolve;
  8900. }),
  8901. );
  8902. vi.mocked(runtime.watchEvents).mockImplementation(
  8903. async function* watchEvents(signal) {
  8904. await new Promise<void>((resolve) => {
  8905. releaseContinuation = resolve;
  8906. signal.addEventListener("abort", resolve, { once: true });
  8907. });
  8908. if (signal.aborted) return;
  8909. yield runtimeEvent({
  8910. type: "session.start",
  8911. timestamp: Date.now(),
  8912. source: "runtime",
  8913. payload: {
  8914. sessionId: "session-review",
  8915. turnId: "turn-questionnaire-continuation",
  8916. },
  8917. });
  8918. yield runtimeEvent({
  8919. type: "session.finish",
  8920. timestamp: Date.now(),
  8921. source: "runtime",
  8922. payload: {
  8923. sessionId: "session-review",
  8924. turnId: "turn-questionnaire-continuation",
  8925. },
  8926. });
  8927. },
  8928. );
  8929. app.start();
  8930. await app.ready;
  8931. await app.submit("/resume session-review");
  8932. expect(app.tui.hasOverlay()).toBe(false);
  8933. expect(app.interaction.isActive()).toBe(true);
  8934. terminal.input?.("2");
  8935. await vi.waitFor(() =>
  8936. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8937. "mavis",
  8938. "question-review",
  8939. [
  8940. {
  8941. stepId: "channel",
  8942. selectedOptionIds: ["stable"],
  8943. selectedOther: false,
  8944. },
  8945. ],
  8946. ),
  8947. );
  8948. expect(app.tui.hasOverlay()).toBe(false);
  8949. expect(app.transcript.get("question:question-review")).toMatchObject({
  8950. status: "pending",
  8951. detail: "Sending your answer…",
  8952. });
  8953. releaseReply?.(true);
  8954. await vi.waitFor(() =>
  8955. expect(app.transcript.get("question:question-review")).toMatchObject({
  8956. status: "resolved",
  8957. detail: "Answer sent · MCode is continuing…",
  8958. }),
  8959. );
  8960. vi.mocked(runtime.getMessages).mockResolvedValue([
  8961. ...previousMessages,
  8962. {
  8963. id: "assistant-after-question",
  8964. role: "assistant",
  8965. content: "Agent continued after your answer.",
  8966. },
  8967. ]);
  8968. releaseContinuation?.();
  8969. await vi.waitFor(() =>
  8970. expect(
  8971. app.transcript
  8972. .snapshot()
  8973. .map((cell) => cell.content)
  8974. .join("\n"),
  8975. ).toContain("Agent continued after your answer."),
  8976. );
  8977. expect(app.transcript.get("question:question-review")).toMatchObject({
  8978. kind: "question",
  8979. status: "resolved",
  8980. title: "Answers sent",
  8981. content: "Choose a channel Stable",
  8982. detail: undefined,
  8983. });
  8984. expect(
  8985. app.transcript
  8986. .snapshot()
  8987. .filter((cell) => cell.kind === "question")
  8988. .map((cell) => cell.content),
  8989. ).toEqual(["Choose a channel Preview", "Choose a channel Stable"]);
  8990. expect(app.tui.render(80).join("\n")).not.toContain("Thinking · Message");
  8991. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  8992. await app.stop();
  8993. });
  8994. it("redraws after a delayed questionnaire reply resolves", async () => {
  8995. const terminal = new FakeTerminal();
  8996. const runtime = createRuntime();
  8997. vi.mocked(runtime.listSessions).mockResolvedValue([
  8998. {
  8999. sessionId: "session-delayed-reply",
  9000. title: "Delayed questionnaire reply",
  9001. workspaceDir: "/workspace",
  9002. },
  9003. ]);
  9004. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9005. id: "question-delayed-reply",
  9006. steps: [
  9007. {
  9008. id: "channel",
  9009. question: "Choose a channel",
  9010. selectionMode: "single",
  9011. options: [{ id: "preview", label: "Preview" }],
  9012. },
  9013. ],
  9014. });
  9015. let finishReply: ((result: boolean) => void) | undefined;
  9016. vi.mocked(runtime.replyQuestionnaire).mockImplementation(
  9017. async () =>
  9018. await new Promise<boolean>((resolve) => {
  9019. finishReply = resolve;
  9020. }),
  9021. );
  9022. const app = createTuiApp({
  9023. runtime,
  9024. terminal,
  9025. version: "0.1.0",
  9026. workspaceDir: "/workspace",
  9027. });
  9028. app.start();
  9029. await app.ready;
  9030. await app.submit("/resume session-delayed-reply");
  9031. terminal.input?.("1");
  9032. await vi.waitFor(() =>
  9033. expect(runtime.replyQuestionnaire).toHaveBeenCalledTimes(1),
  9034. );
  9035. expect(app.tui.hasOverlay()).toBe(false);
  9036. const writesBeforeResolution = terminal.writes.length;
  9037. finishReply?.(true);
  9038. await vi.waitFor(() =>
  9039. expect(
  9040. app.transcript.get("question:question-delayed-reply"),
  9041. ).toMatchObject({
  9042. status: "resolved",
  9043. detail: "Answer sent · MCode is continuing…",
  9044. }),
  9045. );
  9046. await vi.waitFor(() =>
  9047. expect(terminal.writes.length).toBeGreaterThan(writesBeforeResolution),
  9048. );
  9049. await app.stop();
  9050. });
  9051. it("keeps the questionnaire interactive when the Runtime cannot start its continuation", async () => {
  9052. const terminal = new FakeTerminal();
  9053. const runtime = createRuntime();
  9054. vi.mocked(runtime.listSessions).mockResolvedValue([
  9055. {
  9056. sessionId: "session-retry-questionnaire",
  9057. title: "Retry questionnaire",
  9058. workspaceDir: "/workspace",
  9059. },
  9060. ]);
  9061. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9062. id: "question-retry",
  9063. title: "Choose a channel",
  9064. steps: [
  9065. {
  9066. id: "channel",
  9067. question: "Choose a channel",
  9068. selectionMode: "single",
  9069. options: [{ id: "preview", label: "Preview" }],
  9070. },
  9071. ],
  9072. });
  9073. vi.mocked(runtime.replyQuestionnaire).mockRejectedValue(
  9074. new Error(
  9075. "Questionnaire answer was saved, but the continuation could not start.",
  9076. ),
  9077. );
  9078. const app = createTuiApp({
  9079. runtime,
  9080. terminal,
  9081. version: "0.1.0",
  9082. workspaceDir: "/workspace",
  9083. });
  9084. app.start();
  9085. app.start();
  9086. await app.ready;
  9087. await app.submit("/resume session-retry-questionnaire");
  9088. terminal.input?.("1");
  9089. await vi.waitFor(() =>
  9090. expect(app.transcript.get("question:question-retry")).toMatchObject({
  9091. status: "blocked",
  9092. title: "Choose a channel",
  9093. detail: "Answer could not be sent · retry",
  9094. }),
  9095. );
  9096. expect(app.interaction.isActive()).toBe(true);
  9097. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  9098. kind: "error",
  9099. content:
  9100. "Couldn't send your answers: Questionnaire answer was saved, but the continuation could not start. Retry. The question remains open.",
  9101. });
  9102. await app.stop();
  9103. });
  9104. it("redraws after a delayed questionnaire dismissal resolves", async () => {
  9105. const terminal = new FakeTerminal();
  9106. const runtime = createRuntime();
  9107. vi.mocked(runtime.listSessions).mockResolvedValue([
  9108. {
  9109. sessionId: "session-delayed-dismiss",
  9110. title: "Delayed questionnaire dismissal",
  9111. workspaceDir: "/workspace",
  9112. },
  9113. ]);
  9114. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9115. id: "question-delayed-dismiss",
  9116. steps: [{ id: "confirmation", question: "Continue?" }],
  9117. });
  9118. let finishDismiss: ((result: boolean) => void) | undefined;
  9119. vi.mocked(runtime.dismissQuestionnaire).mockImplementation(
  9120. async () =>
  9121. await new Promise<boolean>((resolve) => {
  9122. finishDismiss = resolve;
  9123. }),
  9124. );
  9125. const app = createTuiApp({
  9126. runtime,
  9127. terminal,
  9128. version: "0.1.0",
  9129. workspaceDir: "/workspace",
  9130. });
  9131. app.start();
  9132. await app.ready;
  9133. await app.submit("/resume session-delayed-dismiss");
  9134. const dismissing = app.submit("/ask-cancel");
  9135. await vi.waitFor(() =>
  9136. expect(runtime.dismissQuestionnaire).toHaveBeenCalledTimes(1),
  9137. );
  9138. const writesBeforeResolution = terminal.writes.length;
  9139. finishDismiss?.(true);
  9140. await dismissing;
  9141. expect(
  9142. app.transcript.get("question:question-delayed-dismiss"),
  9143. ).toMatchObject({
  9144. status: "resolved",
  9145. title: "Question dismissed",
  9146. content: "",
  9147. detail: undefined,
  9148. });
  9149. await vi.waitFor(() =>
  9150. expect(terminal.writes.length).toBeGreaterThan(writesBeforeResolution),
  9151. );
  9152. await app.stop();
  9153. });
  9154. it.each([
  9155. { keyName: "Escape", input: "\x1b" },
  9156. { keyName: "Ctrl-C", input: "\x03" },
  9157. ])(
  9158. "keeps AskUser focused while $keyName dismisses the pending questionnaire",
  9159. async ({ input }) => {
  9160. const terminal = new FakeTerminal();
  9161. const runtime = createRuntime();
  9162. vi.mocked(runtime.listSessions).mockResolvedValue([
  9163. {
  9164. sessionId: "session-escape-dismiss",
  9165. title: "Escape questionnaire dismissal",
  9166. workspaceDir: "/workspace",
  9167. },
  9168. ]);
  9169. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9170. id: "question-escape-dismiss",
  9171. steps: [
  9172. {
  9173. id: "channel",
  9174. question: "Choose a channel",
  9175. selectionMode: "single",
  9176. options: [{ id: "preview", label: "Preview" }],
  9177. },
  9178. ],
  9179. });
  9180. let finishDismiss: ((result: boolean) => void) | undefined;
  9181. vi.mocked(runtime.dismissQuestionnaire).mockImplementation(
  9182. async () =>
  9183. await new Promise<boolean>((resolve) => {
  9184. finishDismiss = resolve;
  9185. }),
  9186. );
  9187. const app = createTuiApp({
  9188. runtime,
  9189. terminal,
  9190. version: "0.1.0",
  9191. workspaceDir: "/workspace",
  9192. });
  9193. app.start();
  9194. await app.ready;
  9195. await app.submit("/resume session-escape-dismiss");
  9196. terminal.input?.(input);
  9197. if (input === "\x1b") {
  9198. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9199. "Cancel this question?",
  9200. );
  9201. terminal.input?.("\r");
  9202. }
  9203. await vi.waitFor(() =>
  9204. expect(runtime.dismissQuestionnaire).toHaveBeenCalledWith(
  9205. "mavis",
  9206. "question-escape-dismiss",
  9207. ),
  9208. );
  9209. expect(app.interaction.isActive()).toBe(true);
  9210. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9211. "Closing question",
  9212. );
  9213. expect(
  9214. app.state.snapshot().sessions.get("session-escape-dismiss")?.attention
  9215. .question,
  9216. ).toBe(true);
  9217. finishDismiss?.(true);
  9218. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  9219. expect(
  9220. app.transcript.get("question:question-escape-dismiss"),
  9221. ).toMatchObject({
  9222. status: "resolved",
  9223. title: "Question dismissed",
  9224. });
  9225. expect(
  9226. app.state.snapshot().sessions.get("session-escape-dismiss")?.attention
  9227. .question,
  9228. ).toBe(false);
  9229. expect(app.tui.render(80).join("\n")).not.toContain("Reply required");
  9230. await app.stop();
  9231. },
  9232. );
  9233. it("denies a pending permission explicitly and releases the blocked interaction", async () => {
  9234. const terminal = new FakeTerminal();
  9235. const runtime = createRuntime();
  9236. vi.mocked(runtime.listSessions).mockResolvedValue([
  9237. {
  9238. sessionId: "session-pending",
  9239. title: "Pending permission",
  9240. workspaceDir: "/workspace",
  9241. },
  9242. ]);
  9243. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9244. {
  9245. requestId: "permission-pending",
  9246. sessionId: "session-pending",
  9247. agentName: "mavis",
  9248. toolName: "bash",
  9249. toolInput: "pnpm test",
  9250. ruleContents: ["Bash(pnpm test:*)"],
  9251. allowAlwaysSupported: true,
  9252. },
  9253. ]);
  9254. const app = createTuiApp({
  9255. runtime,
  9256. terminal,
  9257. version: "0.1.0",
  9258. workspaceDir: "/workspace",
  9259. });
  9260. app.start();
  9261. await app.ready;
  9262. await app.submit("/resume session-pending");
  9263. expect(app.tui.hasOverlay()).toBe(false);
  9264. expect(app.interaction.isActive()).toBe(true);
  9265. terminal.input?.("3");
  9266. terminal.input?.("\r");
  9267. await vi.waitFor(() =>
  9268. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9269. "mavis",
  9270. "permission-pending",
  9271. "deny",
  9272. ),
  9273. );
  9274. expect(app.tui.hasOverlay()).toBe(false);
  9275. expect(app.interaction.isActive()).toBe(false);
  9276. expect(app.transcript.get("permission:permission-pending")).toMatchObject({
  9277. status: "resolved",
  9278. detail: "Denied · bash",
  9279. });
  9280. expect(app.tui.render(80).join("\n")).not.toContain("Approval required");
  9281. await app.stop();
  9282. });
  9283. it("resolves a regular inline permission without clearing the terminal viewport", async () => {
  9284. const terminal = new FakeTerminal();
  9285. terminal.rows = 8;
  9286. const runtime = createRuntime();
  9287. vi.mocked(runtime.listSessions).mockResolvedValue([
  9288. {
  9289. sessionId: "session-permission-render",
  9290. title: "Permission render",
  9291. workspaceDir: "/workspace",
  9292. },
  9293. ]);
  9294. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9295. {
  9296. requestId: "permission-render",
  9297. sessionId: "session-permission-render",
  9298. agentName: "mavis",
  9299. toolName: "bash",
  9300. toolInput: "pnpm test",
  9301. reason: "Run focused tests",
  9302. allowAlwaysSupported: true,
  9303. },
  9304. ]);
  9305. const app = createTuiApp({
  9306. runtime,
  9307. terminal,
  9308. version: "0.2.6",
  9309. workspaceDir: "/workspace",
  9310. tuiMode: "regular",
  9311. });
  9312. app.start();
  9313. await app.ready;
  9314. await app.submit("/resume session-permission-render");
  9315. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  9316. app.tui.renderNow();
  9317. terminal.writes.length = 0;
  9318. terminal.input?.("\r");
  9319. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  9320. await vi.waitFor(() => expect(terminal.writes.length).toBeGreaterThan(0));
  9321. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9322. "mavis",
  9323. "permission-render",
  9324. "allowOnce",
  9325. );
  9326. expect(app.transcript.get("permission:permission-render")).toMatchObject({
  9327. status: "resolved",
  9328. detail: "Allowed for this conversation · bash",
  9329. });
  9330. expect(terminal.writes.join("")).not.toContain("\x1b[2J");
  9331. expect(terminal.writes.join("")).not.toContain("\x1b[3J");
  9332. await app.stop();
  9333. });
  9334. it("keeps a submission retryable when a pending decision blocks admission", async () => {
  9335. const terminal = new FakeTerminal();
  9336. const runtime = createRuntime();
  9337. vi.mocked(runtime.listSessions).mockResolvedValue([
  9338. {
  9339. sessionId: "session-draft-blocked",
  9340. title: "Pending decision",
  9341. workspaceDir: "/workspace",
  9342. },
  9343. ]);
  9344. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9345. {
  9346. requestId: "permission-draft-blocked",
  9347. sessionId: "session-draft-blocked",
  9348. agentName: "mavis",
  9349. toolName: "bash",
  9350. allowAlwaysSupported: true,
  9351. },
  9352. ]);
  9353. const app = createTuiApp({
  9354. runtime,
  9355. terminal,
  9356. version: "0.1.0",
  9357. workspaceDir: "/workspace",
  9358. });
  9359. app.start();
  9360. await app.ready;
  9361. await app.submit("/resume session-draft-blocked");
  9362. app.editor.setText("Keep this draft for later");
  9363. app.editor.handleInput("\r");
  9364. await vi.waitFor(() => expect(app.editor.getText()).toBe(""));
  9365. expect(runtime.sendMessage).not.toHaveBeenCalled();
  9366. expect(app.tui.render(80).join("\n")).toContain("Approval required");
  9367. expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
  9368. await app.stop();
  9369. });
  9370. it("keeps a pending questionnaire when Runtime rejects dismissal", async () => {
  9371. const terminal = new FakeTerminal();
  9372. const runtime = createRuntime();
  9373. vi.mocked(runtime.listSessions).mockResolvedValue([
  9374. {
  9375. sessionId: "session-existing",
  9376. title: "Existing session",
  9377. workspaceDir: "/workspace",
  9378. },
  9379. ]);
  9380. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9381. id: "question-rejected",
  9382. steps: [{ id: "step-1", question: "Proceed?" }],
  9383. });
  9384. vi.mocked(runtime.dismissQuestionnaire).mockResolvedValue(false);
  9385. const app = createTuiApp({
  9386. runtime,
  9387. terminal,
  9388. version: "0.1.0",
  9389. workspaceDir: "/workspace",
  9390. });
  9391. await app.ready;
  9392. await app.submit("/resume session-existing");
  9393. await app.submit("/ask-cancel");
  9394. expect(app.transcript.get("question:question-rejected")).toMatchObject({
  9395. status: "blocked",
  9396. });
  9397. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  9398. kind: "error",
  9399. content: "Couldn't dismiss this question. It remains open; retry.",
  9400. });
  9401. });
  9402. it("restores the questionnaire panel when an Escape dismissal request fails", async () => {
  9403. const runtime = createRuntime();
  9404. vi.mocked(runtime.listSessions).mockResolvedValue([
  9405. {
  9406. sessionId: "session-dismiss-retry",
  9407. title: "Dismiss retry",
  9408. workspaceDir: "/workspace",
  9409. },
  9410. ]);
  9411. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9412. id: "question-dismiss-retry",
  9413. steps: [
  9414. {
  9415. id: "step-1",
  9416. question: "Proceed?",
  9417. selectionMode: "single",
  9418. options: [{ id: "yes", label: "Yes" }],
  9419. },
  9420. ],
  9421. });
  9422. vi.mocked(runtime.dismissQuestionnaire).mockRejectedValue(
  9423. new Error("connection lost"),
  9424. );
  9425. const app = createTuiApp({
  9426. runtime,
  9427. terminal: new FakeTerminal(),
  9428. version: "0.1.0",
  9429. workspaceDir: "/workspace",
  9430. });
  9431. await app.ready;
  9432. await app.submit("/resume session-dismiss-retry");
  9433. app.interaction.current()?.handleInput("\u001b");
  9434. app.interaction.current()?.handleInput("\r");
  9435. await vi.waitFor(() =>
  9436. expect(runtime.dismissQuestionnaire).toHaveBeenCalledOnce(),
  9437. );
  9438. await vi.waitFor(() => {
  9439. const panel = app.interaction.current();
  9440. expect(panel).toBeDefined();
  9441. expect(panel?.render(80).join("\n")).toContain("Ask");
  9442. });
  9443. expect(app.transcript.get("question:question-dismiss-retry")).toMatchObject(
  9444. {
  9445. status: "blocked",
  9446. },
  9447. );
  9448. });
  9449. it("settles a questionnaire dismissal that already reached a terminal Runtime state", async () => {
  9450. const terminal = new FakeTerminal();
  9451. const runtime = createRuntime();
  9452. vi.mocked(runtime.listSessions).mockResolvedValue([
  9453. {
  9454. sessionId: "session-terminal-dismiss",
  9455. title: "Terminal dismissal",
  9456. workspaceDir: "/workspace",
  9457. },
  9458. ]);
  9459. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9460. id: "question-terminal-dismiss",
  9461. steps: [{ id: "step-1", question: "Proceed?" }],
  9462. });
  9463. vi.mocked(runtime.dismissQuestionnaire).mockRejectedValue(
  9464. Object.assign(new Error("already superseded"), {
  9465. status: 410,
  9466. code: "QUESTIONNAIRE_NOT_PENDING",
  9467. }),
  9468. );
  9469. const app = createTuiApp({
  9470. runtime,
  9471. terminal,
  9472. version: "0.1.0",
  9473. workspaceDir: "/workspace",
  9474. });
  9475. await app.ready;
  9476. await app.submit("/resume session-terminal-dismiss");
  9477. await app.submit("/ask-cancel");
  9478. expect(
  9479. app.transcript.get("question:question-terminal-dismiss"),
  9480. ).toMatchObject({
  9481. status: "resolved",
  9482. title: "Question closed",
  9483. detail: "Question is no longer pending.",
  9484. });
  9485. expect(app.interaction.isActive()).toBe(false);
  9486. });
  9487. it("projects live Desktop permission events into the transcript", async () => {
  9488. const terminal = new FakeTerminal();
  9489. const runtime = createRuntime();
  9490. vi.mocked(runtime.watchEvents).mockImplementation(
  9491. async function* watchEvents() {
  9492. yield runtimeEvent({
  9493. type: "permission.ask",
  9494. timestamp: 100,
  9495. source: "runtime",
  9496. payload: {
  9497. requestId: "permission-live",
  9498. sessionId: "session-1",
  9499. agentName: "mavis",
  9500. toolName: "bash",
  9501. toolDescription: "Run a shell command",
  9502. reason: "Run checks",
  9503. ruleContents: ["Bash(pnpm test:*)"],
  9504. allowAlwaysSupported: true,
  9505. },
  9506. });
  9507. },
  9508. );
  9509. const app = createTuiApp({
  9510. runtime,
  9511. terminal,
  9512. version: "0.1.0",
  9513. workspaceDir: "/workspace",
  9514. });
  9515. await app.ready;
  9516. await app.submit("Start the current session");
  9517. await app.submit("/transcript");
  9518. expect(app.surfaceHost.getActiveSurface()).toEqual({
  9519. kind: "feature",
  9520. id: "transcript",
  9521. });
  9522. app.start();
  9523. await vi.waitFor(() =>
  9524. expect(app.transcript.get("permission:permission-live")).toMatchObject({
  9525. kind: "permission",
  9526. status: "blocked",
  9527. content: expect.stringContaining("Run checks"),
  9528. }),
  9529. );
  9530. expect(app.transcript.get("permission:permission-live")).toMatchObject({
  9531. title: "bash",
  9532. content: "Run checks",
  9533. });
  9534. expect(
  9535. app.transcript.get("permission:permission-live")?.content,
  9536. ).not.toContain("Rules:");
  9537. expect(app.surfaceHost.getActiveSurface()).toEqual({
  9538. kind: "chat",
  9539. id: "chat",
  9540. });
  9541. await app.submit("/allow");
  9542. expect(app.surfaceHost.getActiveSurface()).toEqual({
  9543. kind: "feature",
  9544. id: "transcript",
  9545. });
  9546. await app.stop();
  9547. });
  9548. it("ignores Desktop interaction events until their session is active", async () => {
  9549. const terminal = new FakeTerminal();
  9550. const runtime = createRuntime();
  9551. let resolveEventsDelivered: (() => void) | undefined;
  9552. const eventsDelivered = new Promise<void>((resolve) => {
  9553. resolveEventsDelivered = resolve;
  9554. });
  9555. vi.mocked(runtime.watchEvents).mockImplementation(
  9556. async function* watchEvents(signal) {
  9557. yield runtimeEvent({
  9558. type: "permission.ask",
  9559. timestamp: 100,
  9560. source: "runtime",
  9561. payload: {
  9562. requestId: "permission-other-session",
  9563. sessionId: "session-other",
  9564. agentName: "mavis",
  9565. toolName: "bash",
  9566. },
  9567. });
  9568. yield runtimeEvent({
  9569. type: "questionnaire.ask",
  9570. timestamp: 101,
  9571. source: "runtime",
  9572. payload: {
  9573. sessionId: "session-other",
  9574. agentName: "mavis",
  9575. request: {
  9576. id: "question-other-session",
  9577. steps: [
  9578. { id: "step-1", question: "Proceed?", selectionMode: "single" },
  9579. ],
  9580. },
  9581. },
  9582. });
  9583. resolveEventsDelivered?.();
  9584. await new Promise<void>((resolve) => {
  9585. signal.addEventListener("abort", () => resolve(), { once: true });
  9586. });
  9587. },
  9588. );
  9589. const app = createTuiApp({
  9590. runtime,
  9591. terminal,
  9592. version: "0.1.0",
  9593. workspaceDir: "/workspace",
  9594. });
  9595. app.start();
  9596. await app.ready;
  9597. await eventsDelivered;
  9598. expect(
  9599. app.transcript.get("permission:permission-other-session"),
  9600. ).toBeUndefined();
  9601. expect(
  9602. app.transcript.get("question:question-other-session"),
  9603. ).toBeUndefined();
  9604. expect(
  9605. app.state.snapshot().sessions.get("session-other")?.interactions
  9606. .permission?.requestId,
  9607. ).toBe("permission-other-session");
  9608. expect(
  9609. app.state.snapshot().sessions.get("session-other")?.interactions
  9610. .questionnaire?.request.id,
  9611. ).toBe("question-other-session");
  9612. await app.stop();
  9613. });
  9614. it("surfaces only descendant permissions while keeping explicit Deny separate from Stop", async () => {
  9615. const terminal = new FakeTerminal();
  9616. const runtime = createRuntime();
  9617. const rootSession = {
  9618. sessionId: "session-root",
  9619. title: "Root session",
  9620. workspaceDir: "/workspace",
  9621. status: "started",
  9622. };
  9623. vi.mocked(runtime.listSessions).mockResolvedValue([rootSession]);
  9624. vi.mocked(runtime.getSession).mockResolvedValue(rootSession);
  9625. vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
  9626. schemaVersion: 1,
  9627. rootSessionId: "session-root",
  9628. members: [
  9629. {
  9630. sessionId: "session-child",
  9631. parentSessionId: "session-root",
  9632. agentName: "worker",
  9633. task: "Delegate nested work",
  9634. status: "running",
  9635. },
  9636. {
  9637. sessionId: "session-grandchild",
  9638. parentSessionId: "session-child",
  9639. agentName: "verifier",
  9640. task: "Verify the result",
  9641. status: "running",
  9642. },
  9643. ],
  9644. });
  9645. vi.mocked(runtime.getActiveRun).mockImplementation(
  9646. async (sessionId: string) => ({
  9647. schemaVersion: 1,
  9648. sessionId,
  9649. state:
  9650. sessionId === rootSession.sessionId ? "decision-blocked" : "running",
  9651. turnId:
  9652. sessionId === rootSession.sessionId
  9653. ? "turn-root"
  9654. : `turn-${sessionId}`,
  9655. actions: { steer: false },
  9656. }),
  9657. );
  9658. const deniedPermissionIds = new Set<string>();
  9659. vi.mocked(runtime.replyPermission).mockImplementation(
  9660. async (_agentName, requestId) => {
  9661. deniedPermissionIds.add(requestId);
  9662. return true;
  9663. },
  9664. );
  9665. vi.mocked(runtime.listPendingPermissions).mockImplementation(async () =>
  9666. deniedPermissionIds.has("permission-grandchild")
  9667. ? [
  9668. {
  9669. requestId: "permission-unrelated-next",
  9670. sessionId: "session-unrelated",
  9671. agentName: "worker",
  9672. toolName: "bash",
  9673. reason: "Must remain hidden",
  9674. },
  9675. {
  9676. requestId: deniedPermissionIds.has("permission-child-next")
  9677. ? "permission-child-stop"
  9678. : "permission-child-next",
  9679. sessionId: "session-child",
  9680. agentName: "worker",
  9681. toolName: "read",
  9682. reason: deniedPermissionIds.has("permission-child-next")
  9683. ? "Wait for an explicit Stop"
  9684. : "Inspect the delegated output",
  9685. },
  9686. ]
  9687. : [],
  9688. );
  9689. vi.mocked(runtime.watchEvents).mockImplementation(
  9690. async function* watchEvents(signal) {
  9691. yield runtimeEvent({
  9692. type: "permission.ask",
  9693. timestamp: 100,
  9694. source: "runtime",
  9695. payload: {
  9696. requestId: "permission-unrelated",
  9697. sessionId: "session-unrelated",
  9698. agentName: "worker",
  9699. toolName: "bash",
  9700. reason: "Must stay hidden",
  9701. },
  9702. });
  9703. yield runtimeEvent({
  9704. type: "permission.ask",
  9705. timestamp: 101,
  9706. source: "runtime",
  9707. payload: {
  9708. requestId: "permission-grandchild",
  9709. sessionId: "session-grandchild",
  9710. agentName: "verifier",
  9711. toolName: "write",
  9712. reason: "Update the verification report",
  9713. allowAlwaysSupported: true,
  9714. },
  9715. });
  9716. await new Promise<void>((resolve) => {
  9717. signal.addEventListener("abort", resolve, { once: true });
  9718. });
  9719. },
  9720. );
  9721. const app = createTuiApp({
  9722. runtime,
  9723. terminal,
  9724. version: "0.1.0",
  9725. workspaceDir: "/workspace",
  9726. });
  9727. await app.ready;
  9728. await app.submit("/resume session-root");
  9729. vi.mocked(runtime.abortSession).mockClear();
  9730. vi.mocked(runtime.stopDelegation).mockClear();
  9731. app.start();
  9732. await vi.waitFor(() =>
  9733. expect(
  9734. app.transcript.get("permission:permission-grandchild"),
  9735. ).toMatchObject({
  9736. kind: "permission",
  9737. status: "blocked",
  9738. }),
  9739. );
  9740. expect(
  9741. app.transcript.get("permission:permission-unrelated"),
  9742. ).toBeUndefined();
  9743. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9744. "Update the verification report",
  9745. );
  9746. app.interaction.current()?.handleInput?.("3");
  9747. app.interaction.current()?.handleInput?.("\r");
  9748. await vi.waitFor(() =>
  9749. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9750. "verifier",
  9751. "permission-grandchild",
  9752. "deny",
  9753. ),
  9754. );
  9755. expect(runtime.stopDelegation).not.toHaveBeenCalled();
  9756. expect(runtime.abortSession).not.toHaveBeenCalled();
  9757. await vi.waitFor(() =>
  9758. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9759. "Inspect the delegated output",
  9760. ),
  9761. );
  9762. expect(
  9763. app.transcript.get("permission:permission-unrelated-next"),
  9764. ).toBeUndefined();
  9765. terminal.input?.("\x1b");
  9766. await vi.waitFor(() =>
  9767. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9768. "worker",
  9769. "permission-child-next",
  9770. "deny",
  9771. ),
  9772. );
  9773. expect(runtime.abortSession).not.toHaveBeenCalled();
  9774. expect(runtime.stopDelegation).not.toHaveBeenCalled();
  9775. await vi.waitFor(() =>
  9776. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9777. "Wait for an explicit Stop",
  9778. ),
  9779. );
  9780. terminal.input?.("\x03");
  9781. await vi.waitFor(() =>
  9782. expect(runtime.abortSession).toHaveBeenCalledWith({
  9783. id: rootSession.sessionId,
  9784. turnId: "turn-root",
  9785. reason: "user_stop",
  9786. }),
  9787. );
  9788. expect(runtime.stopDelegation).toHaveBeenCalledOnce();
  9789. expect(runtime.stopDelegation).toHaveBeenCalledWith(rootSession.sessionId);
  9790. expect(runtime.replyPermission).not.toHaveBeenCalledWith(
  9791. "worker",
  9792. "permission-child-stop",
  9793. "deny",
  9794. );
  9795. await app.stop();
  9796. });
  9797. it("recovers a descendant permission from the Runtime pending list without leaking unrelated requests", async () => {
  9798. const runtime = createRuntime();
  9799. const rootSession = {
  9800. sessionId: "session-recovery-root",
  9801. title: "Recovery root",
  9802. workspaceDir: "/workspace",
  9803. };
  9804. vi.mocked(runtime.listSessions).mockResolvedValue([rootSession]);
  9805. vi.mocked(runtime.getSession).mockResolvedValue(rootSession);
  9806. vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
  9807. schemaVersion: 1,
  9808. rootSessionId: rootSession.sessionId,
  9809. members: [
  9810. {
  9811. sessionId: "session-recovery-child",
  9812. parentSessionId: rootSession.sessionId,
  9813. agentName: "worker",
  9814. task: "Resume delegated work",
  9815. status: "running",
  9816. },
  9817. ],
  9818. });
  9819. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9820. {
  9821. requestId: "permission-recovery-unrelated",
  9822. sessionId: "session-other-root",
  9823. agentName: "worker",
  9824. toolName: "bash",
  9825. reason: "Do not show this request",
  9826. },
  9827. {
  9828. requestId: "permission-recovery-child",
  9829. sessionId: "session-recovery-child",
  9830. agentName: "worker",
  9831. toolName: "write",
  9832. reason: "Resume the child request",
  9833. },
  9834. ]);
  9835. const app = createTuiApp({
  9836. runtime,
  9837. terminal: new FakeTerminal(),
  9838. version: "0.1.0",
  9839. workspaceDir: "/workspace",
  9840. });
  9841. await app.ready;
  9842. await app.submit("/resume session-recovery-root");
  9843. expect(
  9844. app.transcript.get("permission:permission-recovery-child"),
  9845. ).toMatchObject({
  9846. kind: "permission",
  9847. status: "blocked",
  9848. });
  9849. expect(
  9850. app.transcript.get("permission:permission-recovery-unrelated"),
  9851. ).toBeUndefined();
  9852. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9853. "Resume the child request",
  9854. );
  9855. await app.stop();
  9856. });
  9857. it("reconnects the Runtime event stream after a transient disconnect", async () => {
  9858. const terminal = new FakeTerminal();
  9859. const runtime = createRuntime();
  9860. const observability = createObservability();
  9861. let attempt = 0;
  9862. vi.mocked(runtime.watchEvents).mockImplementation(
  9863. async function* watchEvents() {
  9864. attempt += 1;
  9865. if (attempt === 1) throw new Error("connection reset");
  9866. yield runtimeEvent({
  9867. type: "permission.ask",
  9868. timestamp: 101,
  9869. source: "runtime",
  9870. payload: {
  9871. requestId: "permission-after-reconnect",
  9872. sessionId: "session-1",
  9873. toolName: "read",
  9874. },
  9875. });
  9876. },
  9877. );
  9878. const app = createTuiApp({
  9879. runtime,
  9880. terminal,
  9881. version: "0.1.0",
  9882. workspaceDir: "/workspace",
  9883. observability,
  9884. });
  9885. await app.ready;
  9886. await app.submit("Start the current session");
  9887. app.start();
  9888. await vi.waitFor(
  9889. () =>
  9890. expect(
  9891. app.transcript.get("permission:permission-after-reconnect"),
  9892. ).toMatchObject({
  9893. status: "blocked",
  9894. }),
  9895. { timeout: 1500 },
  9896. );
  9897. expect(runtime.watchEvents).toHaveBeenCalledTimes(2);
  9898. expect(observability.recordEventStream).toHaveBeenCalledWith(
  9899. expect.objectContaining({
  9900. state: "retry-scheduled",
  9901. attempt: 1,
  9902. retryDelayMs: 250,
  9903. errorKind: "Error",
  9904. }),
  9905. );
  9906. expect(observability.recordEventStream).toHaveBeenCalledWith(
  9907. expect.objectContaining({
  9908. state: "reconnected",
  9909. attempt: 1,
  9910. downtimeMs: expect.any(Number),
  9911. }),
  9912. );
  9913. expect(app.transcript.snapshot()).not.toEqual(
  9914. expect.arrayContaining([
  9915. expect.objectContaining({
  9916. kind: "warning",
  9917. content: expect.stringContaining("Runtime event stream"),
  9918. }),
  9919. ]),
  9920. );
  9921. await app.stop();
  9922. });
  9923. it("sends pasted local attachments and restores failed sends to the Composer", async () => {
  9924. const terminal = new FakeTerminal();
  9925. const runtime = createRuntime();
  9926. const readClipboardImage = vi.fn(async () => ({
  9927. attachment: {
  9928. type: "image" as const,
  9929. filePath: "/tmp/minimax-code-clipboard/diagram.png",
  9930. fileName: "diagram.png",
  9931. mimeType: "image/png",
  9932. sizeBytes: 2048,
  9933. },
  9934. dispose: vi.fn(async () => undefined),
  9935. }));
  9936. const app = createTuiApp({
  9937. runtime,
  9938. terminal,
  9939. version: "0.1.0",
  9940. workspaceDir: "/workspace",
  9941. readClipboardImage,
  9942. readClipboardText: async () => null,
  9943. });
  9944. app.start();
  9945. await app.ready;
  9946. terminal.input?.("\u001bv");
  9947. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(1));
  9948. await app.submit("Inspect the diagram");
  9949. expect(runtime.sendMessage).toHaveBeenCalledWith(
  9950. expect.objectContaining({
  9951. id: "session-1",
  9952. content: "Inspect the diagram",
  9953. attachments: [
  9954. expect.objectContaining({
  9955. local: { filePath: "/tmp/minimax-code-clipboard/diagram.png" },
  9956. meta: expect.objectContaining({ mimeType: "image/png" }),
  9957. }),
  9958. ],
  9959. }),
  9960. expect.any(AbortSignal),
  9961. );
  9962. expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
  9963. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  9964. async function* sendMessage() {
  9965. yield { type: "error", message: "provider unavailable" };
  9966. },
  9967. );
  9968. terminal.input?.("\x16");
  9969. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(2));
  9970. app.editor.setText("Try again");
  9971. app.editor.handleInput("\r");
  9972. await vi.waitFor(() => expect(app.editor.getText()).toContain("Try again"));
  9973. expect(app.tui.render(80).join("\n")).toContain(
  9974. "Error The model provider is temporarily unavailable.",
  9975. );
  9976. expect(app.tui.render(80).join("\n")).not.toContain("Request failed");
  9977. expect(app.editor.getText()).toContain("[Image #1]");
  9978. expect(app.tui.render(80).join("\n")).not.toContain(
  9979. "Message kept under Failed",
  9980. );
  9981. await app.submit("/retry");
  9982. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  9983. expect.objectContaining({
  9984. content: "Try again",
  9985. attachments: [
  9986. expect.objectContaining({
  9987. local: { filePath: "/tmp/minimax-code-clipboard/diagram.png" },
  9988. }),
  9989. ],
  9990. }),
  9991. expect.any(AbortSignal),
  9992. );
  9993. await app.submit("A fresh turn");
  9994. expect(app.tui.render(80).join("\n")).not.toContain("Couldn't send");
  9995. await app.stop();
  9996. });
  9997. it.each([
  9998. ['content', 'Content review withdrew this response. Rephrase your request, then retry.'],
  9999. ['network', 'Content review did not return a usable result, so this response stopped.'],
  10000. ] as const)("presents a %s review stop without a failed Queue item", async (variant, notice) => {
  10001. const terminal = new FakeTerminal();
  10002. const runtime = createRuntime();
  10003. const busEvents: TuiRuntimeEvent[] = [];
  10004. let wakeBus: (() => void) | undefined;
  10005. vi.mocked(runtime.watchEvents).mockImplementation(
  10006. async function* watchEvents(signal) {
  10007. while (!signal.aborted) {
  10008. if (busEvents.length === 0) {
  10009. await new Promise<void>((resolve) => {
  10010. wakeBus = resolve;
  10011. signal.addEventListener("abort", resolve, { once: true });
  10012. });
  10013. }
  10014. const event = busEvents.shift();
  10015. if (event) yield event;
  10016. }
  10017. },
  10018. );
  10019. let releaseTurn: (() => void) | undefined;
  10020. vi.mocked(runtime.sendMessage).mockImplementation(
  10021. async function* sendMessage() {
  10022. await new Promise<void>((resolve) => {
  10023. releaseTurn = resolve;
  10024. });
  10025. yield { type: "done" };
  10026. },
  10027. );
  10028. const app = createTuiApp({
  10029. runtime,
  10030. terminal,
  10031. version: "0.1.0",
  10032. workspaceDir: "/workspace",
  10033. });
  10034. app.start();
  10035. await app.ready;
  10036. terminal.input?.("review this response");
  10037. terminal.input?.("\r");
  10038. await vi.waitFor(() =>
  10039. expect(app.controller.snapshot().activeTurnId).toBeTruthy(),
  10040. );
  10041. busEvents.push(
  10042. runtimeEvent({
  10043. type: "content.retry.exceeded",
  10044. timestamp: 100,
  10045. source: "runtime-v2",
  10046. payload: { sessionId: "session-1", variant },
  10047. }),
  10048. runtimeEvent({
  10049. type: "message.rewind",
  10050. timestamp: 101,
  10051. source: "runtime-v2",
  10052. payload: { sessionId: "session-1", contextReset: true },
  10053. }),
  10054. );
  10055. wakeBus?.();
  10056. releaseTurn?.();
  10057. await vi.waitFor(() =>
  10058. expect(app.editor.getText()).toBe("review this response"),
  10059. );
  10060. const rendered = app.tui.render(100).join("\n");
  10061. expect(rendered).toContain(notice);
  10062. expect(rendered).not.toContain('Check your network');
  10063. expect(rendered).not.toContain("Message kept under Failed");
  10064. await app.submit("/queue");
  10065. expect(app.interaction.current()).toBeUndefined();
  10066. await app.stop();
  10067. });
  10068. it("sends editable @directory/ input as ordinary text", async () => {
  10069. const terminal = new FakeTerminal();
  10070. const runtime = createRuntime();
  10071. const app = createTuiApp({
  10072. runtime,
  10073. terminal,
  10074. version: "0.1.0",
  10075. workspaceDir: "/workspace",
  10076. });
  10077. await app.submit("Review @src/");
  10078. expect(runtime.sendMessage).toHaveBeenCalledWith(
  10079. { id: "session-1", content: "Review @src/", turnId: expect.any(String) },
  10080. expect.any(AbortSignal),
  10081. );
  10082. await expect(app.submit("Review @generated/")).resolves.toBeUndefined();
  10083. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  10084. });
  10085. it("pastes a clipboard image without replacing the text draft and cleans it after send", async () => {
  10086. const terminal = new FakeTerminal();
  10087. const runtime = createRuntime();
  10088. const dispose = vi.fn(async () => undefined);
  10089. const readClipboardImage = vi.fn(async () => ({
  10090. attachment: {
  10091. type: "image" as const,
  10092. filePath: "/tmp/minimax-code-clipboard/clipboard-1.png",
  10093. fileName: "clipboard-1.png",
  10094. mimeType: "image/png",
  10095. sizeBytes: 4096,
  10096. },
  10097. dispose,
  10098. }));
  10099. const app = createTuiApp({
  10100. runtime,
  10101. terminal,
  10102. version: "0.1.0",
  10103. workspaceDir: "/workspace",
  10104. readClipboardImage,
  10105. readClipboardText: async () => null,
  10106. });
  10107. app.start();
  10108. await app.ready;
  10109. app.editor.setText("Keep this draft");
  10110. terminal.input?.("\u001B[118;9u");
  10111. terminal.input?.("\u001B[118;9:3u");
  10112. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
  10113. await vi.waitFor(() =>
  10114. expect(app.editor.getText()).toContain("[Image #1]"),
  10115. );
  10116. expect(app.editor.getText()).toBe("Keep this draft [Image #1] ");
  10117. expect(app.tui.render(100).join("\n")).not.toContain(
  10118. "A clipboard media paste is already in progress.",
  10119. );
  10120. await app.submit("Keep this draft");
  10121. expect(runtime.sendMessage).toHaveBeenCalledWith(
  10122. expect.objectContaining({
  10123. id: "session-1",
  10124. content: "Keep this draft",
  10125. attachments: [
  10126. expect.objectContaining({
  10127. local: { filePath: "/tmp/minimax-code-clipboard/clipboard-1.png" },
  10128. meta: expect.objectContaining({ mimeType: "image/png" }),
  10129. }),
  10130. ],
  10131. }),
  10132. expect.any(AbortSignal),
  10133. );
  10134. expect(dispose).toHaveBeenCalledOnce();
  10135. await app.stop();
  10136. });
  10137. it("retains existing draft state when clipboard read or send fails", async () => {
  10138. const terminal = new FakeTerminal();
  10139. const runtime = createRuntime();
  10140. const dispose = vi.fn(async () => undefined);
  10141. const readClipboardImage = vi
  10142. .fn()
  10143. .mockResolvedValueOnce({
  10144. attachment: {
  10145. type: "image" as const,
  10146. filePath: "/tmp/minimax-code-clipboard/clipboard-2.png",
  10147. fileName: "clipboard-2.png",
  10148. mimeType: "image/png",
  10149. sizeBytes: 1024,
  10150. },
  10151. dispose,
  10152. })
  10153. .mockRejectedValueOnce(new Error("clipboard has no image"));
  10154. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  10155. async function* sendMessage() {
  10156. yield { type: "error", message: "provider unavailable" };
  10157. },
  10158. );
  10159. const app = createTuiApp({
  10160. runtime,
  10161. terminal,
  10162. version: "0.1.0",
  10163. workspaceDir: "/workspace",
  10164. readClipboardImage,
  10165. readClipboardText: async () => null,
  10166. });
  10167. app.start();
  10168. await app.ready;
  10169. app.editor.setText("Do not clear me");
  10170. terminal.input?.("\x16");
  10171. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(1));
  10172. terminal.input?.("\x16");
  10173. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(2));
  10174. expect(app.editor.getText()).toBe("Do not clear me [Image #1] ");
  10175. await app.submit("Try the image");
  10176. expect(dispose).not.toHaveBeenCalled();
  10177. expect(app.tui.render(80).join("\n")).toContain("[Image #1]");
  10178. terminal.input?.("\x7f");
  10179. expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
  10180. expect(dispose).not.toHaveBeenCalled();
  10181. await app.stop();
  10182. expect(dispose).toHaveBeenCalledOnce();
  10183. });
  10184. it("cancels an in-flight clipboard read with Ctrl+C and keeps the draft", async () => {
  10185. const terminal = new FakeTerminal();
  10186. const runtime = createRuntime();
  10187. let observedSignal: AbortSignal | undefined;
  10188. const readClipboardImage = vi.fn(
  10189. async (signal?: AbortSignal) =>
  10190. await new Promise<never>((_resolve, reject) => {
  10191. observedSignal = signal;
  10192. signal?.addEventListener(
  10193. "abort",
  10194. () => reject(new Error("cancelled")),
  10195. { once: true },
  10196. );
  10197. }),
  10198. );
  10199. const app = createTuiApp({
  10200. runtime,
  10201. terminal,
  10202. version: "0.1.0",
  10203. workspaceDir: "/workspace",
  10204. readClipboardImage,
  10205. readClipboardText: async () => null,
  10206. });
  10207. app.start();
  10208. await app.ready;
  10209. app.editor.setText("Draft survives");
  10210. terminal.input?.("\x16");
  10211. await vi.waitFor(() => expect(observedSignal).toBeDefined());
  10212. terminal.input?.("\x03");
  10213. await vi.waitFor(() => expect(observedSignal?.aborted).toBe(true));
  10214. expect(app.editor.getText()).toBe("Draft survives");
  10215. await app.stop();
  10216. });
  10217. it("keeps queued clipboard files alive until the Runtime reports a terminal queue state", async () => {
  10218. const terminal = new FakeTerminal();
  10219. const runtime = createRuntime();
  10220. const dispose = vi.fn(async () => undefined);
  10221. let finishTurn: (() => void) | undefined;
  10222. let deliverQueueEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  10223. vi.mocked(runtime.sendMessage).mockImplementation(
  10224. async function* sendMessage() {
  10225. await new Promise<void>((resolve) => {
  10226. finishTurn = resolve;
  10227. });
  10228. yield { type: "done" };
  10229. },
  10230. );
  10231. vi.mocked(runtime.watchEvents).mockImplementation(
  10232. async function* watchEvents() {
  10233. const event = await new Promise<TuiRuntimeEvent>((resolve) => {
  10234. deliverQueueEvent = resolve;
  10235. });
  10236. yield event;
  10237. },
  10238. );
  10239. const readClipboardImage = vi.fn(async () => ({
  10240. attachment: {
  10241. type: "image" as const,
  10242. filePath: "/tmp/minimax-code-clipboard/clipboard-queue.png",
  10243. fileName: "clipboard-queue.png",
  10244. mimeType: "image/png",
  10245. sizeBytes: 2048,
  10246. },
  10247. dispose,
  10248. }));
  10249. const app = createTuiApp({
  10250. runtime,
  10251. terminal,
  10252. version: "0.1.0",
  10253. workspaceDir: "/workspace",
  10254. productFeatures: { queue: true },
  10255. readClipboardImage,
  10256. });
  10257. app.start();
  10258. await app.ready;
  10259. const first = app.submit("First turn");
  10260. await vi.waitFor(() =>
  10261. expect(app.controller.snapshot().status).toBe("running"),
  10262. );
  10263. terminal.input?.("\x16");
  10264. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
  10265. await app.submit("Queued with image");
  10266. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  10267. "session-1",
  10268. "Queued with image",
  10269. expect.objectContaining({
  10270. attachments: [
  10271. expect.objectContaining({ fileName: "clipboard-queue.png" }),
  10272. ],
  10273. }),
  10274. );
  10275. expect(dispose).not.toHaveBeenCalled();
  10276. deliverQueueEvent?.(
  10277. runtimeEvent({
  10278. type: "session.queue.updated",
  10279. timestamp: Date.now(),
  10280. source: "runtime",
  10281. payload: {
  10282. sessionId: "session-1",
  10283. itemId: "queue-1",
  10284. status: "completed",
  10285. queuedCount: 0,
  10286. },
  10287. }),
  10288. );
  10289. await vi.waitFor(() => expect(dispose).toHaveBeenCalledOnce());
  10290. finishTurn?.();
  10291. await first;
  10292. await app.stop();
  10293. });
  10294. it("opens the Desktop model picker and applies the selected session model", async () => {
  10295. const terminal = new FakeTerminal();
  10296. const runtime = createRuntime();
  10297. vi.mocked(runtime.listModels).mockResolvedValue([
  10298. {
  10299. providerId: "minimax",
  10300. modelId: "MiniMax-M3",
  10301. displayName: "MiniMax M3",
  10302. variant: "thinking",
  10303. thinkingConfig: { mode: "switchable", defaultValue: "true" },
  10304. providerKind: "minimax-managed",
  10305. selected: true,
  10306. },
  10307. ]);
  10308. const app = createTuiApp({
  10309. runtime,
  10310. terminal,
  10311. version: "0.1.0",
  10312. workspaceDir: "/workspace",
  10313. });
  10314. app.start();
  10315. await app.ready;
  10316. await app.submit("Create a session");
  10317. await app.submit("/model");
  10318. expect(app.tui.hasOverlay()).toBe(false);
  10319. expect(app.interaction.isActive()).toBe(true);
  10320. terminal.input?.("\x1b");
  10321. expect(app.tui.hasOverlay()).toBe(false);
  10322. await app.submit("/model");
  10323. terminal.input?.("\r");
  10324. await vi.waitFor(() =>
  10325. expect(runtime.selectModel).toHaveBeenCalledWith(
  10326. expect.objectContaining({
  10327. providerId: "minimax",
  10328. modelId: "MiniMax-M3",
  10329. variant: "thinking",
  10330. }),
  10331. "session-1",
  10332. ),
  10333. );
  10334. await vi.waitFor(() => {
  10335. const rendered = app.tui.render(120).join("\n");
  10336. expect(rendered).toContain("✦ MiniMax M3");
  10337. expect(rendered).toContain("Thinking On");
  10338. expect(rendered).not.toContain("MiniMax M3#thinking");
  10339. });
  10340. await app.stop();
  10341. });
  10342. it("queues a thinking-on model with the configured effort even when the Session stored none", async () => {
  10343. const terminal = new FakeTerminal();
  10344. const runtime = createRuntime();
  10345. let finishTurn: (() => void) | undefined;
  10346. vi.mocked(runtime.listModels).mockResolvedValue([
  10347. {
  10348. providerId: "minimax",
  10349. modelId: "deep-reasoner-1",
  10350. displayName: "deep-reasoner-1",
  10351. selected: true,
  10352. variant: "thinking",
  10353. thinkingConfig: { mode: "switchable", defaultValue: "true" },
  10354. effortOptions: ["xhigh"],
  10355. },
  10356. ]);
  10357. vi.mocked(runtime.sendMessage).mockImplementation(
  10358. async function* sendMessage() {
  10359. await new Promise<void>((resolve) => {
  10360. finishTurn = resolve;
  10361. });
  10362. yield { type: "done" };
  10363. },
  10364. );
  10365. const app = createTuiApp({
  10366. runtime,
  10367. terminal,
  10368. version: "0.1.0",
  10369. workspaceDir: "/workspace",
  10370. productFeatures: { queue: true },
  10371. });
  10372. app.start();
  10373. await app.ready;
  10374. const first = app.submit("First turn");
  10375. await vi.waitFor(() =>
  10376. expect(app.controller.snapshot().status).toBe("running"),
  10377. );
  10378. await app.submit("Queued turn");
  10379. // The Session echo carries no stored effort, so the per-Turn selection has to
  10380. // resolve the configured level. Sending only `variant: thinking` makes Runtime
  10381. // drop the effort and the provider apply its own default.
  10382. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  10383. "session-1",
  10384. "Queued turn",
  10385. expect.objectContaining({
  10386. model: expect.objectContaining({
  10387. providerId: "minimax",
  10388. modelId: "deep-reasoner-1",
  10389. variant: "thinking",
  10390. thinking: { effort: "xhigh" },
  10391. }),
  10392. }),
  10393. );
  10394. finishTurn?.();
  10395. await first;
  10396. await app.stop();
  10397. });
  10398. it("applies a welcome-screen effort to the new Session before sending its first message", async () => {
  10399. const terminal = new FakeTerminal();
  10400. const runtime = createRuntime();
  10401. vi.mocked(runtime.listModels).mockResolvedValue([
  10402. {
  10403. providerId: "custom_provider:byok",
  10404. modelId: "byok-large-5",
  10405. displayName: "BYOK Large 5",
  10406. selected: true,
  10407. variant: "",
  10408. thinkingConfig: { mode: "switchable", defaultValue: "false" },
  10409. effortOptions: ["low", "medium", "high"],
  10410. },
  10411. ]);
  10412. let releaseDefaultSelection: ((selected: boolean) => void) | undefined;
  10413. let releaseSessionSelection: ((selected: boolean) => void) | undefined;
  10414. vi.mocked(runtime.selectModel)
  10415. .mockImplementationOnce(
  10416. async () =>
  10417. await new Promise<boolean>((resolve) => {
  10418. releaseDefaultSelection = resolve;
  10419. }),
  10420. )
  10421. .mockImplementationOnce(
  10422. async () =>
  10423. await new Promise<boolean>((resolve) => {
  10424. releaseSessionSelection = resolve;
  10425. }),
  10426. );
  10427. const app = createTuiApp({
  10428. runtime,
  10429. terminal,
  10430. version: "0.1.0",
  10431. workspaceDir: "/workspace",
  10432. });
  10433. app.start();
  10434. await app.ready;
  10435. await app.submit("/model");
  10436. terminal.input?.("\u001b[C");
  10437. terminal.input?.("\r");
  10438. const firstTurn = app.submit("First turn");
  10439. await vi.waitFor(() =>
  10440. expect(runtime.selectModel).toHaveBeenNthCalledWith(
  10441. 1,
  10442. expect.objectContaining({ thinking: { effort: "high" }, variant: "" }),
  10443. undefined,
  10444. ),
  10445. );
  10446. expect(runtime.selectModel).toHaveBeenCalledOnce();
  10447. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10448. releaseDefaultSelection?.(true);
  10449. await vi.waitFor(() =>
  10450. expect(runtime.selectModel).toHaveBeenNthCalledWith(
  10451. 2,
  10452. expect.objectContaining({ thinking: { effort: "high" }, variant: "" }),
  10453. "session-1",
  10454. ),
  10455. );
  10456. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10457. releaseSessionSelection?.(true);
  10458. await firstTurn;
  10459. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  10460. expect(runtime.selectModel.mock.invocationCallOrder[1]).toBeLessThan(
  10461. runtime.sendMessage.mock.invocationCallOrder[0] ??
  10462. Number.POSITIVE_INFINITY,
  10463. );
  10464. await app.stop();
  10465. });
  10466. it("does not send the first message when Runtime rejects its pending effort", async () => {
  10467. const terminal = new FakeTerminal();
  10468. const runtime = createRuntime();
  10469. vi.mocked(runtime.listModels).mockResolvedValue([
  10470. {
  10471. providerId: "custom_provider:byok",
  10472. modelId: "byok-large-5",
  10473. displayName: "BYOK Large 5",
  10474. selected: true,
  10475. effortOptions: ["low", "medium", "high"],
  10476. },
  10477. ]);
  10478. vi.mocked(runtime.selectModel)
  10479. .mockResolvedValueOnce(true)
  10480. .mockResolvedValueOnce(false);
  10481. const app = createTuiApp({
  10482. runtime,
  10483. terminal,
  10484. version: "0.1.0",
  10485. workspaceDir: "/workspace",
  10486. });
  10487. app.start();
  10488. await app.ready;
  10489. await app.submit("/model");
  10490. terminal.input?.("\r");
  10491. await vi.waitFor(() => expect(runtime.selectModel).toHaveBeenCalledOnce());
  10492. await app.submit("First turn");
  10493. expect(runtime.selectModel).toHaveBeenCalledTimes(2);
  10494. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10495. await app.stop();
  10496. });
  10497. it("lets Escape cancel the first turn while Desktop is creating its session", async () => {
  10498. const terminal = new FakeTerminal();
  10499. const runtime = createRuntime();
  10500. let finishSessionCreation:
  10501. | ((session: { sessionId: string; workspaceDir: string }) => void)
  10502. | undefined;
  10503. vi.mocked(runtime.createSession).mockImplementation(
  10504. async () =>
  10505. await new Promise<{ sessionId: string; workspaceDir: string }>(
  10506. (resolve) => {
  10507. finishSessionCreation = resolve;
  10508. },
  10509. ),
  10510. );
  10511. const app = createTuiApp({
  10512. runtime,
  10513. terminal,
  10514. version: "0.1.0",
  10515. workspaceDir: "/workspace",
  10516. });
  10517. app.start();
  10518. await app.ready;
  10519. const submitting = app.submit("Wait for the session");
  10520. await vi.waitFor(() =>
  10521. expect(app.controller.snapshot()).toMatchObject({
  10522. status: "starting",
  10523. activeTurnId: expect.any(String),
  10524. }),
  10525. );
  10526. expect(app.tui.render(80).join("\n")).toContain("Loading");
  10527. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  10528. expect(app.tui.render(80).join("\n")).not.toContain("MCode ·");
  10529. terminal.input?.("\x1b");
  10530. await vi.waitFor(() =>
  10531. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  10532. );
  10533. finishSessionCreation?.({
  10534. sessionId: "session-created",
  10535. workspaceDir: "/workspace",
  10536. });
  10537. await submitting;
  10538. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10539. expect(app.transcript.snapshot()).toEqual(
  10540. expect.arrayContaining([
  10541. expect.objectContaining({ kind: "assistant", status: "cancelled" }),
  10542. ]),
  10543. );
  10544. await app.stop();
  10545. });
  10546. it("restores a submission attempted while the previous cancellation fence is active", async () => {
  10547. const terminal = new FakeTerminal();
  10548. const runtime = createRuntime();
  10549. let releaseCancelledStream: (() => void) | undefined;
  10550. let sendCount = 0;
  10551. vi.mocked(runtime.sendMessage).mockImplementation(
  10552. async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
  10553. sendCount += 1;
  10554. if (sendCount === 1) {
  10555. await new Promise<void>((resolve) => {
  10556. signal?.addEventListener("abort", resolve, { once: true });
  10557. });
  10558. await new Promise<void>((resolve) => {
  10559. releaseCancelledStream = resolve;
  10560. });
  10561. } else {
  10562. yield { type: "delta", content: "Second response" };
  10563. }
  10564. yield { type: "done" };
  10565. },
  10566. );
  10567. vi.mocked(runtime.abortSession).mockImplementation(async () => {
  10568. setTimeout(() => releaseCancelledStream?.(), 10);
  10569. return true;
  10570. });
  10571. const app = createTuiApp({
  10572. runtime,
  10573. terminal,
  10574. version: "0.1.0",
  10575. workspaceDir: "/workspace",
  10576. });
  10577. app.start();
  10578. await app.ready;
  10579. terminal.input?.("First request");
  10580. terminal.input?.("\r");
  10581. await vi.waitFor(() =>
  10582. expect(app.controller.snapshot().status).toBe("running"),
  10583. );
  10584. terminal.input?.("\x1b");
  10585. await vi.waitFor(() =>
  10586. expect(app.controller.snapshot().cancelling).toBe(true),
  10587. );
  10588. terminal.input?.("Second request");
  10589. terminal.input?.("\r");
  10590. await vi.waitFor(() => expect(app.editor.getText()).toBe("Second request"));
  10591. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  10592. await vi.waitFor(() =>
  10593. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  10594. );
  10595. await vi.waitFor(() =>
  10596. expect(app.controller.snapshot().retiringTurnId).toBeUndefined(),
  10597. );
  10598. expect(app.controller.snapshot().cancelling).toBe(false);
  10599. expect(app.tui.render(80).join("\n")).not.toContain(
  10600. "Stopping the current response",
  10601. );
  10602. app.editor.handleInput("\r");
  10603. await vi.waitFor(() =>
  10604. expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
  10605. );
  10606. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  10607. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  10608. expect(app.transcript.snapshot()).toEqual(
  10609. expect.arrayContaining([
  10610. expect.objectContaining({ kind: "assistant", status: "cancelled" }),
  10611. ]),
  10612. );
  10613. await app.stop();
  10614. });
  10615. it("restores a failed submission before text typed while cancellation is retiring", async () => {
  10616. const terminal = new FakeTerminal();
  10617. const runtime = createRuntime();
  10618. let releaseRuntimeOwnership: (() => void) | undefined;
  10619. const runtimeOwnershipReleased = new Promise<void>((resolve) => {
  10620. releaseRuntimeOwnership = resolve;
  10621. });
  10622. vi.mocked(runtime.sendMessage).mockImplementation(
  10623. async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
  10624. await new Promise<void>((resolve) => {
  10625. signal?.addEventListener("abort", resolve, { once: true });
  10626. });
  10627. await runtimeOwnershipReleased;
  10628. yield { type: "done" };
  10629. },
  10630. );
  10631. const app = createTuiApp({
  10632. runtime,
  10633. terminal,
  10634. version: "0.1.0",
  10635. workspaceDir: "/workspace",
  10636. });
  10637. app.start();
  10638. await app.ready;
  10639. terminal.input?.("First request");
  10640. terminal.input?.("\r");
  10641. await vi.waitFor(() =>
  10642. expect(app.controller.snapshot().status).toBe("running"),
  10643. );
  10644. terminal.input?.("\x1b");
  10645. await vi.waitFor(
  10646. () => expect(app.controller.snapshot().retiringTurnId).toBeTruthy(),
  10647. {
  10648. timeout: 2_000,
  10649. },
  10650. );
  10651. expect(app.controller.snapshot()).toMatchObject({
  10652. status: "idle",
  10653. activeTurnId: undefined,
  10654. cancelling: false,
  10655. });
  10656. terminal.input?.("Second request");
  10657. terminal.input?.("\r");
  10658. terminal.input?.("extra detail");
  10659. await vi.waitFor(() => expect(app.editor.getText()).toBe("extra detail"));
  10660. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  10661. await vi.waitFor(() =>
  10662. expect(app.tui.render(160).join("\n")).toContain("Second request"),
  10663. );
  10664. expect(app.editor.getText()).toBe("Second request\nextra detail");
  10665. releaseRuntimeOwnership?.();
  10666. await vi.waitFor(() =>
  10667. expect(app.controller.snapshot().retiringTurnId).toBeUndefined(),
  10668. );
  10669. expect(app.tui.render(160).join("\n")).not.toContain(
  10670. "Runtime is still stopping; your draft is preserved",
  10671. );
  10672. await app.stop();
  10673. });
  10674. it("aborts session creation when the TUI stops during its first turn", async () => {
  10675. const terminal = new FakeTerminal();
  10676. const runtime = createRuntime();
  10677. let finishSessionCreation:
  10678. | ((session: { sessionId: string; workspaceDir: string }) => void)
  10679. | undefined;
  10680. vi.mocked(runtime.createSession).mockImplementation(
  10681. async () =>
  10682. await new Promise<{ sessionId: string; workspaceDir: string }>(
  10683. (resolve) => {
  10684. finishSessionCreation = resolve;
  10685. },
  10686. ),
  10687. );
  10688. const app = createTuiApp({
  10689. runtime,
  10690. terminal,
  10691. version: "0.1.0",
  10692. workspaceDir: "/workspace",
  10693. });
  10694. app.start();
  10695. await app.ready;
  10696. const submitting = app.submit("Wait for the session");
  10697. await vi.waitFor(() =>
  10698. expect(app.controller.snapshot().activeTurnId).toEqual(
  10699. expect.any(String),
  10700. ),
  10701. );
  10702. const stopping = app.stop();
  10703. finishSessionCreation?.({
  10704. sessionId: "session-created",
  10705. workspaceDir: "/workspace",
  10706. });
  10707. await Promise.all([submitting, stopping]);
  10708. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10709. expect(app.transcript.snapshot()).toEqual(
  10710. expect.arrayContaining([
  10711. expect.objectContaining({ kind: "assistant", status: "cancelled" }),
  10712. ]),
  10713. );
  10714. expect(terminal.stopped).toBe(true);
  10715. });
  10716. it.each(["minimax", "custom_provider:work"])(
  10717. "hydrates the Runtime-selected startup model for %s",
  10718. async (providerId) => {
  10719. const runtime = createRuntime();
  10720. vi.mocked(runtime.listModels).mockResolvedValue([
  10721. { providerId, modelId: "MiniMax-M3", selected: true },
  10722. ]);
  10723. const app = createTuiApp({
  10724. runtime,
  10725. terminal: new FakeTerminal(),
  10726. version: "0.1.0",
  10727. workspaceDir: "/workspace",
  10728. });
  10729. try {
  10730. await app.ready;
  10731. expect(runtime.listModels).toHaveBeenCalled();
  10732. expect(runtime.selectModel).not.toHaveBeenCalled();
  10733. await app.submit("/model");
  10734. expect(runtime.selectModel).not.toHaveBeenCalled();
  10735. } finally {
  10736. await app.stop();
  10737. }
  10738. },
  10739. );
  10740. it("offers provider onboarding when Desktop has no models", async () => {
  10741. const terminal = new FakeTerminal();
  10742. const runtime = createRuntime();
  10743. vi.mocked(runtime.listModels).mockResolvedValue([]);
  10744. const app = createTuiApp({
  10745. runtime,
  10746. terminal,
  10747. version: "0.1.0",
  10748. workspaceDir: "/workspace",
  10749. });
  10750. await app.ready;
  10751. await app.submit("/model unavailable");
  10752. expect(app.tui.hasOverlay()).toBe(false);
  10753. expect(app.interaction.isActive()).toBe(true);
  10754. const rendered = app.tui.render(120).join("\n");
  10755. expect(rendered).toContain("No matching models");
  10756. expect(rendered).toContain("Add 3rd-party provider");
  10757. terminal.input?.("\x1b");
  10758. await app.stop();
  10759. });
  10760. it("keeps the TUI usable when the Runtime model catalog fails to load", async () => {
  10761. const terminal = new FakeTerminal();
  10762. const runtime = createRuntime();
  10763. vi.mocked(runtime.listModels).mockRejectedValue(
  10764. new Error("catalog unavailable"),
  10765. );
  10766. const app = createTuiApp({
  10767. runtime,
  10768. terminal,
  10769. version: "0.1.0",
  10770. workspaceDir: "/workspace",
  10771. });
  10772. await app.ready;
  10773. await expect(app.submit("/model")).resolves.toBeUndefined();
  10774. expect(app.tui.hasOverlay()).toBe(false);
  10775. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  10776. kind: "warning",
  10777. content: "Couldn't load models: catalog unavailable. Retry /model.",
  10778. });
  10779. });
  10780. it("shows a follow-up as queued while Runtime admission is pending", async () => {
  10781. const terminal = new FakeTerminal();
  10782. const runtime = createRuntime();
  10783. let finishFirstTurn: (() => void) | undefined;
  10784. let finishEnqueue: (() => void) | undefined;
  10785. let admitted = false;
  10786. vi.mocked(runtime.sendMessage).mockImplementation(
  10787. async function* sendMessage() {
  10788. await new Promise<void>((resolve) => {
  10789. finishFirstTurn = resolve;
  10790. });
  10791. yield { type: "done" };
  10792. },
  10793. );
  10794. vi.mocked(runtime.enqueueMessage).mockImplementation(async () => {
  10795. await new Promise<void>((resolve) => {
  10796. finishEnqueue = resolve;
  10797. });
  10798. admitted = true;
  10799. return { itemId: "queue-pending-1", status: "queued", position: 1 };
  10800. });
  10801. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () =>
  10802. admitted
  10803. ? [
  10804. {
  10805. itemId: "queue-pending-1",
  10806. sessionId: "session-1",
  10807. status: "queued",
  10808. content: "Second turn",
  10809. },
  10810. ]
  10811. : [],
  10812. );
  10813. const app = createTuiApp({
  10814. runtime,
  10815. terminal,
  10816. version: "0.1.0",
  10817. workspaceDir: "/workspace",
  10818. });
  10819. app.start();
  10820. await app.ready;
  10821. const first = app.submit("First turn");
  10822. await vi.waitFor(() =>
  10823. expect(app.controller.snapshot().activeTurnId).toEqual(
  10824. expect.any(String),
  10825. ),
  10826. );
  10827. terminal.input?.("Second turn");
  10828. terminal.input?.("\x1b\r");
  10829. await vi.waitFor(() =>
  10830. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  10831. );
  10832. try {
  10833. expect(
  10834. app.transcript
  10835. .snapshot()
  10836. .find((cell) => cell.content.includes("Second turn")),
  10837. ).toBeUndefined();
  10838. const rendered = app.tui.render(100).join("\n");
  10839. expect(rendered).not.toContain("Adding to Queue");
  10840. expect(rendered).toContain("Next · after current response");
  10841. expect(rendered).toContain("Second turn");
  10842. finishEnqueue?.();
  10843. await vi.waitFor(() => {
  10844. const confirmed = app.tui.render(100).join("\n");
  10845. expect(confirmed).not.toContain("Adding to Queue");
  10846. expect(confirmed).toContain("Next · after current response");
  10847. expect(confirmed).toContain("Second turn");
  10848. });
  10849. } finally {
  10850. finishEnqueue?.();
  10851. finishFirstTurn?.();
  10852. await first;
  10853. await app.stop();
  10854. }
  10855. });
  10856. it("removes the local Queue admission and restores the Draft when Runtime rejects it", async () => {
  10857. const terminal = new FakeTerminal();
  10858. const runtime = createRuntime();
  10859. let finishFirstTurn: (() => void) | undefined;
  10860. let rejectEnqueue: ((error: Error) => void) | undefined;
  10861. vi.mocked(runtime.sendMessage).mockImplementation(
  10862. async function* sendMessage() {
  10863. await new Promise<void>((resolve) => {
  10864. finishFirstTurn = resolve;
  10865. });
  10866. yield { type: "done" };
  10867. },
  10868. );
  10869. vi.mocked(runtime.enqueueMessage).mockImplementation(
  10870. async () =>
  10871. await new Promise<never>((_resolve, reject) => {
  10872. rejectEnqueue = reject;
  10873. }),
  10874. );
  10875. const app = createTuiApp({
  10876. runtime,
  10877. terminal,
  10878. version: "0.1.0",
  10879. workspaceDir: "/workspace",
  10880. });
  10881. app.start();
  10882. await app.ready;
  10883. const first = app.submit("First turn");
  10884. await vi.waitFor(() =>
  10885. expect(app.controller.snapshot().activeTurnId).toEqual(
  10886. expect.any(String),
  10887. ),
  10888. );
  10889. terminal.input?.("Keep this Draft");
  10890. terminal.input?.("\x1b\r");
  10891. await vi.waitFor(() =>
  10892. expect(app.tui.render(100).join("\n")).toContain(
  10893. "Next · after current response",
  10894. ),
  10895. );
  10896. await vi.waitFor(() =>
  10897. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  10898. );
  10899. rejectEnqueue?.(new Error("queue unavailable"));
  10900. await vi.waitFor(() =>
  10901. expect(app.editor.getText()).toBe("Keep this Draft"),
  10902. );
  10903. const rendered = app.tui.render(100).join("\n");
  10904. expect(rendered).not.toContain("Next · after current response");
  10905. expect(rendered).toContain("Couldn't add this message to the Queue");
  10906. finishFirstTurn?.();
  10907. await first;
  10908. await app.stop();
  10909. });
  10910. it("shows every rapid follow-up as queued while Runtime admissions are serialized", async () => {
  10911. const terminal = new FakeTerminal();
  10912. const runtime = createRuntime();
  10913. let finishFirstTurn: (() => void) | undefined;
  10914. const releaseAdmissions: Array<() => void> = [];
  10915. const queued: TuiQueuedMessage[] = [];
  10916. vi.mocked(runtime.sendMessage).mockImplementation(
  10917. async function* sendMessage() {
  10918. await new Promise<void>((resolve) => {
  10919. finishFirstTurn = resolve;
  10920. });
  10921. yield { type: "done" };
  10922. },
  10923. );
  10924. vi.mocked(runtime.enqueueMessage).mockImplementation(
  10925. async (sessionId, content) => {
  10926. await new Promise<void>((resolve) => releaseAdmissions.push(resolve));
  10927. const item = {
  10928. itemId: `queue-rapid-${String(queued.length + 1)}`,
  10929. sessionId,
  10930. status: "queued",
  10931. content,
  10932. } satisfies TuiQueuedMessage;
  10933. queued.push(item);
  10934. return {
  10935. itemId: item.itemId,
  10936. status: item.status,
  10937. position: queued.length,
  10938. };
  10939. },
  10940. );
  10941. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  10942. ...queued,
  10943. ]);
  10944. const app = createTuiApp({
  10945. runtime,
  10946. terminal,
  10947. version: "0.1.0",
  10948. workspaceDir: "/workspace",
  10949. });
  10950. app.start();
  10951. await app.ready;
  10952. const first = app.submit("First turn");
  10953. await vi.waitFor(() =>
  10954. expect(app.controller.snapshot().activeTurnId).toEqual(
  10955. expect.any(String),
  10956. ),
  10957. );
  10958. terminal.input?.("Second turn");
  10959. terminal.input?.("\x1b\r");
  10960. terminal.input?.("Third turn");
  10961. terminal.input?.("\x1b\r");
  10962. await vi.waitFor(() => {
  10963. const rendered = app.tui.render(100).join("\n");
  10964. expect(rendered).not.toContain("Adding");
  10965. expect(rendered).toContain("Queue · 2 next");
  10966. expect(rendered).toContain("Second turn");
  10967. expect(rendered).toContain("Third turn");
  10968. });
  10969. expect(
  10970. app.transcript
  10971. .snapshot()
  10972. .filter(
  10973. (cell) =>
  10974. cell.content.includes("Second turn") ||
  10975. cell.content.includes("Third turn"),
  10976. ),
  10977. ).toEqual([]);
  10978. await vi.waitFor(() =>
  10979. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  10980. );
  10981. releaseAdmissions[0]?.();
  10982. await vi.waitFor(() =>
  10983. expect(runtime.enqueueMessage).toHaveBeenCalledTimes(2),
  10984. );
  10985. const partiallyConfirmed = app.tui.render(100).join("\n");
  10986. expect(partiallyConfirmed).toContain("Queue · 2 next");
  10987. expect(partiallyConfirmed.indexOf("Second turn")).toBeLessThan(
  10988. partiallyConfirmed.indexOf("Third turn"),
  10989. );
  10990. releaseAdmissions[1]?.();
  10991. await vi.waitFor(() =>
  10992. expect(app.tui.render(100).join("\n")).toContain("Queue · 2 next"),
  10993. );
  10994. finishFirstTurn?.();
  10995. await first;
  10996. await app.stop();
  10997. });
  10998. it("submits follow-ups to the runtime-owned queue and never drains them in the CLI", async () => {
  10999. const terminal = new FakeTerminal();
  11000. const runtime = createRuntime();
  11001. let finishFirstTurn: (() => void) | undefined;
  11002. vi.mocked(runtime.sendMessage).mockImplementation(
  11003. async function* sendMessage(req: SendMessageReq) {
  11004. const content = req.content ?? "";
  11005. if (content === "First turn") {
  11006. await new Promise<void>((resolve) => {
  11007. finishFirstTurn = resolve;
  11008. });
  11009. }
  11010. yield { type: "delta", content: `Reply to ${content || "attachment"}` };
  11011. yield { type: "done" };
  11012. },
  11013. );
  11014. const attachment = {
  11015. type: "file" as const,
  11016. filePath: "/workspace/notes.md",
  11017. fileName: "notes.md",
  11018. mimeType: "text/markdown",
  11019. sizeBytes: 32,
  11020. };
  11021. const queued: Array<{
  11022. itemId: string;
  11023. sessionId: string;
  11024. status: string;
  11025. content: string;
  11026. }> = [];
  11027. vi.mocked(runtime.enqueueMessage).mockImplementation(
  11028. async (sessionId, content) => {
  11029. const item = {
  11030. itemId: `queue-${queued.length + 1}`,
  11031. sessionId,
  11032. status: "queued",
  11033. content,
  11034. };
  11035. queued.push(item);
  11036. return {
  11037. itemId: item.itemId,
  11038. status: item.status,
  11039. position: queued.length,
  11040. };
  11041. },
  11042. );
  11043. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  11044. ...queued,
  11045. ]);
  11046. vi.mocked(runtime.deleteQueuedMessage).mockImplementation(
  11047. async (_sessionId, itemId) => {
  11048. const index = queued.findIndex((item) => item.itemId === itemId);
  11049. if (index < 0) return undefined;
  11050. return queued.splice(index, 1)[0];
  11051. },
  11052. );
  11053. const readClipboardImage = vi.fn(async () => ({
  11054. attachment,
  11055. dispose: vi.fn(async () => undefined),
  11056. }));
  11057. const app = createTuiApp({
  11058. runtime,
  11059. terminal,
  11060. version: "0.1.0",
  11061. workspaceDir: "/workspace",
  11062. readClipboardImage,
  11063. });
  11064. app.start();
  11065. await app.ready;
  11066. const first = app.submit("First turn");
  11067. await vi.waitFor(() =>
  11068. expect(app.controller.snapshot().activeTurnId).toEqual(
  11069. expect.any(String),
  11070. ),
  11071. );
  11072. terminal.input?.("\x16");
  11073. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
  11074. await app.submit("Second turn");
  11075. await app.submit("Third turn");
  11076. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  11077. expect(runtime.enqueueMessage).toHaveBeenNthCalledWith(
  11078. 1,
  11079. "session-1",
  11080. "Second turn",
  11081. {
  11082. attachments: [attachment],
  11083. model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
  11084. },
  11085. );
  11086. expect(runtime.enqueueMessage).toHaveBeenNthCalledWith(
  11087. 2,
  11088. "session-1",
  11089. "Third turn",
  11090. {
  11091. attachments: [],
  11092. model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
  11093. },
  11094. );
  11095. expect(app.transcript.get("queue:queue-1")).toBeUndefined();
  11096. expect(app.transcript.get("queue:queue-2")).toBeUndefined();
  11097. const queuedUi = app.tui.render(80).join("\n");
  11098. expect(queuedUi).toContain("Queue · 2 next");
  11099. expect(queuedUi).toContain("after current response");
  11100. expect(queuedUi).toContain("Second turn");
  11101. expect(queuedUi).toContain("Third turn");
  11102. expect(queuedUi).toContain("/queue manage");
  11103. await app.submit("/queue");
  11104. expect(app.interaction.render(80).join("\n")).toContain("Queue");
  11105. expect(app.interaction.render(80).join("\n")).toContain("2 next");
  11106. expect(app.interaction.render(80).join("\n")).toContain("› 2. Third turn");
  11107. expect(app.editor.getText()).toBe("");
  11108. terminal.input?.("d");
  11109. expect(app.interaction.render(80).join("\n")).toContain(
  11110. "Remove this next message?",
  11111. );
  11112. terminal.input?.("\r");
  11113. await vi.waitFor(() =>
  11114. expect(runtime.deleteQueuedMessage).toHaveBeenCalledWith(
  11115. "session-1",
  11116. "queue-2",
  11117. ),
  11118. );
  11119. await vi.waitFor(() =>
  11120. expect(app.tui.render(80).join("\n")).not.toContain("Third turn"),
  11121. );
  11122. expect(app.tui.render(80).join("\n")).toContain("Second turn");
  11123. terminal.input?.("\x1b");
  11124. finishFirstTurn?.();
  11125. await first;
  11126. expect(
  11127. vi.mocked(runtime.sendMessage).mock.calls.map((call) => call[0].content),
  11128. ).toEqual(["First turn"]);
  11129. expect(app.tui.render(80).join("\n")).toContain(
  11130. "Next · after current response",
  11131. );
  11132. expect(app.tui.render(80).join("\n")).toContain("Second turn");
  11133. expect(app.tui.render(80).join("\n")).not.toContain("Sending next");
  11134. await app.stop();
  11135. });
  11136. it("uses the Runtime queue when a resumed started session is active before queue/model hydration finishes", async () => {
  11137. const terminal = new FakeTerminal();
  11138. const runtime = createRuntime();
  11139. let releaseQueue: ((items: TuiQueuedMessage[]) => void) | undefined;
  11140. const slowQueue = new Promise<TuiQueuedMessage[]>((resolve) => {
  11141. releaseQueue = resolve;
  11142. });
  11143. let releaseModels: ((models: TuiModel[]) => void) | undefined;
  11144. const slowModels = new Promise<TuiModel[]>((resolve) => {
  11145. releaseModels = resolve;
  11146. });
  11147. const session = {
  11148. sessionId: "session-running",
  11149. title: "Running session",
  11150. workspaceDir: "/workspace",
  11151. status: "started",
  11152. };
  11153. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11154. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11155. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  11156. schemaVersion: 1,
  11157. sessionId: "session-running",
  11158. state: "running",
  11159. turnId: "turn-running",
  11160. actions: { steer: true },
  11161. });
  11162. vi.mocked(runtime.listQueuedMessages).mockImplementation(
  11163. async () => slowQueue,
  11164. );
  11165. vi.mocked(runtime.listModels).mockImplementation(async (sessionId) =>
  11166. sessionId ? slowModels : [],
  11167. );
  11168. vi.mocked(runtime.enqueueMessage).mockResolvedValue({
  11169. itemId: "queue-running-1",
  11170. status: "queued",
  11171. position: 1,
  11172. });
  11173. const app = createTuiApp({
  11174. runtime,
  11175. terminal,
  11176. version: "0.1.0",
  11177. workspaceDir: "/workspace",
  11178. productFeatures: { queue: true },
  11179. });
  11180. await app.ready;
  11181. const resuming = app.submit("/resume session-running");
  11182. await vi.waitFor(() =>
  11183. expect(app.tui.render(80).join("\n")).toContain("Loading"),
  11184. );
  11185. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  11186. const followUp = app.submit("Send this through the Runtime queue");
  11187. await vi.waitFor(() =>
  11188. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  11189. "session-running",
  11190. "Send this through the Runtime queue",
  11191. { attachments: [] },
  11192. ),
  11193. );
  11194. expect(runtime.sendMessage).not.toHaveBeenCalled();
  11195. releaseQueue?.([]);
  11196. releaseModels?.([]);
  11197. await Promise.all([resuming, followUp]);
  11198. await app.stop();
  11199. });
  11200. it("does not recover a terminal session as an active turn", async () => {
  11201. const terminal = new FakeTerminal();
  11202. const runtime = createRuntime();
  11203. const session = {
  11204. sessionId: "session-finished",
  11205. title: "Finished session",
  11206. workspaceDir: "/workspace",
  11207. status: "finished",
  11208. };
  11209. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11210. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11211. const app = createTuiApp({
  11212. runtime,
  11213. terminal,
  11214. version: "0.1.0",
  11215. workspaceDir: "/workspace",
  11216. });
  11217. await app.ready;
  11218. await app.submit("/resume session-finished");
  11219. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  11220. expect(app.tui.render(80).join("\n")).toContain("Message · Enter send");
  11221. await app.stop();
  11222. });
  11223. it("does not recover a stale started Session when Runtime is already idle", async () => {
  11224. const terminal = new FakeTerminal();
  11225. const runtime = createRuntime();
  11226. const session = {
  11227. sessionId: "session-stale",
  11228. title: "Stale session",
  11229. workspaceDir: "/workspace",
  11230. status: "started",
  11231. };
  11232. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11233. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11234. const app = createTuiApp({
  11235. runtime,
  11236. terminal,
  11237. version: "0.1.0",
  11238. workspaceDir: "/workspace",
  11239. });
  11240. app.start();
  11241. await app.ready;
  11242. await app.submit("/resume session-stale");
  11243. await vi.waitFor(() =>
  11244. expect(app.tui.render(80).join("\n")).not.toContain("Loading"),
  11245. );
  11246. const rendered = app.tui.render(80).join("\n");
  11247. expect(rendered).not.toContain("Thinking");
  11248. expect(rendered).not.toContain("Stopping response");
  11249. expect(rendered).not.toContain("Stopping the current response");
  11250. expect(rendered).toContain("Message · Enter send");
  11251. await app.stop();
  11252. });
  11253. it("stops a recovered Runtime turn with /stop and Escape through abortSession", async () => {
  11254. const terminal = new FakeTerminal();
  11255. const runtime = createRuntime();
  11256. const session = {
  11257. sessionId: "session-running",
  11258. title: "Running session",
  11259. workspaceDir: "/workspace",
  11260. status: "started",
  11261. };
  11262. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11263. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11264. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  11265. schemaVersion: 1,
  11266. sessionId: "session-running",
  11267. state: "running",
  11268. turnId: "turn-running",
  11269. actions: { steer: true },
  11270. });
  11271. vi.mocked(runtime.abortSession).mockResolvedValue(true);
  11272. const app = createTuiApp({
  11273. runtime,
  11274. terminal,
  11275. version: "0.1.0",
  11276. workspaceDir: "/workspace",
  11277. });
  11278. app.start();
  11279. await app.ready;
  11280. await app.submit("/resume session-running");
  11281. await app.submit("/stop");
  11282. expect(runtime.abortSession).toHaveBeenCalledWith(
  11283. expect.objectContaining({ id: "session-running" }),
  11284. );
  11285. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  11286. vi.mocked(runtime.abortSession).mockClear();
  11287. await app.submit("/resume session-running");
  11288. terminal.input?.("\x1b");
  11289. await vi.waitFor(() =>
  11290. expect(runtime.abortSession).toHaveBeenCalledWith(
  11291. expect.objectContaining({ id: "session-running" }),
  11292. ),
  11293. );
  11294. await vi.waitFor(() =>
  11295. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt"),
  11296. );
  11297. expect(app.tui.render(80).join("\n")).not.toMatch(
  11298. /Stopped after|Interrupted after/u,
  11299. );
  11300. await app.stop();
  11301. });
  11302. it.each([
  11303. [
  11304. "rejects the abort",
  11305. async () => false,
  11306. "Runtime did not confirm that the active response stopped.",
  11307. ],
  11308. [
  11309. "fails the abort request",
  11310. async () => Promise.reject(new Error("connection lost")),
  11311. "Couldn't stop the current response:",
  11312. ],
  11313. ])(
  11314. "clears the recovered foreground projection and reports when Runtime %s",
  11315. async (_label, abort, expectedError) => {
  11316. const terminal = new FakeTerminal();
  11317. const runtime = createRuntime();
  11318. const session = {
  11319. sessionId: "session-running",
  11320. title: "Running session",
  11321. workspaceDir: "/workspace",
  11322. status: "started",
  11323. };
  11324. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11325. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11326. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  11327. schemaVersion: 1,
  11328. sessionId: "session-running",
  11329. state: "running",
  11330. turnId: "turn-running",
  11331. actions: { steer: false },
  11332. });
  11333. vi.mocked(runtime.abortSession).mockImplementation(abort);
  11334. const app = createTuiApp({
  11335. runtime,
  11336. terminal,
  11337. version: "0.1.0",
  11338. workspaceDir: "/workspace",
  11339. });
  11340. app.start();
  11341. await app.ready;
  11342. await app.submit("/resume session-running");
  11343. terminal.input?.("\x1b");
  11344. await vi.waitFor(() =>
  11345. expect(runtime.abortSession).toHaveBeenCalledWith(
  11346. expect.objectContaining({ id: "session-running" }),
  11347. ),
  11348. );
  11349. await vi.waitFor(() =>
  11350. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt"),
  11351. );
  11352. await vi.waitFor(() =>
  11353. expect(app.tui.render(80).join("\n")).toContain(expectedError),
  11354. );
  11355. await app.stop();
  11356. },
  11357. );
  11358. it("keeps Request failed visible when Runtime still has queued follow-ups", async () => {
  11359. const terminal = new FakeTerminal();
  11360. const runtime = createRuntime();
  11361. let finishTurn: (() => void) | undefined;
  11362. const queued = [
  11363. {
  11364. itemId: "queue-after-error",
  11365. sessionId: "session-1",
  11366. status: "queued",
  11367. content: "Continue after failure",
  11368. },
  11369. ];
  11370. vi.mocked(runtime.listQueuedMessages).mockResolvedValue(queued);
  11371. vi.mocked(runtime.enqueueMessage).mockResolvedValue({
  11372. itemId: "queue-after-error",
  11373. status: "queued",
  11374. position: 1,
  11375. });
  11376. vi.mocked(runtime.sendMessage).mockImplementation(
  11377. async function* sendMessage() {
  11378. await new Promise<void>((resolve) => {
  11379. finishTurn = resolve;
  11380. });
  11381. yield { type: "error", message: "provider unavailable" };
  11382. },
  11383. );
  11384. const app = createTuiApp({
  11385. runtime,
  11386. terminal,
  11387. version: "0.1.0",
  11388. workspaceDir: "/workspace",
  11389. productFeatures: { queue: true },
  11390. });
  11391. await app.ready;
  11392. const first = app.submit("First turn");
  11393. await vi.waitFor(() =>
  11394. expect(app.controller.snapshot().activeTurnId).toEqual(
  11395. expect.any(String),
  11396. ),
  11397. );
  11398. await app.submit("Continue after failure");
  11399. finishTurn?.();
  11400. await first;
  11401. expect(app.tui.render(80).join("\n")).toContain(
  11402. "Error The model provider is temporarily unavailable.",
  11403. );
  11404. expect(app.tui.render(80).join("\n")).not.toContain("Request failed");
  11405. await app.stop();
  11406. });
  11407. it("converges a recovered running state after the Runtime emits a terminal event", async () => {
  11408. const terminal = new FakeTerminal();
  11409. const runtime = createRuntime();
  11410. const session = {
  11411. sessionId: "session-recovered",
  11412. title: "Recovered session",
  11413. workspaceDir: "/workspace",
  11414. status: "started",
  11415. };
  11416. const busEvents: TuiRuntimeEvent[] = [];
  11417. let wakeBus: (() => void) | undefined;
  11418. const waitForNextBusEvent = (signal: AbortSignal) =>
  11419. new Promise<void>((resolve) => {
  11420. wakeBus = resolve;
  11421. signal.addEventListener("abort", resolve, { once: true });
  11422. });
  11423. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11424. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11425. let activeRecoveredTurn = true;
  11426. vi.mocked(runtime.getActiveRun).mockImplementation(async () =>
  11427. activeRecoveredTurn
  11428. ? {
  11429. schemaVersion: 1,
  11430. sessionId: "session-recovered",
  11431. state: "running",
  11432. turnId: "turn-recovered",
  11433. actions: { steer: true },
  11434. }
  11435. : {
  11436. schemaVersion: 1,
  11437. sessionId: "session-recovered",
  11438. state: "terminal",
  11439. turnId: "turn-recovered",
  11440. actions: { steer: false },
  11441. },
  11442. );
  11443. let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
  11444. vi.mocked(runtime.getMessages).mockImplementation(
  11445. async () => durableMessages,
  11446. );
  11447. vi.mocked(runtime.watchEvents).mockImplementation(
  11448. async function* watchEvents(signal) {
  11449. while (!signal.aborted) {
  11450. if (busEvents.length === 0) await waitForNextBusEvent(signal);
  11451. if (signal.aborted) return;
  11452. const event = busEvents.shift();
  11453. if (event) yield event;
  11454. }
  11455. },
  11456. );
  11457. const app = createTuiApp({
  11458. runtime,
  11459. terminal,
  11460. version: "0.1.0",
  11461. workspaceDir: "/workspace",
  11462. });
  11463. app.start();
  11464. await app.ready;
  11465. await app.submit("/resume session-recovered");
  11466. expect(app.tui.render(80).join("\n")).toContain("Loading");
  11467. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  11468. await vi.waitFor(() =>
  11469. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  11470. "session-recovered",
  11471. "turn-recovered",
  11472. expect.any(AbortSignal),
  11473. ),
  11474. );
  11475. activeRecoveredTurn = false;
  11476. const historyCallsBeforeTerminal = vi.mocked(runtime.getMessages).mock.calls
  11477. .length;
  11478. durableMessages = [
  11479. {
  11480. id: "message-recovered-assistant",
  11481. turnId: "turn-recovered",
  11482. role: "assistant",
  11483. content: "Recovered answer",
  11484. timestamp: 101,
  11485. },
  11486. ];
  11487. busEvents.push(
  11488. runtimeEvent({
  11489. type: "session.finish",
  11490. timestamp: 101,
  11491. source: "runtime",
  11492. payload: {
  11493. sessionId: "session-recovered",
  11494. turnId: "turn-recovered",
  11495. status: "finished",
  11496. },
  11497. }),
  11498. );
  11499. wakeBus?.();
  11500. wakeBus = undefined;
  11501. await vi.waitFor(() =>
  11502. expect(vi.mocked(runtime.getMessages).mock.calls.length).toBeGreaterThan(
  11503. historyCallsBeforeTerminal,
  11504. ),
  11505. );
  11506. await vi.waitFor(() => {
  11507. const rendered = app.tui.render(80).join("\n");
  11508. expect(rendered).not.toContain("Esc to interrupt");
  11509. expect(app.transcript.snapshot()).toEqual(
  11510. expect.arrayContaining([
  11511. expect.objectContaining({
  11512. kind: "assistant",
  11513. content: "Recovered answer",
  11514. }),
  11515. ]),
  11516. );
  11517. });
  11518. await app.stop();
  11519. });
  11520. it("clears a recovered decision block when switching to a session without a pending decision", async () => {
  11521. const terminal = new FakeTerminal();
  11522. const runtime = createRuntime();
  11523. let controllerSessionId = "";
  11524. const firstSession = {
  11525. sessionId: "session-blocked",
  11526. title: "Blocked session",
  11527. workspaceDir: "/workspace",
  11528. status: "started",
  11529. };
  11530. const secondSession = {
  11531. sessionId: "session-clear",
  11532. title: "Clear session",
  11533. workspaceDir: "/workspace",
  11534. status: "finished",
  11535. };
  11536. vi.mocked(runtime.listSessions).mockResolvedValue([
  11537. firstSession,
  11538. secondSession,
  11539. ]);
  11540. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  11541. sessionId === firstSession.sessionId ? firstSession : secondSession,
  11542. );
  11543. vi.mocked(runtime.listPendingPermissions).mockImplementation(async () =>
  11544. controllerSessionId === firstSession.sessionId
  11545. ? [
  11546. {
  11547. requestId: "permission-blocked",
  11548. sessionId: firstSession.sessionId,
  11549. agentName: "mavis",
  11550. toolName: "bash",
  11551. reason: "Run checks",
  11552. allowAlwaysSupported: true,
  11553. },
  11554. ]
  11555. : [],
  11556. );
  11557. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue(undefined);
  11558. const app = createTuiApp({
  11559. runtime,
  11560. terminal,
  11561. version: "0.1.0",
  11562. workspaceDir: "/workspace",
  11563. });
  11564. await app.ready;
  11565. controllerSessionId = firstSession.sessionId;
  11566. await app.submit("/resume session-blocked");
  11567. expect(app.tui.hasOverlay()).toBe(false);
  11568. expect(app.interaction.isActive()).toBe(true);
  11569. expect(app.tui.render(80).join("\n")).toContain("Approval required");
  11570. controllerSessionId = secondSession.sessionId;
  11571. await app.submit("/resume session-clear");
  11572. expect(app.tui.hasOverlay()).toBe(false);
  11573. const rendered = app.tui.render(80).join("\n");
  11574. expect(rendered).not.toContain("Approval required");
  11575. expect(rendered).not.toContain("Reply required");
  11576. await app.stop();
  11577. });
  11578. it("moves a sending follow-up from the Composer area into the user transcript", async () => {
  11579. const terminal = new FakeTerminal();
  11580. const runtime = createRuntime();
  11581. const busEvents: TuiRuntimeEvent[] = [];
  11582. let wakeBus: (() => void) | undefined;
  11583. const waitForNextBusEvent = (signal: AbortSignal) =>
  11584. new Promise<void>((resolve) => {
  11585. wakeBus = resolve;
  11586. signal.addEventListener("abort", resolve, { once: true });
  11587. });
  11588. vi.mocked(runtime.listSessions).mockResolvedValue([
  11589. {
  11590. sessionId: "session-existing",
  11591. title: "Existing",
  11592. workspaceDir: "/workspace",
  11593. },
  11594. ]);
  11595. vi.mocked(runtime.listQueuedMessages).mockResolvedValue([
  11596. {
  11597. itemId: "queue-with-attachment",
  11598. sessionId: "session-existing",
  11599. status: "queued",
  11600. content: "Review the attached plan",
  11601. attachments: [
  11602. {
  11603. meta: {
  11604. attachmentType: "file",
  11605. fileName: "plan.md",
  11606. mimeType: "text/markdown",
  11607. sizeBytes: 42,
  11608. },
  11609. local: { filePath: "/workspace/plan.md" },
  11610. },
  11611. ],
  11612. },
  11613. {
  11614. itemId: "queue-that-fails",
  11615. sessionId: "session-existing",
  11616. status: "queued",
  11617. content: "Run the failing follow-up",
  11618. },
  11619. ]);
  11620. vi.mocked(runtime.watchEvents).mockImplementation(
  11621. async function* watchEvents(signal) {
  11622. while (!signal.aborted) {
  11623. if (busEvents.length === 0) await waitForNextBusEvent(signal);
  11624. if (signal.aborted) return;
  11625. const event = busEvents.shift();
  11626. if (event) yield event;
  11627. }
  11628. },
  11629. );
  11630. const emitQueueStatus = (
  11631. itemId: string,
  11632. status: string,
  11633. failedReason?: string,
  11634. ) => {
  11635. busEvents.push(
  11636. runtimeEvent({
  11637. type: "session.queue.updated",
  11638. timestamp: Date.now(),
  11639. source: "runtime",
  11640. payload: {
  11641. sessionId: "session-existing",
  11642. itemId,
  11643. status,
  11644. queuedCount: status === "queued" ? 1 : 0,
  11645. ...(failedReason ? { failedReason } : {}),
  11646. },
  11647. }),
  11648. );
  11649. wakeBus?.();
  11650. wakeBus = undefined;
  11651. };
  11652. const app = createTuiApp({
  11653. runtime,
  11654. terminal,
  11655. version: "0.1.0",
  11656. workspaceDir: "/workspace",
  11657. productFeatures: { queue: true },
  11658. });
  11659. app.start();
  11660. await app.ready;
  11661. await app.submit("/resume session-existing");
  11662. expect(app.tui.render(80).join("\n")).toContain("Queue · 2 next");
  11663. expect(app.tui.render(80).join("\n")).toContain("Review the attached plan");
  11664. expect(app.transcript.get("queue:queue-with-attachment")).toBeUndefined();
  11665. emitQueueStatus("queue-with-attachment", "running");
  11666. await vi.waitFor(() =>
  11667. expect(app.transcript.get("queue:queue-with-attachment")).toMatchObject({
  11668. kind: "user",
  11669. status: "succeeded",
  11670. content: expect.stringContaining("Review the attached plan"),
  11671. }),
  11672. );
  11673. expect(app.tui.render(80).join("\n")).not.toContain("SENDING");
  11674. expect(app.tui.render(80).join("\n")).toContain(
  11675. "Next · after current response",
  11676. );
  11677. expect(app.tui.render(80).join("\n")).toContain(
  11678. "Run the failing follow-up",
  11679. );
  11680. expect(
  11681. app.transcript.get("queue:queue-with-attachment")?.attachments,
  11682. ).toEqual([
  11683. expect.objectContaining({
  11684. fileName: "plan.md",
  11685. mimeType: "text/markdown",
  11686. sizeBytes: 42,
  11687. }),
  11688. ]);
  11689. emitQueueStatus("queue-with-attachment", "completed");
  11690. await vi.waitFor(() =>
  11691. expect(app.transcript.get("queue:queue-with-attachment")).toMatchObject({
  11692. kind: "user",
  11693. status: "succeeded",
  11694. content: expect.stringContaining("Review the attached plan"),
  11695. }),
  11696. );
  11697. emitQueueStatus("queue-that-fails", "running");
  11698. await vi.waitFor(() =>
  11699. expect(app.transcript.get("queue:queue-that-fails")).toMatchObject({
  11700. kind: "user",
  11701. status: "succeeded",
  11702. }),
  11703. );
  11704. emitQueueStatus(
  11705. "queue-that-fails",
  11706. "admission-rejected",
  11707. "provider unavailable",
  11708. );
  11709. await vi.waitFor(() =>
  11710. expect(app.editor.getText()).toBe("Run the failing follow-up"),
  11711. );
  11712. expect(app.tui.render(80).join("\n")).toContain(
  11713. "Error Message was not added to the Queue: provider unavailable.",
  11714. );
  11715. expect(app.transcript.get("queue:queue-that-fails")).toMatchObject({
  11716. kind: "user",
  11717. status: "succeeded",
  11718. });
  11719. expect(app.tui.render(80).join("\n")).toContain(
  11720. "Run the failing follow-up",
  11721. );
  11722. await app.stop();
  11723. });
  11724. it("refreshes history when Desktop Runtime finishes an auto-drained queued turn", async () => {
  11725. const terminal = new FakeTerminal();
  11726. const runtime = createRuntime();
  11727. const busEvents: TuiRuntimeEvent[] = [];
  11728. let wakeBus: (() => void) | undefined;
  11729. const waitForNextBusEvent = (signal: AbortSignal) =>
  11730. new Promise<void>((resolve) => {
  11731. wakeBus = resolve;
  11732. signal.addEventListener("abort", resolve, { once: true });
  11733. });
  11734. vi.mocked(runtime.listSessions).mockResolvedValue([
  11735. {
  11736. sessionId: "session-existing",
  11737. title: "Existing",
  11738. workspaceDir: "/workspace",
  11739. },
  11740. ]);
  11741. vi.mocked(runtime.getMessages)
  11742. .mockResolvedValueOnce([])
  11743. .mockResolvedValue([
  11744. {
  11745. id: "message-user-queued",
  11746. turnId: "turn-queued",
  11747. role: "user",
  11748. content: "Runtime follow-up",
  11749. timestamp: 100,
  11750. },
  11751. {
  11752. id: "message-assistant-queued",
  11753. turnId: "turn-queued",
  11754. role: "assistant",
  11755. content: "Runtime follow-up answer",
  11756. timestamp: 101,
  11757. },
  11758. ]);
  11759. vi.mocked(runtime.watchEvents).mockImplementation(
  11760. async function* watchEvents(signal) {
  11761. while (!signal.aborted) {
  11762. if (busEvents.length === 0) {
  11763. await waitForNextBusEvent(signal);
  11764. }
  11765. if (signal.aborted) return;
  11766. const event = busEvents.shift();
  11767. if (event) yield event;
  11768. }
  11769. },
  11770. );
  11771. const emit = (event: RawTuiRuntimeEvent) => {
  11772. busEvents.push(runtimeEvent(event));
  11773. wakeBus?.();
  11774. wakeBus = undefined;
  11775. };
  11776. const app = createTuiApp({
  11777. runtime,
  11778. terminal,
  11779. version: "0.1.0",
  11780. workspaceDir: "/workspace",
  11781. });
  11782. app.start();
  11783. await app.ready;
  11784. await app.submit("/resume session-existing");
  11785. emit({
  11786. type: "session.start",
  11787. timestamp: 100,
  11788. source: "runtime",
  11789. payload: {
  11790. sessionId: "session-existing",
  11791. turnId: "turn-queued",
  11792. source: "queued-drain",
  11793. queueItemIds: ["queue-1"],
  11794. },
  11795. });
  11796. await vi.waitFor(() =>
  11797. expect(app.tui.render(80).join("\n")).toContain("Loading"),
  11798. );
  11799. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  11800. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  11801. "session-existing",
  11802. "turn-queued",
  11803. expect.any(AbortSignal),
  11804. );
  11805. emit({
  11806. type: "session.finish",
  11807. timestamp: 101,
  11808. source: "runtime",
  11809. payload: {
  11810. sessionId: "session-existing",
  11811. turnId: "turn-queued",
  11812. status: "finished",
  11813. },
  11814. });
  11815. await vi.waitFor(() =>
  11816. expect(app.transcript.snapshot()).toEqual(
  11817. expect.arrayContaining([
  11818. expect.objectContaining({
  11819. kind: "assistant",
  11820. content: "Runtime follow-up answer",
  11821. }),
  11822. ]),
  11823. ),
  11824. );
  11825. const historyProjectionCalls = vi
  11826. .mocked(runtime.getMessages)
  11827. .mock.calls.filter(
  11828. ([sessionId, limit]) =>
  11829. sessionId === "session-existing" && limit === undefined,
  11830. );
  11831. expect(historyProjectionCalls).toHaveLength(2);
  11832. await app.stop();
  11833. });
  11834. it("writes one structured result when an auto-drained queued turn finishes", async () => {
  11835. const dataDir = await mkdtemp(join(tmpdir(), "mcode-queued-result-"));
  11836. const resultPath = join(dataDir, "results.jsonl");
  11837. const terminal = new FakeTerminal();
  11838. const runtime = createRuntime();
  11839. const busEvents: TuiRuntimeEvent[] = [];
  11840. let wakeBus: (() => void) | undefined;
  11841. let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
  11842. vi.mocked(runtime.listSessions).mockResolvedValue([
  11843. {
  11844. sessionId: "session-existing",
  11845. title: "Existing",
  11846. workspaceDir: "/workspace",
  11847. },
  11848. ]);
  11849. vi.mocked(runtime.getMessages).mockImplementation(
  11850. async () => durableMessages,
  11851. );
  11852. const waitForBusEvent = (signal: AbortSignal) =>
  11853. new Promise<void>((resolve) => {
  11854. wakeBus = resolve;
  11855. signal.addEventListener("abort", resolve, { once: true });
  11856. });
  11857. vi.mocked(runtime.watchEvents).mockImplementation(
  11858. async function* watchEvents(signal) {
  11859. while (!signal.aborted) {
  11860. if (busEvents.length === 0) await waitForBusEvent(signal);
  11861. if (signal.aborted) return;
  11862. const event = busEvents.shift();
  11863. if (event) yield event;
  11864. }
  11865. },
  11866. );
  11867. const emit = (event: RawTuiRuntimeEvent) => {
  11868. busEvents.push(runtimeEvent(event));
  11869. wakeBus?.();
  11870. wakeBus = undefined;
  11871. };
  11872. const app = createTuiApp({
  11873. runtime,
  11874. terminal,
  11875. version: "0.1.0",
  11876. workspaceDir: "/workspace",
  11877. statusLineItems: ["build-mode"],
  11878. automationResultPath: resultPath,
  11879. });
  11880. try {
  11881. app.start();
  11882. await app.ready;
  11883. await app.submit("/resume session-existing");
  11884. emit({
  11885. type: "session.start",
  11886. timestamp: 100,
  11887. source: "runtime",
  11888. payload: {
  11889. sessionId: "session-existing",
  11890. turnId: "turn-queued-result",
  11891. source: "queued-drain",
  11892. queueItemIds: ["queue-result"],
  11893. },
  11894. });
  11895. await vi.waitFor(() =>
  11896. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  11897. "session-existing",
  11898. "turn-queued-result",
  11899. expect.any(AbortSignal),
  11900. ),
  11901. );
  11902. durableMessages = [
  11903. {
  11904. id: "message-user-result",
  11905. turnId: "turn-queued-result",
  11906. role: "user",
  11907. content: "Queued request",
  11908. timestamp: 101,
  11909. },
  11910. {
  11911. id: "message-assistant-result",
  11912. turnId: "turn-queued-result",
  11913. role: "assistant",
  11914. content: "Queued structured answer",
  11915. timestamp: 102,
  11916. },
  11917. ];
  11918. emit({
  11919. type: "session.finish",
  11920. timestamp: 103,
  11921. source: "runtime",
  11922. payload: {
  11923. sessionId: "session-existing",
  11924. turnId: "turn-queued-result",
  11925. status: "finished",
  11926. },
  11927. });
  11928. await vi.waitFor(async () => {
  11929. const records = (await readFile(resultPath, "utf8"))
  11930. .trim()
  11931. .split("\n")
  11932. .map(JSON.parse);
  11933. expect(records).toEqual([
  11934. expect.objectContaining({
  11935. type: "exec.result",
  11936. sessionId: "session-existing",
  11937. turnId: "turn-queued-result",
  11938. status: "succeeded",
  11939. answer: "Queued structured answer",
  11940. }),
  11941. ]);
  11942. });
  11943. expect(app.controller.snapshot().lastSettledTurn).toEqual({
  11944. sessionId: "session-existing",
  11945. turnId: "turn-queued-result",
  11946. status: "succeeded",
  11947. });
  11948. } finally {
  11949. await app.stop();
  11950. await rm(dataDir, { recursive: true, force: true });
  11951. }
  11952. });
  11953. it("settles an auto-drained follow-up once and replaces waiting state with run duration", async () => {
  11954. const terminal = new FakeTerminal();
  11955. const runtime = createRuntime();
  11956. const busEvents: TuiRuntimeEvent[] = [];
  11957. const queuedItems: TuiQueuedMessage[] = [];
  11958. let wakeBus: (() => void) | undefined;
  11959. let finishFirstTurn: (() => void) | undefined;
  11960. let finishQueuedStream: (() => void) | undefined;
  11961. const queuedStreamClosed = vi.fn();
  11962. let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
  11963. const waitForNextBusEvent = (signal: AbortSignal) =>
  11964. new Promise<void>((resolve) => {
  11965. wakeBus = resolve;
  11966. signal.addEventListener("abort", resolve, { once: true });
  11967. });
  11968. vi.mocked(runtime.sendMessage).mockImplementation(
  11969. async function* sendMessage() {
  11970. await new Promise<void>((resolve) => {
  11971. finishFirstTurn = resolve;
  11972. });
  11973. yield { type: "delta", content: "First answer" };
  11974. yield { type: "done" };
  11975. },
  11976. );
  11977. vi.mocked(runtime.watchSessionTurn).mockImplementation(
  11978. async function* watchSessionTurn() {
  11979. try {
  11980. await new Promise<void>((resolve) => {
  11981. finishQueuedStream = resolve;
  11982. });
  11983. yield { type: "delta", content: "Queued answer" };
  11984. yield { type: "done" };
  11985. } finally {
  11986. queuedStreamClosed();
  11987. }
  11988. },
  11989. );
  11990. vi.mocked(runtime.enqueueMessage).mockImplementation(
  11991. async (sessionId, content) => {
  11992. const item: TuiQueuedMessage = {
  11993. itemId: "queue-b",
  11994. sessionId,
  11995. status: "queued",
  11996. content,
  11997. };
  11998. queuedItems.push(item);
  11999. return { itemId: item.itemId, status: item.status, position: 1 };
  12000. },
  12001. );
  12002. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  12003. ...queuedItems,
  12004. ]);
  12005. vi.mocked(runtime.getMessages).mockImplementation(
  12006. async () => durableMessages,
  12007. );
  12008. vi.mocked(runtime.watchEvents).mockImplementation(
  12009. async function* watchEvents(signal) {
  12010. while (!signal.aborted) {
  12011. if (busEvents.length === 0) await waitForNextBusEvent(signal);
  12012. if (signal.aborted) return;
  12013. const event = busEvents.shift();
  12014. if (event) yield event;
  12015. }
  12016. },
  12017. );
  12018. const emit = (event: RawTuiRuntimeEvent) => {
  12019. busEvents.push(runtimeEvent(event));
  12020. wakeBus?.();
  12021. wakeBus = undefined;
  12022. };
  12023. const app = createTuiApp({
  12024. runtime,
  12025. terminal,
  12026. version: "0.1.0",
  12027. workspaceDir: "/workspace",
  12028. productFeatures: { queue: true },
  12029. });
  12030. app.start();
  12031. await app.ready;
  12032. const first = app.submit("A");
  12033. await vi.waitFor(() =>
  12034. expect(app.controller.snapshot().activeTurnId).toBeDefined(),
  12035. );
  12036. await app.submit("B");
  12037. expect(app.tui.render(80).join("\n")).toContain(
  12038. "Next · after current response",
  12039. );
  12040. expect(app.tui.render(80).join("\n")).toContain("B");
  12041. finishFirstTurn?.();
  12042. await first;
  12043. const queuedItem = queuedItems[0];
  12044. expect(queuedItem).toBeDefined();
  12045. if (!queuedItem) throw new Error("Expected B to be queued.");
  12046. queuedItems[0] = { ...queuedItem, status: "running" };
  12047. emit({
  12048. type: "session.queue.updated",
  12049. timestamp: 200,
  12050. source: "runtime",
  12051. payload: {
  12052. sessionId: "session-1",
  12053. itemId: "queue-b",
  12054. status: "running",
  12055. queuedCount: 0,
  12056. },
  12057. });
  12058. emit({
  12059. type: "session.start",
  12060. timestamp: 201,
  12061. source: "runtime",
  12062. payload: {
  12063. sessionId: "session-1",
  12064. turnId: "turn_queue_b",
  12065. source: "queued-drain",
  12066. queueItemIds: ["queue-b"],
  12067. },
  12068. });
  12069. await vi.waitFor(() =>
  12070. expect(app.tui.render(80).join("\n")).toContain("Loading"),
  12071. );
  12072. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  12073. queuedItems.length = 0;
  12074. durableMessages = [
  12075. {
  12076. id: "history-user-b",
  12077. turnId: "turn_queue_b",
  12078. role: "user",
  12079. content: "B",
  12080. timestamp: 202,
  12081. },
  12082. {
  12083. id: "history-assistant-b",
  12084. turnId: "turn_queue_b",
  12085. role: "assistant",
  12086. content: "Queued answer",
  12087. timestamp: 203,
  12088. },
  12089. ];
  12090. finishQueuedStream?.();
  12091. await vi.waitFor(() => expect(queuedStreamClosed).toHaveBeenCalledOnce());
  12092. emit({
  12093. type: "session.finish",
  12094. timestamp: 3_201,
  12095. source: "runtime",
  12096. payload: {
  12097. sessionId: "session-1",
  12098. turnId: "turn_queue_b",
  12099. status: "finished",
  12100. },
  12101. });
  12102. await vi.waitFor(() =>
  12103. expect(
  12104. app.transcript
  12105. .snapshot()
  12106. .filter((cell) => cell.content === "Queued answer"),
  12107. ).toHaveLength(1),
  12108. );
  12109. await vi.waitFor(() =>
  12110. expect(app.transcript.get("turn-duration:turn_queue_b")).toMatchObject({
  12111. status: "succeeded",
  12112. durationMs: 3_000,
  12113. }),
  12114. );
  12115. const settledUi = app.tui.render(80).join("\n");
  12116. expect(settledUi).toContain("Completed in 3s");
  12117. expect(settledUi.indexOf("Completed in 3s")).toBeGreaterThan(
  12118. settledUi.indexOf("Queued answer"),
  12119. );
  12120. expect(settledUi).not.toContain("message waiting");
  12121. expect(settledUi).not.toContain("Next · after current response");
  12122. await app.stop();
  12123. });
  12124. it("records submitted drafts in editor history", async () => {
  12125. const terminal = new FakeTerminal();
  12126. const runtime = createRuntime();
  12127. const app = createTuiApp({
  12128. runtime,
  12129. terminal,
  12130. version: "0.1.0",
  12131. workspaceDir: "/workspace",
  12132. });
  12133. await app.ready;
  12134. app.editor.setText("Remember this draft");
  12135. app.editor.handleInput("\r");
  12136. await vi.waitFor(() =>
  12137. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  12138. );
  12139. app.editor.handleInput("\u001b[A");
  12140. expect(app.editor.getText()).toBe("Remember this draft");
  12141. });
  12142. it("continues sending and switching sessions when draft cleanup fails", async () => {
  12143. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-warning-"));
  12144. const runtime = createRuntime();
  12145. const app = createTuiApp({
  12146. runtime,
  12147. terminal: new FakeTerminal(),
  12148. version: "0.1.0",
  12149. dataDir,
  12150. workspaceDir: "/workspace",
  12151. });
  12152. const flush = vi.spyOn(TuiDraftRecovery.prototype, "flush");
  12153. try {
  12154. await app.ready;
  12155. flush.mockRejectedValue(
  12156. new TuiDraftRecoveryError("cleanup", new Error("deletion denied")),
  12157. );
  12158. app.editor.setText("hello");
  12159. app.editor.handleInput("\r");
  12160. await vi.waitFor(() =>
  12161. expect(
  12162. app.transcript.snapshot().filter((cell) => cell.kind === "warning"),
  12163. ).toHaveLength(1),
  12164. );
  12165. const warnings = app.transcript
  12166. .snapshot()
  12167. .filter((cell) => cell.kind === "warning");
  12168. expect(warnings[0]?.content).toContain(
  12169. composerText("draftCleanupNextStep"),
  12170. );
  12171. expect(warnings[0]?.content).not.toContain(
  12172. composerText("draftRecoveryUnavailable"),
  12173. );
  12174. expect(warnings[0]?.content).toContain("deletion denied");
  12175. await vi.waitFor(() =>
  12176. expect(runtime.sendMessage).toHaveBeenCalledOnce(),
  12177. );
  12178. await vi.waitFor(() =>
  12179. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  12180. );
  12181. await expect(app.openSession("session-2")).resolves.toBeUndefined();
  12182. expect(app.controller.snapshot().session?.sessionId).toBe("session-2");
  12183. app.editor.setText("after switching");
  12184. app.editor.handleInput("\r");
  12185. await vi.waitFor(() =>
  12186. expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
  12187. );
  12188. await expect(app.stop()).resolves.toBeUndefined();
  12189. } finally {
  12190. await app.stop();
  12191. flush.mockRestore();
  12192. await rm(dataDir, { recursive: true, force: true });
  12193. }
  12194. });
  12195. it("does not read or restore a persisted Draft during TUI startup", async () => {
  12196. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
  12197. try {
  12198. const first = createTuiApp({
  12199. runtime: createRuntime(),
  12200. terminal: new FakeTerminal(),
  12201. version: "0.1.0",
  12202. dataDir,
  12203. workspaceDir: "/workspace/recovery",
  12204. });
  12205. await first.ready;
  12206. first.editor.setText("/exit");
  12207. await first.stop();
  12208. const loadDraft = vi.spyOn(TuiDraftRecovery.prototype, "load");
  12209. const restored = createTuiApp({
  12210. runtime: createRuntime(),
  12211. terminal: new FakeTerminal(),
  12212. version: "0.1.0",
  12213. dataDir,
  12214. workspaceDir: "/workspace/recovery",
  12215. });
  12216. await restored.ready;
  12217. expect(loadDraft).not.toHaveBeenCalled();
  12218. expect(restored.editor.getText()).toBe("");
  12219. expect(restored.tui.render(80).join("\n")).not.toContain(
  12220. "Draft restored",
  12221. );
  12222. loadDraft.mockRestore();
  12223. restored.editor.setText("");
  12224. await restored.stop();
  12225. } finally {
  12226. await rm(dataDir, { recursive: true, force: true });
  12227. }
  12228. });
  12229. it("does not resume a persisted Draft during startup when login recovery is enabled", async () => {
  12230. const dataDir = await mkdtemp(join(tmpdir(), "mcode-login-restart-draft-"));
  12231. try {
  12232. const first = createTuiApp({
  12233. runtime: createRuntime(),
  12234. terminal: new FakeTerminal(),
  12235. version: "0.1.0",
  12236. dataDir,
  12237. workspaceDir: "/workspace/login-recovery",
  12238. });
  12239. await first.ready;
  12240. first.editor.setText("send after Global login");
  12241. await first.stop();
  12242. const restored = createTuiApp({
  12243. runtime: createRuntime(),
  12244. terminal: new FakeTerminal(),
  12245. version: "0.1.0",
  12246. dataDir,
  12247. workspaceDir: "/workspace/login-recovery",
  12248. resumeDraftAfterLogin: true,
  12249. });
  12250. await restored.ready;
  12251. restored.start();
  12252. expect(restored.editor.getText()).toBe("");
  12253. expect(restored.getSurface()).toBe("welcome");
  12254. expect(restored.tui.render(80).join("\n")).toContain(
  12255. "Tips for getting started",
  12256. );
  12257. await restored.stop();
  12258. } finally {
  12259. await rm(dataDir, { recursive: true, force: true });
  12260. }
  12261. });
  12262. it("keeps the submitted Draft recoverable when shutdown wins before Runtime admission", async () => {
  12263. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-pending-draft-"));
  12264. try {
  12265. const runtime = createRuntime();
  12266. vi.spyOn(runtime, "sendMessage").mockImplementation(
  12267. async function* sendMessage(
  12268. _req: SendMessageReq,
  12269. signal?: AbortSignal,
  12270. ) {
  12271. yield* [];
  12272. await new Promise<void>((_resolve, reject) => {
  12273. signal?.addEventListener(
  12274. "abort",
  12275. () => reject(new Error("admission aborted")),
  12276. {
  12277. once: true,
  12278. },
  12279. );
  12280. });
  12281. throw new Error("unreachable");
  12282. },
  12283. );
  12284. const first = createTuiApp({
  12285. runtime,
  12286. terminal: new FakeTerminal(),
  12287. version: "0.1.0",
  12288. dataDir,
  12289. workspaceDir: "/workspace/pending-recovery",
  12290. });
  12291. await first.ready;
  12292. first.editor.setText("recover me until Runtime accepts");
  12293. await new Promise((resolve) => setTimeout(resolve, 300));
  12294. first.editor.handleInput("\r");
  12295. await vi.waitFor(() =>
  12296. expect(runtime.sendMessage).toHaveBeenCalledOnce(),
  12297. );
  12298. await first.stop();
  12299. const restored = createTuiApp({
  12300. runtime: createRuntime(),
  12301. terminal: new FakeTerminal(),
  12302. version: "0.1.0",
  12303. dataDir,
  12304. workspaceDir: "/workspace/pending-recovery",
  12305. });
  12306. await restored.ready;
  12307. await restored.openSession("session-1");
  12308. expect(restored.editor.getText()).toBe(
  12309. "recover me until Runtime accepts",
  12310. );
  12311. const rendered = restored.tui.render(80).join("\n");
  12312. expect(rendered).toContain("recover me until Runtime accepts");
  12313. expect(rendered).not.toContain("Message kept under Failed");
  12314. await restored.stop();
  12315. } finally {
  12316. await rm(dataDir, { recursive: true, force: true });
  12317. }
  12318. });
  12319. it("does not restore a submitted Draft after Runtime accepts the turn", async () => {
  12320. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-accepted-draft-"));
  12321. try {
  12322. const runtime = createRuntime();
  12323. vi.mocked(runtime.sendMessage).mockImplementation(
  12324. async function* sendMessage(
  12325. _req: SendMessageReq,
  12326. signal?: AbortSignal,
  12327. ) {
  12328. await new Promise<void>((resolve) => {
  12329. signal?.addEventListener("abort", resolve, { once: true });
  12330. });
  12331. yield { type: "done" };
  12332. },
  12333. );
  12334. const first = createTuiApp({
  12335. runtime,
  12336. terminal: new FakeTerminal(),
  12337. version: "0.1.0",
  12338. dataDir,
  12339. workspaceDir: "/workspace/accepted-recovery",
  12340. });
  12341. await first.ready;
  12342. first.editor.setText("already accepted by Runtime");
  12343. await new Promise((resolve) => setTimeout(resolve, 300));
  12344. first.editor.handleInput("\r");
  12345. await vi.waitFor(() =>
  12346. expect(runtime.sendMessage).toHaveBeenCalledOnce(),
  12347. );
  12348. await first.stop();
  12349. const restored = createTuiApp({
  12350. runtime: createRuntime(),
  12351. terminal: new FakeTerminal(),
  12352. version: "0.1.0",
  12353. dataDir,
  12354. workspaceDir: "/workspace/accepted-recovery",
  12355. });
  12356. await restored.ready;
  12357. expect(restored.editor.getText()).toBe("");
  12358. await restored.stop();
  12359. } finally {
  12360. await rm(dataDir, { recursive: true, force: true });
  12361. }
  12362. });
  12363. it("serializes rapid Session switches without mixing their Drafts", async () => {
  12364. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
  12365. try {
  12366. const app = createTuiApp({
  12367. runtime: createRuntime(),
  12368. terminal: new FakeTerminal(),
  12369. version: "0.1.0",
  12370. dataDir,
  12371. workspaceDir: "/workspace/recovery",
  12372. });
  12373. await app.ready;
  12374. await app.openSession("session-a");
  12375. app.editor.setText("Draft for Session A");
  12376. await app.openSession("session-b");
  12377. app.editor.setText("Draft for Session B");
  12378. await Promise.all([
  12379. app.openSession("session-a"),
  12380. app.openSession("session-b"),
  12381. ]);
  12382. expect(app.controller.snapshot().session?.sessionId).toBe("session-b");
  12383. expect(app.editor.getText()).toBe("Draft for Session B");
  12384. await app.openSession("session-a");
  12385. expect(app.editor.getText()).toBe("Draft for Session A");
  12386. await app.openSession("session-b");
  12387. expect(app.editor.getText()).toBe("Draft for Session B");
  12388. await app.stop();
  12389. } finally {
  12390. await rm(dataDir, { recursive: true, force: true });
  12391. }
  12392. });
  12393. it("moves to the new-session Draft namespace after archiving the current Session", async () => {
  12394. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
  12395. try {
  12396. const app = createTuiApp({
  12397. runtime: createRuntime(),
  12398. terminal: new FakeTerminal(),
  12399. version: "0.1.0",
  12400. dataDir,
  12401. workspaceDir: "/workspace/recovery",
  12402. });
  12403. await app.ready;
  12404. await app.openSession("session-a");
  12405. app.editor.setText("Archived Session Draft");
  12406. await app.submit("/archive");
  12407. app.editor.setText("Fresh Session Draft");
  12408. await app.openSession("session-a");
  12409. expect(app.editor.getText()).toBe("Archived Session Draft");
  12410. await app.submit("/new");
  12411. expect(app.editor.getText()).toBe("Fresh Session Draft");
  12412. await app.stop();
  12413. } finally {
  12414. await rm(dataDir, { recursive: true, force: true });
  12415. }
  12416. });
  12417. });
  12418. describe("interactive CLI model startup", () => {
  12419. it.each([
  12420. [
  12421. "new with prompt",
  12422. ["-m", "custom_provider:relay/vendor/model#thinking", "hello"],
  12423. "session-1",
  12424. true,
  12425. ],
  12426. [
  12427. "new without prompt",
  12428. ["--model=custom_provider:relay/vendor/model#thinking"],
  12429. "session-1",
  12430. false,
  12431. ],
  12432. [
  12433. "explicit session",
  12434. ["--session", "existing", "--model", "custom_provider:relay/vendor/model#thinking", "hello"],
  12435. "existing",
  12436. true,
  12437. ],
  12438. [
  12439. "continue",
  12440. ["--continue", "--model", "custom_provider:relay/vendor/model#thinking", "hello"],
  12441. "existing",
  12442. true,
  12443. ],
  12444. [
  12445. "missing session",
  12446. ["--session", "missing", "-m", "custom_provider:relay/vendor/model#thinking", "hello"],
  12447. "missing",
  12448. false,
  12449. ],
  12450. [
  12451. "empty continue",
  12452. ["--continue", "-m", "custom_provider:relay/vendor/model#thinking", "hello"],
  12453. "existing",
  12454. false,
  12455. ],
  12456. ["invalid provider", ["--model", "missing/model", "hello"], "session-1", false],
  12457. ["invalid model", ["--model", "custom_provider:relay/missing", "hello"], "session-1", false],
  12458. ] as const)(
  12459. "routes %s through launch, hydration and submission",
  12460. async (_name, args, sessionId, hasPrompt) => {
  12461. const dataDir = await mkdtemp(join(tmpdir(), "mcode-model-startup-"));
  12462. const terminal = new FakeTerminal();
  12463. const runtime = createRuntime();
  12464. runtime.listBackgroundTasks = vi.fn(async () => []);
  12465. const models = new Map<string, { providerId: string; modelId: string; variant?: string }>();
  12466. const requested = {
  12467. providerId: "custom_provider:relay",
  12468. modelId: "vendor/model",
  12469. variant: "thinking",
  12470. };
  12471. const existing = { sessionId: "existing", workspaceDir: "/workspace", updatedAt: 10 };
  12472. vi.mocked(runtime.listSessions).mockResolvedValue([existing]);
  12473. vi.mocked(runtime.listSessionPage).mockResolvedValue({
  12474. sessions: [existing],
  12475. hasMore: false,
  12476. });
  12477. vi.mocked(runtime.getSession).mockImplementation(async (id) => ({
  12478. sessionId: id,
  12479. workspaceDir: "/workspace",
  12480. model: models.get(id),
  12481. }));
  12482. const failedResume = _name === "missing session" || _name === "empty continue";
  12483. if (_name === "missing session")
  12484. vi.mocked(runtime.getSession).mockRejectedValue(new Error("Session not found"));
  12485. if (_name === "empty continue") vi.mocked(runtime.listSessions).mockResolvedValue([]);
  12486. runtime.selectModel = vi.fn(async () => true);
  12487. runtime.selectSessionModel = vi.fn(async (model, id) => {
  12488. if (model.providerId !== requested.providerId || model.modelId !== requested.modelId) {
  12489. throw new Error("Unknown provider or model");
  12490. }
  12491. models.set(id, model);
  12492. return true;
  12493. });
  12494. vi.mocked(runtime.listModels).mockImplementation(async (id) => [
  12495. { ...requested, name: "Startup model", selected: Boolean(id && models.has(id)) },
  12496. ]);
  12497. // A global managed default needs login; the selected BYOK Session does not.
  12498. vi.mocked(runtime.getAccountStatus).mockImplementation(async (id) => ({
  12499. status: id && models.has(id) ? "ready" : "needs-login",
  12500. modelSource: id && models.has(id) ? "byok" : "token-plan",
  12501. managedTokenPresent: false,
  12502. warnings: [],
  12503. }));
  12504. const sentModels: unknown[] = [];
  12505. vi.mocked(runtime.sendMessage).mockImplementation(async function* (request) {
  12506. sentModels.push(models.get(request.id));
  12507. yield { type: "delta", content: "offline reply" };
  12508. yield { type: "done" };
  12509. });
  12510. const invalid = _name.startsWith("invalid");
  12511. const stderr = vi.fn((_text: string, callback?: () => void) => callback?.());
  12512. const processRef = {
  12513. title: "test",
  12514. argv: ["node", "cli.js", ...args],
  12515. env: {},
  12516. versions: { node: "24.2.0" },
  12517. stdout: {
  12518. destroyed: false,
  12519. writableEnded: false,
  12520. write: vi.fn((_text: string, cb?: () => void) => cb?.()),
  12521. },
  12522. stderr: { destroyed: false, writableEnded: false, write: stderr },
  12523. exit: vi.fn(),
  12524. exitCode: 0,
  12525. };
  12526. let app: ReturnType<typeof createTuiApp> | undefined;
  12527. const running = runTuiCli({
  12528. processRef,
  12529. configureNetworkProxy: () => undefined,
  12530. launchTui: (input) =>
  12531. launchTui(
  12532. { ...input, dataDir, terminal, workspaceDir: "/workspace" },
  12533. {
  12534. createObservability,
  12535. readTelemetryEnabled: () => false,
  12536. installProcessGuards: () => () => undefined,
  12537. loadRuntimeLifecycle: async () => ({
  12538. createTuiRuntime: async () => ({ adapter: runtime }) as never,
  12539. shutdownTuiRuntime: async () => false,
  12540. }),
  12541. loadUpdateApplication: async () =>
  12542. ({ inspect: async () => ({ status: "up-to-date" }) }) as never,
  12543. createApp: (options) => {
  12544. app = createTuiApp({ ...options, productFeatures: { queue: false } });
  12545. return app;
  12546. },
  12547. writeExitMessage: () => undefined,
  12548. },
  12549. ),
  12550. });
  12551. try {
  12552. if (invalid) {
  12553. await running;
  12554. expect(processRef.exitCode).toBe(1);
  12555. expect(stderr.mock.calls.flat().join(" ")).toContain("Unknown provider or model");
  12556. expect(runtime.sendMessage).not.toHaveBeenCalled();
  12557. } else if (failedResume) {
  12558. await vi.waitFor(() => expect(app?.editor.disableSubmit).toBe(false));
  12559. expect(runtime.selectSessionModel).not.toHaveBeenCalled();
  12560. expect(runtime.createSession).not.toHaveBeenCalled();
  12561. expect(runtime.sendMessage).not.toHaveBeenCalled();
  12562. } else {
  12563. await vi.waitFor(() => {
  12564. expect(app?.editor.disableSubmit).toBe(false);
  12565. expect(app?.controller.snapshot().session?.model).toEqual(requested);
  12566. if (hasPrompt) expect(sentModels).toEqual([requested]);
  12567. });
  12568. expect(runtime.selectSessionModel).toHaveBeenCalledWith(requested, sessionId);
  12569. expect(app?.controller.snapshot().account?.modelSource).toBe("byok");
  12570. if (sessionId === "existing") expect(runtime.createSession).not.toHaveBeenCalled();
  12571. if (!hasPrompt) {
  12572. expect(runtime.sendMessage).not.toHaveBeenCalled();
  12573. await app?.submit("later prompt");
  12574. expect(sentModels).toEqual([requested]);
  12575. }
  12576. await vi.waitFor(() => expect(app?.controller.snapshot().status).toBe("idle"));
  12577. await app?.submit("/new");
  12578. expect(app?.controller.snapshot().session).toBeUndefined();
  12579. expect(runtime.selectSessionModel).toHaveBeenCalledOnce();
  12580. }
  12581. expect(runtime.selectModel).not.toHaveBeenCalled();
  12582. } finally {
  12583. await app?.stop();
  12584. await running;
  12585. await rm(dataDir, { recursive: true, force: true });
  12586. }
  12587. },
  12588. );
  12589. });
  12590. describe("interactive model argument contract", () => {
  12591. function program() {
  12592. const launch = vi.fn(async () => undefined);
  12593. const command = createTuiProgram({
  12594. version: "test",
  12595. launchTui: launch,
  12596. runExec: vi.fn(),
  12597. runLogin: vi.fn(),
  12598. runLogout: vi.fn(),
  12599. runUpdate: vi.fn(),
  12600. })
  12601. .exitOverride()
  12602. .configureOutput({ writeErr: () => undefined });
  12603. return { command, launch };
  12604. }
  12605. it.each(["-m", "--model"])("rejects missing values for %s", async (flag) => {
  12606. const { command, launch } = program();
  12607. await expect(command.parseAsync([flag], { from: "user" })).rejects.toThrow();
  12608. expect(launch).not.toHaveBeenCalled();
  12609. });
  12610. it.each(["", "bare-model", "provider/", "/model", "provider/model#"])(
  12611. "rejects malformed model %j before launch",
  12612. async (model) => {
  12613. const { command, launch } = program();
  12614. await expect(command.parseAsync(["--model", model], { from: "user" })).rejects.toThrow(
  12615. "--model must use provider/model",
  12616. );
  12617. expect(launch).not.toHaveBeenCalled();
  12618. },
  12619. );
  12620. it("rejects a model with an untargeted Session picker", async () => {
  12621. const { command, launch } = program();
  12622. await expect(
  12623. command.parseAsync(["--session", "--model", "provider/model"], { from: "user" }),
  12624. ).rejects.toThrow("requires a Session id");
  12625. expect(launch).not.toHaveBeenCalled();
  12626. });
  12627. it("retains the default launch contract without a model", async () => {
  12628. const { command, launch } = program();
  12629. await command.parseAsync(["hello"], { from: "user" });
  12630. expect(launch).toHaveBeenCalledWith({ initialPrompt: "hello" });
  12631. });
  12632. it.each(["-m", "--model"])("scans startup environment after %s values", (flag) => {
  12633. expect(
  12634. resolveTuiStartupEnvironmentOption([flag, "provider/model", "--env", "staging"], true),
  12635. ).toBe("staging");
  12636. expect(() =>
  12637. resolveTuiStartupEnvironmentOption([flag, "provider/model", "--env", "prod"], false),
  12638. ).toThrow("only available");
  12639. expect(
  12640. resolveTuiStartupEnvironmentOption(
  12641. [flag, "provider/model", "exec", "--env", "staging"],
  12642. true,
  12643. ),
  12644. ).toBeUndefined();
  12645. });
  12646. });